Skip to main content
Verticopolis engine

verticopolis_engine/
rent.rs

1//! Setting what rooms charge: one room at a time
2//! ([`Simulation::adjust_rent`], [`Simulation::price_unit`],
3//! [`Simulation::set_no_rate`]) or every room of a kind at once
4//! ([`Simulation::apply_rent_batch`]).
5//!
6//! In Classic a priced room picks one of four rungs (very low, low, average,
7//! high), as in the original. In Modern it takes any price inside its kind's
8//! band, in steps. [`crate::catalog::catalog`] publishes the rungs, bands and
9//! defaults for each kind. A condo that has been sold keeps its price.
10
11use crate::clock::GameMode;
12use crate::econ::{rent_config, rent_of};
13use crate::facilities::Kind;
14use crate::gameplay::GameplayEvent;
15use crate::rules::RentModel;
16use crate::sim::Simulation;
17use crate::tower::Unit;
18
19/// The Average rung of a Classic price ladder (four rungs: Very Low, Low,
20/// Average, High): the Classic catalog's default price (`catalog_rent_default`),
21/// the mode's neutral price, and where the editor's picker puts a price that
22/// is not a finite number.
23pub(crate) const AVERAGE_RUNG: usize = 2;
24
25#[doc(hidden)]
26pub fn snap_to_ladder(rungs: &[f64; 4], value: f64) -> f64 {
27    if !value.is_finite() {
28        return rungs[AVERAGE_RUNG];
29    }
30    let mut best = rungs[0];
31    let mut best_dist = f64::INFINITY;
32    for &r in rungs {
33        let d = (value - r).abs();
34        if d <= best_dist {
35            best_dist = d;
36            best = r;
37        }
38    }
39    best
40}
41
42/// `ladderRungFor(...).level`.
43pub(crate) fn ladder_level(rungs: &[f64; 4], value: f64) -> usize {
44    let snapped = snap_to_ladder(rungs, value);
45    rungs
46        .iter()
47        .position(|&r| r == snapped)
48        .unwrap_or(AVERAGE_RUNG)
49}
50
51/// `priceOptions(kind)`: `Some(Some(ladder))` in Classic for the canon kinds,
52/// `Some(None)` for a Modern band, `None` for an unpriced kind.
53pub(crate) fn price_options(mode: GameMode, kind: Kind) -> Option<Option<[f64; 4]>> {
54    mode.rent_model(kind).map(|model| match model {
55        RentModel::Ladder(rungs) => Some(rungs),
56        RentModel::Band(_) => None,
57    })
58}
59
60fn price_neutral(mode: GameMode, kind: Kind) -> Option<f64> {
61    match price_options(mode, kind)? {
62        Some(l) => Some(l[AVERAGE_RUNG]),
63        None => Some(rent_config(kind)?.default),
64    }
65}
66
67/// Whether an effective price is the neutral price: an exact match, the test
68/// the batch reprice's "on the default" makes and the Map's Average band tier
69/// shares. A price off the neutral price by any amount is not neutral.
70pub(crate) fn is_neutral_price(price: f64, neutral: f64) -> bool {
71    price == neutral
72}
73
74/// The price [`Simulation::apply_rent_batch`] sets.
75#[derive(Clone, Copy, Debug, PartialEq)]
76pub enum BatchTarget {
77    /// The kind's default price: the average rung in Classic.
78    Default,
79    /// Off the market: the rooms take no new tenants (Classic only).
80    NoRate,
81    /// This price, snapped to a rung in Classic or kept inside the band in
82    /// Modern.
83    Price(f64),
84}
85
86/// What a batch reprice did, counted in rooms.
87#[derive(Clone, Debug, Default, PartialEq, Eq)]
88pub struct BatchRentResult {
89    /// Rooms of the kind.
90    pub matched: i64,
91    /// Rooms the batch applied to (`matched` less the two skips).
92    pub eligible: i64,
93    /// Rooms whose price actually moved.
94    pub changed: i64,
95    /// Sold condos, which keep their price.
96    pub skipped_sold: i64,
97    /// Rooms skipped for having a price of their own, when the batch asked
98    /// for default-priced rooms only.
99    pub skipped_custom: i64,
100    /// Rooms that had a price of their own and now have the batch's.
101    pub custom_overwritten: i64,
102    /// Rooms whose price was raised to the bottom of the band (Modern).
103    pub clamped_low: i64,
104    /// Rooms whose price was lowered to the top of the band (Modern).
105    pub clamped_high: i64,
106}
107
108impl Simulation {
109    /// Sets the price of every room of `kind` to `target`. With
110    /// `only_default_priced`, rooms the player priced themselves keep their
111    /// price. Returns `None`, changing nothing, for a kind that has no price,
112    /// for [`BatchTarget::NoRate`] in Modern, or for a price that is not a
113    /// finite number.
114    ///
115    /// ```
116    /// use verticopolis_engine::clock::GameMode;
117    /// use verticopolis_engine::facilities::Kind;
118    /// use verticopolis_engine::rent::BatchTarget;
119    /// use verticopolis_engine::sim::Simulation;
120    ///
121    /// let mut sim = Simulation::new_game(1, GameMode::Modern);
122    /// let none = sim.apply_rent_batch(Kind::Office, BatchTarget::Default, false).unwrap();
123    /// assert_eq!(none.matched, 0);
124    /// assert!(sim.apply_rent_batch(Kind::Lobby, BatchTarget::Default, false).is_none());
125    /// ```
126    pub fn apply_rent_batch(
127        &mut self,
128        kind: Kind,
129        target: BatchTarget,
130        only_default_priced: bool,
131    ) -> Option<BatchRentResult> {
132        let r = self.compute_batch(kind, target, only_default_priced, true);
133        if r.as_ref().is_some_and(|r| r.changed > 0) {
134            self.gameplay.push(GameplayEvent::PricingChanged { kind });
135        }
136        r
137    }
138
139    #[doc(hidden)]
140    /// `computeBatch(kind, target, opts, mutate)`: `None` for an unpriced
141    /// kind, a No Rate target off the ladder, or a non-finite price.
142    pub fn compute_batch(
143        &mut self,
144        kind: Kind,
145        target: BatchTarget,
146        only_default_priced: bool,
147        mutate: bool,
148    ) -> Option<BatchRentResult> {
149        let cfg = rent_config(kind)?;
150        let ladder = price_options(self.mode, kind)?;
151        if target == BatchTarget::NoRate && ladder.is_none() {
152            return None;
153        }
154        if let BatchTarget::Price(p) = target {
155            if !p.is_finite() {
156                return None;
157            }
158        }
159        let neutral = price_neutral(self.mode, kind)?;
160        let mut r = BatchRentResult::default();
161        // A priced kind is never structural, so the room list holds every
162        // unit of it, in list order: R units visited, not all of them.
163        let rooms = self.tower.room_index();
164        for &i in rooms.iter() {
165            let u = &mut self.tower.units[i];
166            if u.kind != kind {
167                continue;
168            }
169            r.matched += 1;
170            if u.kind == Kind::Condo && u.ever_occupied {
171                r.skipped_sold += 1;
172                continue;
173            }
174            // On the default means the effective price is the neutral anchor,
175            // read through the same fallback `rentOf` applies, and never off
176            // the market.
177            let neutral_priced =
178                !u.no_rate && is_neutral_price(u.rent.unwrap_or(cfg.default), neutral);
179            if only_default_priced && !neutral_priced {
180                r.skipped_custom += 1;
181                continue;
182            }
183            r.eligible += 1;
184            if target == BatchTarget::NoRate {
185                if !u.no_rate {
186                    r.changed += 1;
187                }
188                if mutate {
189                    if let Some(j) = self.tower.journal.as_mut() {
190                        j.unit_edit(i, u);
191                    }
192                    u.no_rate = true;
193                }
194                continue;
195            }
196            if !neutral_priced && !u.no_rate {
197                r.custom_overwritten += 1;
198            }
199            let before = rent_of(u.kind, u.rent, u.no_rate);
200            let value = match (target, ladder) {
201                (BatchTarget::Default, _) => neutral,
202                (BatchTarget::Price(p), Some(l)) => snap_to_ladder(&l, p),
203                (BatchTarget::Price(p), None) => {
204                    if p < cfg.min {
205                        r.clamped_low += 1;
206                    } else if p > cfg.max {
207                        r.clamped_high += 1;
208                    }
209                    p.min(cfg.max).max(cfg.min)
210                }
211                (BatchTarget::NoRate, _) => unreachable!("handled above"),
212            };
213            if before != value {
214                r.changed += 1;
215            }
216            if mutate {
217                if let Some(j) = self.tower.journal.as_mut() {
218                    j.unit_edit(i, u);
219                }
220                // `storeRent`: the default is stored as no override; an
221                // explicit reprice returns a No Rate unit to the market.
222                u.rent = if value == cfg.default {
223                    None
224                } else {
225                    Some(value)
226                };
227                u.no_rate = false;
228            }
229        }
230        Some(r)
231    }
232
233    #[doc(hidden)]
234    /// `demandFactor(u)`.
235    pub fn demand_factor(&self, u: &Unit) -> f64 {
236        let Some(neutral) = price_neutral(self.mode, u.kind) else {
237            return 1.0;
238        };
239        if u.no_rate {
240            return 0.0;
241        }
242        let ratio = rent_of(u.kind, u.rent, u.no_rate) / neutral;
243        (2.0 - ratio).min(1.6).max(0.15)
244    }
245
246    /// Sets room `id`'s price to `target` (snapped to a rung in Classic, kept
247    /// inside the band in Modern) and puts it back on the market. Returns the
248    /// price it set, or `None` for a room with no price, a sold condo or a
249    /// `target` that is not a finite number.
250    pub fn price_unit(&mut self, id: i64, target: f64) -> Option<f64> {
251        let mode = self.mode;
252        let u = self.tower.get_unit_mut(id)?;
253        let cfg = rent_config(u.kind)?;
254        let opts = price_options(mode, u.kind)?;
255        if !target.is_finite() {
256            return None;
257        }
258        if u.kind == Kind::Condo && u.ever_occupied {
259            return None;
260        }
261        let applied = match opts {
262            Some(l) => snap_to_ladder(&l, target),
263            None => target.min(cfg.max).max(cfg.min),
264        };
265        let before = (!u.no_rate).then(|| rent_of(u.kind, u.rent, u.no_rate));
266        u.rent = if applied == cfg.default {
267            None
268        } else {
269            Some(applied)
270        };
271        u.no_rate = false;
272        // A write that leaves the price where it was is not a change.
273        let changed = Some(rent_of(u.kind, u.rent, false)) != before;
274        let kind = u.kind;
275        if changed {
276            self.gameplay.push(GameplayEvent::PricingChanged { kind });
277        }
278        Some(applied)
279    }
280
281    /// Takes room `id` off the market, so it takes no new tenants. Classic
282    /// only, as in the original. Returns `false` for a room that cannot be,
283    /// such as a sold condo or any room in Modern.
284    pub fn set_no_rate(&mut self, id: i64) -> bool {
285        let mode = self.mode;
286        let Some(u) = self.tower.get_unit_mut(id) else {
287            return false;
288        };
289        if !matches!(price_options(mode, u.kind), Some(Some(_))) {
290            return false;
291        }
292        if u.kind == Kind::Condo && u.ever_occupied {
293            return false;
294        }
295        let was_off = u.no_rate;
296        u.no_rate = true;
297        let kind = u.kind;
298        if !was_off {
299            self.gameplay.push(GameplayEvent::PricingChanged { kind });
300        }
301        true
302    }
303
304    /// Moves room `id`'s price up (`dir` 1) or down (`dir` -1) by one rung in
305    /// Classic or one step in Modern. Returns the new price, or `None` as
306    /// [`price_unit`](Simulation::price_unit) does.
307    pub fn adjust_rent(&mut self, id: i64, dir: i64) -> Option<f64> {
308        let mode = self.mode;
309        let (kind, rent, no_rate) = {
310            let u = self.tower.get_unit(id)?;
311            (u.kind, u.rent, u.no_rate)
312        };
313        let cfg = rent_config(kind)?;
314        let opts = price_options(mode, kind)?;
315        let current = rent_of(kind, rent, no_rate);
316        match opts {
317            Some(l) => {
318                let idx = ladder_level(&l, current) as i64;
319                let next = l[(idx + dir).clamp(0, 3) as usize];
320                self.price_unit(id, next)
321            }
322            None => self.price_unit(id, current + dir as f64 * cfg.step),
323        }
324    }
325}