Skip to main content

ob_game/game/
save.rs

1//! Saved games: the complete mutable game state serialized with bincode.
2//! Static data (tiles, animations, sounds) is reloaded from the original files.
3
4use super::{Ai, Game};
5use crate::anim::AnimLib;
6use crate::inventory::{Inventory, Powerups};
7use crate::player::Player;
8use crate::resources::Resources;
9use crate::triggers::Triggers;
10use crate::weapons::Arsenal;
11use crate::world::World;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::io;
15use std::path::{Path, PathBuf};
16
17const MAGIC: &str = "OPENBLOOD-SAVE";
18const VERSION: u32 = 2;
19
20#[derive(Serialize, Deserialize)]
21struct SaveGame {
22    magic: String,
23    version: u32,
24    /// Shown in the load menu.
25    title: String,
26    world: World,
27    player: Player,
28    triggers: Triggers,
29    arsenal: Arsenal,
30    inventory: Inventory,
31    powerups: Powerups,
32    air: f64,
33    clock: i32,
34    kills: i32,
35    total_kills: i32,
36    skill: i32,
37    last_sector: i32,
38    rng: u32,
39    ai: Vec<Ai>,
40    attack_cd: Vec<f64>,
41    provoked: Vec<bool>,
42    sees: Vec<bool>,
43    pic_for_type: HashMap<i16, i16>,
44    level_messages: HashMap<u32, String>,
45}
46
47/// Borrowed mirror of [`SaveGame`] (same field order, so bincode output matches).
48#[derive(Serialize)]
49struct SaveRef<'a> {
50    magic: &'a str,
51    version: u32,
52    title: &'a str,
53    world: &'a World,
54    player: &'a Player,
55    triggers: &'a Triggers,
56    arsenal: &'a Arsenal,
57    inventory: &'a Inventory,
58    powerups: &'a Powerups,
59    air: f64,
60    clock: i32,
61    kills: i32,
62    total_kills: i32,
63    skill: i32,
64    last_sector: i32,
65    rng: u32,
66    ai: &'a Vec<Ai>,
67    attack_cd: &'a Vec<f64>,
68    provoked: &'a Vec<bool>,
69    sees: &'a Vec<bool>,
70    pic_for_type: &'a HashMap<i16, i16>,
71    level_messages: &'a HashMap<u32, String>,
72}
73
74/// Minimal header used to list saves without loading them fully.
75#[derive(Deserialize)]
76struct SaveHeader {
77    magic: String,
78    version: u32,
79    title: String,
80}
81
82fn invalid(m: impl Into<String>) -> io::Error {
83    io::Error::new(io::ErrorKind::InvalidData, m.into())
84}
85
86impl Game {
87    /// Serializes the game; `title` describes the save (map, time...).
88    pub fn save_bytes(&self, title: &str) -> io::Result<Vec<u8>> {
89        let sg = SaveRef {
90            magic: MAGIC,
91            version: VERSION,
92            title,
93            world: &self.world,
94            player: &self.player,
95            triggers: &self.triggers,
96            arsenal: &self.arsenal,
97            inventory: &self.inventory,
98            powerups: &self.powerups,
99            air: self.air,
100            clock: self.clock,
101            kills: self.kills,
102            total_kills: self.total_kills,
103            skill: self.skill,
104            last_sector: self.last_sector,
105            rng: self.rng,
106            ai: &self.ai,
107            attack_cd: &self.attack_cd,
108            provoked: &self.provoked,
109            sees: &self.sees,
110            pic_for_type: &self.pic_for_type,
111            level_messages: &self.level_messages,
112        };
113        bincode::serialize(&sg).map_err(|e| invalid(e.to_string()))
114    }
115
116    /// Restores a game saved with [`Game::save_bytes`].
117    pub fn from_save(res: &Resources, bytes: &[u8]) -> io::Result<Game> {
118        let sg: SaveGame = bincode::deserialize(bytes).map_err(|e| invalid(format!("corrupt save: {e}")))?;
119        if sg.magic != MAGIC || sg.version != VERSION {
120            return Err(invalid("not an OpenBlood save (or from another version)"));
121        }
122        let n = sg.world.sprites.len();
123        let mut triggers = sg.triggers;
124        triggers.rebuild(&sg.world);
125        let mut g = Game {
126            world: sg.world,
127            player: sg.player,
128            triggers,
129            arsenal: sg.arsenal,
130            anims: AnimLib::new(&res.blood),
131            clock: sg.clock,
132            events: Vec::new(),
133            messages: Vec::new(),
134            kills: sg.kills,
135            total_kills: sg.total_kills,
136            damage_flash: 0.0,
137            pickup_flash: 0.0,
138            skill: sg.skill,
139            last_sector: sg.last_sector,
140            acc: 0.0,
141            use_down: true,
142            rng: sg.rng,
143            ai: sg.ai,
144            attack_cd: sg.attack_cd,
145            pic_for_type: sg.pic_for_type,
146            weapon_switch_down: false,
147            level_messages: sg.level_messages,
148            inventory: sg.inventory,
149            powerups: sg.powerups,
150            air: sg.air,
151            inv_keys: (true, true, true),
152            provoked: sg.provoked,
153            sees: sg.sees,
154            burn_kill: false,
155            prev_xyz: Vec::new(),
156            prev_eye: (0.0, 0.0, 0.0),
157            started: true,
158        };
159        g.ai.resize(n, Ai::Idle);
160        g.attack_cd.resize(n, 0.0);
161        g.provoked.resize(n, false);
162        g.sees.resize(n, false);
163        Ok(g)
164    }
165
166    pub fn save_to(&self, path: &Path, title: &str) -> io::Result<()> {
167        if let Some(dir) = path.parent() {
168            std::fs::create_dir_all(dir)?;
169        }
170        let bytes = self.save_bytes(title)?;
171        // Write atomically so a crash can't corrupt an existing save.
172        let tmp = path.with_extension("tmp");
173        std::fs::write(&tmp, bytes)?;
174        std::fs::rename(&tmp, path)
175    }
176
177    pub fn load_from(res: &Resources, path: &Path) -> io::Result<Game> {
178        Game::from_save(res, &std::fs::read(path)?)
179    }
180}
181
182/// Save slot file: `dir/SAVEn.OBS` (slot 0 = quick save).
183pub fn slot_path(dir: &Path, slot: usize) -> PathBuf {
184    if slot == 0 {
185        dir.join("QUICK.OBS")
186    } else {
187        dir.join(format!("SAVE{slot}.OBS"))
188    }
189}
190
191/// Title stored in a save file, if it is a valid OpenBlood save.
192pub fn slot_title(path: &Path) -> Option<String> {
193    let b = std::fs::read(path).ok()?;
194    let h: SaveHeader = bincode::deserialize(&b).ok()?;
195    (h.magic == MAGIC && h.version == VERSION).then_some(h.title)
196}