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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
#![warn(missing_docs)]

//! Gvas
//!
//! UE4 Save File parsing library
//!
//! # Examples
//!
//! ```no_run
//! use gvas::{error::Error, GvasFile};
//! use std::{
//!     fs::File,
//! };
//!
//! let mut file = File::open("save.sav")?;
//! let gvas_file = GvasFile::read(&mut file);
//!
//! println!("{:#?}", gvas_file);
//! # Ok::<(), Error>(())
//! ```
//!
//! ## Hints
//!
//! If your file fails while parsing with a [`DeserializeError::MissingHint`] error you need hints.
//! When a struct is stored inside ArrayProperty/SetProperty/MapProperty in GvasFile it does not contain type annotations.
//! This means that a library parsing the file must know the type beforehand. That's why you need hints.
//!
//! The error usually looks like this:
//! ```no_run,ignore
//! MissingHint(
//!         "StructProperty" /* property type */,
//!         "UnLockedMissionParameters.MapProperty.Key.StructProperty" /* property path */,
//!         120550 /* position */)
//! ```
//! To get a hint type you need to look at the position of [`DeserializeError::MissingHint`] error.
//! Then you go to that position in the file and try to determine which type the struct has.
//! Afterwards you parse the file like this:
//!
//!
//!  [`DeserializeError::MissingHint`]: error/enum.DeserializeError.html#variant.MissingHint
//!
//! ```no_run
//! use gvas::{error::Error, GvasFile};
//! use std::{
//!     collections::HashMap,
//!     fs::File,
//! };
//!
//! let mut file = File::open("save.sav")?;
//!
//! let mut hints = HashMap::new();
//! hints.insert("UnLockedMissionParameters.MapProperty.Key.StructProperty".to_string(), "Guid".to_string());
//!
//! let gvas_file = GvasFile::read_with_hints(&mut file, &hints);
//!
//! println!("{:#?}", gvas_file);
//! # Ok::<(), Error>(())
//! ```

/// Extensions for `Cursor`.
pub mod cursor_ext;
/// Error types.
pub mod error;
/// Extensions for `Ord`.
mod ord_ext;
/// Property types.
pub mod properties;
pub(crate) mod scoped_stack_entry;
/// Various types.
pub mod types;

use std::{
    collections::HashMap,
    fmt::{Debug, Display},
    io::{Read, Seek, Write},
};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use cursor_ext::{ReadExt, WriteExt};
use error::Error;
use indexmap::IndexMap;
use ord_ext::OrdExt;
use properties::{Property, PropertyOptions, PropertyTrait};
use types::Guid;

use crate::error::DeserializeError;

/// Stores UE4 version in which the GVAS file was saved
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FEngineVersion {
    /// Major version number.
    pub major: u16,
    /// Minor version number.
    pub minor: u16,
    /// Patch version number.
    pub patch: u16,
    /// Build id.
    pub change_list: u32,
    /// Build id string.
    pub branch: String,
}

impl Display for FEngineVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}.{}.{}-{}+++{}",
            self.major, self.minor, self.patch, self.change_list, self.branch
        )
    }
}

impl FEngineVersion {
    /// Creates a new instance of `FEngineVersion`
    #[inline]
    pub fn new(major: u16, minor: u16, patch: u16, change_list: u32, branch: String) -> Self {
        FEngineVersion {
            major,
            minor,
            patch,
            change_list,
            branch,
        }
    }

    /// Read FEngineVersion from a binary file
    pub(crate) fn read<R: Read + Seek>(cursor: &mut R) -> Result<Self, Error> {
        let major = cursor.read_u16::<LittleEndian>()?;
        let minor = cursor.read_u16::<LittleEndian>()?;
        let patch = cursor.read_u16::<LittleEndian>()?;
        let change_list = cursor.read_u32::<LittleEndian>()?;
        let branch = cursor.read_string()?;
        Ok(FEngineVersion {
            major,
            minor,
            patch,
            change_list,
            branch,
        })
    }

