pak 0.7.4

An easy-to-use data pak format for games.
Documentation
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
pub mod anim;
pub mod bitmap;
pub mod bitmap_font;
pub mod index;
pub mod mesh;
pub mod scene;

#[cfg(feature = "bake")]
pub mod buf;

mod compression;

use {
    self::{
        anim::Animation, bitmap::Bitmap, bitmap_font::BitmapFont, compression::Compression,
        mesh::Mesh, scene::Scene,
    },
    bitflags::bitflags,
    log::{trace, warn},
    paste::paste,
    serde::{Deserialize, Serialize, de::DeserializeOwned},
    std::{
        collections::HashMap,
        fmt::{Debug, Formatter},
        fs::File,
        io::{BufReader, Cursor, Error, ErrorKind, Read, Seek, SeekFrom},
        mem::size_of,
        ops::Range,
        path::{Path, PathBuf},
    },
};

pub type Vec3 = [f32; 3];
pub type Quat = [f32; 4];
pub type Mat4 = [f32; 16];

pub(crate) const PAK_HASH_LEN: usize = size_of::<u64>();

const FNV_OFFSET: u64 = 0xcbf29ce484222325;
const FNV_PRIME: u64 = 0x100000001b3;

fn update_hash(hash: u64, data: &[u8]) -> u64 {
    data.iter().fold(hash, |hash, byte| {
        (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
    })
}

pub(crate) fn pak_hash_stream(reader: &mut impl Read, len: u64) -> Result<u64, Error> {
    let mut hash = FNV_OFFSET;
    let mut remaining = len;
    let mut buf = [0; 8192];

    while remaining > 0 {
        let limit = if remaining < buf.len() as u64 {
            remaining as usize
        } else {
            buf.len()
        };
        let read = reader.read(&mut buf[..limit])?;
        if read == 0 {
            return Err(Error::from(ErrorKind::UnexpectedEof));
        }

        hash = update_hash(hash, &buf[..read]);
        remaining -= read as u64;
    }

    Ok(hash)
}

fn read_hash_trailer(reader: &mut impl Read) -> Result<u64, Error> {
    let mut hash = [0; PAK_HASH_LEN];
    reader.read_exact(&mut hash)?;
    let (hash, consumed) =
        bincode::serde::decode_from_slice::<u64, _>(&hash, bincode::config::legacy())
            .map_err(|_| Error::from(ErrorKind::InvalidData))?;

    if consumed == PAK_HASH_LEN {
        Ok(hash)
    } else {
        Err(Error::from(ErrorKind::InvalidData))
    }
}

#[derive(Debug, Default, Deserialize, Serialize)]
struct Data {
    // These fields are handled by bincode serialization as-is
    ids: HashMap<String, Id>,
    materials: Vec<MaterialInfo>,

    // These fields are loaded on demand
    anims: Vec<DataRef<Animation>>,
    bitmap_fonts: Vec<DataRef<BitmapFont>>,
    bitmaps: Vec<DataRef<Bitmap>>,
    blobs: Vec<DataRef<Vec<u8>>>,
    meshes: Vec<DataRef<Mesh>>,
    scenes: Vec<DataRef<Scene>>,
}

#[derive(Deserialize, PartialEq, Serialize)]
enum DataRef<T> {
    Data(T),
    Ref(Range<u32>),
}

impl<T> DataRef<T> {
    fn pos_len(&self) -> Result<(u64, usize), Error> {
        match self {
            Self::Ref(range) => {
                let len = range
                    .end
                    .checked_sub(range.start)
                    .ok_or_else(|| Error::from(ErrorKind::InvalidData))?;

                Ok((range.start as _, len as _))
            }
            _ => {
                warn!("Expected position and length but found data");

                Err(Error::from(ErrorKind::InvalidInput))
            }
        }
    }
}

impl<T> DataRef<T>
where
    T: Serialize,
{
    #[cfg(feature = "bake")]
    fn serialize(&self) -> Result<Vec<u8>, Error> {
        let mut buf = vec![];
        let data = match self {
            Self::Data(t) => t,
            Self::Ref(_) => return Err(Error::from(ErrorKind::InvalidData)),
        };
        bincode::serde::encode_into_std_write(data, &mut buf, bincode::config::legacy())
            .map_err(|_| Error::from(ErrorKind::InvalidData))?;

        Ok(buf)
    }
}

impl<T> Debug for DataRef<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Data(_) => "Data",
            Self::Ref(_) => "DataRef",
        })
    }
}

