Skip to main content

unbanished_core/
scheduler.rs

1//! Game time, and the entity manager's update buckets.
2//!
3//! **Time.** The engine counts time in integer microseconds (`System::Time`). [`ticks`] and
4//! [`seconds`] convert as the original does: through `f64`, truncating to time and rounding to
5//! `f32` seconds.
6//!
7//! **Buckets.** A town has tens of thousands of entities, so the game does not update all of them
8//! in every simulation iteration. [`EntityScheduler`] keeps them in five buckets, and each
9//! iteration visits at most [`QUOTAS`] entities of each bucket, starting where the last visit
10//! stopped. Each entity receives the time since its own last visit, so no time is lost.
11//!
12//! ```
13//! use unbanished_core::scheduler::{seconds, ticks};
14//!
15//! assert_eq!(ticks(1.5), 1_500_000);
16//! assert_eq!(seconds(ticks(1.5)), 1.5);
17//! ```
18//!
19//! The port's handles are stable indices; the engine uses object pointers. Removing an entity
20//! still swaps it with the last one of its bucket, as in the engine.
21//!
22//! Original: `FUN_1400c9460`, `FUN_1400c9560`, `FUN_1400c9d70`.
23
24/// The length of one tick of game time, in seconds: the engine's timer counts 1,000,000 ticks per
25/// second.
26///
27/// Original: `System::Timer::Startup`, Runtime `0x1800cd030`.
28pub const SECONDS_PER_TICK: f64 = 1e-6;
29
30/// Seconds to game time: through `f64`, truncated.
31///
32/// Original: constructing a `System::Time`, Runtime `0x1800078c0`.
33pub fn ticks(seconds: f32) -> i64 {
34    (seconds as f64 / SECONDS_PER_TICK) as i64
35}
36
37/// Game time to seconds: through `f64`, rounded to `f32`.
38///
39/// Original: `System::Time::AsSeconds`, Runtime `0x180007900`.
40pub fn seconds(time: i64) -> f32 {
41    (time as f64 * SECONDS_PER_TICK) as f32
42}
43
44// The entity manager's +0xa8..+0xb8.
45/// How many entities of each bucket one iteration visits, for buckets 0 to 4.
46///
47/// Original: `FUN_1400c9460`.
48pub const QUOTAS: [usize; 5] = [50, 15, 8, 5, 2];
49
50struct Entity<T> {
51    value: T,
52    bucket: usize,
53    slot: usize,
54    last_time: i64,
55    live: bool,
56}
57
58/// The bucket of a handle held free by [`EntityScheduler::register_at`] until its entity registers.
59const FREE: usize = usize::MAX;
60
61/// Handles of entities registered with [`EntityScheduler::register_extra`] start here, so that
62/// a placed entity's handle stays its index. The game gives such entities values from here too:
63/// citizens `EXTRA + citizen`, and entities the town does not model (the map ambience, a
64/// saved game's entities of templates it skips) from [`FOREIGN`].
65pub const EXTRA: usize = 1 << 30;
66/// Values of scheduled entities with no behaviour in the port (visited for the cursors' sake).
67pub const FOREIGN: usize = EXTRA + (1 << 29);
68
69/// The entity manager's buckets: which entities are visited in each simulation iteration, and
70/// the time each one has had since its last visit. `T` is the caller's value for an entity.
71pub struct EntityScheduler<T> {
72    /// The current game time.
73    pub time: i64,
74    entities: Vec<Entity<T>>,
75    /// Entities outside the placed index space (handles from [`EXTRA`]).
76    extra: Vec<Entity<T>>,
77    buckets: [Vec<usize>; 5],
78    cursors: [usize; 5],
79    /// This iteration's visits, in order: the value and the time since its last visit.
80    visited: Vec<(T, i64)>,
81}
82
83impl<T: Copy> Default for EntityScheduler<T> {
84    fn default() -> Self {
85        Self {
86            time: 0,
87            entities: Vec::new(),
88            extra: Vec::new(),
89            buckets: std::array::from_fn(|_| Vec::new()),
90            cursors: [0; 5],
91            visited: Vec::new(),
92        }
93    }
94}
95
96impl<T: Copy> EntityScheduler<T> {
97    /// Register an entity in a bucket, at the end, with its last visit set to now. Returns its
98    /// handle. Bucket 6 means "not scheduled": the entity is registered but never visited.
99    ///
100    /// Original: `FUN_1400c9d70`.
101    pub fn register(&mut self, value: T, bucket: usize) -> usize {
102        assert!(
103            bucket < 5 || bucket == 6,
104            "invalid component-description bucket"
105        );
106        let id = self.entities.len();
107        let slot = if bucket < 5 {
108            let slot = self.buckets[bucket].len();
109            self.buckets[bucket].push(id);
110            slot
111        } else {
112            0
113        };
114        self.entities.push(Entity {
115            value,
116            bucket,
117            slot,
118            last_time: self.time,
119            live: true,
120        });
121        id
122    }
123
124    /// [`register`](Self::register) at handle `id`: the entity's own index, whatever the
125    /// order the entities are registered in. Indices below `id` not yet registered are held
126    /// free until they are. The port makes some entities first and registers them at the end
127    /// of the iteration (piles), while others register as they are made (spawned trees), so
128    /// handing out the next free handle gave a tree a pile's handle and its bucket.
129    ///
130    /// Original: `FUN_1400c9d70`.
131    pub fn register_at(&mut self, id: usize, value: T, bucket: usize) -> usize {
132        assert!(
133            bucket < 5 || bucket == 6,
134            "invalid component-description bucket"
135        );
136        while self.entities.len() < id {
137            self.entities.push(Entity {
138                value,
139                bucket: FREE,
140                slot: 0,
141                last_time: self.time,
142                live: false,
143            });
144        }
145        let slot = if bucket < 5 {
146            let slot = self.buckets[bucket].len();
147            self.buckets[bucket].push(id);
148            slot
149        } else {
150            0
151        };
152        let entity = Entity {
153            value,
154            bucket,
155            slot,
156            last_time: self.time,
157            live: true,
158        };
159        if id < self.entities.len() {
160            self.entities[id] = entity;
161        } else {
162            self.entities.push(entity);
163        }
164        id
165    }
166
167    /// [`register`](Self::register) in the extra handle space (from [`EXTRA`]): the same
168    /// buckets, cursors and timing, without taking a placed entity's index.
169    pub fn register_extra(&mut self, value: T, bucket: usize) -> usize {
170        let id = EXTRA + self.extra.len();
171        let slot = if bucket < 5 {
172            let slot = self.buckets[bucket].len();
173            self.buckets[bucket].push(id);
174            slot
175        } else {
176            0
177        };
178        self.extra.push(Entity {
179            value,
180            bucket,
181            slot,
182            last_time: self.time,
183            live: true,
184        });
185        id
186    }
187
188    fn entity_mut(&mut self, id: usize) -> &mut Entity<T> {
189        if id >= EXTRA {
190            &mut self.extra[id - EXTRA]
191        } else {
192            &mut self.entities[id]
193        }
194    }
195
196    /// Whether `handle` was registered.
197    pub fn contains(&self, handle: usize) -> bool {
198        if handle >= EXTRA {
199            handle - EXTRA < self.extra.len()
200        } else {
201            self.entities.get(handle).is_some_and(|e| e.bucket != FREE)
202        }
203    }
204
205    /// A bucket's handles in visiting order.
206    pub fn bucket(&self, bucket: usize) -> &[usize] {
207        &self.buckets[bucket]
208    }
209
210    // +0xbc
211    /// A bucket's cursor, the slot its next visit starts at.
212    pub fn cursor(&self, bucket: usize) -> usize {
213        self.cursors[bucket]
214    }
215
216    /// An entity's bucket (6: none) and last visit time.
217    pub fn schedule(&self, handle: usize) -> (usize, i64) {
218        let e = if handle >= EXTRA {
219            &self.extra[handle - EXTRA]
220        } else {
221            &self.entities[handle]
222        };
223        (e.bucket, e.last_time)
224    }
225
226    /// A saved game's bucket lists, cursors and schedules: `order` lists each bucket's handles
227    /// in its saved order, `saved` each saved entity's bucket (6: none) and last visit time.
228    /// Registered entities the save does not know keep their bucket and follow its listed ones.
229    pub fn restore(
230        &mut self,
231        order: &[Vec<usize>; 5],
232        cursors: [usize; 5],
233        saved: &[(usize, usize, i64)],
234    ) {
235        let listed: std::collections::HashSet<usize> = order
236            .iter()
237            .flatten()
238            .copied()
239            .chain(saved.iter().map(|s| s.0))
240            .collect();
241        let mut lists: [Vec<usize>; 5] = std::array::from_fn(|b| {
242            order[b]
243                .iter()
244                .copied()
245                .filter(|&h| self.contains(h))
246                .collect()
247        });
248        for b in 0..5 {
249            for &h in &self.buckets[b] {
250                if !listed.contains(&h) {
251                    lists[b].push(h);
252                }
253            }
254        }
255        for (b, list) in lists.iter().enumerate() {
256            for (slot, &h) in list.iter().enumerate() {
257                let e = self.entity_mut(h);
258                e.bucket = b;
259                e.slot = slot;
260            }
261        }
262        self.buckets = lists;
263        self.cursors = cursors;
264        let in_lists: std::collections::HashSet<usize> =
265            self.buckets.iter().flatten().copied().collect();
266        for &(h, bucket, t) in saved {
267            if !self.contains(h) {
268                continue;
269            }
270            let e = self.entity_mut(h);
271            e.last_time = t;
272            if !in_lists.contains(&h) {
273                e.bucket = if bucket < 5 { 6 } else { bucket };
274            }
275        }
276    }
277
278    /// The values visited since the last call, each with the time since its previous visit,
279    /// in visiting order (the bucket pass's scheduled components run for these).
280    pub fn take_visits(&mut self) -> Vec<(T, i64)> {
281        std::mem::take(&mut self.visited)
282    }
283
284    /// Advance the clock by `dt` seconds. Then the caller visits each bucket, then removes the
285    /// entities that were deleted.
286    ///
287    /// Original: `FUN_1400c9560` (the clock).
288    pub fn advance(&mut self, dt: f32) {
289        self.time += ticks(dt);
290    }
291
292    /// Visit one bucket: from its cursor, at most its quota of entities or one full round. Each
293    /// visit gives the entity's handle, value and the time since its own last visit. Entities
294    /// registered during the visits wait until the next iteration.
295    ///
296    /// Original: `FUN_1400c9560`.
297    pub fn visit_bucket(&mut self, bucket: usize) -> Vec<(usize, T, i64)> {
298        let list = &self.buckets[bucket];
299        let count = list.len();
300        if count == 0 {
301            return Vec::new();
302        }
303        let mut cursor = if self.cursors[bucket] < count {
304            self.cursors[bucket]
305        } else {
306            0
307        };
308        let mut visits = Vec::with_capacity(QUOTAS[bucket].min(count));
309        let time = self.time;
310        for _ in 0..QUOTAS[bucket].min(count) {
311            let id = self.buckets[bucket][cursor];
312            let entity = self.entity_mut(id);
313            let dt = time - entity.last_time;
314            if entity.live && dt > 0 {
315                entity.last_time = time;
316                let value = entity.value;
317                visits.push((id, value, dt));
318                self.visited.push((value, dt));
319            }
320            cursor = (cursor + 1) % count;
321        }
322        self.cursors[bucket] = cursor;
323        visits
324    }
325
326    /// Remove an entity: it swaps places with the last entity of its bucket, and the cursor does
327    /// not move. Call it after all visits of the iteration, as the original deletes late.
328    ///
329    /// Original: `FUN_1400c8db0`.
330    pub fn remove(&mut self, id: usize) {
331        let entity = self.entity_mut(id);
332        if !entity.live {
333            return;
334        }
335        let (bucket, slot) = (entity.bucket, entity.slot);
336        if bucket < 5 {
337            self.buckets[bucket].swap_remove(slot);
338            if let Some(&moved) = self.buckets[bucket].get(slot) {
339                self.entity_mut(moved).slot = slot;
340            }
341        }
342        self.entity_mut(id).live = false;
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    #[test]
351    fn quotas_elapsed_time_and_registration() {
352        let mut scheduler = EntityScheduler::default();
353        for i in 0..11 {
354            scheduler.register(i, 3);
355        }
356        scheduler.register(99, 6);
357        scheduler.advance(0.5);
358        let first = scheduler.visit_bucket(3);
359        assert_eq!(
360            first.iter().map(|v| v.1).collect::<Vec<_>>(),
361            [0, 1, 2, 3, 4]
362        );
363        assert!(first.iter().all(|v| v.2 == ticks(0.5)));
364        scheduler.advance(0.5);
365        let second = scheduler.visit_bucket(3);
366        assert_eq!(
367            second.iter().map(|v| v.1).collect::<Vec<_>>(),
368            [5, 6, 7, 8, 9]
369        );
370        assert!(second.iter().all(|v| v.2 == 2 * ticks(0.5)));
371        scheduler.advance(0.5);
372        let third = scheduler.visit_bucket(3);
373        assert_eq!(
374            third.iter().map(|v| v.1).collect::<Vec<_>>(),
375            [10, 0, 1, 2, 3]
376        );
377        assert_eq!(third[0].2, 3 * ticks(0.5));
378        assert_eq!(third[1].2, 2 * ticks(0.5));
379    }
380
381    #[test]
382    fn deletion_preserves_swap_order_and_zero_delta_skips_callbacks() {
383        let mut scheduler = EntityScheduler::default();
384        let ids: Vec<_> = (0..4).map(|i| scheduler.register(i, 4)).collect();
385        assert!(scheduler.visit_bucket(4).is_empty());
386        // Even zero-delta visits move the cursor; the next live visit starts with 2, 3.
387        scheduler.advance(1.0);
388        scheduler.visit_bucket(4);
389        scheduler.remove(ids[1]); // [0, 3, 2], cursor still 0
390        scheduler.advance(1.0);
391        assert_eq!(
392            scheduler
393                .visit_bucket(4)
394                .iter()
395                .map(|v| v.1)
396                .collect::<Vec<_>>(),
397            [0, 3]
398        );
399        scheduler.remove(ids[3]);
400        scheduler.advance(1.0);
401        assert_eq!(
402            scheduler
403                .visit_bucket(4)
404                .iter()
405                .map(|v| v.1)
406                .collect::<Vec<_>>(),
407            [0, 2]
408        );
409    }
410
411    /// A pile made first and registered at the end of the iteration keeps its own handle and
412    /// bucket when a tree made after it registers at once.
413    #[test]
414    fn registering_out_of_order_keeps_each_handle_and_bucket() {
415        let mut scheduler = EntityScheduler::default();
416        scheduler.register_at(0, 0usize, 4);
417        assert!(!scheduler.contains(1));
418        assert_eq!(scheduler.register_at(2, 2, 4), 2);
419        assert!(!scheduler.contains(1));
420        assert_eq!(scheduler.register_at(1, 1, 3), 1);
421        assert!(scheduler.contains(1));
422        assert_eq!(scheduler.bucket(4), &[0, 2]);
423        assert_eq!(scheduler.bucket(3), &[1]);
424        assert_eq!(scheduler.schedule(1).0, 3);
425    }
426}