    /// Write FEngineVersion to a binary file
    pub(crate) fn write<W: Write>(&self, cursor: &mut W) -> Result<(), Error> {
        cursor.write_u16::<LittleEndian>(self.major)?;
        cursor.write_u16::<LittleEndian>(self.minor)?;
        cursor.write_u16::<LittleEndian>(self.patch)?;
        cursor.write_u32::<LittleEndian>(self.change_list)?;
        cursor.write_string(&self.branch)?;
        Ok(())
    }
}

/// Stores CustomVersions serialized by UE4
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FCustomVersion {
    /// Key
    pub key: Guid,
    /// Value
    pub version: u32,
}

impl FCustomVersion {
    /// Creates a new instance of `FCustomVersion`
    #[inline]
    pub fn new(key: Guid, version: u32) -> Self {
        FCustomVersion { key, version }
    }

    /// Read FCustomVersion from a binary file
    pub(crate) fn read<R: Read + Seek>(cursor: &mut R) -> Result<Self, Error> {
        let key = cursor.read_guid()?;
        let version = cursor.read_u32::<LittleEndian>()?;

        Ok(FCustomVersion { key, version })
    }

    /// Write FCustomVersion to a binary file
    pub(crate) fn write<W: Write>(&self, cursor: &mut W) -> Result<(), Error> {
        cursor.write_guid(&self.key)?;
        cursor.write_u32::<LittleEndian>(self.version)?;
        Ok(())
    }
}

/// The four bytes 'GVAS' appear at the beginning of every GVAS file.
pub const FILE_TYPE_GVAS: u32 = u32::from_le_bytes([b'G', b'V', b'A', b'S']);

/// Stores information about GVAS file, engine version, etc.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "type"))]
pub enum GvasHeader {
    /// Version 2
    Version2 {
        /// File format version.
        package_file_version: u32,
        /// Unreal Engine version.
        engine_version: FEngineVersion,
        /// Custom version format.
        custom_version_format: u32,
        /// Custom versions.
        custom_versions: Vec<FCustomVersion>,
        /// Save game class name.
        save_game_class_name: String,
    },
    /// Version 3
    Version3 {
        /// File format version.
        package_file_version: u32,
        /// Unknown.
        unknown: u32,
        /// Unreal Engine version.
        engine_version: FEngineVersion,
        /// Custom version format.
        custom_version_format: u32,
        /// Custom versions.
        custom_versions: Vec<FCustomVersion>,
        /// Save game class name.
        save_game_class_name: String,
    },
}

impl GvasHeader {
    /// Read GvasHeader from a binary file
    ///
    /// # Errors
    ///
    /// If this function reads an invalid header it returns [`Error`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use gvas::{error::Error, GvasHeader};
    /// use std::{
    ///     fs::File,
    /// };
    ///
    /// let mut file = File::open("save.sav")?;
    ///
    /// let gvas_header = GvasHeader::read(&mut file)?;
    ///
    /// println!("{:#?}", gvas_header);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn read<R: Read + Seek>(cursor: &mut R) -> Result<Self, Error> {
        let file_type_tag = cursor.read_u32::<LittleEndian>()?;
        if file_type_tag != FILE_TYPE_GVAS {
            Err(DeserializeError::InvalidHeader(format!(
                "File type {file_type_tag} not recognized",
            )))?
        }

        let save_game_file_version = cursor.read_u32::<LittleEndian>()?;
        if !save_game_file_version.between(2, 3) {
            Err(DeserializeError::InvalidHeader(format!(
                "GVAS version {save_game_file_version} not supported"
            )))?
        }

        let package_file_version = cursor.read_u32::<LittleEndian>()?;
        if !package_file_version.between(0x205, 0x20A) {
            Err(DeserializeError::InvalidHeader(format!(
                "Package file version {package_file_version} not supported"
            )))?
        }

        // This field is only present in the v3 header
        let unknown = match save_game_file_version {
            3 => Some(cursor.read_u32::<LittleEndian>()?),
            _ => None,
        };

