1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
use std::{
    fs,
    io::Read,
    path::{Path, PathBuf},
};

use common::{assets::ASSETS_PATH, consts::DAY_LENGTH_DEFAULT};
use serde::{Deserialize, Serialize};
use server::{FileOpts, GenOpts, DEFAULT_WORLD_MAP, DEFAULT_WORLD_SEED};
use tracing::error;

pub struct SingleplayerWorld {
    pub name: String,
    pub gen_opts: Option<GenOpts>,
    pub day_length: f64,
    pub seed: u32,
    pub is_generated: bool,
    pub path: PathBuf,
    pub map_path: PathBuf,
}

impl SingleplayerWorld {
    pub fn copy_default_world(&self) {
        if let Err(e) = fs::copy(asset_path(DEFAULT_WORLD_MAP), &self.map_path) {
            println!("Error when trying to copy default world: {e}");
        }
    }
}

fn load_map(path: &Path) -> Option<SingleplayerWorld> {
    let meta_path = path.join("meta.ron");

    let Ok(f) = fs::File::open(&meta_path) else {
        error!("Failed to open {}", meta_path.to_string_lossy());
        return None;
    };

    let Ok(bytes) = f.bytes().collect::<Result<Vec<u8>, _>>() else {
        error!("Failed to read {}", meta_path.to_string_lossy());
        return None;
    };

    version::try_load(std::io::Cursor::new(bytes), path)
}

fn write_world_meta(world: &SingleplayerWorld) {
    let path = &world.path;

    if let Err(e) = fs::create_dir_all(path) {
        error!("Failed to create world folder: {e}");
    }

    match fs::File::create(path.join("meta.ron")) {
        Ok(file) => {
            if let Err(e) = ron::ser::to_writer_pretty(
                file,
                &version::Current::from_world(world),
                ron::ser::PrettyConfig::new(),
            ) {
                error!("Failed to create world meta file: {e}")
            }
        },
        Err(e) => error!("Failed to create world meta file: {e}"),
    }
}

fn asset_path(asset: &str) -> PathBuf {
    let mut s = asset.replace('.', "/");
    s.push_str(".bin");
    ASSETS_PATH.join(s)
}

fn migrate_old_singleplayer(from: &Path, to: &Path) {
    if fs::metadata(from).map_or(false, |meta| meta.is_dir()) {
        if let Err(e) = fs::rename(from, to) {
            error!("Failed to migrate singleplayer: {e}");
            return;
        }

        let mut seed = DEFAULT_WORLD_SEED;
        let mut day_length = DAY_LENGTH_DEFAULT;
        let (map_file, gen_opts) = fs::read_to_string(to.join("server_config/settings.ron"))
            .ok()
            .and_then(|settings| {
                let settings: server::Settings = ron::from_str(&settings).ok()?;
                seed = settings.world_seed;
                day_length = settings.day_length;
                Some(match settings.map_file? {
                    FileOpts::LoadOrGenerate { name, opts, .. } => {
                        (Some(PathBuf::from(name)), Some(opts))
                    },
                    FileOpts::Generate(opts) => (None, Some(opts)),
                    FileOpts::LoadLegacy(_) => return None,
                    FileOpts::Load(path) => (Some(path), None),
                    FileOpts::LoadAsset(asset) => (Some(asset_path(&asset)), None),
                    FileOpts::Save(_, gen_opts) => (None, Some(gen_opts)),
                })
            })
            .unwrap_or((Some(asset_path(DEFAULT_WORLD_MAP)), None));

        let map_path = to.join("map.bin");
        if let Some(map_file) = map_file {
            if let Err(err) = fs::copy(map_file, &map_path) {
                error!("Failed to copy map file to singleplayer world: {err}");
            }
        }

        write_world_meta(&SingleplayerWorld {
            name: "singleplayer world".to_string(),
            gen_opts,
            seed,
            day_length,
            path: to.to_path_buf(),
            // Isn't persisted so doesn't matter what it's set to.
            is_generated: false,
            map_path,
        });
    }
}

fn load_worlds(path: &Path) -> Vec<SingleplayerWorld> {
    let Ok(paths) = fs::read_dir(path) else {
        let _ = fs::create_dir_all(path);
        return Vec::new();
    };

    paths
        .filter_map(|entry| {
            let entry = entry.ok()?;
            if entry.file_type().ok()?.is_dir() {
                let path = entry.path();
                load_map(&path)
            } else {
                None
            }
        })
        .collect()
}

#[derive(Default)]
pub struct SingleplayerWorlds {
    pub worlds: Vec<SingleplayerWorld>,
    pub current: Option<usize>,
    worlds_folder: PathBuf,
}

impl SingleplayerWorlds {
    pub fn load(userdata_folder: &Path) -> SingleplayerWorlds {
        let worlds_folder = userdata_folder.join("singleplayer_worlds");

        if let Err(e) = fs::create_dir_all(&worlds_folder) {
            error!("Failed to create singleplayer worlds folder: {e}");
        }

        migrate_old_singleplayer(
            &userdata_folder.join("singleplayer"),
            &worlds_folder.join("singleplayer"),
        );

        let worlds = load_worlds(&worlds_folder);

        SingleplayerWorlds {
            worlds,
            current: None,
            worlds_folder,
        }
    }

    pub fn delete_map_file(&mut self, map: usize) {
        let w = &mut self.worlds[map];
        if w.is_generated {
            // We don't care about the result here since we aren't sure the file exists.
            let _ = fs::remove_file(&w.map_path);
        }
        w.is_generated = false;
    }