macro_rules! id_enum {
    ($($variant:ident),*) => {
        paste::paste! {
            #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
            enum Id {
                $(
                    $variant([<$variant Id>]),
                )*
            }

            impl Id {
                $(
                    fn [<as_ $variant:snake>](&self) -> Option<[<$variant Id>]> {
                        match self {
                            Self::$variant(id) => Some(*id),
                            _ => None,
                        }
                    }
                )*
            }

            $(
                impl From<[<$variant Id>]> for Id {
                    fn from(id: [<$variant Id>]) -> Self {
                        Self::$variant(id)
                    }
                }
            )*
        }
    };
}

id_enum!(Animation, Bitmap, BitmapFont, Blob, Material, Mesh, Scene);

macro_rules! id_struct {
    ($name: ident) => {
        paste! {
            #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord,
                Serialize)]
            pub struct [<$name Id>](pub usize);
        }
    };
}

id_struct!(Animation);
id_struct!(Bitmap);
id_struct!(BitmapFont);
id_struct!(Blob);
id_struct!(Material);
id_struct!(Mesh);
id_struct!(Scene);

/// Holds bitmap handles to match what was setup in the asset `.toml` file.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MaterialInfo {
    /// Three or four channel base color, aka albedo or diffuse, of the material.
    pub color: BitmapId,

    /// A standard three channel emissive color map.
    pub emissive: Option<BitmapId>,

    /// A standard three channel normal map.
    pub normal: Option<BitmapId>,

    /// Optional RGBA material parameter map: metal, rough, height, transmission.
    pub params: Option<BitmapId>,

    /// Indicates which `params` channels were authored in the material source.
    pub params_used: MaterialParameterFlags,
}

bitflags! {
    #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
    pub struct MaterialParameterFlags: u8 {
        const METAL = 1 << 0;
        const ROUGH = 1 << 1;
        const HEIGHT = 1 << 2;
        const TRANSMISSION = 1 << 3;
    }
}

pub trait Pak {
    // --- "Get by id" functions

    /// Gets the pak-unique `AnimationId` corresponding to the given key, if one exists.
    fn animation_id(&self, key: impl AsRef<str>) -> Option<AnimationId>;

    /// Gets the pak-unique `BitmapFontId` corresponding to the given key, if one exists.
    fn bitmap_font_id(&self, key: impl AsRef<str>) -> Option<BitmapFontId>;

    /// Gets the pak-unique `BitmapId` corresponding to the given key, if one exists.
    fn bitmap_id(&self, key: impl AsRef<str>) -> Option<BitmapId>;

    /// Gets the pak-unique `BlobId` corresponding to the given key, if one exists.
    fn blob_id(&self, key: impl AsRef<str>) -> Option<BlobId>;

    /// Gets the pak-unique `MaterialId` corresponding to the given key, if one exists.
    fn material_id(&self, key: impl AsRef<str>) -> Option<MaterialId>;

    /// Gets the pak-unique `MeshId` corresponding to the given key, if one exists.
    fn mesh_id(&self, key: impl AsRef<str>) -> Option<MeshId>;

    /// Gets the pak-unique `SceneId` corresponding to the given key, if one exists.
    fn scene_id(&self, key: impl AsRef<str>) -> Option<SceneId>;

    // --- "Read" functions

    /// Gets the corresponding animation for the given ID.
    fn read_animation_id(&mut self, id: impl Into<AnimationId>) -> Result<Animation, Error>;

    /// Reads the corresponding bitmap for the given ID.
    fn read_bitmap_font_id(&mut self, id: impl Into<BitmapFontId>) -> Result<BitmapFont, Error>;

    /// Reads the corresponding bitmap for the given ID.
    fn read_bitmap_id(&mut self, id: impl Into<BitmapId>) -> Result<Bitmap, Error>;

    /// Gets the corresponding blob for the given ID.
    fn read_blob_id(&mut self, id: impl Into<BlobId>) -> Result<Vec<u8>, Error>;