        let engine_version = FEngineVersion::read(cursor)?;
        let custom_version_format = cursor.read_u32::<LittleEndian>()?;
        if custom_version_format != 3 {
            Err(DeserializeError::InvalidHeader(format!(
                "Custom version format {custom_version_format} not supported"
            )))?
        }

        let custom_versions_len = cursor.read_u32::<LittleEndian>()? as usize;
        let mut custom_versions = Vec::with_capacity(custom_versions_len);
        for _ in 0..custom_versions_len {
            custom_versions.push(FCustomVersion::read(cursor)?);
        }

        let save_game_class_name = cursor.read_string()?;

        Ok(match unknown {
            None => GvasHeader::Version2 {
                package_file_version,
                engine_version,
                custom_version_format,
                custom_versions,
                save_game_class_name,
            },
            Some(unknown) => GvasHeader::Version3 {
                package_file_version,
                unknown,
                engine_version,
                custom_version_format,
                custom_versions,
                save_game_class_name,
            },
        })
    }

    /// Write GvasHeader to a binary file
    ///
    /// # Examples
    /// ```no_run
    /// use gvas::{error::Error, GvasHeader};
    /// use std::{
    ///     fs::File,
    ///     io::Cursor,
    /// };
    ///
    /// let mut file = File::open("save.sav")?;
    /// let gvas_header = GvasHeader::read(&mut file)?;
    ///
    /// let mut writer = Cursor::new(Vec::new());
    /// gvas_header.write(&mut writer)?;
    /// println!("{:#?}", writer.get_ref());
    /// # Ok::<(), Error>(())
    /// ```
    pub fn write<W: Write>(&self, cursor: &mut W) -> Result<(), Error> {
        cursor.write_u32::<LittleEndian>(FILE_TYPE_GVAS)?;
        match self {
            GvasHeader::Version2 {
                package_file_version,
                engine_version,
                custom_version_format,
                custom_versions,
                save_game_class_name,
            } => {
                cursor.write_u32::<LittleEndian>(2)?;
                cursor.write_u32::<LittleEndian>(*package_file_version)?;
                engine_version.write(cursor)?;
                cursor.write_u32::<LittleEndian>(*custom_version_format)?;
                cursor.write_u32::<LittleEndian>(custom_versions.len() as u32)?;

                for custom_version in custom_versions {
                    custom_version.write(cursor)?;
                }

                cursor.write_string(save_game_class_name)?;
            }
            GvasHeader::Version3 {
                package_file_version,
                unknown,
                engine_version,
                custom_version_format,
                custom_versions,
                save_game_class_name,
            } => {
                cursor.write_u32::<LittleEndian>(3)?;
                cursor.write_u32::<LittleEndian>(*package_file_version)?;
                cursor.write_u32::<LittleEndian>(*unknown)?;
                engine_version.write(cursor)?;
                cursor.write_u32::<LittleEndian>(*custom_version_format)?;
                cursor.write_u32::<LittleEndian>(custom_versions.len() as u32)?;

                for custom_version in custom_versions {
                    custom_version.write(cursor)?;
                }

                cursor.write_string(save_game_class_name)?;
            }
        }
        Ok(())
    }
}

/// Main UE4 save file struct
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GvasFile {
    /// GVAS file header.
    pub header: GvasHeader,
    /// GVAS properties.
    #[cfg_attr(feature = "serde", serde(with = "indexmap::serde_seq"))]
    pub properties: IndexMap<String, Property>,
}

trait GvasHeaderTrait {
    fn use_large_world_coordinates(&self) -> bool;
}

impl GvasHeaderTrait for GvasHeader {
    fn use_large_world_coordinates(&self) -> bool {
        match self {
            GvasHeader::Version2 {
                package_file_version: _,
                engine_version: _,
                custom_version_format: _,
                custom_versions: _,
                save_game_class_name: _,
            } => false,
            GvasHeader::Version3 {
                package_file_version: _,
                unknown: _,
                engine_version: _,
                custom_version_format: _,
                custom_versions: _,
                save_game_class_name: _,
            } => true,
        }
    }
}

