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
//! Provides an Age of Empires series recorded game file reader.
//!
//! ## Version Support
//! This crate can read Age of Empires 1, Age of Empires 2: The Conquerors, and HD Edition recorded game files.
//!
//! ## Credits
//! Most of the `.mgl`, `.mgx`, `.mgz` format specification was taken from Bari's classic [mgx
//! format description][], the [recage][] Node.js library, and Happyleaves' [aoc-mgz][] Python library.
//!
//! [mgx format description]: https://web.archive.org/web/20090215065209/http://members.at.infoseek.co.jp/aocai/mgx_format.html
//! [recage]: https://github.com/genie-js/recage
//! [aoc-mgz]: https://github.com/happyleavesaoc/aoc-mgz

pub mod actions;
pub mod ai;
pub mod header;
pub mod map;
pub mod player;
pub mod string_table;
pub mod unit;
pub mod unit_action;
pub mod unit_type;

use crate::actions::{Action, Meta};
use byteorder::{ReadBytesExt, LE};
use flate2::bufread::DeflateDecoder;
use genie_scx::DLCOptions;
use genie_support::{fallible_try_from, fallible_try_into, infallible_try_into};
pub use header::Header;
use std::fmt::{self, Debug, Display};
use std::io::{self, BufRead, BufReader, Read, Seek, SeekFrom};

/// ID identifying a player (0-8).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct PlayerID(u8);

impl PlayerID {
    /// Player ID for GAIA, the "nature" player.
    pub const GAIA: Self = Self(0);
}

impl From<u8> for PlayerID {
    #[inline]
    fn from(n: u8) -> Self {
        Self(n)
    }
}

impl From<PlayerID> for u8 {
    #[inline]
    fn from(player_id: PlayerID) -> Self {
        player_id.0
    }
}

fallible_try_from!(PlayerID, i32);
fallible_try_from!(PlayerID, u32);
fallible_try_from!(PlayerID, i16);
fallible_try_from!(PlayerID, u16);
fallible_try_from!(PlayerID, i8);
infallible_try_into!(PlayerID, i16);
infallible_try_into!(PlayerID, u16);
infallible_try_into!(PlayerID, i32);
infallible_try_into!(PlayerID, u32);

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ObjectID(u32);

impl From<u32> for ObjectID {
    #[inline]
    fn from(n: u32) -> Self {
        Self(n)
    }
}

impl From<u16> for ObjectID {
    #[inline]
    fn from(n: u16) -> Self {
        Self(n.into())
    }
}

impl From<ObjectID> for u32 {
    #[inline]
    fn from(n: ObjectID) -> Self {
        n.0
    }
}

fallible_try_from!(ObjectID, i16);
fallible_try_from!(ObjectID, i32);
fallible_try_into!(ObjectID, i16);
fallible_try_into!(ObjectID, i32);

/// The game data version string. In practice, this does not really reflect the game version.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct GameVersion([u8; 8]);

impl Default for GameVersion {
    fn default() -> Self {
        Self([0; 8])
    }
}

impl Debug for GameVersion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", std::str::from_utf8(&self.0).unwrap())
    }
}

impl Display for GameVersion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", std::str::from_utf8(&self.0).unwrap())
    }
}

impl GameVersion {
    /// Read the game version string from an input stream.
    pub fn read_from(mut input: impl Read) -> Result<Self> {
        let mut game_version = [0; 8];
        input.read_exact(&mut game_version)?;
        Ok(Self(game_version))
    }
}