    /// Gets the material for the given handle, if one exists.
    fn read_material_id(&self, id: impl Into<MaterialId>) -> Option<MaterialInfo>;

    /// Gets the corresponding mesh for the given ID.
    fn read_mesh_id(&mut self, id: impl Into<MeshId>) -> Result<Mesh, Error>;

    /// Gets the corresponding scene for the given ID.
    fn read_scene_id(&mut self, id: impl Into<SceneId>) -> Result<Scene, Error>;

    // --- Convenience functions

    /// Gets the material corresponding to the given key, if one exists.
    fn read_material(&self, key: impl AsRef<str>) -> Option<MaterialInfo> {
        trace!("Reading material {}", key.as_ref());

        if let Some(id) = self.material_id(key) {
            self.read_material_id(id)
        } else {
            None
        }
    }

    fn read_animation(&mut self, key: impl AsRef<str>) -> Result<Animation, Error> {
        trace!("Reading animation {}", key.as_ref());

        if let Some(h) = self.animation_id(key) {
            self.read_animation_id(h)
        } else {
            Err(Error::from(ErrorKind::InvalidInput))
        }
    }

    fn read_bitmap_font(&mut self, key: impl AsRef<str>) -> Result<BitmapFont, Error> {
        trace!("Reading bitmap font {}", key.as_ref());

        if let Some(h) = self.bitmap_font_id(key) {
            self.read_bitmap_font_id(h)
        } else {
            Err(Error::from(ErrorKind::InvalidInput))
        }
    }

    fn read_bitmap(&mut self, key: impl AsRef<str>) -> Result<Bitmap, Error> {
        trace!("Reading bitmap {}", key.as_ref());

        if let Some(h) = self.bitmap_id(key) {
            self.read_bitmap_id(h)
        } else {
            Err(Error::from(ErrorKind::InvalidInput))
        }
    }

    fn read_blob(&mut self, key: impl AsRef<str>) -> Result<Vec<u8>, Error> {
        trace!("Reading blob {}", key.as_ref());

        if let Some(h) = self.blob_id(key) {
            self.read_blob_id(h)
        } else {
            Err(Error::from(ErrorKind::InvalidInput))
        }
    }

    fn read_mesh(&mut self, key: impl AsRef<str>) -> Result<Mesh, Error> {
        trace!("Reading mesh {}", key.as_ref());

        if let Some(h) = self.mesh_id(key) {
            self.read_mesh_id(h)
        } else {
            Err(Error::from(ErrorKind::InvalidInput))
        }
    }

    fn read_scene(&mut self, key: impl AsRef<str>) -> Result<Scene, Error> {
        trace!("Reading scene {}", key.as_ref());

        if let Some(h) = self.scene_id(key) {
            self.read_scene_id(h)
        } else {
            Err(Error::from(ErrorKind::InvalidInput))
        }
    }
}

/// Main serialization container for the `.pak` file format.
#[derive(Debug)]
pub struct PakBuf {
    compression: Option<Compression>,
    data: Data,
    reader: Box<dyn Stream>,
}

impl PakBuf {
    pub fn animation_count(&self) -> usize {
        self.data.anims.len()
    }

    pub fn bitmap_count(&self) -> usize {
        self.data.bitmaps.len()
    }

    pub fn bitmap_font_count(&self) -> usize {
        self.data.bitmap_fonts.len()
    }

    pub fn blob_count(&self) -> usize {
        self.data.blobs.len()
    }

