dayzmake-core 0.2.1

Readers and writers for DayZ file formats: PBO, rapified config, P3D, PAA, BI keys and signatures
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
//! Reading, writing and inspecting P3D models.
//!
//! [`crate::p3d::P3D`] handles the editable MLOD format and keeps everything the file holds, so that
//! `write(read(x))` reproduces `x` byte for byte. Binarized ODOL models are only recognised
//! (format and version); they are produced by BI's binarize.exe, not by this crate.

use std::collections::{BTreeMap, HashSet};
use std::fs::File;
use std::io::{BufReader, BufWriter, Error, ErrorKind, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

use crate::error::{ErrorExt, printable};
use crate::io::{ReadExt, WriteExt};
use crate::warning::{Warning, WarningSink};

fn invalid<S: Into<String>>(msg: S) -> Error {
    Error::new(ErrorKind::InvalidData, msg.into())
}

/// Counts in the file are not trusted for preallocation.
fn capacity(n: u32) -> usize {
    (n as usize).min(1 << 16)
}

/// A vertex position with its flags.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct Point {
    /// Position in model space.
    pub coords: (f32, f32, f32),
    /// Point flags.
    pub flags: u32,
}

/// A face vertex: indices into the point and normal arrays plus a UV pair.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct Vertex {
    /// Index into the LOD's points.
    pub point_index: u32,
    /// Index into the LOD's face normals.
    pub normal_index: u32,
    /// Texture coordinates.
    pub uv: (f32, f32),
}

/// A face with its vertices, texture and material.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct Face {
    /// The face's vertices (3 for a triangle, 4 for a quad).
    pub vertices: Vec<Vertex>,
    /// Face flags.
    pub flags: u32,
    /// Texture path.
    pub texture: String,
    /// Material (rvmat) path.
    pub material: String,
    /// Triangles are stored with a fourth, unused vertex; kept so the file round-trips.
    pub spare_vertex: Option<Vertex>,
}

/// One entry of a LOD's TAGG section. The same name can occur several times
/// (`#Property#`, `#UVSet#`), so these are kept in file order in a `Vec`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Tagg {
    /// The tagg's active byte.
    pub active: u8,
    /// The tagg's name (e.g. `#Property#` or a selection name).
    pub name: String,
    /// The tagg's payload.
    pub data: Vec<u8>,
}

/// One level of detail of the model.
#[derive(Debug)]
#[non_exhaustive]
pub struct LOD {
    /// LOD format version, major part.
    pub version_major: u32,
    /// LOD format version, minor part.
    pub version_minor: u32,
    /// The 4 bytes after the counts in the LOD header.
    pub flags: u32,
    /// The LOD's resolution; special values name named LODs (geometry etc.).
    pub resolution: f32,
    /// Positions.
    pub points: Vec<Point>,
    /// Face normals.
    pub face_normals: Vec<(f32, f32, f32)>,
    /// Faces.
    pub faces: Vec<Face>,
    /// TAGG entries in file order.
    pub taggs: Vec<Tagg>,
}

/// An MLOD model.
///
/// ```compile_fail,E0639
/// let _ = dayzmake_core::p3d::P3D { version: 0, lods: Vec::new() };
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct P3D {
    /// MLOD format version.
    pub version: u32,
    /// The model's LODs, in file order.
    pub lods: Vec<LOD>,
}

impl Point {
    /// Creates an all-zero point.
    #[must_use]
    pub fn new() -> Point {
        Point {
            coords: (0.0, 0.0, 0.0),
            flags: 0,
        }
    }

    fn read<I: Read>(input: &mut I) -> Result<Point, Error> {
        Ok(Point {
            coords: (
                input.read_f32::<LittleEndian>()?,
                input.read_f32::<LittleEndian>()?,
                input.read_f32::<LittleEndian>()?,
            ),
            flags: input.read_u32::<LittleEndian>()?,
        })
    }

    fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        output.write_f32::<LittleEndian>(self.coords.0)?;
        output.write_f32::<LittleEndian>(self.coords.1)?;
        output.write_f32::<LittleEndian>(self.coords.2)?;
        output.write_u32::<LittleEndian>(self.flags)?;
        Ok(())
    }
}

