Skip to main content
Verticopolis engine

verticopolis_engine/
sim_loop.rs

1// The time step (from the TypeScript reference's `sim/loop.ts`) and the
2// weather hash.
3
4use crate::crowd::{motion, spawn, PState, CROWD_SECONDS_PER_MINUTE, GIVE_UP};
5use crate::economy::films::fills_blockbuster_slot;
6use crate::facilities::Kind;
7use crate::sim::{LogKind, Simulation};
8use crate::tower::UnitState;
9
10pub const CROWD_MAX_STEP: f64 = 60.0;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum Weather {
14    Clear,
15    Cloudy,
16    Rain,
17}
18
19/// `weatherFor(day)`.
20pub fn weather_for(day: i64) -> Weather {
21    let mut h = (day as i32 as u32).wrapping_mul(2654435761);
22    h ^= h >> 13;
23    h = h.wrapping_mul(1274126177);
24    let r = ((h >> 8) & 0xffff) as f64 / 65536.0;
25    if r < 0.62 {
26        Weather::Clear
27    } else if r < 0.85 {
28        Weather::Cloudy
29    } else {
30        Weather::Rain
31    }
32}
33
34impl Simulation {
35    /// Advances the game by `dt_minutes` game minutes.
36    ///
37    /// Any `dt` works: the engine splits it into steps of at most 30 minutes
38    /// that never cross an hour, so hourly rules always run. The same seed,
39    /// the same commands and the same sequence of `dt` give the same game.
40    /// A host that runs on display frames should let
41    /// [`FrameStepper`](crate::fixed_step::FrameStepper) choose the `dt`, so
42    /// the tower comes out the same at any frame rate.
43    ///
44    /// ```
45    /// use verticopolis_engine::clock::GameMode;
46    /// use verticopolis_engine::sim::Simulation;
47    ///
48    /// let mut sim = Simulation::new_game(1, GameMode::Classic);
49    /// let day = sim.clock.day();
50    /// sim.tick(24.0 * 60.0);
51    /// assert_eq!(sim.clock.day(), day + 1);
52    /// ```
53    pub fn tick(&mut self, dt_minutes: f64) {
54        const EPS: f64 = 1e-6;
55        let mut remaining = dt_minutes;
56        while remaining > EPS {
57            let to_next_hour = 60.0 - (self.clock.minute_of_day() % 60.0);
58            let cap = if to_next_hour > EPS {
59                to_next_hour.min(30.0)
60            } else {
61                30.0
62            };
63            let step = remaining.min(cap);
64            self.advance_step(step);
65            remaining -= step;
66        }
67    }
68
69    #[doc(hidden)]
70    /// One simulation step. An open undo gesture is paused around it, so
71    /// what time does to the tower is never part of an undo step.
72    pub fn advance_step(&mut self, dt_minutes: f64) {
73        let paused = self.pause_undo_journal();
74        self.advance_step_inner(dt_minutes);
75        self.resume_undo_journal(paused);
76    }
77
78    fn advance_step_inner(&mut self, dt_minutes: f64) {
79        self.clock.advance(dt_minutes);
80        // While a bomb search runs, everyone but Security's guards holds
81        // still: no one arrives, walks or rides, and the cars stay put
82        // (owner, 2026-11-13). The guards walk the emergency stairs.
83        if !self.bomb_lockdown() {
84            self.move_people_and_cars(dt_minutes);
85        }
86        self.finish_construction_and_search();
87
88        let hour = self.clock.hour();
89        if hour != self.last_hour {
90            self.last_hour = hour;
91            self.on_hour();
92        }
93        let day = self.clock.day();
94        if day != self.last_day {
95            self.last_day = day;
96            self.on_day();
97        }
98    }
99
100    /// The crowd's and the cars' share of a step: demand, arrivals, the
101    /// cars' moves and the walks, and the staff jobs those walks finished.
102    fn move_people_and_cars(&mut self, dt_minutes: f64) {
103        let rush = self.rush_factor();
104        let population = self.elevators.accumulate(&self.tower, dt_minutes, rush);
105        self.crowd.begin_step();
106        self.crowd.hour = Some(self.clock.hour());
107        self.crowd.weekend = self.clock.is_weekend();
108        // The renderer's queue projection, built once a step at its start
109        // (`Crowd::queue_view`), as the TypeScript loop primes it.
110        self.crowd.queue_view(&self.tower);
111        // A fractional id (a forged save) matches no cinema, so only whole
112        // ids reach the crowd's set, refilled in place so a step allocates
113        // nothing.
114        self.crowd.blockbusters.clear();
115        self.crowd.blockbusters.extend(
116            self.blockbusters
117                .iter()
118                .filter(|b| b.fract() == 0.0)
119                .map(|b| *b as i64),
120        );
121        spawn::spawn_step(
122            &mut self.crowd,
123            (dt_minutes * CROWD_SECONDS_PER_MINUTE).min(CROWD_MAX_STEP),
124            &mut self.tower,
125            &self.clock,
126            Some(self.weather),
127            population,
128        );
129        let move_minutes = dt_minutes.min(CROWD_MAX_STEP / CROWD_SECONDS_PER_MINUTE);
130        let mut left = move_minutes;
131        let mut staff_moved = false;
132        let step_ends = self.clock.minute_of_day();
133        while left > 0.0 {
134            let chunk = left.min(2.5);
135            // The walks end with the step, so a chunk ends `left - chunk`
136            // minutes before it does: the minute the Metro's train reads.
137            self.crowd.minute = Some((step_ends - left + chunk).rem_euclid(1440.0));
138            let calls = self.crowd.elevator_calls(&self.tower);
139            let (hour, weekend) = (self.clock.hour(), self.clock.is_weekend());
140            self.elevators
141                .move_cars(&mut self.tower, chunk, &calls, hour, weekend);
142            self.elevators.swap_closed_cars(&mut self.crowd.closed_cars);
143            self.elevators.swap_open_cars(&mut self.crowd.open_cars);
144            motion::advance(
145                &mut self.crowd,
146                chunk * CROWD_SECONDS_PER_MINUTE,
147                &mut self.tower,
148            );
149            // The rooms cleaned, and where the housekeepers who came free go
150            // next, chunk by chunk so a long step loses no time between rooms.
151            staff_moved |= self.staff_after_chunk();
152            left -= chunk;
153        }
154        self.staff_after_step(staff_moved);
155    }
156
157    #[doc(hidden)]
158    pub fn on_hour(&mut self) {
159        self.on_hour_runs += 1;
160        self.update_presence();
161        // Office workers come in and go home as people (`commuters`).
162        self.crowd.book_commutes(&mut self.tower, &self.clock);
163        let hour = self.clock.hour();
164        if hour == 8 {
165            self.hotel_checkout();
166        }
167        let today = self.clock.day();
168        if hour == crate::economy::visitors::MORNING_VENUE_DAY_ENDS_AT_HOUR
169            && self.morning_venue_day != today
170        {
171            self.morning_venue_day = today;
172            self.roll_over_morning_venues();
173        }
174        if (14..17).contains(&hour) {
175            self.hotel_late_checkout();
176        }
177        let shift = self.mode.housekeeping_shift();
178        // Crews come in two hours early, and none sets out during a bomb
179        // search, when everyone but the guards stands still.
180        if self.crews_on_duty() && !self.bomb_lockdown() {
181            self.bring_in_crews();
182        }
183        if hour >= shift.start && hour < shift.end {
184            self.resolve_extermination();
185            if !self.bomb_lockdown() {
186                self.dispatch_housekeepers();
187            }
188        }
189        self.send_idle_crews_out();
190        self.update_satisfaction();
191        self.attempt_move_ins();
192        self.collect_traffic_income();
193        self.sample_elevator_util();
194        self.evaluate_star();
195        self.warn_long_lines();
196    }
197
198    /// A line in which someone has waited past an hour since the last
199    /// hourly pass is news: the longest such wait, with the shaft and the
200    /// floor, so the player sees where transit is jammed. Modern only, since
201    /// Classic riders give up within the hour. Read from the people
202    /// themselves, whose waits a save carries, so a reload warns as the game
203    /// that saved would.
204    fn warn_long_lines(&mut self) {
205        if !self.tower.mode.routes_by_expected_time() {
206            return;
207        }
208        let hour = 60.0 * CROWD_SECONDS_PER_MINUTE;
209        let news = |w: f64| (GIVE_UP..GIVE_UP + hour).contains(&w);
210        let waiting = self
211            .crowd
212            .people
213            .iter()
214            .filter(|p| p.state == PState::Waiting);
215        let worst = (waiting.filter(|p| news(p.wait)))
216            .filter_map(|p| Some(((p.shaft_id?, p.floor), p.wait)))
217            .max_by(|a, b| a.1.total_cmp(&b.1).then(b.0.cmp(&a.0)));
218        let Some(((shaft, floor), _)) = worst else {
219            return;
220        };
221        let Some(t) = self.tower.transports.iter().find(|t| t.id == shaft) else {
222            return;
223        };
224        let msg = format!(
225            "Riders on {} have waited over an hour for the {} there. Add cars, or another way up, to clear the line.",
226            self.floor_label(floor),
227            t.kind.facility().name,
228        );
229        self.emit(&msg, LogKind::Bad);
230    }
231
232    #[doc(hidden)]
233    pub fn on_day(&mut self) {
234        self.weather = weather_for(self.clock.day());
235        let period = self.maintenance_period();
236        let lease_monthly = self.mode.lease_rent_lands_monthly();
237        let mut lease_due = false;
238        if period != self.last_month {
239            self.last_month = period;
240            self.collect_monthly_rent();
241            self.pay_maintenance();
242            self.roll_condo_relocations();
243            lease_due = lease_monthly;
244        }
245        let q = self.clock.quarter();
246        if q != self.last_quarter {
247            self.last_quarter = q;
248            self.last_quarter_money = self.money;
249            lease_due |= !lease_monthly;
250        }
251        // Lease rent lands after the quarter's opening balance is noted, on
252        // either cadence, as it always has (#2255).
253        if lease_due {
254            self.collect_rent();
255        }
256        self.maybe_random_event();
257        self.maybe_vip_stay();
258        self.check_vip();
259        self.report_move_ins();
260        self.check_milestones();
261        self.nudge_stranded();
262        self.nudge_metro_platform();
263        self.nudge_service_shortfalls();
264        self.roll_over_retail_day();
265        // A rebooked film opens tonight, after the spent one's last count.
266        self.rebook_spent_films();
267        self.ledger.end_day();
268    }
269
270    /// Settles the bomb search up to now before any new Security office
271    /// joins it, so guards already out move on from the minutes they
272    /// finished, and an office opening late in a long step cannot take a
273    /// floor they reached first (or join a search that already ended).
274    /// A Security office that opens inside the step joins at the minute it
275    /// opened (Modern), after the search has run up to that minute, so a
276    /// long step plays out as shorter ones would. The clock is set back to
277    /// each opening only for that catch-up, then restored.
278    pub(crate) fn finish_construction_and_search(&mut self) {
279        if self.events.bomb.is_some() && self.mode.security_joins_bomb_search() {
280            let now = self.clock.minutes;
281            for at in self.security_openings_by(now) {
282                self.clock.minutes = at;
283                self.advance_bomb_search();
284                self.finish_construction();
285                self.clock.minutes = now;
286                if self.events.bomb.is_none() {
287                    break;
288                }
289            }
290        }
291        self.advance_bomb_search();
292        self.finish_construction();
293    }
294
295    /// The minutes at which Security offices still under construction open
296    /// by `now`, earliest first. Empty when nothing is being built.
297    fn security_openings_by(&self, now: f64) -> Vec<f64> {
298        let mut at: Vec<f64> = self
299            .constructing
300            .iter()
301            .filter_map(|id| self.tower.get_unit(*id))
302            .filter(|u| u.kind == Kind::Security && u.state == UnitState::Construction)
303            .filter_map(|u| u.extras().complete_at)
304            .filter(|t| *t <= now)
305            .collect();
306        at.sort_by(f64::total_cmp);
307        at
308    }
309
310    #[doc(hidden)]
311    pub fn finish_construction(&mut self) {
312        if self.constructing.is_empty() {
313            return;
314        }
315        let ids: Vec<i64> = self.constructing.iter().copied().collect();
316        let mut crew_wanted = false;
317        for id in ids {
318            let Some(u) = self.tower.get_unit(id) else {
319                self.constructing.shift_remove(&id);
320                continue;
321            };
322            if u.state != UnitState::Construction {
323                self.constructing.shift_remove(&id);
324                continue;
325            }
326            // `minutes >= (u.completeAt ?? 0)`: a non-numeric value the save
327            // carried goes through `Number()`, so NaN never completes.
328            let threshold = match (u.extras().complete_at, &u.extras().complete_at_raw) {
329                (Some(v), _) => v,
330                (None, Some(raw)) => crate::load::js_number(Some(raw)),
331                (None, None) => 0.0,
332            };
333            if self.clock.minutes >= threshold {
334                let (name, floor, x, kind) = (u.kind.facility().name, u.floor, u.x, u.kind);
335                let mode = self.tower.mode;
336                let (u, at) = self.tower.marked_by_id(id).unwrap();
337                u.set_state(at, UnitState::Empty);
338                u.extras_mut().complete_at = None;
339                u.extras_mut().complete_at_raw = None;
340                let full_house = kind == Kind::Cinema && fills_blockbuster_slot(mode, u);
341                self.constructing.shift_remove(&id);
342                let msg = format!(
343                    "{} on {} is now open for business.",
344                    name,
345                    self.floor_label(floor)
346                );
347                self.emit(&msg, LogKind::Good);
348                if kind == Kind::Security {
349                    self.join_bomb_search(floor, x);
350                }
351                crew_wanted |= kind.waits_for_staff(mode);
352                // A theater opens with its mode's first film free: a Classic
353                // new film fills the house tonight (#1932), so it is a
354                // blockbuster from its first evening rather than from the
355                // next rollover. A Modern theater opens with a feature.
356                if full_house && !self.blockbusters.contains(&(id as f64)) {
357                    self.blockbusters.push(id as f64);
358                }
359            }
360        }
361        // A venue that opens mid-hour calls its crew in now, so a save
362        // never holds it open with nobody booked.
363        if crew_wanted {
364            self.crowd.book_venue_crews(&self.tower, &self.clock);
365        }
366    }
367
368    #[doc(hidden)]
369    /// `floorLabel`: "floor N" above ground, "B{n}" below.
370    pub fn floor_label(&self, floor: i64) -> String {
371        if floor >= 1 {
372            format!("floor {floor}")
373        } else {
374            format!("B{}", 1 - floor)
375        }
376    }
377}