    fn deserialize<T>(&mut self, pos: u64, len: usize) -> Result<T, Error>
    where
        T: DeserializeOwned,
    {
        trace!("Read data: {len} bytes ({pos}..{})", pos + len as u64);

        // Create a zero-filled buffer
        let mut buf = vec![0; len];

        // Read the data into our buffer
        self.reader.seek(SeekFrom::Start(pos))?;
        self.reader.read_exact(&mut buf)?;
        let data = buf.as_slice();

        // Optionally create a compression reader (or just use the one we have)
        if let Some(compressed) = self.compression {
            let mut reader = compressed.new_reader(data);
            let decoded =
                bincode::serde::decode_from_std_read(&mut reader, bincode::config::legacy())
                    .map_err(|err| {
                        warn!("Unable to deserialize: {}", err);

                        Error::from(ErrorKind::InvalidData)
                    })?;

            let mut trailing = [0; 1];
            match reader.read(&mut trailing) {
                Ok(0) => Ok(decoded),
                Ok(_) => {
                    warn!("Trailing bytes after deserialized data");

                    Err(Error::from(ErrorKind::InvalidData))
                }
                Err(err) => {
                    warn!("Unable to verify deserialized data end: {}", err);

                    Err(Error::from(ErrorKind::InvalidData))
                }
            }
        } else {
            let (decoded, consumed) =
                bincode::serde::decode_from_slice(data, bincode::config::legacy()).map_err(
                    |err| {
                        warn!("Unable to deserialize: {}", err);

                        Error::from(ErrorKind::InvalidData)
                    },
                )?;

            if consumed == data.len() {
                Ok(decoded)
            } else {
                warn!("Trailing bytes after deserialized data");

                Err(Error::from(ErrorKind::InvalidData))
            }
        }
    }

    pub fn from_stream(mut stream: impl Stream + 'static) -> Result<Self, Error> {
        fn decode<T>(stream: &mut impl Read, msg: &str) -> Result<T, Error>
        where
            T: DeserializeOwned,
        {
            bincode::serde::decode_from_std_read(stream, bincode::config::legacy()).map_err(|_| {
                warn!("{}", msg);
                Error::from(ErrorKind::InvalidData)
            })
        }

        let magic_bytes: [u8; 20] = decode(&mut stream, "Unable to read magic bytes")?;
        if &magic_bytes != b"ATTACKGOAT-PAK-V1.0 " {
            warn!("Unsupported magic bytes");

            return Err(Error::from(ErrorKind::InvalidData));
        }

        // Read the number of bytes we must 'skip' in order to read the main data
        let skip: u32 = decode(&mut stream, "Unable to read skip length")?;

        let compression: Option<Compression> =
            decode(&mut stream, "Unable to read compression data")?;

        // Read the main data, excluding the hash trailer. The trailer is not validated here.
        let stream_end = stream.seek(SeekFrom::End(0))?;
        let header_end = stream_end
            .checked_sub(PAK_HASH_LEN as u64)
            .ok_or_else(|| Error::from(ErrorKind::InvalidData))?;
        let header_len = header_end
            .checked_sub(skip as u64)
            .ok_or_else(|| Error::from(ErrorKind::InvalidData))?;
        stream.seek(SeekFrom::Start(skip as _))?;

        let data: Data = if let Some(compressed) = compression {
            let mut header = (&mut stream).take(header_len);
            let mut compressed = compressed.new_reader(&mut header);
            decode(&mut compressed, "Unable to read header")?
        } else {
            let mut header = (&mut stream).take(header_len);
            decode(&mut header, "Unable to read header")?
        };

        trace!(
            "Read header: {} bytes ({} keys)",
            header_len,
            data.ids.len()
        );

        Ok(Self {
            compression,
            data,
            reader: Box::new(stream),
        })
    }

    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.data.ids.keys().map(|key| key.as_str())
    }

    pub fn validate_hash(&self) -> Result<bool, Error> {
        let mut reader = self.reader.open()?;
        let stream_end = reader.seek(SeekFrom::End(0))?;
        let payload_len = stream_end
            .checked_sub(PAK_HASH_LEN as u64)
            .ok_or_else(|| Error::from(ErrorKind::InvalidData))?;

        reader.seek(SeekFrom::Start(0))?;
        let actual = pak_hash_stream(&mut reader, payload_len)?;
        let expected = read_hash_trailer(&mut reader)?;
        Ok(actual == expected)
    }

    pub fn mesh_count(&self) -> usize {
        self.data.meshes.len()
    }

    pub fn material_count(&self) -> usize {
        self.data.materials.len()
    }

    /// Opens the given path and decodes a `Pak`.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
        let path = path.as_ref().to_path_buf();
        let file = File::open(&path)?;
        let buf = BufReader::new(file);

        Self::from_stream(PakFile { buf, path })
    }

    pub fn scene_count(&self) -> usize {
        self.data.scenes.len()
    }
}