impl Vertex {
    /// Creates an all-zero vertex.
    #[must_use]
    pub fn new() -> Vertex {
        Vertex {
            point_index: 0,
            normal_index: 0,
            uv: (0.0, 0.0),
        }
    }

    fn read<I: Read>(input: &mut I) -> Result<Vertex, Error> {
        Ok(Vertex {
            point_index: input.read_u32::<LittleEndian>()?,
            normal_index: input.read_u32::<LittleEndian>()?,
            uv: (
                input.read_f32::<LittleEndian>()?,
                input.read_f32::<LittleEndian>()?,
            ),
        })
    }

    fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        output.write_u32::<LittleEndian>(self.point_index)?;
        output.write_u32::<LittleEndian>(self.normal_index)?;
        output.write_f32::<LittleEndian>(self.uv.0)?;
        output.write_f32::<LittleEndian>(self.uv.1)?;
        Ok(())
    }
}

impl Face {
    /// Creates an empty face.
    #[must_use]
    pub fn new() -> Face {
        Face {
            vertices: Vec::with_capacity(4),
            flags: 0,
            texture: String::new(),
            material: String::new(),
            spare_vertex: None,
        }
    }

    fn read<I: Read>(input: &mut I) -> Result<Face, Error> {
        let num_verts = input.read_u32::<LittleEndian>()?;
        if num_verts != 3 && num_verts != 4 {
            return Err(invalid(format!(
                "face with {num_verts} vertices (expected 3 or 4)"
            )));
        }

        let mut vertices: Vec<Vertex> = Vec::with_capacity(num_verts as usize);
        for _i in 0..num_verts {
            vertices.push(Vertex::read(input)?);
        }

        let spare_vertex = if num_verts == 3 {
            Some(Vertex::read(input)?)
        } else {
            None
        };

        let flags = input.read_u32::<LittleEndian>()?;
        let texture = input.read_cstring()?;
        let material = input.read_cstring()?;

        Ok(Face {
            vertices,
            flags,
            texture,
            material,
            spare_vertex,
        })
    }

    fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        if self.vertices.len() != 3 && self.vertices.len() != 4 {
            return Err(invalid(format!(
                "face with {} vertices (expected 3 or 4)",
                self.vertices.len()
            )));
        }
        let num_verts =
            u32::try_from(self.vertices.len()).map_err(|_| invalid("too many vertices in face"))?;
        output.write_u32::<LittleEndian>(num_verts)?;

        for vert in &self.vertices {
            vert.write(output)?;
        }
        if self.vertices.len() == 3 {
            match self.spare_vertex {
                Some(ref vert) => vert.write(output)?,
                None => Vertex::new().write(output)?,
            }
        }

        output.write_u32::<LittleEndian>(self.flags)?;
        output.write_cstring(&self.texture)?;
        output.write_cstring(&self.material)?;
        Ok(())
    }
}

impl Tagg {
    /// Creates a tagg; a selection when `name` does not start with `#`.
    ///
    /// For a selection, `data` holds one weight byte per point followed by one per face of the
    /// LOD (`points + faces` bytes). For `#Property#` it is the 128 byte name/value pair (see
    /// [`Tagg::property`]); other taggs carry their format's raw payload.
    #[must_use]
    pub fn new(active: u8, name: impl Into<String>, data: Vec<u8>) -> Tagg {
        Tagg {
            active,
            name: name.into(),
            data,
        }
    }

    /// For `#Property#`: the (name, value) pair, two NUL-padded 64 byte strings.
    #[must_use]
    pub fn property(&self) -> Option<(String, String)> {
        if self.name != "#Property#" || self.data.len() != 128 {
            return None;
        }
        let field = |b: &[u8]| {
            let end = b.iter().position(|&c| c == 0).unwrap_or(b.len());
            String::from_utf8_lossy(b.get(..end).unwrap_or(b)).into_owned()
        };
        let (Some(low), Some(high)) = (self.data.get(..64), self.data.get(64..)) else {
            return None;
        };
        Some((field(low), field(high)))
    }

    /// Selections are the tags whose name isn't one of the `#...#` markers.
    #[must_use]
    pub fn is_selection(&self) -> bool {
        !self.name.starts_with('#')
    }
}