/// Errors that may occur while reading a recorded game file.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    IoError(#[from] io::Error),
    #[error(transparent)]
    DecodeStringError(#[from] genie_support::DecodeStringError),
    #[error("Could not read embedded scenario data: {0}")]
    ReadScenarioError(#[from] genie_scx::Error),
}

impl From<genie_support::ReadStringError> for Error {
    fn from(err: genie_support::ReadStringError) -> Self {
        match err {
            genie_support::ReadStringError::DecodeStringError(inner) => inner.into(),
            genie_support::ReadStringError::IoError(inner) => inner.into(),
        }
    }
}

/// Result type alias with `genie_rec::Error` as the error type.
pub type Result<T> = std::result::Result<T, Error>;

/// Iterator over body actions.
pub struct BodyActions<R>
where
    R: BufRead,
{
    input: R,
    version: f32,
    meta: Meta,
    remaining_syncs_until_checksum: u32,
}

impl<R> BodyActions<R>
where
    R: BufRead,
{
    pub fn new(mut input: R, version: f32) -> Result<Self> {
        let meta = if version >= 11.76 {
            Meta::read_from_mgx(&mut input)?
        } else {
            Meta::read_from_mgl(&mut input)?
        };
        let remaining_syncs_until_checksum = meta.checksum_interval;
        Ok(Self {
            input,
            version,
            meta,
            remaining_syncs_until_checksum,
        })
    }
}

impl<R> Iterator for BodyActions<R>
where
    R: BufRead,
{
    type Item = Result<Action>;
    fn next(&mut self) -> Option<Self::Item> {
        match self.input.read_i32::<LE>() {
            Ok(0x01) => Some(actions::Command::read_from(&mut self.input).map(Action::Command)),
            Ok(0x02) => {
                self.remaining_syncs_until_checksum -= 1;
                let includes_checksum = self.remaining_syncs_until_checksum == 0;
                if includes_checksum {
                    self.remaining_syncs_until_checksum = self.meta.checksum_interval;
                }
                Some(
                    actions::Sync::read_from(
                        &mut self.input,
                        self.meta.use_sequence_numbers,
                        includes_checksum,
                    )
                    .map(Action::Sync),
                )
            }
            Ok(0x03) => Some(actions::ViewLock::read_from(&mut self.input).map(Action::ViewLock)),
            Ok(0x04) => Some(actions::Chat::read_from(&mut self.input).map(Action::Chat)),
            Ok(id) => panic!("unsupported action type {:#x}", id),
            Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => None,
            Err(err) => Some(Err(err.into())),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Difficulty {
    Easiest,
    Easy,
    Standard,
    Hard,
    Hardest,
    /// Age of Empires 2: Definitive Edition only.
    Extreme,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MapSize {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MapType {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Visibility {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ResourceLevel {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Age {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GameMode {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GameSpeed {}

#[derive(Debug, Clone)]
pub struct HDGameOptions {
    pub dlc_options: DLCOptions,
    pub difficulty: Difficulty,
    pub map_size: MapSize,
    pub map_type: MapType,
    pub visibility: Visibility,
    pub starting_resources: ResourceLevel,
    pub starting_age: Age,
    pub ending_age: Age,
    pub game_mode: GameMode,
    // if version < 1001
    pub random_map_name: Option<String>,
    // if version < 1001
    pub scenario_name: Option<String>,
    pub game_speed: GameSpeed,
    pub treaty_length: i32,
    pub population_limit: i32,
    pub num_players: i32,
    pub victory_amount: i32,
    pub trading_enabled: bool,
    pub team_bonuses_enabled: bool,
    pub randomize_positions_enabled: bool,
    pub full_tech_tree_enabled: bool,
    pub num_starting_units: i8,
    pub teams_locked: bool,
    pub speed_locked: bool,
    pub multiplayer: bool,
    pub cheats_enabled: bool,
    pub record_game: bool,
    pub animals_enabled: bool,
    pub predators_enabled: bool,
    // if version > 1.16 && version < 1002
    pub scenario_player_indices: Vec<i32>,
}

/// A struct implementing `BufRead` that uses a small, single-use, stack-allocated buffer, intended
/// for reading only the first few bytes from a file.
struct SmallBufReader<R>
where
    R: Read,
{
    buffer: [u8; 256],
    pointer: usize,
    reader: R,
}

impl<R> SmallBufReader<R>
where
    R: Read,
{
    fn new(reader: R) -> Self {
        Self {
            buffer: [0; 256],
            pointer: 0,
            reader,
        }
    }
}

impl<R> Read for SmallBufReader<R>
where
    R: Read,
{
    fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
        self.reader.read(output)
    }
}

impl<R> BufRead for SmallBufReader<R>
where
    R: Read,
{
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        self.reader.read_exact(&mut self.buffer[self.pointer..])?;
        Ok(&self.buffer[self.pointer..])
    }

    fn consume(&mut self, len: usize) {
        self.pointer += len;
    }
}

/// Recorded game reader.
pub struct RecordedGame<R>
where
    R: Read + Seek,
{
    inner: R,
    /// Offset of the main compressed header.
    header_start: u64,
    /// Size of the compressed header.
    header_end: u64,
    /// Offset of the next header, for saved chapters.
    next_header: Option<u64>,
    game_version: GameVersion,
    save_version: f32,
}

impl<R> RecordedGame<R>
where
    R: Read + Seek,
{
    pub fn new(mut input: R) -> Result<Self> {
        let file_size = {
            let size = input.seek(SeekFrom::End(0))?;
            input.seek(SeekFrom::Start(0))?;
            size
        };

        let header_end = u64::from(input.read_u32::<LE>()?);
        let next_header = u64::from(input.read_u32::<LE>()?);

        let header_start = if next_header > file_size { 4 } else { 8 };

        let next_header = if next_header > 0 && next_header < file_size {
            Some(next_header)
        } else {
            None
        };

        let (game_version, save_version) = {
            input.seek(SeekFrom::Start(header_start))?;
            let version_reader = SmallBufReader::new(&mut input);
            let mut deflate = DeflateDecoder::new(version_reader);
            let game_version = GameVersion::read_from(&mut deflate)?;
            let save_version = deflate.read_f32::<LE>()?;
            (game_version, save_version)
        };

        Ok(Self {
            inner: input,
            header_start,
            header_end,
            next_header,
            game_version,
            save_version,
        })
    }

    fn seek_to_first_header(&mut self) -> Result<()> {
        self.inner.seek(SeekFrom::Start(self.header_start))?;

        Ok(())
    }

    fn seek_to_body(&mut self) -> Result<()> {
        self.inner.seek(SeekFrom::Start(self.header_end))?;

        Ok(())
    }

    pub fn header(&mut self) -> Result<Header> {
        self.seek_to_first_header()?;
        let reader = BufReader::new(&mut self.inner).take(self.header_end - self.header_start);
        let deflate = DeflateDecoder::new(reader);
        let header = Header::read_from(deflate)?;
        Ok(header)
    }

    pub fn actions(&mut self) -> Result<BodyActions<BufReader<&mut R>>> {
        self.seek_to_body()?;
        BodyActions::new(BufReader::new(&mut self.inner), self.save_version)
    }

    pub fn into_inner(self) -> R {
        self.inner
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;

    #[test]
    // AI data parsing is incomplete: remove this attribute when the test starts passing
    #[should_panic]
    fn incomplete_up_15_rec_with_ai() {
        let f = File::open("test/rec.20181208-195117.mgz").unwrap();
        let mut r = RecordedGame::new(f).unwrap();
        r.header().expect("AI data cannot be fully parsed");
        for act in r.actions().unwrap() {
            let _act = act.unwrap();
        }
    }

    #[test]
    fn aoc_1_0_rec() -> anyhow::Result<()> {
        let f = File::open("test/missyou_finally_vs_11.mgx")?;
        let mut r = RecordedGame::new(f)?;
        r.header()?;
        for act in r.actions()? {
            match act {
                Ok(act) => println!("{:?}", act),
                Err(Error::DecodeStringError(_)) => {
                    // Skip invalid utf8 chat for now
                }
                Err(err) => return Err(err.into()),
            }
        }
        Ok(())
    }

    #[test]
    fn aok_rec() -> anyhow::Result<()> {
        let f = File::open("test/aok.mgl")?;
        let mut r = RecordedGame::new(f)?;
        r.header()?;
        for act in r.actions()? {
            println!("{:?}", act?);
        }
        Ok(())
    }
}