impl Pak for PakBuf {
    /// Gets the pak-unique `AnimationId` corresponding to the given key, if one exists.
    fn animation_id(&self, key: impl AsRef<str>) -> Option<AnimationId> {
        self.data
            .ids
            .get(key.as_ref())
            .and_then(|id| id.as_animation())
    }

    /// Gets the pak-unique `BitmapFontId` corresponding to the given key, if one exists.
    fn bitmap_font_id(&self, key: impl AsRef<str>) -> Option<BitmapFontId> {
        self.data
            .ids
            .get(key.as_ref())
            .and_then(|id| id.as_bitmap_font())
    }

    /// Gets the pak-unique `BitmapId` corresponding to the given key, if one exists.
    fn bitmap_id(&self, key: impl AsRef<str>) -> Option<BitmapId> {
        self.data
            .ids
            .get(key.as_ref())
            .and_then(|id| id.as_bitmap())
    }

    /// Gets the pak-unique `BlobId` corresponding to the given key, if one exists.
    fn blob_id(&self, key: impl AsRef<str>) -> Option<BlobId> {
        self.data.ids.get(key.as_ref()).and_then(|id| id.as_blob())
    }

    /// Gets the pak-unique `MaterialId` corresponding to the given key, if one exists.
    fn material_id(&self, key: impl AsRef<str>) -> Option<MaterialId> {
        self.data
            .ids
            .get(key.as_ref())
            .and_then(|id| id.as_material())
    }

    /// Gets the pak-unique `MeshId` corresponding to the given key, if one exists.
    fn mesh_id(&self, key: impl AsRef<str>) -> Option<MeshId> {
        self.data.ids.get(key.as_ref()).and_then(|id| id.as_mesh())
    }

    /// Gets the pak-unique `SceneId` corresponding to the given key, if one exists.
    fn scene_id(&self, key: impl AsRef<str>) -> Option<SceneId> {
        self.data.ids.get(key.as_ref()).and_then(|id| id.as_scene())
    }

    /// Gets the corresponding animation for the given ID.
    fn read_animation_id(&mut self, id: impl Into<AnimationId>) -> Result<Animation, Error> {
        let id = id.into();

        trace!("Deserializing animation {}", id.0);

        let (pos, len) = self
            .data
            .anims
            .get(id.0)
            .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?
            .pos_len()?;
        self.deserialize(pos, len)
    }

    /// Reads the corresponding bitmap for the given ID.
    fn read_bitmap_font_id(&mut self, id: impl Into<BitmapFontId>) -> Result<BitmapFont, Error> {
        let id = id.into();

        trace!("Deserializing bitmap font {}", id.0);

        let (pos, len) = self
            .data
            .bitmap_fonts
            .get(id.0)
            .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?
            .pos_len()?;
        self.deserialize(pos, len)
    }

    /// Reads the corresponding bitmap for the given ID.
    fn read_bitmap_id(&mut self, id: impl Into<BitmapId>) -> Result<Bitmap, Error> {
        let id = id.into();

        trace!("Deserializing bitmap {}", id.0);

        let (pos, len) = self
            .data
            .bitmaps
            .get(id.0)
            .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?
            .pos_len()?;
        self.deserialize(pos, len)
    }

    /// Gets the corresponding blob for the given ID.
    fn read_blob_id(&mut self, id: impl Into<BlobId>) -> Result<Vec<u8>, Error> {
        let id = id.into();

        trace!("Deserializing blob {}", id.0);

        let (pos, len) = self
            .data
            .blobs
            .get(id.0)
            .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?
            .pos_len()?;
        self.deserialize(pos, len)
    }

    /// Gets the material for the given ID.
    fn read_material_id(&self, id: impl Into<MaterialId>) -> Option<MaterialInfo> {
        let id = id.into();

        self.data.materials.get(id.0).copied()
    }

    /// Gets the corresponding mesh for the given ID.
    fn read_mesh_id(&mut self, id: impl Into<MeshId>) -> Result<Mesh, Error> {
        let id = id.into();

        trace!("Deserializing mesh {}", id.0);

        let (pos, len) = self
            .data
            .meshes
            .get(id.0)
            .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?
            .pos_len()?;
        self.deserialize(pos, len)
    }