/// Human readable name of a LOD resolution, for the values that are well known.
#[must_use]
pub fn lod_name(resolution: f32) -> Option<&'static str> {
    const NAMES: &[(f32, &str)] = &[
        (1.0e3, "View - Gunner"),
        (1.1e3, "View - Pilot"),
        (1.2e3, "View - Cargo"),
        (1.0e4, "Shadow Volume"),
        (1.0e13, "Geometry"),
        (1.0e15, "Memory"),
        (2.0e15, "Land Contact"),
        (3.0e15, "Roadway"),
        (4.0e15, "Paths"),
        (5.0e15, "Hit-points"),
        (6.0e15, "View Geometry"),
        (7.0e15, "Fire Geometry"),
    ];
    NAMES
        .iter()
        .find(|(r, _)| (resolution - r).abs() <= r * 1e-4)
        .map(|(_, n)| *n)
}

impl LOD {
    /// Creates an empty LOD with the format version (28.256) MLOD files normally carry.
    #[must_use]
    pub fn new(resolution: f32) -> LOD {
        LOD {
            version_major: 0x1c,
            version_minor: 0x100,
            flags: 0,
            resolution,
            points: Vec::new(),
            face_normals: Vec::new(),
            faces: Vec::new(),
            taggs: Vec::new(),
        }
    }

    /// Human readable name of this LOD (e.g. "Geometry", or its resolution).
    #[must_use]
    pub fn name(&self) -> String {
        match lod_name(self.resolution) {
            Some(n) => n.to_string(),
            None if self.resolution < 1.0e3 => format!("Resolution {}", self.resolution),
            None => format!("{:e}", self.resolution),
        }
    }

    /// The LOD's `#Property#` taggs as (name, value) pairs.
    #[must_use]
    pub fn properties(&self) -> Vec<(String, String)> {
        self.taggs.iter().filter_map(Tagg::property).collect()
    }

    /// Selections are the tags whose name isn't one of the `#...#` markers.
    #[must_use]
    pub fn selections(&self) -> Vec<&str> {
        self.taggs
            .iter()
            .filter(|t| t.is_selection())
            .map(|t| t.name.as_str())
            .collect()
    }

    /// Number of `#UVSet#` taggs.
    #[must_use]
    pub fn uv_set_count(&self) -> usize {
        self.taggs.iter().filter(|t| t.name == "#UVSet#").count()
    }

    fn read<I: Read>(input: &mut I) -> Result<LOD, Error> {
        let mut buffer = [0; 4];
        input.read_exact(&mut buffer)?;
        if &buffer != b"P3DM" {
            return Err(invalid("LOD doesn't start with P3DM"));
        }

        let version_major = input.read_u32::<LittleEndian>()?;
        let version_minor = input.read_u32::<LittleEndian>()?;

        let num_points = input.read_u32::<LittleEndian>()?;
        let num_face_normals = input.read_u32::<LittleEndian>()?;
        let num_faces = input.read_u32::<LittleEndian>()?;
        let flags = input.read_u32::<LittleEndian>()?;

        let mut points: Vec<Point> = Vec::with_capacity(capacity(num_points));
        let mut face_normals: Vec<(f32, f32, f32)> = Vec::with_capacity(capacity(num_face_normals));
        let mut faces: Vec<Face> = Vec::with_capacity(capacity(num_faces));

        for _i in 0..num_points {
            points.push(Point::read(input)?);
        }

        for _i in 0..num_face_normals {
            face_normals.push((
                input.read_f32::<LittleEndian>()?,
                input.read_f32::<LittleEndian>()?,
                input.read_f32::<LittleEndian>()?,
            ));
        }

        for _i in 0..num_faces {
            faces.push(Face::read(input)?);
        }

        input.read_exact(&mut buffer)?;
        if &buffer != b"TAGG" {
            return Err(invalid("LOD has no TAGG section"));
        }

        let mut taggs: Vec<Tagg> = Vec::new();

        loop {
            let active = input.read_u8()?;
            let name = input.read_cstring()?;
            let size = input.read_u32::<LittleEndian>()?;
            let mut data = Vec::with_capacity(capacity(size));
            let got = input
                .by_ref()
                .take(u64::from(size))
                .read_to_end(&mut data)?;
            if got != size as usize {
                return Err(Error::new(
                    ErrorKind::UnexpectedEof,
                    format!("tag \"{}\" is truncated", printable(&name)),
                ));
            }

            if name == "#EndOfFile#" {
                break;
            }

            taggs.push(Tagg { active, name, data });
        }

        let resolution = input.read_f32::<LittleEndian>()?;

        Ok(LOD {
            version_major,
            version_minor,
            flags,
            resolution,
            points,
            face_normals,
            faces,
            taggs,
        })
    }

