Skip to main content

unbanished_formats/
savegame.rs

1//! The game-state stream of a save: the game loop's serializer over every manager and every object.
2//! See docs/SAVE-GAME-STATE.md.
3//!
4//! Objects (`Object::Internal`) are written where they are first referenced
5//! (`InternalBasePtr::Serialize`): a present byte, the object's factory index, its tag and its type
6//! id; the first time an index appears its serializer follows inline
7//! (`InternalFactory::PersistObject`).
8//!
9//! Each type's serializer is described by a schema ([`crate::savegame_schema`]) of fields, blocks,
10//! lists and version conditions, read (and written) by one interpreter. Every block must be
11//! consumed exactly.
12//!
13//! Original: `FUN_14009af60`, Runtime `0x1800c29f0`, Runtime `0x1800c2780`.
14mod decoder;
15mod encoder;
16mod fields;
17use decoder::Decoder;
18use encoder::Encoder;
19pub use fields::{Fields, Value};
20
21// vtable +0x18
22
23use std::collections::{BTreeMap, BTreeSet};
24
25use crate::crs::{Reader, Writer, BLOCK_END, BLOCK_START};
26use crate::error::{format_err, Error, Result};
27use crate::savegame_schema::{schema_for, Cond, Op, ACHIEVEMENTS, ANIMATIONS, TOWN};
28
29// Internal +0x08
30/// An object's factory index (`Internal`).
31pub type ObjId = i32;
32
33/// A decoded object.
34#[derive(Debug, Clone)]
35pub struct Object {
36    /// Its number in the stream.
37    pub index: ObjId,
38    // Internal +0x0c
39    /// `Internal`, drawn on the factory's own Random.
40    pub tag: u32,
41    /// The type's id.
42    pub type_id: u32,
43    /// The type's name.
44    pub type_name: &'static str,
45    /// The decoded fields.
46    pub fields: Fields,
47}
48
49/// The whole game state.
50#[derive(Debug, Clone, Default)]
51pub struct GameState {
52    /// The external reference table (`ExternalFactory::SerializeReferenceTable`).
53    pub references: BTreeMap<u32, String>,
54    // +0x40; +0x48; +0x30; +0x34; +0xd0; +0x15c; Game +0x50
55    /// The climate.
56    pub climate: u32,
57    /// The start condition.
58    pub start_condition: u32,
59    /// The terrain type.
60    pub terrain: u32,
61    /// The map seed.
62    pub seed: u32,
63    /// The map size.
64    pub size: i32,
65    /// The game's flags.
66    pub flags: u32,
67    /// The scenario.
68    pub scenario: i32,
69    /// The index of the game's Random (`System::Random::Serialize`).
70    pub random_index: u32,
71    /// The 624 words of the game's Random.
72    pub random_state: Vec<u32>,
73    /// The town's name.
74    pub town_name: String,
75    // +0x158, +0x150
76    /// The goal's state.
77    pub goal_done: bool,
78    /// The goal, if any.
79    pub goal: Option<ObjId>,
80    // +0xa8; +0xbc; +0x18; +0x1f; +0x1c; +0x20
81    /// The entity manager's clock.
82    ///
83    /// Original: `FUN_1400c9970`, `FUN_140022500`.
84    pub entity_time: i64,
85    /// The entities.
86    pub entities: Vec<Option<ObjId>>,
87    /// The scheduler's five bucket lists.
88    pub buckets: Vec<Vec<Option<ObjId>>>,
89    /// The scheduler's two five-int arrays.
90    pub bucket_values: [[i32; 5]; 2],
91    /// Each entity's schedule (the low 24 bits; the time).
92    pub schedules: Vec<(i32, i32, i32, i64)>,
93    /// The game loop serializer's version (3 in the samples).
94    pub version: u32,
95    /// The strings were written as UTF-16 (2015 builds) rather than 8-bit.
96    pub wide_strings: bool,
97    /// `InternalFactory::ResetPersistState`'s block, as written.
98    pub persist_state: Vec<u8>,
99    /// The entity manager block's version.
100    pub entity_manager_version: u32,
101    /// `AchievementManager::Persist`: the achievement instances.
102    pub achievements: Fields,
103    /// `AnimationManager::Serialize`: the shared instances of instanced clips
104    /// ([`ANIMATIONS`](crate::savegame_schema::ANIMATIONS)). Empty (a new game) is written as the
105    /// engine's empty state ([`empty_animations`]).
106    pub animations: Fields,
107    /// The sound scene: a whole block carried through undecoded. An empty one is written as the engine's empty state ([`empty_audio_scene`]).
108    pub audio_scene: Vec<u8>,
109    /// The game camera.
110    ///
111    /// Original: `FUN_14009dd90`.
112    pub camera: Option<crate::menu_scene::SceneCamera>,
113    /// The terrain.
114    ///
115    /// Original: `FUN_1400b59a0`.
116    pub terrain_map: Option<crate::menu_scene::MapComponent>,
117    /// The town manager.
118    ///
119    /// Original: `FUN_140094c30`.
120    pub town: Fields,
121    /// The gameplay map.
122    ///
123    /// Original: `FUN_1400a45d0`.
124    pub map: GameMap,
125    /// The blocks after the map: `jobs`, `tools`, `calendar`, `event_log`, `environment` and
126    /// `minimap` (see `savegame_schema`).
127    pub managers: Fields,
128    /// Every object in the stream, by number.
129    pub objects: BTreeMap<ObjId, Object>,
130}
131
132/// One cell of the gameplay map, as the game state stores it (48 bytes in memory).
133///
134/// Original: `FUN_14001b570`.
135#[derive(Debug, Clone, Default, PartialEq)]
136pub struct GameMapCell {
137    // +0x00; +0x08
138    /// Not identified yet.
139    pub entities: [Option<ObjId>; 2],
140    // +0x10
141    /// The description at (reference id, `u32::MAX` when unset).
142    pub description: u32,
143    // +0x1c..+0x25
144    /// Bytes.
145    pub flags: [u8; 9],
146    // +0x26
147    /// Not identified yet.
148    pub value: u16,
149    // +0x29; +0x28..+0x2d
150    /// Bytes; `[1]` is the cell type.
151    pub bytes: [u8; 6],
152}
153
154// +0x90
155/// The gameplay map (version 4).
156///
157/// Original: `FUN_1400a45d0`.
158#[derive(Debug, Clone, Default)]
159pub struct GameMap {
160    /// The map's size in cells.
161    pub size: i32,
162    /// The `size × size` cells.
163    pub cells: Vec<GameMapCell>,
164    /// Nine shorts after the cells; not identified yet.
165    pub trailer: [i16; 9],
166}
167
168impl GameState {
169    // Internal +0x0c
170    /// A new object of type `name` with default fields ([`crate::savegame_schema::default_fields`])
171    /// and the next free factory index. The tag (`Internal`, drawn on the factory's own Random in
172    /// the original) is the index here; returns its id.
173    pub fn new_object(&mut self, name: &'static str) -> Option<ObjId> {
174        let fields = crate::savegame_schema::default_fields(name)?;
175        let index = self.objects.keys().next_back().map_or(1, |&k| k + 1);
176        self.objects.insert(
177            index,
178            Object {
179                index,
180                tag: index as u32,
181                type_id: crate::crc::type_id(name),
182                type_name: name,
183                fields,
184            },
185        );
186        Some(index)
187    }
188
189    /// Decode an expanded game-state stream (`crate::save::Save::state`).
190    pub fn decode(state: &[u8]) -> Result<GameState> {
191        let mut d = Decoder {
192            r: Reader::new(state),
193            objects: BTreeMap::new(),
194            defining: BTreeSet::new(),
195        };
196        let mut g = GameState::default();
197        d.block(|d, version| {
198            g.version = version;
199            g.references = d.block(|d, _| {
200                let n = d.r.count()?;
201                (0..n)
202                    .map(|_| Ok((d.r.u32()?, d.r.string()?)))
203                    .collect::<Result<BTreeMap<_, _>>>()
204            })?;
205            d.r.set_reference_ids(std::sync::Arc::new(g.references.clone()));
206            g.persist_state = d.raw_block()?;
207            g.climate = d.r.u32()?;
208            g.start_condition = d.r.u32()?;
209            g.terrain = d.r.u32()?;
210            g.seed = d.r.u32()?;
211            g.size = d.r.i32()?;
212            if version > 0 {
213                g.flags = d.r.u32()?;
214            }
215            if version > 2 {
216                g.scenario = d.r.i32()?;
217            }
218            g.random_index = d.r.u32()?;
219            g.random_state = (0..0x270).map(|_| d.r.u32()).collect::<Result<_>>()?;
220            g.town_name = d.r.string()?;
221            g.goal_done = d.r.bool()?;
222            g.goal = d.ptr()?;
223            // `Audio::Scene::Serialize` is kept as written (engine side, not yet decoded).
224            d.ops_into(&[ACHIEVEMENTS], 0, &mut g.achievements)?;
225            d.ops_into(&[ANIMATIONS], 0, &mut g.animations)?;
226            g.audio_scene = d.raw_block()?;
227            g.camera = Some(crate::menu_scene::read_camera(&mut d.r)?);
228            d.block(|d, version| {
229                g.entity_manager_version = version;
230                g.entity_time = d.r.i64()?;
231                g.entities = d.ptrs()?;
232                g.buckets = (0..5).map(|_| d.ptrs()).collect::<Result<_>>()?;
233                for k in 0..2 {
234                    for v in 0..5 {
235                        g.bucket_values[k][v] = d.r.i32()?;
236                    }
237                }
238                g.schedules = (0..g.entities.len())
239                    .map(|_| Ok((d.r.i32()?, d.r.i32()?, d.r.i32()?, d.r.i64()?)))
240                    .collect::<Result<_>>()?;
241                Ok(())
242            })?;
243            g.terrain_map = Some(crate::menu_scene::read_map_component(&mut d.r)?);
244            d.ops_into(&[TOWN], 0, &mut g.town)?;
245            g.map = d.game_map()?;
246            d.ops_into(&managers(version), 0, &mut g.managers)?;
247            Ok(())
248        })?;
249        g.objects = d.objects;
250        g.wide_strings = d.r.wide_seen;
251        Ok(g)
252    }
253
254    /// The writing side of [`GameState::decode`]: the same stream, with each object written
255    /// inline where it is first referenced, in the order the decoder met them.
256    pub fn encode(&self) -> Result<Vec<u8>> {
257        let mut e = Encoder {
258            w: Writer::new(),
259            objects: &self.objects,
260            written: BTreeSet::new(),
261        };
262        e.w.wide_strings = self.wide_strings;
263        let at = e.w.begin_block(self.version);
264        let refs = e.w.begin_block(0);
265        e.w.count(self.references.len());
266        for (&id, path) in &self.references {
267            e.w.u32(id);
268            e.w.string(path);
269        }
270        e.w.end_block(refs);
271        e.w.set_reference_ids(&self.references);
272        // `InternalFactory::ResetPersistState`: the number of object slots, which every index
273        // must be below (raised when objects were added).
274        let slots = self
275            .objects
276            .keys()
277            .max()
278            .map_or(0, |&m| m as u32 + 1)
279            .max(persist_slots(&self.persist_state));
280        let at_persist = e.w.begin_block(0);
281        e.w.u32(slots);
282        e.w.end_block(at_persist);
283        e.w.u32(self.climate);
284        e.w.u32(self.start_condition);
285        e.w.u32(self.terrain);
286        e.w.u32(self.seed);
287        e.w.i32(self.size);
288        if self.version > 0 {
289            e.w.u32(self.flags);
290        }
291        if self.version > 2 {
292            e.w.i32(self.scenario);
293        }
294        e.w.u32(self.random_index);
295        self.random_state.iter().for_each(|&v| e.w.u32(v));
296        e.w.string(&self.town_name);
297        e.w.bool(self.goal_done);
298        e.ptr(self.goal)?;
299        e.ops(&[ACHIEVEMENTS], 0, &self.achievements)?;
300        if self.animations.0.is_empty() {
301            e.w.bytes(&empty_animations());
302        } else {
303            e.ops(&[ANIMATIONS], 0, &self.animations)?;
304        }
305        if self.audio_scene.is_empty() {
306            e.w.bytes(&empty_audio_scene());
307        } else {
308            e.w.bytes(&self.audio_scene);
309        }
310        let camera = self
311            .camera
312            .as_ref()
313            .ok_or_else(|| Error::Format("no camera".into()))?;
314        crate::menu_scene::write_camera(&mut e.w, camera)?;
315        let em = e.w.begin_block(self.entity_manager_version);
316        e.w.i64(self.entity_time);
317        e.ptrs(&self.entities)?;
318        for b in &self.buckets {
319            e.ptrs(b)?;
320        }
321        self.bucket_values
322            .iter()
323            .flatten()
324            .for_each(|&v| e.w.i32(v));
325        for &(a, b, c, t) in &self.schedules {
326            e.w.i32(a);
327            e.w.i32(b);
328            e.w.i32(c);
329            e.w.i64(t);
330        }
331        e.w.end_block(em);
332        let terrain = self
333            .terrain_map
334            .as_ref()
335            .ok_or_else(|| Error::Format("no terrain".into()))?;
336        crate::menu_scene::write_map_component(&mut e.w, terrain)?;
337        e.ops(&[TOWN], 0, &self.town)?;
338        e.game_map(&self.map)?;
339        e.ops(&managers(self.version), 0, &self.managers)?;
340        e.w.end_block(at);
341        Ok(e.w.data)
342    }
343}
344
345/// A `Bool` field as the game reads it: any non-zero byte is true.
346fn truthy(v: Option<&Value>) -> bool {
347    matches!(v, Some(Value::Bool(true))) || matches!(v, Some(Value::I8(b)) if *b != 0)
348}
349
350/// The blocks after the map; the event log from game-loop version 2.
351/// The object slot count in a `ResetPersistState` block (marker, size, version, count).
352fn persist_slots(block: &[u8]) -> u32 {
353    block
354        .get(12..16)
355        .map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap()))
356}
357
358/// `Graphics::AnimationManager::Serialize` with no animated instances: a count of 0.
359///
360/// Original: Runtime `0x1800fea20`.
361pub fn empty_animations() -> Vec<u8> {
362    let mut w = Writer::new();
363    let at = w.begin_block(0);
364    w.u32(0);
365    w.end_block(at);
366    w.data
367}
368
369// Each slot is written by Runtime 0x180053110; the five bytes are the scene's +0x30.
370/// The sound scene's block with nothing playing, as a new save writes it: 4,096 empty sound slots
371/// (a position, a value, the effect, a time, a value, the volume 1.0 and no points), then the five
372/// bytes that every sample save has.
373///
374/// Original: `Audio::Scene::Serialize`, Runtime `0x1800e28a0`.
375pub fn empty_audio_scene() -> Vec<u8> {
376    let mut w = Writer::new();
377    let at = w.begin_block(0);
378    w.u32(0x1000);
379    for _ in 0..0x1000 {
380        (0..3).for_each(|_| w.f32(0.0));
381        w.u32(0);
382        w.u32(u32::MAX);
383        w.i64(0);
384        w.u32(0);
385        w.f32(1.0);
386        w.u32(0);
387    }
388    w.bytes(&[0, 0, 1, 1, 1]);
389    w.end_block(at);
390    w.data
391}
392
393/// The blocks after the gameplay map (`jobs`, `tools`, `calendar`, `event_log`, `environment`,
394/// `minimap`) at serializer version `version`.
395pub fn managers(version: u32) -> Vec<Op> {
396    use crate::savegame_schema::{CALENDAR, ENVIRONMENT, EVENT_LOG, JOBS, MINIMAP, TOOLS};
397    let mut ops = vec![JOBS, TOOLS, CALENDAR];
398    if version > 1 {
399        ops.push(EVENT_LOG);
400    }
401    ops.extend([ENVIRONMENT, MINIMAP]);
402    ops
403}