verticopolis_engine/load/
reader.rs1use super::*;
4use crate::economy::visitors::census_follows_the_day;
5use crate::tower::Extras;
6
7#[doc(hidden)]
8pub const NEWER_SAVE_REFUSAL: &str =
10 "This save was made by a newer version of Verticopolis. Update the game to load it.";
11
12#[doc(hidden)]
13pub const NOT_A_SAVE_REFUSAL: &str =
16 "This is not a saved tower: it has no game clock or no list of rooms.";
17
18pub(crate) fn has_save_shape(raw: &Value) -> bool {
22 raw.get("minutes").is_some_and(Value::is_number)
23 && raw.get("units").is_some_and(Value::is_array)
24}
25
26pub fn deserialize(raw: &Value) -> Result<Simulation, String> {
33 deserialize_owned(raw.clone())
34}
35
36#[doc(hidden)]
41pub fn deserialize_tdt(raw: &Value) -> Result<Simulation, String> {
42 let mut sim = deserialize(raw)?;
43 if raw.get("morningVenueDay").is_none()
46 && sim.clock.hour() < crate::economy::visitors::MORNING_VENUE_DAY_ENDS_AT_HOUR
47 {
48 sim.morning_venue_day = sim.clock.day() - 1;
49 }
50 let Some(source) = raw.get("transports").and_then(Value::as_array) else {
51 return Ok(sim);
52 };
53 let mut changed = false;
54 for shaft in &mut sim.tower.transports {
55 if shaft.kind != Kind::ElevatorExpress || shaft.bottom >= 0 {
56 continue;
57 }
58 let original = source.iter().find(|t| {
59 t.get("kind").and_then(Value::as_str) == Some("elevatorExpress")
60 && t.get("x").and_then(Value::as_i64) == Some(shaft.x)
61 && t.get("bottom").and_then(Value::as_i64) == Some(shaft.bottom)
62 && t.get("top").and_then(Value::as_i64) == Some(shaft.top)
63 });
64 let Some(authored) = original
65 .and_then(|t| t.get("skipFloors"))
66 .and_then(Value::as_array)
67 else {
68 continue;
69 };
70 let saved_skips: Vec<f64> = authored
71 .iter()
72 .filter_map(Value::as_f64)
73 .filter(|v| v.is_finite())
74 .collect();
75 shaft.preserve_basement_stops = true;
79 let (bottom, top) = (shaft.bottom as f64, shaft.top as f64);
80 let have = shaft.skip_floors.as_deref().unwrap_or(&[]);
81 let mut back: Vec<f64> = saved_skips
82 .iter()
83 .copied()
84 .filter(|&floor| crate::facilities::is_basement_stop(floor))
85 .filter(|&floor| floor > bottom && floor < top && !have.contains(&floor))
86 .collect();
87 back.dedup();
88 if back.is_empty() {
89 continue;
90 }
91 let skips = shaft.skip_floors.get_or_insert_with(Vec::new);
93 skips.extend(back);
94 skips.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
95 skips.dedup();
96 changed = true;
97 }
98 if changed {
99 sim.tower.revision += 1;
100 }
101 Ok(sim)
102}
103
104pub fn deserialize_owned(raw: Value) -> Result<Simulation, String> {
108 if raw.is_null() {
111 return Err("not a tower save (the save is null)".into());
112 }
113 if let Some(version) = raw.get("version").and_then(Value::as_f64) {
117 if version.is_finite() && version > SAVE_VERSION as f64 {
118 return Err(NEWER_SAVE_REFUSAL.into());
119 }
120 }
121 if !has_save_shape(&raw) {
124 return Err(NOT_A_SAVE_REFUSAL.into());
125 }
126 let written = founder_keys(&raw);
129 let mut data = migrate_save_owned(raw);
130 let modern = data.get("mode").and_then(Value::as_str) == Some("modern");
131 let runs = reads_floor_runs(version_of(&data));
132 let listed = match data.get_mut("units") {
133 Some(Value::Array(units)) => std::mem::take(units),
134 _ => Vec::new(),
135 };
136 let mut kept = 0usize;
140 for u in listed.iter().filter(|u| kind_of(u).is_some()) {
141 kept += listed_units(u, runs);
142 if kept > UNIT_CAP {
143 break;
144 }
145 }
146 if kept > UNIT_CAP {
147 return Err(format!(
148 "This save lists more than {UNIT_CAP} units, more than the whole lot can hold, so it cannot be a real tower."
149 ));
150 }
151 let mut units = Vec::with_capacity(kept + unit_list_headroom(kept));
152 let mut ids = Vec::with_capacity(kept);
153 for entry in listed {
154 each_listed_unit(&entry, runs, |tile| {
155 if let Some((unit, id)) = unit_from_value(tile, modern) {
156 units.push(unit);
157 ids.push(id);
158 }
159 true
160 });
161 }
162 debug_assert_eq!(units.len(), kept, "unit_from_value skipped a counted entry");
163 Ok(assemble(&data, units, ids, &written))
164}
165
166pub(crate) fn founder_keys(raw: &Value) -> Value {
168 let mut keys = Map::new();
169 for key in ["founder", "appVersion"] {
170 if let Some(v) = raw.get(key) {
171 keys.insert(key.to_string(), v.clone());
172 }
173 }
174 Value::Object(keys)
175}
176
177pub(crate) fn unit_from_value(u: &Value, modern: bool) -> Option<(Unit, Option<i64>)> {
183 let kind = kind_of(u)?;
184 let cat = kind.facility().width;
185 let floor =
188 (round(num(u.get("floor"), 1.0)) as i64).clamp(MIN_FLOOR, kind.highest_base_floor());
189 let x = (round(num(u.get("x"), 0.0)) as i64).clamp(0, LOT - 1);
190 let cap = if kind.is_structural() { cat } else { LOT - x };
191 let width = (round(num(u.get("width"), cat as f64)) as i64)
192 .min(cap)
193 .min(LOT - x)
194 .max(1);
195 let state = if kind.is_structural() {
196 UnitState::Empty
197 } else {
198 parse_state(u.get("state")).unwrap_or(UnitState::Empty)
199 };
200 let not_owned = matches!(
201 state,
202 UnitState::Empty | UnitState::Construction | UnitState::Gutted
203 );
204 let ever_occupied =
205 u.get("everOccupied") == Some(&Value::Bool(true)) && !(not_owned && !kind.is_hotel());
206 let sold_condo = kind == Kind::Condo && ever_occupied;
207 let keep_household = ever_occupied && kind.has_household();
208 let ladder_priced = !modern && classic_ladder(kind).is_some();
209 let mut rent: Option<f64> = match u.get("rent") {
210 None => None,
211 Some(r) if ladder_priced => Some(r.as_f64().unwrap_or(f64::NAN)),
212 Some(r) => Some(num(
213 Some(r),
214 rent_config(kind).map(|c| c.default).unwrap_or(0.0),
215 )),
216 };
217 if let Some(r) = rent {
218 if kind == Kind::Condo {
219 let ladder = if modern {
220 None
221 } else {
222 classic_ladder(Kind::Condo)
223 };
224 if sold_condo {
225 rent = Some(match ladder {
226 Some(l) => js_max(l[0], js_min(l[3], r)),
227 None => js_max(SOLD_CONDO_MIN_PRICE, js_min(SOLD_CONDO_MAX_PRICE, r)),
228 });
229 } else if ladder.is_none() {
230 let band = rent_config(Kind::Condo).unwrap();
231 rent = Some(js_max(band.min, js_min(band.max, r)));
232 }
233 }
234 }
235 let residents = if keep_household && modern {
236 match u.get("residents") {
237 None => None,
238 Some(r) => {
239 let v = if r.as_f64().is_some_and(|x| x.is_finite()) {
240 r.as_f64().unwrap()
241 } else {
242 3.0
243 };
244 Some((round(v) as i64).clamp(2, 5))
245 }
246 }
247 } else {
248 None
249 };
250 let film_policy = film_policy(u.get("filmPolicy"));
251 let subtype: Option<&'static str> = match (
252 u.get("subtype").and_then(Value::as_str),
253 kind.subtype_list(),
254 ) {
255 (Some(s), Some(list)) => list.iter().copied().find(|c| *c == s),
256 _ => None,
257 };
258 let retail = kind.subtype_list().is_some();
259 let retail_field = |key: &str| -> Option<f64> {
260 if !retail {
261 return None;
262 }
263 let v = u.get(key)?;
264 Some(num(Some(v), 0.0).max(0.0))
265 };
266 let no_rate =
267 rent_config(kind).is_some() && !modern && u.get("noRate") == Some(&Value::Bool(true));
268 let unit = Unit {
269 id: 0,
270 kind,
271 floor,
272 x,
273 width,
274 state,
275 satisfaction: if kind.is_structural() {
276 1.0
277 } else {
278 num(u.get("satisfaction"), 1.0).min(1.0).max(0.0)
279 },
280 occupants: if kind.counts_visitors() || kind.is_structural() {
281 0
282 } else {
283 let occupants = num(u.get("occupants"), 0.0).clamp(0.0, MAX_SAFE_INTEGER) as i64;
284 if kind == Kind::Office {
288 occupants.min(kind.facility().population)
289 } else {
290 occupants
291 }
292 },
293 customers_in: None,
294 hotel_customers_in: None,
295 staff_in: 0,
296 out_for_meal: None,
297 residents,
298 visitors_yest: if census_follows_the_day(kind) {
299 u.get("visitorsYest")
300 .map(|v| num(Some(v), 0.0).clamp(0.0, f64::from(u8::MAX)).floor() as u8)
301 } else {
302 None
303 },
304 ever_occupied,
305 pending_income: num(u.get("pendingIncome"), 0.0),
306 rent,
307 no_rate,
308 label: u
309 .get("label")
310 .and_then(Value::as_str)
311 .map(|s| s.to_string())
312 .unwrap_or_else(|| kind.facility().name.to_string()),
313 subtype,
314 extras: Extras {
315 vacate_reason: vacate_reason(u.get("vacateReason")),
316 vacate_at: u.get("vacateAt").map(|v| num(Some(v), 0.0)),
317 film_policy,
318 film_days: film_days(kind, u.get("filmDays")),
319 film_classic: cinema_flag(kind, u.get("filmClassic")),
320 film_blockbuster: modern && cinema_flag(kind, u.get("filmBlockbuster")),
322 ticket_price: ticket_price(kind, modern, u.get("ticketPrice")),
323 second_screen: second_screen(kind, u.get("screen2")),
324 patronage_today: retail_field("patronageToday"),
325 patronage_yest: retail_field("patronageYest"),
326 profit_today: retail_field("profitToday"),
327 profit_yest: retail_field("profitYest"),
328 complete_at: u.get("completeAt").and_then(Value::as_f64),
329 complete_at_raw: match u.get("completeAt") {
330 Some(v) if !v.is_number() => Some(v.clone()),
331 _ => None,
332 },
333 dirty_days: coerce_dirty_days(state, kind, u.get("dirtyDays")),
334 lobby_stories: None,
336 }
337 .without_mirrored_screen()
338 .boxed(),
339 };
340 Some((unit, sane_id(u.get("id"))))
341}