    /// Checks that the LOD is consistent: selection sizes and vertex indices.
    fn validate(&self, index: usize) -> Result<(), Error> {
        // the index tells apart LODs of the same resolution
        let label = format!("LOD {index} ({})", self.name());
        let expected = self
            .points
            .len()
            .checked_add(self.faces.len())
            .ok_or_else(|| invalid("LOD section count out of range"))?;
        for (i, tagg) in self.taggs.iter().enumerate() {
            if tagg.name.contains('\0') {
                return Err(invalid(format!(
                    "{label}: tagg {i} name \"{}\" contains a NUL byte",
                    printable(&tagg.name),
                )));
            }
            // The length of an inactive tagg is not enforced (real files carry empty ones).
            if tagg.active != 0 && tagg.is_selection() && tagg.data.len() != expected {
                return Err(invalid(format!(
                    "{label}: tagg {i} \"{}\" is a selection with {} bytes, expected {expected} ({} points + {} faces)",
                    printable(&tagg.name),
                    tagg.data.len(),
                    self.points.len(),
                    self.faces.len(),
                )));
            }
        }
        for (i, face) in self.faces.iter().enumerate() {
            for (field, value) in [("texture", &face.texture), ("material", &face.material)] {
                if value.contains('\0') {
                    return Err(invalid(format!(
                        "{label}: face {i} {field} \"{}\" contains a NUL byte",
                        printable(value),
                    )));
                }
            }
            if face.vertices.len() != 3 && face.vertices.len() != 4 {
                return Err(invalid(format!(
                    "{label}: face {i} has {} vertices (expected 3 or 4)",
                    face.vertices.len(),
                )));
            }
            for (j, vertex) in face.vertices.iter().enumerate() {
                let point = usize::try_from(vertex.point_index).unwrap_or(usize::MAX);
                if point >= self.points.len() {
                    return Err(invalid(format!(
                        "{label}: face {i} vertex {j} has point index {} but there are {} points",
                        vertex.point_index,
                        self.points.len(),
                    )));
                }
                let normal = usize::try_from(vertex.normal_index).unwrap_or(usize::MAX);
                if normal >= self.face_normals.len() {
                    return Err(invalid(format!(
                        "{label}: face {i} vertex {j} has normal index {} but there are {} normals",
                        vertex.normal_index,
                        self.face_normals.len(),
                    )));
                }
            }
        }
        Ok(())
    }

    fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        let len32 =
            |len: usize| u32::try_from(len).map_err(|_| invalid("LOD section count out of range"));
        output.write_all(b"P3DM")?;
        output.write_u32::<LittleEndian>(self.version_major)?;
        output.write_u32::<LittleEndian>(self.version_minor)?;
        output.write_u32::<LittleEndian>(len32(self.points.len())?)?;
        output.write_u32::<LittleEndian>(len32(self.face_normals.len())?)?;
        output.write_u32::<LittleEndian>(len32(self.faces.len())?)?;
        output.write_u32::<LittleEndian>(self.flags)?;

        for point in &self.points {
            point.write(output)?;
        }

        for normal in &self.face_normals {
            output.write_f32::<LittleEndian>(normal.0)?;
            output.write_f32::<LittleEndian>(normal.1)?;
            output.write_f32::<LittleEndian>(normal.2)?;
        }

        for face in &self.faces {
            face.write(output)?;
        }

        output.write_all(b"TAGG")?;

        for tagg in &self.taggs {
            output.write_all(&[tagg.active])?;
            output.write_cstring(&tagg.name)?;
            let size = u32::try_from(tagg.data.len()).map_err(|_| invalid("tag data too large"))?;
            output.write_u32::<LittleEndian>(size)?;
            output.write_all(&tagg.data)?;
        }

