Skip to main content
Verticopolis engine

verticopolis_engine/
catalog.rs

1//! The catalog: engine-authored data a frontend draws menus, prices and
2//! placement ghosts from, resolved for one mode so the frontend never applies
3//! simulation rules itself.
4//!
5//! [`catalog`] returns a [`Catalog`]: world geometry, economy constants, pooled
6//! caps and one [`FacilityEntry`] per facility kind. It serializes to JSON
7//! with camelCase keys, the same JSON the JavaScript package returns.
8//!
9//! ```
10//! use verticopolis_engine::catalog::{catalog, CATALOG_VERSION};
11//! use verticopolis_engine::clock::GameMode;
12//! use verticopolis_engine::facilities::Kind;
13//!
14//! let classic = catalog(GameMode::Classic);
15//! assert_eq!(classic.version, CATALOG_VERSION);
16//! let office = classic.facilities.iter().find(|f| f.key == Kind::Office.as_str()).unwrap();
17//! println!("{} costs ${} and opens at {} star", office.name, office.cost, office.min_star);
18//! ```
19//!
20//! The conformance suite pins each mode's catalog by hash, so a change to a
21//! price or a rule shows up as a deliberate change to the lock.
22
23use serde::Serialize;
24
25use crate::build::pays_for_floor;
26use crate::charges::{car_resale_refund, ADD_CAR_COST, TRANSPORT_FLOOR_COST};
27use crate::clock::{resolve_calendar, CalendarKind, GameMode};
28use crate::economy::films::{FilmOffer, FilmRebook};
29use crate::economy::tickets::TicketPrice;
30use crate::economy::{
31    catalog_spend_per_customer, commercial_daily_income, service_maintenance_monthly,
32    MAINTENANCE_PER_CAR_MONTHLY, NIGHTCLUB_DJ_MONTHLY, REAL_WORLD_MAINT_PERIOD_DAYS,
33};
34use crate::facilities::{
35    build_cap_in, ground_floor_structure_kind, no_basement, pools_for, Kind, Pool, FACILITIES,
36    LOBBY_INTERVAL, LOT_WIDTH, MAX_FLOOR, MIN_FLOOR, POOLED_CAPS,
37};
38use crate::rules::{RentModel, MAX_HOUSEHOLD};
39use crate::services::GARBAGE_COLLECT_HOUR;
40use crate::sim::STARTING_MONEY;
41mod build;
42mod halo;
43mod json;
44mod lock;
45mod noise;
46mod rules;
47
48pub use build::catalog;
49pub use halo::HaloEntry;
50pub use json::{catalog_digest, catalog_json, catalog_value};
51#[doc(hidden)]
52pub use lock::{lock_view, LOCK_FOOTPRINT_EXEMPT};
53pub use noise::NoiseEntry;
54pub use rules::Rules;
55
56/// The version of the catalog's shape. It moves when a field is added,
57/// renamed or removed, so a frontend can refuse a shape it does not know.
58pub const CATALOG_VERSION: u32 = 21;
59
60/// Every price, size and build rule of one mode.
61#[derive(Clone, Debug, PartialEq, Serialize)]
62#[serde(rename_all = "camelCase")]
63pub struct Catalog {
64    /// [`CATALOG_VERSION`].
65    pub version: u32,
66    /// The mode the values are resolved for: `classic` or `modern`.
67    pub mode: &'static str,
68    /// The lot and floor limits.
69    pub world: World,
70    /// Money figures a UI shows.
71    pub economy: Economy,
72    /// The mode's rules a UI shows.
73    pub rules: Rules,
74    /// The caps several kinds share, in the engine's order.
75    pub pools: Vec<PoolEntry>,
76    /// One entry per facility kind, in the engine's catalog order, the
77    /// kinds this mode cannot build included (`available: false`).
78    pub facilities: Vec<FacilityEntry>,
79}
80
81/// The tower geometry a placement needs.
82#[derive(Clone, Debug, PartialEq, Serialize)]
83#[serde(rename_all = "camelCase")]
84pub struct World {
85    /// The buildable lot width in tiles.
86    pub lot_width: i64,
87    /// The lowest floor (the deepest basement). Floors number without a gap:
88    /// 1 is the ground floor, 0 the first basement.
89    pub min_floor: i64,
90    /// The highest floor.
91    pub max_floor: i64,
92    /// The ground floor, where the main lobby sits.
93    pub ground_floor: i64,
94    /// What the floor tool lays on the ground floor: a lobby. A current game
95    /// holds no plain floor there, so each tile the floor tool lays pays for
96    /// its floor too (`paysForFloor`).
97    pub ground_floor_structure: &'static str,
98    /// Floors between lobbies: besides the ground floor, a sky lobby may sit
99    /// on every floor from 2 up that is a multiple of it (15, 30, ...).
100    pub lobby_interval: i64,
101    /// The Metro's timetable, which riders leaving by train keep.
102    pub metro_train: MetroTrain,
103}
104
105/// When the one train on a Metro line runs, in game time
106/// (`crowd::metro_train`). Each hour from `first_hour` to `last_hour` it
107/// comes out of the left tunnel, takes `leg_minutes` to each station, waits
108/// at each, and leaves by the right tunnel. On a line of `n` stations it
109/// waits `min(dwell_minutes, floor((run_minutes - leg_minutes * (n + 1)) /
110/// n))` minutes, or, when that is under one, every leg and wait takes
111/// `run_minutes / (2n + 1)`.
112#[derive(Clone, Debug, PartialEq, Serialize)]
113#[serde(rename_all = "camelCase")]
114pub struct MetroTrain {
115    /// The first hour a train runs.
116    pub first_hour: i64,
117    /// The last hour a train runs; its run ends before the next.
118    pub last_hour: i64,
119    /// Minutes from a tunnel mouth, or the station before, to a station.
120    pub leg_minutes: f64,
121    /// The longest wait at a station.
122    pub dwell_minutes: f64,
123    /// Minutes of each hour the run along a line may take.
124    pub run_minutes: f64,
125}
126
127/// The mode's economy constants a UI shows, in dollars.
128#[derive(Clone, Debug, PartialEq, Serialize)]
129#[serde(rename_all = "camelCase")]
130pub struct Economy {
131    /// The treasury a new tower starts with.
132    pub starting_money: f64,
133    /// The price of one more elevator car on a shaft (`add_car` charges it).
134    pub add_car_cost: f64,
135    /// What `remove_car` refunds for one car.
136    pub car_resale_refund: f64,
137    /// The price of each floor an elevator spans past its first, charged by
138    /// the build and by each floor an extend adds; stairs and escalators pay none.
139    pub transport_floor_cost: f64,
140    /// The calendars a tower of this mode can run, its default first. Every
141    /// `...Monthly` figure here and each facility's `upkeepMonthly` is quoted
142    /// per 30-day real-world month: the engine charges it once per
143    /// maintenance period, multiplied by that calendar's `maintenanceScale`.
144    pub calendars: Vec<CalendarEntry>,
145    /// Monthly upkeep per elevator car.
146    pub maintenance_per_car_monthly: f64,
147    /// Monthly operating overhead per leasable or trading unit (0 where the
148    /// mode charges none).
149    pub overhead_per_unit_monthly: f64,
150    /// Monthly tax on an unsold condo, as a fraction of its asking price (0
151    /// where the mode charges none). Each period the engine charges
152    /// `ceil(price * rate)`, multiplied by `maintenanceScale` and rounded.
153    pub condo_hold_tax_rate: f64,
154    /// A nightclub's monthly DJ booking.
155    pub nightclub_dj_monthly: f64,
156    /// Hour of the daily garbage-truck collection that empties recycling bins.
157    pub garbage_collect_hour: f64,
158    /// The paid exterminator's fees, or null where the mode has none.
159    pub exterminator: Option<ExterminatorFees>,
160    /// The films a theater shows, priced, in card order; none bills a period.
161    pub films: &'static [FilmOffer],
162    /// The Auto-rebook choices in the card button's order: each policy and
163    /// the film it books once a theater's film is spent; empty if none (#1950).
164    pub film_rebooks: &'static [FilmRebook],
165    /// The policy a theater with none (or an old save's "auto") rebooks by.
166    pub film_rebook_default: Option<&'static str>,
167    /// The screens a theater runs, each with its own film and booking (#1950).
168    pub cinema_screens: usize,
169    /// A theater's ticket price steps, cheapest first, against Normal's 1.
170    pub ticket_prices: &'static [TicketPrice],
171    /// The step a theater with none set charges, or null (#1950).
172    pub ticket_price_default: Option<&'static str>,
173    /// Whether the player can switch automatic bridging off. When false,
174    /// bridging is always on. When true, a tower starts bridged unless it
175    /// was founded unbridged, and the live setting is per tower (the
176    /// engine's `autoBridge()`, the save's `autoBridge`).
177    pub auto_bridge_toggleable: bool,
178}
179
180/// One calendar a tower can run and how it scales the quoted figures.
181#[derive(Clone, Debug, PartialEq, Serialize)]
182#[serde(rename_all = "camelCase")]
183pub struct CalendarEntry {
184    /// `canon` or `realWorld`, as a save names it.
185    pub key: &'static str,
186    /// Days per quarter, when quarterly rent lands.
187    pub quarter_days: i64,
188    /// Days between maintenance charges (and monthly rent collections).
189    pub maintenance_period_days: i64,
190    /// What a `...Monthly` figure and a monthly rent are multiplied by on
191    /// each maintenance period.
192    pub maintenance_scale: f64,
193    /// Days between lease rent collections (offices and the lease
194    /// amenities): the quarter in Classic, the maintenance period in Modern.
195    pub lease_period_days: i64,
196    /// What a quarterly rent is multiplied by on each lease collection.
197    pub quarterly_rent_scale: f64,
198}
199
200#[derive(Clone, Debug, PartialEq, Serialize)]
201#[serde(rename_all = "camelCase")]
202/// What the exterminator charges, where the mode has one.
203pub struct ExterminatorFees {
204    /// The flat fee of one call.
205    pub callout_fee: f64,
206    /// Added per infested room treated.
207    pub per_room_fee: f64,
208}
209
210/// A cap several kinds share.
211#[derive(Clone, Debug, PartialEq, Serialize)]
212#[serde(rename_all = "camelCase")]
213pub struct PoolEntry {
214    /// The name a [`FacilityEntry::pool`] refers to it by.
215    pub key: &'static str,
216    /// The label the engine's refusal names the pool by.
217    pub label: &'static str,
218    /// The most units of all its kinds together a tower may hold.
219    pub cap: i64,
220    /// The facility keys that share it.
221    pub kinds: Vec<&'static str>,
222}
223
224/// One facility kind, resolved for the catalog's mode.
225#[derive(Clone, Debug, PartialEq, Serialize)]
226#[serde(rename_all = "camelCase")]
227pub struct FacilityEntry {
228    /// The key saves and commands name the kind by.
229    pub key: &'static str,
230    /// The name a player sees, such as `Fast Food`.
231    pub name: &'static str,
232    /// `structure`, `transport`, `office`, `residential`, `hotel`, `food`,
233    /// `retail`, `entertainment`, `service` or `special`.
234    pub category: &'static str,
235    /// Width in tiles. A transport's width is its shaft's.
236    pub width: i64,
237    /// Height in floors (1 for an ordinary room, and 1 for a transport,
238    /// whose height is its span).
239    pub floors: i64,
240    /// The build price. An elevator adds `transportFloorCost` for each floor
241    /// past its first (top minus bottom). A room adds the floor's price for
242    /// every floor tile laid under it, and so does a kind that pays for its
243    /// floor (`paysForFloor`) placed where there is no floor yet. With
244    /// automatic bridging on, every gap tile bridged to the tower adds one
245    /// substrate tile: the lobby's price plus the floor's when placing a
246    /// lobby (on any floor), the floor's price for a floor tile or a room.
247    pub cost: f64,
248    /// Whether a tile of this kind placed where there is no floor yet also
249    /// pays the floor's price, for the floor it lays (the lobby). Over a
250    /// floor tile it pays `cost` alone.
251    pub pays_for_floor: bool,
252    /// The star rating that unlocks it.
253    pub min_star: i64,
254    /// The people it holds (tenants, residents or customers at a time).
255    pub population: i64,
256    /// The largest generated household size for this kind, or null.
257    pub max_household: Option<i64>,
258    /// The audience an attendance venue seats, or null.
259    pub attendance: Option<i64>,
260    /// Only Modern games build it.
261    pub modern_only: bool,
262    /// An elevator, stairs or an escalator.
263    pub transport: bool,
264    /// A staff-only transport (the service elevator).
265    pub staff_only: bool,
266    /// Built underground only.
267    pub basement: bool,
268    /// Never built underground.
269    pub no_basement: bool,
270    /// Whether this mode can build it at all (the star gate aside).
271    pub available: bool,
272    /// In-game minutes of construction (0 for structure and for transports,
273    /// which work as soon as they are placed).
274    pub build_minutes: f64,
275    /// What selling it refunds (a gutted unit refunds nothing).
276    pub resale_refund: f64,
277    /// The most a tower may hold of this kind alone, or null when uncapped.
278    pub build_cap: Option<i64>,
279    /// The [`PoolEntry::key`] of the cap it shares, or null.
280    pub pool: Option<&'static str>,
281    /// For a transport, the largest top floor minus bottom floor it may
282    /// have, else null. It serves `maxSpan + 1` floors: stairs and
283    /// escalators have 1 and link two floors.
284    pub max_span: Option<i64>,
285    /// For a transport, whether it is a fixed two-floor unit placed with one
286    /// tap and never resized (stairs, escalators).
287    pub fixed_span: bool,
288    /// For an elevator, the most cars a shaft takes, else null.
289    pub max_cars: Option<i64>,
290    /// For a transport, the passengers one car (or one flight) carries, else null.
291    pub car_capacity: Option<f64>,
292    /// The varieties a new unit draws from, in the engine's order, or null.
293    pub subtypes: Option<Vec<&'static str>>,
294    /// How the player prices it in this mode, or null when its price is not
295    /// player-set.
296    pub rent: Option<Rent>,
297    /// A trading venue's headline daily take in this mode, or null: the
298    /// ceiling the money loop pays a sold-out venue.
299    pub daily_income: Option<f64>,
300    /// The average ticket per customer the engine counts customers with,
301    /// for the venues that track them in this mode (those with subtypes and
302    /// a daily income), else null.
303    pub spend_per_customer: Option<f64>,
304    /// A service facility's monthly maintenance, or null.
305    pub upkeep_monthly: Option<f64>,
306    /// Whether it is open in each hour of the day, 0 to 23, for a kind that
307    /// keeps business hours (`hasBusinessHours`), else null (always open).
308    pub open_hours: Option<Vec<bool>>,
309    /// Whether a unit may carry its own household size (`residents`), which
310    /// then stands in for `population`; a condo's price scales with it
311    /// against the condo's `population` (`householdPrice`).
312    pub own_household: bool,
313    /// A foot-traffic trading kind: the one predicate the noise and
314    /// lobby-proximity rules key off (`isCommercial`).
315    pub commercial: bool,
316    /// A hotel room of any size.
317    pub hotel: bool,
318    /// A Modern lease amenity (fitness club, clinic): lease tenants that erode
319    /// on unserved placement and an over-market rent.
320    pub lease_amenity: bool,
321    /// A demand tenant whose unmet coverage drains satisfaction.
322    pub unmet_demand: bool,
323    /// The venue's cross-floor halo in this mode, or null (#1980).
324    pub halo: Option<HaloEntry>,
325    /// How far the room's same-floor noise carries and how far it hears
326    /// its neighbors, shown while placing it; empty in Classic.
327    pub noise: Vec<NoiseEntry>,
328}
329
330/// How the player prices a kind: a ladder of fixed rungs (Classic) or a
331/// continuous band (Modern).
332#[derive(Clone, Debug, PartialEq, Serialize)]
333#[serde(
334    tag = "shape",
335    rename_all = "camelCase",
336    rename_all_fields = "camelCase"
337)]
338pub enum Rent {
339    /// Four rungs plus the No Rate off-market state.
340    Ladder {
341        /// When the price is collected: `quarterly`, `maintenancePeriod`, `sale` or `nightly`.
342        cadence: &'static str,
343        /// The price a new unit starts at (the Average rung).
344        default: f64,
345        /// The four rungs, Very Low to High.
346        rungs: Vec<Rung>,
347        /// Whether the mode offers No Rate (always true on a ladder).
348        no_rate: bool,
349    },
350    /// Any price from `min` to `max` in steps of `step`.
351    Band {
352        /// When the price is collected: `quarterly`, `maintenancePeriod`, `sale` or `nightly`.
353        cadence: &'static str,
354        /// The price a new unit starts at.
355        default: f64,
356        /// The lowest price.
357        min: f64,
358        /// The highest price.
359        max: f64,
360        /// How far one step up or down moves the price.
361        step: f64,
362        /// Whether the mode offers No Rate (always false on a band).
363        no_rate: bool,
364    },
365}
366
367/// One rung of a price ladder.
368#[derive(Clone, Debug, PartialEq, Serialize)]
369#[serde(rename_all = "camelCase")]
370pub struct Rung {
371    /// 0 (Very Low) to 3 (High).
372    pub level: i64,
373    /// `Very Low`, `Low`, `Average` or `High`.
374    pub label: &'static str,
375    /// The price.
376    pub value: f64,
377}
378
379pub(crate) const RUNG_LABELS: [&str; 4] = ["Very Low", "Low", "Average", "High"];
380
381/// The key each of [`POOLED_CAPS`] goes by, in its order.
382const POOL_KEYS: [&str; 2] = ["elevators", "walkways"];
383const _: () = assert!(
384    POOL_KEYS.len() == POOLED_CAPS.len(),
385    "every pooled cap needs a key"
386);
387
388/// The calendars a mode can run, its default first.
389fn calendars_for(mode: GameMode) -> Vec<CalendarEntry> {
390    let kinds: &[CalendarKind] = if mode.lets_player_choose_calendar() {
391        &[CalendarKind::RealWorld, CalendarKind::Canon]
392    } else {
393        &[CalendarKind::Canon]
394    };
395    kinds
396        .iter()
397        .map(|&kind| {
398            let c = resolve_calendar(mode, kind);
399            CalendarEntry {
400                key: c.kind.as_str(),
401                quarter_days: c.quarter_days,
402                maintenance_period_days: c.maint_period_days,
403                maintenance_scale: c.maint_period_days as f64 / REAL_WORLD_MAINT_PERIOD_DAYS,
404                lease_period_days: mode.lease_period_days(&c),
405                quarterly_rent_scale: mode.quarterly_rent_scale(&c),
406            }
407        })
408        .collect()
409}
410
411/// When a priced kind's price is collected: `quarterly` (offices and the
412/// lease amenities, every `leasePeriodDays`, scaled by the calendar's
413/// `quarterlyRentScale`),
414/// `maintenancePeriod` (rental living, every maintenance period, scaled by
415/// `maintenanceScale`), `sale` (a condo, once) or `nightly` (hotel rooms).
416/// A priced kind with no collector here is a programming error, so the
417/// `one_entry_per_kind_in_catalog_order` test builds every mode's catalog
418/// and trips it before a build ships.
419fn rent_cadence(kind: Kind) -> &'static str {
420    match kind {
421        Kind::Office | Kind::FitnessClub | Kind::Clinic => "quarterly",
422        Kind::RentalStudio | Kind::RentalApartment => "maintenancePeriod",
423        Kind::Condo => "sale",
424        Kind::HotelSingle | Kind::HotelDouble | Kind::HotelSuite => "nightly",
425        _ => unreachable!("{kind:?} has a price but no rent cadence"),
426    }
427}
428
429/// `rules.priceOptions(kind)` as a [`Rent`]: the canon ladder in Classic for
430/// the kinds that have one, the tuned band in Modern for every priced kind.
431fn rent_for(mode: GameMode, kind: Kind) -> Option<Rent> {
432    mode.rent_model(kind).map(|model| match model {
433        RentModel::Ladder(values) => Rent::Ladder {
434            cadence: rent_cadence(kind),
435            default: values[crate::rent::AVERAGE_RUNG],
436            rungs: values
437                .iter()
438                .enumerate()
439                .map(|(i, &value)| Rung {
440                    level: i as i64,
441                    label: RUNG_LABELS[i],
442                    value,
443                })
444                .collect(),
445            no_rate: true,
446        },
447        RentModel::Band(c) => Rent::Band {
448            cadence: rent_cadence(kind),
449            default: c.default,
450            min: c.min,
451            max: c.max,
452            step: c.step,
453            no_rate: false,
454        },
455    })
456}
457
458/// The key of Classic's [`crate::facilities::CLASSIC_VENUE_POOL`].
459const VENUE_POOL_KEY: &str = "venues";
460
461/// Each pool `mode` enforces, with the key the catalog gives it.
462pub(crate) fn keyed_pools(mode: GameMode) -> impl Iterator<Item = (&'static str, &'static Pool)> {
463    POOL_KEYS
464        .into_iter()
465        .chain(std::iter::once(VENUE_POOL_KEY))
466        .zip(pools_for(mode))
467}
468
469fn pool_key(mode: GameMode, kind: Kind) -> Option<&'static str> {
470    keyed_pools(mode)
471        .find(|(_, p)| p.kinds.contains(&kind))
472        .map(|(key, _)| key)
473}
474
475#[cfg(test)]
476mod tests;
477
478#[cfg(test)]
479mod charge_tests;
480
481#[cfg(test)]
482mod rules_tests;