    pub fn remove(&mut self, idx: usize) {
        if let Some(ref mut i) = self.current {
            match (*i).cmp(&idx) {
                std::cmp::Ordering::Less => {},
                std::cmp::Ordering::Equal => self.current = None,
                std::cmp::Ordering::Greater => *i -= 1,
            }
        }
        let _ = fs::remove_dir_all(&self.worlds[idx].path);
        self.worlds.remove(idx);
    }

    fn world_folder_name(&self) -> String {
        use chrono::{Datelike, Timelike};
        let now = chrono::Local::now().naive_local();
        let name = format!(
            "world-{}-{}-{}-{}_{}_{}_{}",
            now.year(),
            now.month(),
            now.day(),
            now.hour(),
            now.minute(),
            now.second(),
            now.and_utc().timestamp_subsec_millis() /* .and_utc() necessary, as other fn is
                                                     * deprecated */
        );

        let mut test_name = name.clone();
        let mut i = 0;
        'fail: loop {
            for world in self.worlds.iter() {
                if world.path.ends_with(&test_name) {
                    test_name.clone_from(&name);
                    test_name.push('_');
                    test_name.push_str(&i.to_string());
                    i += 1;
                    continue 'fail;
                }
            }
            break;
        }
        test_name
    }

    pub fn current(&self) -> Option<&SingleplayerWorld> {
        self.current.and_then(|i| self.worlds.get(i))
    }

    pub fn new_world(&mut self) {
        let folder_name = self.world_folder_name();
        let path = self.worlds_folder.join(folder_name);

        let new_world = SingleplayerWorld {
            name: "New World".to_string(),
            gen_opts: None,
            day_length: DAY_LENGTH_DEFAULT,
            seed: DEFAULT_WORLD_SEED,
            is_generated: false,
            map_path: path.join("map.bin"),
            path,
        };

        write_world_meta(&new_world);

        self.worlds.push(new_world)
    }

    pub fn save_current_meta(&self) {
        if let Some(world) = self.current() {
            write_world_meta(world);
        }
    }
}

mod version {
    use std::any::{type_name, Any};

    use serde::de::DeserializeOwned;

    use super::*;

    pub type Current = V2;

    type LoadWorldFn<R> =
        fn(R, &Path) -> Result<SingleplayerWorld, (&'static str, ron::de::SpannedError)>;
    fn loaders<'a, R: std::io::Read + Clone>() -> &'a [LoadWorldFn<R>] {
        // Step [4]
        &[load_raw::<V2, _>, load_raw::<V1, _>]
    }

    #[derive(Deserialize, Serialize)]
    pub struct V1 {
        #[serde(deserialize_with = "version::<_, 1>")]
        version: u64,
        name: String,
        gen_opts: Option<GenOpts>,
        seed: u32,
    }

    impl ToWorld for V1 {
        fn to_world(self, path: PathBuf) -> SingleplayerWorld {
            let map_path = path.join("map.bin");
            let is_generated = fs::metadata(&map_path).is_ok_and(|f| f.is_file());

            SingleplayerWorld {
                name: self.name,
                gen_opts: self.gen_opts,
                seed: self.seed,
                day_length: DAY_LENGTH_DEFAULT,
                is_generated,
                path,
                map_path,
            }
        }
    }

    #[derive(Deserialize, Serialize)]
    pub struct V2 {
        #[serde(deserialize_with = "version::<_, 2>")]
        version: u64,
        name: String,
        gen_opts: Option<GenOpts>,
        seed: u32,
        day_length: f64,
    }

    impl V2 {
        pub fn from_world(world: &SingleplayerWorld) -> Self {
            V2 {
                version: 2,
                name: world.name.clone(),
                gen_opts: world.gen_opts.clone(),
                seed: world.seed,
                day_length: world.day_length,
            }
        }
    }

    impl ToWorld for V2 {
        fn to_world(self, path: PathBuf) -> SingleplayerWorld {
            let map_path = path.join("map.bin");
            let is_generated = fs::metadata(&map_path).is_ok_and(|f| f.is_file());

            SingleplayerWorld {
                name: self.name,
                gen_opts: self.gen_opts,
                seed: self.seed,
                day_length: self.day_length,
                is_generated,
                path,
                map_path,
            }
        }
    }

    // Utilities
    fn version<'de, D: serde::Deserializer<'de>, const V: u64>(de: D) -> Result<u64, D::Error> {
        u64::deserialize(de).and_then(|x| {
            if x == V {
                Ok(x)
            } else {
                Err(serde::de::Error::invalid_value(
                    serde::de::Unexpected::Unsigned(x),
                    &"incorrect magic/version bytes",
                ))
            }
        })
    }

    trait ToWorld {
        fn to_world(self, path: PathBuf) -> SingleplayerWorld;
    }

    fn load_raw<RawWorld: Any + ToWorld + DeserializeOwned, R: std::io::Read + Clone>(
        reader: R,
        path: &Path,
    ) -> Result<SingleplayerWorld, (&'static str, ron::de::SpannedError)> {
        ron::de::from_reader::<_, RawWorld>(reader)
            .map(|s| s.to_world(path.to_path_buf()))
            .map_err(|e| (type_name::<RawWorld>(), e))
    }

    pub fn try_load<R: std::io::Read + Clone>(reader: R, path: &Path) -> Option<SingleplayerWorld> {
        loaders()
            .iter()
            .find_map(|load_raw| match load_raw(reader.clone(), path) {
                Ok(chunk) => Some(chunk),
                Err((raw_name, e)) => {
                    error!(
                        "Attempt to load chunk with raw format `{}` failed: {:?}",
                        raw_name, e
                    );
                    None
                },
            })
    }
}