        output.write_all(&[1])?;
        output.write_cstring("#EndOfFile#")?;
        output.write_u32::<LittleEndian>(0)?;

        output.write_f32::<LittleEndian>(self.resolution)?;

        Ok(())
    }
}

impl P3D {
    /// Creates a model without LODs; `version` is the MLOD version (0x101 in practice).
    #[must_use]
    pub fn new(version: u32) -> P3D {
        P3D {
            version,
            lods: Vec::new(),
        }
    }

    /// Reads an MLOD model.
    ///
    /// # Errors
    ///
    /// Returns an error if the input is not an MLOD model or is malformed.
    pub fn read<I: Read>(input: &mut I) -> Result<P3D, Error> {
        let mut reader = BufReader::new(input);

        let mut buffer = [0; 4];
        reader.read_exact(&mut buffer)?;
        match &buffer {
            b"MLOD" => {}
            b"ODOL" => {
                return Err(invalid(
                    "this is a binarized ODOL model; only MLOD models can be read",
                ));
            }
            _ => return Err(invalid("not an MLOD model")),
        }

        let version = reader.read_u32::<LittleEndian>()?;
        let num_lods = reader.read_u32::<LittleEndian>()?;
        let mut lods: Vec<LOD> = Vec::with_capacity(capacity(num_lods));

        for i in 0..num_lods {
            lods.push(LOD::read(&mut reader).prepend_error(format!("Failed to read LOD {i}:"))?);
        }

        Ok(P3D { version, lods })
    }

    /// Writes the model as MLOD.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failure, or if a LOD is inconsistent (a selection whose size is not
    /// points + faces, a vertex index out of range, a tagg name or face texture or material
    /// containing a NUL byte, a face that does not have 3 or 4 vertices).
    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        for (index, lod) in self.lods.iter().enumerate() {
            lod.validate(index)?;
        }
        let mut writer = BufWriter::new(output);

        writer.write_all(b"MLOD")?;
        writer.write_u32::<LittleEndian>(self.version)?;
        let num_lods = u32::try_from(self.lods.len()).map_err(|_| invalid("too many LODs"))?;
        writer.write_u32::<LittleEndian>(num_lods)?;

        for lod in &self.lods {
            lod.write(&mut writer)?;
        }

        writer.flush()
    }

    /// Texture and material paths used by the faces of all LODs, with the number of faces using them.
    /// Empty names are left out.
    #[must_use]
    pub fn textures(&self) -> BTreeMap<&str, usize> {
        self.count_faces(|f| &f.texture)
    }

    /// Material (rvmat) paths used by the faces of all LODs, with the number of faces using them.
    /// Empty names are left out.
    #[must_use]
    pub fn materials(&self) -> BTreeMap<&str, usize> {
        self.count_faces(|f| &f.material)
    }

    fn count_faces<'a>(
        &'a self,
        field: impl Fn(&'a Face) -> &'a String,
    ) -> BTreeMap<&'a str, usize> {
        let mut map = BTreeMap::new();
        for face in self.lods.iter().flat_map(|l| l.faces.iter()) {
            let name = field(face);
            if !name.is_empty() {
                *map.entry(name.as_str()).or_insert(0) += 1;
            }
        }
        map
    }
}

/// Whether `rel` (relative, `\\` or `/` separated) exists below `root`, ignoring case like the game does.
fn exists_ignore_case(root: &Path, rel: &str) -> bool {
    let mut dir = root.to_path_buf();
    for part in rel.split('\\').filter(|p| !p.is_empty()) {
        let found = std::fs::read_dir(&dir).ok().and_then(|rd| {
            rd.filter_map(std::result::Result::ok)
                .find(|e| e.file_name().to_string_lossy().to_lowercase() == part)
                .map(|e| e.path())
        });
        match found {
            Some(p) => dir = p,
            None => return false,
        }
    }
    dir != root
}