    /// Gets the corresponding animation for the given ID.
    fn read_scene_id(&mut self, id: impl Into<SceneId>) -> Result<Scene, Error> {
        let id = id.into();

        trace!("Deserializing scene {}", id.0);

        let (pos, len) = self
            .data
            .scenes
            .get(id.0)
            .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?
            .pos_len()?;
        self.deserialize(pos, len)
    }
}

#[derive(Debug)]
struct PakFile {
    buf: BufReader<File>,
    path: PathBuf,
}

impl From<&'static [u8]> for PakBuf {
    fn from(data: &'static [u8]) -> Self {
        Self::from_stream(Cursor::new(data)).expect("invalid pak data")
    }
}

pub trait Stream: Debug + Read + Seek + Send {
    fn open(&self) -> Result<Box<dyn Stream>, Error>;
}

impl Stream for PakFile {
    fn open(&self) -> Result<Box<dyn Stream>, Error> {
        let file = File::open(&self.path)?;
        let buf = BufReader::new(file);

        Ok(Box::new(PakFile {
            buf,
            path: self.path.clone(),
        }))
    }
}

impl Read for PakFile {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.buf.read(buf)
    }
}

impl Seek for PakFile {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        self.buf.seek(pos)
    }
}

impl Stream for Cursor<&'static [u8]> {
    fn open(&self) -> Result<Box<dyn Stream>, Error> {
        Ok(Box::new(Cursor::new(*self.get_ref())))
    }
}

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

    fn empty_pak() -> PakBuf {
        PakBuf {
            compression: None,
            data: Data::default(),
            reader: Box::new(Cursor::new(&[] as &'static [u8])),
        }
    }

    #[test]
    fn invalid_read_ids_return_invalid_input() {
        assert_eq!(
            empty_pak()
                .read_animation_id(AnimationId(0))
                .expect_err("invalid animation id should error")
                .kind(),
            ErrorKind::InvalidInput,
        );
        assert_eq!(
            empty_pak()
                .read_bitmap_font_id(BitmapFontId(0))
                .expect_err("invalid bitmap font id should error")
                .kind(),
            ErrorKind::InvalidInput,
        );
        assert_eq!(
            empty_pak()
                .read_bitmap_id(BitmapId(0))
                .expect_err("invalid bitmap id should error")
                .kind(),
            ErrorKind::InvalidInput,
        );
        assert_eq!(
            empty_pak()
                .read_blob_id(BlobId(0))
                .expect_err("invalid blob id should error")
                .kind(),
            ErrorKind::InvalidInput,
        );
        assert_eq!(
            empty_pak()
                .read_mesh_id(MeshId(0))
                .expect_err("invalid mesh id should error")
                .kind(),
            ErrorKind::InvalidInput,
        );
        assert_eq!(
            empty_pak()
                .read_scene_id(SceneId(0))
                .expect_err("invalid scene id should error")
                .kind(),
            ErrorKind::InvalidInput,
        );
    }

    #[test]
    fn invalid_data_ref_range_returns_invalid_data() {
        let mut pak = empty_pak();
        pak.data.blobs.push(DataRef::Ref(10..5));

        assert_eq!(
            pak.read_blob_id(BlobId(0))
                .expect_err("invalid blob range should error")
                .kind(),
            ErrorKind::InvalidData,
        );
    }

    #[test]
    fn trailing_asset_bytes_return_invalid_data() {
        let mut encoded = Vec::new();
        bincode::serde::encode_into_std_write(
            b"blob".to_vec(),
            &mut encoded,
            bincode::config::legacy(),
        )
        .unwrap();
        encoded.extend_from_slice(b"junk");
        let encoded: &'static [u8] = Box::leak(encoded.into_boxed_slice());

        let mut pak = empty_pak();
        pak.data.blobs.push(DataRef::Ref(0..encoded.len() as u32));
        pak.reader = Box::new(Cursor::new(encoded));

        assert_eq!(
            pak.read_blob_id(BlobId(0))
                .expect_err("trailing asset bytes should error")
                .kind(),
            ErrorKind::InvalidData,
        );
    }
}