verticopolis_engine/sim.rs
1//! One game: [`Simulation`] holds a whole tower, its people, its money and
2//! its clock, and every player command and time step goes through it.
3//!
4//! ```
5//! use verticopolis_engine::clock::GameMode;
6//! use verticopolis_engine::facilities::Kind;
7//! use verticopolis_engine::sim::Simulation;
8//!
9//! let mut sim = Simulation::new_game(42, GameMode::Classic);
10//! for x in 100..124 {
11//! sim.build(Kind::Lobby, 1, x);
12//! }
13//! sim.tick(60.0);
14//! assert!(sim.money < verticopolis_engine::sim::STARTING_MONEY);
15//! ```
16
17use indexmap::IndexSet;
18use serde_json::Value;
19
20use std::collections::HashMap;
21
22use crate::clock::{resolve_calendar, CalendarKind, Clock, GameMode};
23use crate::crowd::Crowd;
24use crate::dispatch::ElevatorDispatch;
25use crate::events::EventSystem;
26use crate::gameplay::{GameplayEvent, GameplayEvents};
27use crate::housekeeping::Housekeeping;
28use crate::ledger::Ledger;
29use crate::rng::Rng;
30use crate::sim_loop::{weather_for, Weather};
31use crate::telemetry::ElevatorTelemetry;
32use crate::tower::Tower;
33
34#[doc(hidden)]
35#[derive(Clone, Copy, Debug, Default)]
36pub struct MoveIns {
37 pub offices: i64,
38 pub condos: i64,
39 pub rooms: i64,
40 pub fitness: i64,
41 pub clinic: i64,
42 pub rentals: i64,
43}
44
45/// The newest save format version this engine writes. It loads every older
46/// version back to the oldest one [`crate::identity::identity`] names.
47///
48/// Version 8 adds one key, `lobbyHeights` (#308), and version 9 lists it
49/// per hall (#2068), so a save is stamped with the oldest version that reads
50/// it whole ([`save_version`]): 9 when it holds a tall lobby, which a build
51/// from before tall lobbies refuses rather than drop, and
52/// [`PLAIN_SAVE_VERSION`] otherwise, which every build from version 7 on
53/// still loads. Version 10 adds an elevator schedule's `heldBack` hours
54/// (#1546), held when a sold car left a cut-back hour at the fleet's size.
55/// Version 11 folds floor tiles into runs (`save_floor_runs`).
56pub const SAVE_VERSION: i64 = 11;
57/// The version a save with a held hour and no floor run is written at.
58pub const HELD_HOURS_SAVE_VERSION: i64 = 10;
59/// The version a save with a tall lobby and no held hour is written at.
60pub const TALL_LOBBY_SAVE_VERSION: i64 = 9;
61/// The version a save with no tall lobby is written at: the format before
62/// `lobbyHeights`, which it does not need.
63pub const PLAIN_SAVE_VERSION: i64 = 7;
64
65/// A save with no held hour is stamped [`TALL_LOBBY_SAVE_VERSION`] with a tall
66/// lobby, else [`PLAIN_SAVE_VERSION`]; [`stamped_save_version`] also weighs the
67/// held hours.
68pub fn save_version(has_tall_lobby: bool) -> i64 {
69 stamped_save_version(has_tall_lobby, false)
70}
71
72/// A save with no floor run is stamped [`HELD_HOURS_SAVE_VERSION`] when a
73/// schedule holds an hour back (an older build runs the whole fleet there),
74/// else [`TALL_LOBBY_SAVE_VERSION`] with a tall lobby, else [`PLAIN_SAVE_VERSION`].
75pub fn stamped_save_version(has_tall_lobby: bool, holds_an_hour_back: bool) -> i64 {
76 if holds_an_hour_back {
77 HELD_HOURS_SAVE_VERSION
78 } else if has_tall_lobby {
79 TALL_LOBBY_SAVE_VERSION
80 } else {
81 PLAIN_SAVE_VERSION
82 }
83}
84/// The money a new game starts with.
85pub const STARTING_MONEY: f64 = 2_000_000.0;
86/// How many messages [`Simulation::log`] keeps; the oldest goes first.
87pub const LOG_RING_CAP: usize = 300;
88#[doc(hidden)]
89pub const LOG_SAVE_CAP: usize = LOG_RING_CAP;
90
91/// How the game styles a message in its log.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub enum LogKind {
94 /// News: a guest arrived, an event started.
95 Info,
96 /// Good news: a new star, a milestone.
97 Good,
98 /// Bad news: a fire, a tenant leaving.
99 Bad,
100 /// A payment or a charge.
101 Money,
102}
103
104impl LogKind {
105 /// The kind as a save writes it: `info`, `good`, `bad` or `money`.
106 pub fn as_str(self) -> &'static str {
107 match self {
108 LogKind::Info => "info",
109 LogKind::Good => "good",
110 LogKind::Bad => "bad",
111 LogKind::Money => "money",
112 }
113 }
114}
115
116/// One message in the game's log.
117#[derive(Clone, Debug)]
118pub struct LogEntry {
119 /// The game minute it was written ([`crate::clock::Clock::minutes`]).
120 pub minute: f64,
121 /// The message, in American English, ready to show a player.
122 pub text: String,
123 /// How to style it.
124 pub kind: LogKind,
125}
126
127#[doc(hidden)]
128/// A cosmetic event the renderer polls: `explosionFx` and `treasureFx`
129/// carry a point, `thiefFx` a floor and whether the thief was caught. The
130/// sequence numbers are what the renderer compares; nothing here is saved
131/// or hashed (`SimContext.trigger*`).
132#[derive(Clone, Copy, Debug, Default, PartialEq)]
133pub struct PointFx {
134 pub floor: i64,
135 pub x: f64,
136 pub seq: i64,
137}
138
139#[doc(hidden)]
140#[derive(Clone, Copy, Debug, PartialEq)]
141pub struct ThiefFx {
142 pub caught: bool,
143 pub floor: i64,
144 /// A tile of the stretch of floor (one tower's part of it, on a lot with
145 /// several) the thief prowls.
146 pub x: i64,
147 pub seq: i64,
148}
149
150#[doc(hidden)]
151#[derive(Clone, Copy, Debug, PartialEq)]
152pub struct FxState {
153 pub santa_seq: i64,
154 pub explosion: PointFx,
155 pub thief: ThiefFx,
156 pub treasure: PointFx,
157 pub vip_seq: i64,
158}
159
160impl Default for FxState {
161 fn default() -> FxState {
162 FxState {
163 santa_seq: 0,
164 explosion: PointFx::default(),
165 thief: ThiefFx {
166 caught: false,
167 floor: 1,
168 x: 0,
169 seq: 0,
170 },
171 treasure: PointFx::default(),
172 vip_seq: 0,
173 }
174 }
175}
176
177/// One game of Verticopolis.
178///
179/// Start one with [`Simulation::new_game`], or load one from a save with
180/// [`crate::load::deserialize`]. Advance it with [`Simulation::tick`] and
181/// change it only through its commands ([`build`](Simulation::build),
182/// [`add_car`](Simulation::add_car), [`adjust_rent`](Simulation::adjust_rent)
183/// and the rest), which apply the rules, charge the money and refuse what a
184/// player could not do. The public fields are for reading; writing one skips
185/// those rules.
186///
187/// A renderer reads the tower through [`crate::view`] or [`crate::frame`],
188/// and an analytics or achievements layer drains [`Simulation::gameplay`].
189pub struct Simulation {
190 #[doc(hidden)]
191 pub rng: Rng,
192 /// The game mode, fixed when the game starts.
193 pub mode: GameMode,
194 /// The calendar a Modern game runs on. A Classic game always runs the canon
195 /// calendar.
196 pub modern_calendar: CalendarKind,
197 /// Whether a new floor joins the floor next to it automatically. Only a
198 /// Modern game can turn this off ([`Simulation::toggle_auto_bridge`]).
199 pub auto_bridge: bool,
200 /// Whether the tower was started before saves carried a build stamp. The
201 /// web game shows these towers a founder badge.
202 pub founder: bool,
203 /// The game clock: day, hour, minute, quarter and year.
204 pub clock: Clock,
205 /// The people moving through the tower.
206 pub crowd: Crowd,
207 /// Emergencies, and the choice waiting for the player's answer.
208 pub events: EventSystem,
209 #[doc(hidden)]
210 pub ledger: Ledger,
211 /// The tower: its floors, rooms and transport. A renderer reads it through
212 /// [`crate::view`] instead of walking it.
213 pub tower: Tower,
214 /// The player's money, in dollars. It can go negative.
215 pub money: f64,
216 /// The tower's rating: 1 to 5 stars, and 6 once it is a TOWER.
217 pub star: i64,
218 #[doc(hidden)]
219 pub last_quarter_money: f64,
220 #[doc(hidden)]
221 /// `evaluatedTower`; `None` when the save carried no key.
222 pub evaluated_tower: Option<bool>,
223 #[doc(hidden)]
224 /// The day the VIP inspection is due, as the save carries it (a forged
225 /// save may hold a fraction, which the day comparisons then honor).
226 pub vip_visit_day: f64,
227 #[doc(hidden)]
228 pub vip_favorable: bool,
229 #[doc(hidden)]
230 pub vip_visits: i64,
231 #[doc(hidden)]
232 pub last_vip_nag_day: i64,
233 #[doc(hidden)]
234 pub treasures_found: f64,
235 #[doc(hidden)]
236 pub extermination_due_day: Option<f64>,
237 #[doc(hidden)]
238 /// The infested room ids a booking billed, saved while it is due. `None`
239 /// on a legacy save, which treats every infested room.
240 pub extermination_room_ids: Option<Vec<i64>>,
241 #[doc(hidden)]
242 /// `"floor:x"` keys in insertion order.
243 pub excavated: Vec<String>,
244 #[doc(hidden)]
245 /// This month's blockbuster cinemas by id, as saved (a forged save may hold a fraction).
246 pub blockbusters: Vec<f64>,
247 /// The milestone ids reached, in order. The ids are stable across versions.
248 pub milestones: Vec<String>,
249 /// The recent messages, oldest first, at most [`LOG_RING_CAP`] ([`crate::frame::log_since`]).
250 pub log: Vec<LogEntry>,
251 #[doc(hidden)]
252 pub log_seq: i64,
253 #[doc(hidden)]
254 /// Unit ids under construction, in insertion order.
255 pub constructing: IndexSet<i64>,
256 // ---- loop state ----
257 #[doc(hidden)]
258 /// The cars mid-stop and each floor's wait estimate, saved as `dispatch`.
259 pub elevators: ElevatorDispatch,
260 #[doc(hidden)]
261 /// `elevatorUtil` / `elevatorHourly` / `elevatorOrigins` (never saved).
262 pub telemetry: ElevatorTelemetry,
263 #[doc(hidden)]
264 pub housekeeping: Housekeeping,
265 #[doc(hidden)]
266 pub weather: Weather,
267 #[doc(hidden)]
268 /// The cosmetic event counters the renderer polls (never saved).
269 pub fx: FxState,
270 #[doc(hidden)]
271 pub last_hour: i64,
272 #[doc(hidden)]
273 pub last_day: i64,
274 #[doc(hidden)]
275 /// The day whose 10:00 last closed the shops' day (#1500); an old save loads as today.
276 pub morning_venue_day: i64,
277 #[doc(hidden)]
278 pub last_month: i64,
279 #[doc(hidden)]
280 pub last_quarter: i64,
281 #[doc(hidden)]
282 pub on_hour_runs: i64,
283 #[doc(hidden)]
284 pub move_ins_today: MoveIns,
285 #[doc(hidden)]
286 pub waste_nudged: bool,
287 #[doc(hidden)]
288 pub suite_parking_nudged: bool,
289 #[doc(hidden)]
290 pub office_parking_nudged: bool,
291 #[doc(hidden)]
292 pub stranded_nudged: bool,
293 #[doc(hidden)]
294 pub metro_platform_nudged: bool,
295 #[doc(hidden)]
296 /// `floorReachable` memo keyed by tower revision.
297 pub reach_memo: (i64, HashMap<i64, bool>),
298 #[doc(hidden)]
299 /// `noiseMemo`: unit id to `noiseAfflicted`, keyed by tower revision.
300 pub noise_memo: (i64, crate::crowd::fasthash::FastMap<i64, bool>),
301 #[doc(hidden)]
302 /// The inspector's demand map memo (never saved; see
303 /// `diagnostics/memo.rs`).
304 pub diag_memo: crate::diagnostics::DiagMemo,
305 #[doc(hidden)]
306 /// The saved camera view (inert cargo the save carries).
307 pub view: Option<Value>,
308 /// The gameplay events since the host last drained them. Call
309 /// `sim.gameplay.drain()` after each frame. Never saved.
310 pub gameplay: GameplayEvents,
311 #[doc(hidden)]
312 /// The open extend gesture (#990) as `(id, bottom, top)`: the shaft and
313 /// the furthest span the gesture has paid for (never saved, and not in
314 /// the state view; see `begin_extend`).
315 pub extend_gesture: Option<(i64, i64, i64)>,
316}
317
318impl Simulation {
319 #[doc(hidden)]
320 // `new Simulation(seed, mode, modernCalendar, startUnbridged)`.
321 pub fn new(
322 seed: u32,
323 mode: GameMode,
324 modern_calendar: CalendarKind,
325 start_unbridged: bool,
326 ) -> Simulation {
327 let modern_calendar = if mode.lets_player_choose_calendar() {
328 modern_calendar
329 } else {
330 CalendarKind::RealWorld
331 };
332 Simulation {
333 rng: Rng::new(seed),
334 mode,
335 modern_calendar,
336 auto_bridge: if mode.bridging_toggleable() {
337 !start_unbridged
338 } else {
339 true
340 },
341 founder: false,
342 clock: Clock::new(0.0, resolve_calendar(mode, modern_calendar)),
343 crowd: Crowd::new(seed),
344 events: EventSystem::new(seed),
345 ledger: Ledger::new(),
346 tower: {
347 let mut t = Tower::new();
348 t.allows_escalator_on_office_floors = mode.escalators_on_office_floors();
349 t.mode = mode;
350 t
351 },
352 money: STARTING_MONEY,
353 star: 1,
354 last_quarter_money: 0.0,
355 evaluated_tower: Some(false),
356 vip_visit_day: -1.0,
357 vip_favorable: false,
358 vip_visits: 0,
359 last_vip_nag_day: -100,
360 treasures_found: 0.0,
361 extermination_due_day: None,
362 excavated: Vec::new(),
363 blockbusters: Vec::new(),
364 milestones: Vec::new(),
365 log: Vec::new(),
366 log_seq: 0,
367 constructing: IndexSet::new(),
368 elevators: ElevatorDispatch::new(),
369 telemetry: ElevatorTelemetry::default(),
370 housekeeping: Housekeeping::default(),
371 weather: weather_for(0),
372 fx: FxState::default(),
373 last_hour: -1,
374 last_day: 0,
375 morning_venue_day: -1,
376 last_month: -1,
377 last_quarter: -1,
378 on_hour_runs: 0,
379 move_ins_today: MoveIns::default(),
380 waste_nudged: false,
381 suite_parking_nudged: false,
382 office_parking_nudged: false,
383 stranded_nudged: false,
384 metro_platform_nudged: false,
385 extermination_room_ids: None,
386 reach_memo: (-1, HashMap::new()),
387 noise_memo: (-1, Default::default()),
388 diag_memo: Default::default(),
389 view: None,
390 gameplay: GameplayEvents::default(),
391 extend_gesture: None,
392 }
393 }
394
395 #[doc(hidden)]
396 /// `recordMoney(cat, amount)`.
397 pub fn record_money(&mut self, cat: &'static str, amount: f64) {
398 self.ledger.record(cat, amount);
399 }
400
401 /// How many people live and work in the tower: the number the star
402 /// ratings count.
403 pub fn population(&self) -> i64 {
404 self.tower.total_population()
405 }
406
407 #[doc(hidden)]
408 /// `floorReachable(floor)`: memoized per tower revision, no rng.
409 pub fn floor_reachable(&mut self, floor: i64) -> bool {
410 if floor == 1 {
411 return true;
412 }
413 if self.reach_memo.0 != self.tower.revision {
414 self.reach_memo = (self.tower.revision, HashMap::new());
415 }
416 if let Some(&hit) = self.reach_memo.1.get(&floor) {
417 return hit;
418 }
419 let hit = self.crowd.floor_reachable(&self.tower, floor);
420 self.reach_memo.1.insert(floor, hit);
421 hit
422 }
423
424 #[doc(hidden)]
425 /// `positionReachable(floor, x)`.
426 pub fn position_reachable(&mut self, floor: i64, x: i64) -> bool {
427 if floor == 1 {
428 return true;
429 }
430 if self.tower.segment_runs(floor).len() <= 1 {
431 return self.floor_reachable(floor);
432 }
433 self.crowd.position_reachable(&self.tower, floor, x)
434 }
435
436 #[doc(hidden)]
437 /// `unitReachable` (sim/demand.ts).
438 pub fn unit_reachable(&mut self, floor: i64, x: i64) -> bool {
439 self.position_reachable(floor, x)
440 }
441
442 /// Starts a new game: an empty lot, [`STARTING_MONEY`], 07:00 on day 0.
443 ///
444 /// The same `seed` and the same commands give the same game. A Modern
445 /// game gets the real-world calendar and automatic floor bridging; use
446 /// [`Simulation::new_game_with`] to choose them.
447 ///
448 /// ```
449 /// use verticopolis_engine::clock::GameMode;
450 /// use verticopolis_engine::sim::Simulation;
451 ///
452 /// let sim = Simulation::new_game(7, GameMode::Modern);
453 /// assert_eq!(sim.star, 1);
454 /// assert_eq!(sim.population(), 0);
455 /// ```
456 pub fn new_game(seed: u32, mode: GameMode) -> Simulation {
457 Simulation::new_game_with(seed, mode, CalendarKind::RealWorld, false)
458 }
459
460 /// Starts a new game with a choice of calendar and bridging. Both apply
461 /// to a Modern game only: a Classic game always runs the canon calendar
462 /// with bridging on, whatever these say.
463 ///
464 /// ```
465 /// use verticopolis_engine::clock::{CalendarKind, GameMode};
466 /// use verticopolis_engine::sim::Simulation;
467 ///
468 /// let sim = Simulation::new_game_with(7, GameMode::Modern, CalendarKind::Canon, true);
469 /// assert!(!sim.auto_bridge);
470 /// ```
471 pub fn new_game_with(
472 seed: u32,
473 mode: GameMode,
474 modern_calendar: CalendarKind,
475 start_unbridged: bool,
476 ) -> Simulation {
477 let mut sim = Simulation::new(seed, mode, modern_calendar, start_unbridged);
478 sim.emit(
479 "Welcome! Lay a lobby on the ground line to open your tower.",
480 LogKind::Info,
481 );
482 sim.gameplay
483 .push(GameplayEvent::TowerFounded { mode: sim.mode });
484 sim
485 }
486
487 #[doc(hidden)]
488 /// `sim.emit(text, kind)`: append to the ring, no dedupe.
489 pub fn emit(&mut self, text: &str, kind: LogKind) {
490 self.log.push(LogEntry {
491 minute: self.clock.minutes,
492 text: text.to_string(),
493 kind,
494 });
495 self.log_seq += 1;
496 if self.log.len() > LOG_RING_CAP {
497 self.log.remove(0);
498 }
499 }
500}