/// Warns about textures and materials of the MLOD model at `path` that don't exist, before it
/// is handed to binarize.exe (which silently leaves the model's alpha flags unset instead).
///
/// References that start with the addon's `prefix` are looked up in the addon, whose files are
/// `addon_files` (lowercase, relative to the addon, separated by `\`). Anything else
/// (vanilla `dz\...`, other mods) can only be checked if it is below one of `search_roots`;
/// if it isn't, there is no way to know whether the reference is wrong, so it is not reported.
/// Procedural textures (`#(argb,...)`) are skipped. A model that can't be read only gets a warning.
pub(crate) fn check_dependencies<S: std::hash::BuildHasher>(
    path: &Path,
    display: &str,
    prefix: &str,
    addon_files: &HashSet<String, S>,
    search_roots: &[PathBuf],
    warnings: &mut dyn WarningSink,
) {
    let p3d = match File::open(path).and_then(|f| P3D::read(&mut BufReader::new(f))) {
        Ok(p) => p,
        Err(e) => {
            warnings.warn(
                Warning::new(
                    Some("model-unreadable"),
                    format!(
                        "Cannot check textures and materials: {}",
                        printable(&e.to_string().replace('\n', " "))
                    ),
                )
                .in_file(display),
            );
            return;
        }
    };

    let prefix = prefix.replace('/', "\\").trim_matches('\\').to_lowercase();
    let own = format!("{prefix}\\");

    let kinds: [(&str, &'static str, BTreeMap<&str, usize>); 2] = [
        ("texture", "missing-texture", p3d.textures()),
        ("material", "missing-material", p3d.materials()),
    ];
    for (kind, warning_name, refs) in &kinds {
        for name in refs.keys().filter(|n| !n.starts_with('#')) {
            let normalized = name
                .replace('/', "\\")
                .trim_start_matches('\\')
                .to_lowercase();
            let exists = if !prefix.is_empty() && normalized.starts_with(&own) {
                Some(addon_files.contains(&normalized[own.len()..]))
            } else if search_roots
                .iter()
                .any(|r| exists_ignore_case(r, &normalized))
            {
                Some(true)
            } else {
                None
            };
            if exists == Some(false) {
                warnings.warn(
                    Warning::new(
                        Some(*warning_name),
                        format!(
                            "Model references {kind} \"{}\", which is not in the addon.",
                            printable(name)
                        ),
                    )
                    .in_file(display),
                );
            }
        }
    }
}

/// The 4 byte magic of a model file ("MLOD", "ODOL" or "BMTR"), if it is one. The reader is
/// put back to where it was.
///
/// # Errors
///
/// Returns an error if seeking or reading fails (a short read is not an error).
pub fn model_magic<I: Read + Seek>(input: &mut I) -> Result<Option<[u8; 4]>, Error> {
    let start = input.stream_position()?;
    let mut magic = [0; 4];
    let complete = input.read_exact(&mut magic).is_ok();
    input.seek(SeekFrom::Start(start))?;
    Ok(
        if complete && (&magic == b"MLOD" || &magic == b"ODOL" || &magic == b"BMTR") {
            Some(magic)
        } else {
            None
        },
    )
}

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

    fn mlod(lod_body: &[u8]) -> Vec<u8> {
        let mut b = b"MLOD".to_vec();
        b.extend_from_slice(&[0x01, 0x01, 0, 0, 1, 0, 0, 0]);
        b.extend_from_slice(lod_body);
        b
    }

    #[test]
    fn garbage_is_an_error_not_a_panic() {
        assert!(P3D::read(&mut Cursor::new(b"".to_vec())).is_err());
        assert!(P3D::read(&mut Cursor::new(b"XXXXXXXX".to_vec())).is_err());
        assert!(P3D::read(&mut Cursor::new(b"ODOL\x38\0\0\0".to_vec())).is_err());
        assert!(P3D::read(&mut Cursor::new(mlod(b"NOPE"))).is_err());
        // claims 4 billion points, has none
        let mut lod = b"P3DM".to_vec();
        lod.extend_from_slice(&[
            0x1c, 0, 0, 0, 0, 1, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        ]);
        assert!(P3D::read(&mut Cursor::new(mlod(&lod))).is_err());
    }

    #[test]
    fn bad_face_vertex_count_is_an_error() {
        let mut lod = b"P3DM".to_vec();
        lod.extend_from_slice(&[
            0x1c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
        ]);
        lod.extend_from_slice(&[7, 0, 0, 0]);
        let err = P3D::read(&mut Cursor::new(mlod(&lod))).unwrap_err();
        assert!(err.to_string().contains("7 vertices"), "{}", err);
    }
}