impl GvasFile {
    /// Read GvasFile from a binary file
    ///
    /// # Errors
    ///
    /// If this function reads an invalid file it returns [`Error`]
    ///
    /// If this function reads a file which needs hints it returns [`DeserializeError::MissingHint`]
    ///
    /// [`DeserializeError::MissingHint`]: error/enum.DeserializeError.html#variant.MissingHint
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use gvas::{error::Error, GvasFile};
    /// use std::fs::File;
    ///
    /// let mut file = File::open("save.sav")?;
    /// let gvas_file = GvasFile::read(&mut file);
    ///
    /// println!("{:#?}", gvas_file);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn read<R: Read + Seek>(cursor: &mut R) -> Result<Self, Error> {
        let hints = HashMap::new();
        Self::read_with_hints(cursor, &hints)
    }

    /// Read GvasFile from a binary file
    ///
    /// # Errors
    ///
    /// If this function reads an invalid file it returns [`Error`]
    ///
    /// If this function reads a file which needs a hint that is missing it returns [`DeserializeError::MissingHint`]
    ///
    /// [`DeserializeError::MissingHint`]: error/enum.DeserializeError.html#variant.MissingHint
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use gvas::{error::Error, GvasFile};
    /// use std::{collections::HashMap, fs::File};
    ///
    /// let mut file = File::open("save.sav")?;
    ///
    /// let mut hints = HashMap::new();
    /// hints.insert(
    ///     "SeasonSave.StructProperty.Seasons.MapProperty.Key.StructProperty".to_string(),
    ///     "Guid".to_string(),
    /// );
    ///
    /// let gvas_file = GvasFile::read_with_hints(&mut file, &hints);
    ///
    /// println!("{:#?}", gvas_file);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn read_with_hints<R: Read + Seek>(
        cursor: &mut R,
        hints: &HashMap<String, String>,
    ) -> Result<Self, Error> {
        let header = GvasHeader::read(cursor)?;

        let mut options = PropertyOptions {
            hints,
            properties_stack: &mut vec![],
            large_world_coordinates: header.use_large_world_coordinates(),
        };

        let mut properties = IndexMap::new();
        loop {
            let property_name = cursor.read_string()?;
            if property_name == "None" {
                break;
            }

            let property_type = cursor.read_string()?;

            options.properties_stack.push(property_name.clone());

            let property = Property::new(cursor, &property_type, true, &mut options, None)?;
            properties.insert(property_name, property);

            let _ = options.properties_stack.pop();
        }

        Ok(GvasFile { header, properties })
    }

    /// Write GvasFile to a binary file
    ///
    /// # Errors
    ///
    /// If the file was modified in a way that makes it invalid this function returns [`Error`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use gvas::{error::Error, GvasFile};
    /// use std::{
    ///     fs::File,
    ///     io::Cursor,
    /// };
    ///
    /// let mut file = File::open("save.sav")?;
    /// let gvas_file = GvasFile::read(&mut file)?;
    ///
    /// let mut writer = Cursor::new(Vec::new());
    /// gvas_file.write(&mut writer)?;
    /// println!("{:#?}", writer.get_ref());
    /// # Ok::<(), Error>(())
    /// ```
    pub fn write<W: Write + Seek>(&self, cursor: &mut W) -> Result<(), Error> {
        self.header.write(cursor)?;

        let mut options = PropertyOptions {
            hints: &HashMap::new(),
            properties_stack: &mut vec![],
            large_world_coordinates: self.header.use_large_world_coordinates(),
        };

        for (name, property) in &self.properties {
            cursor.write_string(name)?;
            property.write(cursor, true, &mut options)?;
        }
        cursor.write_string("None")?;
        cursor.write_i32::<LittleEndian>(0)?; // padding
        Ok(())
    }
}