brres 0.1.7

brres is a Rust crate designed for reading and writing .brres 3d model archives used in the Nintendo Wii games. The library provides C bindings, making it useful in both Rust and C/C++ based projects.
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
//! # brres
//!
//! BRRES (.brres) is Nintendo's first-party 3D model format for the Nintendo Wii. Used in games like *Mario Kart Wii*, *Twilight Princess* and *Super Smash Bros: Brawl*, .brres is a versatile and efficient file format.
//! Nearly all data is stored as raw GPU display lists that are directly read by the Wii's "flipper" GPU.
//!
//! ## File format: .brres
//!
//! At the very root, ".brres" is an archive format for the following sub-files. All but SHP0 are supported.
//!
//! Filetype   | Description                              | Rust structure
//! -----------|------------------------------------------|--------------------------
//! BRRES v0   | 3D Resource                              | [`Archive`](https://docs.rs/brres/latest/brres/struct.Archive.html)
//! MDL0 v11   | 3D Model                                 | [`Model`](https://docs.rs/brres/latest/brres/struct.Model.html)
//! TEX0 v1/v3 | Texture                                  | [`Texture`](https://docs.rs/brres/latest/brres/struct.Texture.html)
//! SRT0 v5    | Texture scale/rotate/translate animation | [`JSONSrtData`](https://docs.rs/brres/latest/brres/json/struct.JSONSrtData.html)
//! VIS0 v4    | Bone visibility animation                | [`JSONVisData`](https://docs.rs/brres/latest/brres/json/struct.JSONVisData.html)
//! CLR0 v4    | Shader uniform animation                 | [`JSONClrAnim`](https://docs.rs/brres/latest/brres/json/struct.JSONClrAnim.html), editing limitations
//! CHR0 v4    | Bone/character animation                 | [`ChrData`](https://docs.rs/brres/latest/brres/struct.ChrData.html), editing limitations
//! PAT0 v4    | Texture image animation                  | [`JSONPatAnim`](https://docs.rs/brres/latest/brres/json/struct.JSONPatAnim.html), editing limitations
//! SHP0       | Vertex morph animation                   | Unsupported
//!
//! ## File format: .mdl0
//!
//! Filetype         | Description            | Rust structure
//! -----------------|------------------------|--------------
//! MDL0.ByteCode    | Draw calls + Skeleton  | Merged into [`JSONBoneData`](https://docs.rs/brres/latest/brres/json/struct.JSONBoneData.html), [`JSONDrawMatrix`](https://docs.rs/brres/latest/brres/json/struct.JSONDrawMatrix.html)
//! MDL0.Bone        | Bone                   | [`JSONBoneData`](https://docs.rs/brres/latest/brres/json/struct.JSONBoneData.html)
//! MDL0.PositionBuf | Holds vertex positions | [`VertexPositionBuffer`](https://docs.rs/brres/latest/brres/struct.VertexPositionBuffer.html)
//! MDL0.NormalBuf   | Holds vertex normals   | [`VertexNormalBuffer`](https://docs.rs/brres/latest/brres/struct.VertexNormalBuffer.html)
//! MDL0.ColorBuf    | Holds vertex colors    | [`VertexColorBuffer`](https://docs.rs/brres/latest/brres/struct.VertexColorBuffer.html)
//! MDL0.UVBuf       | Holds UV maps          | [`VertexTextureCoordinateBuffer`](https://docs.rs/brres/latest/brres/struct.VertexTextureCoordinateBuffer.html)
//! MDL0.FurVecBuf   | Fur related            | Not supported
//! MDL0.FurPosBuf   | Fur related            | Not supported
//! MDL0.Material    | Material data          | [`JSONMaterial`](https://docs.rs/brres/latest/brres/json/struct.JSONMaterial.html)
//! MDL0.TEV         | Shader data            | Merged into [`JSONMaterial`](https://docs.rs/brres/latest/brres/json/struct.JSONMaterial.html)
//! MDL0.Mesh        | 3D mesh data           | [`Mesh`](https://docs.rs/brres/latest/brres/struct.Mesh.html)
//! MDL0.TextureLink | Internal               | Recomputed
//! MDL0.PaletteLink | Internal               | Recomputed
//! MDL0.UserData    | Metadata               | Not supported
//!
//! Thus, the Rust view of a MDL0 file looks like this:
//! ```
//! use brres::*;
//! use brres::json::*;
//!
//! struct Model {
//!     pub name: String,
//!     pub info: JSONModelInfo,
//!
//!     pub bones: Vec<JSONBoneData>,
//!     pub materials: Vec<JSONMaterial>,
//!     pub meshes: Vec<Mesh>,
//!
//!     // Vertex buffers
//!     pub positions: Vec<VertexPositionBuffer>,
//!     pub normals: Vec<VertexNormalBuffer>,
//!     pub texcoords: Vec<VertexTextureCoordinateBuffer>,
//!     pub colors: Vec<VertexColorBuffer>,
//!
//!     /// For skinning
//!     pub matrices: Vec<JSONDrawMatrix>,
//! }
//! ```
//!
//! ## Reading a file
//! Read a .brres file from a path on the filesystem.
//!
//! ```
//! let archive = brres::Archive::from_path("kuribo.brres").unwrap();
//! assert!(archive.models[1].name == "kuribo");
//!
//! println!("{:#?}", archive.get_model("kuribo").unwrap().meshes[0]);
//! ```
//! Read a .brres file from a raw slice of bytes.
//!
//! ```rs
//! let raw_bytes = std::fs::read("kuribo.brres").expect("Expected kuribo :)");
//!
//! let archive = brres::Archive::from_memory(&raw_bytes).unwrap();
//! assert!(archive.models[1].name == "kuribo");
//!
//! println!("{:#?}", archive.get_model("kuribo").unwrap().meshes[0]);
//! ```
//!
//! ## Writing a file
//! (to a file)
//! ```
//! let kuribo = brres::Archive::from_path("kuribo.brres").unwrap();
//! let buf = kuribo.write_path("kuribo_modified.brres").unwrap();
//! ```
//! (to memory)
//! ```
//! let kuribo = brres::Archive::from_path("kuribo.brres").unwrap();
//! let buf = kuribo.write_memory().unwrap();
//! std::fs::write("kuribo_modified.brres", buf).unwrap();
//! ```
//!
//! ## Current limitations
//! - PAT0, CLR0 and CHR0 support is slightly less than ideal. In particular, existing code emphasizes bit-perfect rebuilding, but lacks the flexibility useful for editing. Future versions should address this.
//! - The internal parts of the library are written in C++. Additionally, the `clang` compiler is needed on Windows. The Microsoft Visual C++ compiler cannot be used.
//! - A lot of documentation is still needed.
//! - SHP0 is unsupported, although almost never used.
//! - Only V11 MDL0 is supported. For older titles we should support older (and newer) versions (v7: Wii Sports?, v9: Brawl, v12: Kirby, etc.)
//! - JSON* structures probably shouldn't be directly exposed.
//! - The names of enum values do not always follow Rust convention.
//!

use std::fs::File;
use std::io::BufReader;

mod buffers;
pub mod enums;
pub mod json;

use brres_sys::ffi;
use enums::*;

use bytemuck;

use json::*;

use std::path::Path;

use anyhow::anyhow;

/// Corresponds to a single `.brres` file
#[derive(Debug, Clone, PartialEq)]
pub struct Archive {
    /// 3D model data. Typically one per Archive, but multiple may appear here. For instance, a normal model, a LOD (low resolution) model and a shadow model.
    pub models: Vec<Model>,

    /// Textures shared by all models in the Archive.
    pub textures: Vec<Texture>,

    // Animation data
    /// Bone (character motion) animation
    pub chrs: Vec<ChrData>,

    /// Texture matrix ("SRT" a.k.a. "Scale, Rotate, Translate") animation
    pub srts: Vec<JSONSrtData>,

    /// Texture data (pattern) animation (e.g. like a GIF)
    pub pats: Vec<JSONPatAnim>,

    /// GPU uniform (color) animation
    pub clrs: Vec<JSONClrAnim>,

    /// Bone visibility animation
    pub viss: Vec<JSONVisData>,
}

/// Corresponds to a single MDL0 file
#[derive(Debug, Clone, PartialEq)]
pub struct Model {
    pub name: String,
    pub info: JSONModelInfo,

    pub bones: Vec<JSONBoneData>,
    pub materials: Vec<JSONMaterial>,
    pub meshes: Vec<Mesh>,

    // Vertex buffers
    pub positions: Vec<VertexPositionBuffer>,
    pub normals: Vec<VertexNormalBuffer>,
    pub texcoords: Vec<VertexTextureCoordinateBuffer>,
    pub colors: Vec<VertexColorBuffer>,

    /// For skinning
    pub matrices: Vec<JSONDrawMatrix>,
}

/// Holds triangle data.
///
/// If you want to optimize the mesh data, see https://crates.io/crates/rsmeshopt
#[derive(Debug, Clone, PartialEq)]
pub struct Mesh {
    pub name: String,

    pub visible: bool,

    // String (for now) references to vertex data arrays in the Model
    pub clr_buffer: Vec<String>,
    pub nrm_buffer: String,
    pub pos_buffer: String,
    pub uv_buffer: Vec<String>,

    /// Bitfield of attributes (1 << n) for n in GXAttr enum
    pub vcd: i32,

    /// For unrigged meshes which matrix (in the Model matrices list) are we referencing? (usually 0, bound to the root bone)
    pub current_matrix: i32,

    /// Actual primitive data. In unrigged models, there will only be one MatrixPrimitive per Mesh.
    pub mprims: Vec<MatrixPrimitive>,
}

/// A group of triangles sharing the same skinning information. In unrigged models, there will only be one MatrixPrimitive per Mesh.
#[derive(Debug, Clone, PartialEq)]
pub struct MatrixPrimitive {
    /// Indices into a `Model`'s `matrices` list.
    ///
    /// When skinning indices are used in the actual vertex data (`vertex_data_buffer` field), they are relative to this list.
    /// (e.g. if `MatrixPrimitive.matrices` was [1, 10, 23] then a vertex PNM index of `1` in a vertex would refer to `Model.matrices[10]`)
    pub matrices: Vec<i32>,

    /// Number of primitives (triangles, quads, tristrips, etc) contained in this draw call. Required for decoding the `vertex_data_buffer` field below.
    pub num_prims: i32,

    /**

    Stored as a giant buffer for convenience. To parse / edit it, the format is described below:

    Format:
    ```c
        struct MatrixPrimitiveBlob {
            Primitive prims[num_prims]; // field above
        };

        struct Primitive __packed__ {
            u8 primitive_type; // e.g. triangles, quads (GXPrimitiveType enum)
            u24 vertex_count;  // big endian
            IndexedVertex vertices[vertex_count];
        };

        struct IndexedVertex {
            u16 indices[26]; // e.g. indices[9] is position (GXAttr enum, GX_POSITION == 9)
                             // little endian
        };
    ```

    Reference code to decode (untested):
    ```py
        cursor = 0
        for i in range(num_prims):
            prim_type = buf[cursor]
            prim_vtx_count = (buf[cursor + 1] << 16) | (buf[cursor + 2] << 8) | buf[cursor + 3]
            cursor += 4

            print(f"Primitive of type {prim_type}:")
            for j in range(prim_vtx_count):
                raw_vertex = buf[cursor:cursor+26*2]
                cursor += 26*2

                decoded_vertex = [raw_vertex[p*2] | (raw_vertex[p*2 + 1] << 8)) for p in range(26)]
                print(f"  -> Vertex: {decoded_vertex}")
    ```
    */
    pub vertex_data_buffer: Vec<u8>,
}

/// Holds positions of vertices in 3D space.
#[derive(Debug, Clone, PartialEq)]
pub struct VertexPositionBuffer {
    /// TODO: Can't we recompute this?
    pub id: i32,
    pub name: String,
    pub q_comp: i32,
    pub q_divisor: i32,
    pub q_stride: i32,
    pub q_type: i32,
    pub data: Vec<[f32; 3]>,
    /// Only here to make unit tests simple (1:1 matching)
    pub cached_minmax: Option<([f32; 3], [f32; 3])>,
}

/// Holds normal vectors of vertices in 3D space.
#[derive(Debug, Clone, PartialEq)]
pub struct VertexNormalBuffer {
    /// TODO: Can't we recompute this?
    pub id: i32,
    pub name: String,
    pub q_comp: i32,
    pub q_divisor: i32,
    pub q_stride: i32,
    pub q_type: i32,
    pub data: Vec<[f32; 3]>,
    /// Only here to make unit tests simple (1:1 matching)
    pub cached_minmax: Option<([f32; 3], [f32; 3])>,
}

/// Holds vertex colors.
#[derive(Debug, Clone, PartialEq)]
pub struct VertexColorBuffer {
    /// TODO: Can't we recompute this?
    pub id: i32,
    pub name: String,
    pub q_comp: i32,
    pub q_divisor: i32,
    pub q_stride: i32,
    pub q_type: i32,
    pub data: Vec<[u8; 4]>,
    /// Only here to make unit tests simple (1:1 matching)
    pub cached_minmax: Option<([u8; 4], [u8; 4])>,
}

/// Holds vertex UV coordinates.
#[derive(Debug, Clone, PartialEq)]
pub struct VertexTextureCoordinateBuffer {
    /// TODO: Can't we recompute this?
    pub id: i32,
    pub name: String,
    pub q_comp: i32,
    pub q_divisor: i32,
    pub q_stride: i32,
    pub q_type: i32,
    pub data: Vec<[f32; 2]>,
    /// Only here to make unit tests simple (1:1 matching)
    pub cached_minmax: Option<([f32; 2], [f32; 2])>,
}

/// Holds a hardware-encoded image. Potentially may store multiple mip levels in a hierarchy. See <https://en.wikipedia.org/wiki/Mipmap#Mechanism>.
#[derive(Debug, Clone, PartialEq)]
pub struct Texture {
    /// Name of this resource.
    pub name: String,

    /// Valid in range `[1, 1024]`. Hardware register is only 10 bits--you cannot exceed this limitation, even on emulator.
    pub width: u32,
    /// Valid in range `[1, 1024]`. Hardware register is only 10 bits--you cannot exceed this limitation, even on emulator.
    pub height: u32,

    /// GPU texture format to be directly loaded into VRAM. Most commonly CMPR a.k.a. BC1 a.k.a. DXT1 (`tex.format == 14`).
    ///
    /// Full enum (from gctex):
    ///
    /// ```rust
    /// pub enum TextureFormat {
    ///     I4 = 0,
    ///     I8,
    ///     IA4,
    ///     IA8,
    ///     RGB565,
    ///     RGB5A3,
    ///     RGBA8,
    ///
    ///     C4 = 0x8,
    ///     C8,
    ///     C14X2,
    ///     CMPR = 0xE,
    /// };
    /// ```
    /// With `gctex`, use `gctex::TextureFormat::from_u32(...)` on this field.
    pub format: u32,

    /// Set to `1` for no mipmaps. Valid in range `[1, 11]`. More tightly bounded above by `1 + floor(log2(min(width, height)))`.
    pub number_of_images: u32,

    /// Raw GPU texture data. Use [`gctex`](https://crates.io/crates/gctex) or similar to decode.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gctex;
    ///
    /// let tex = brres::Texture {
    ///     name: "Example".to_string(),
    ///     width: 8,
    ///     height: 8,
    ///     format: 14,
    ///     number_of_images: 1,
    ///     data: vec![0xF7, 0xBE, 0x6B, 0x0D, 0x34, 0x0E, 0x0D, 0x02, 0xF7, 0x7D, 0x52, 0x4A, 0x20, 0x28, 0xD8, 0xE0,
    ///                0xFF, 0xDF, 0x08, 0x25, 0x00, 0xAA, 0xDE, 0xFC, 0xEF, 0x5C, 0x31, 0x07, 0x00, 0xF8, 0x5C, 0x9C],
    ///     min_lod: 0.0,
    ///     max_lod: 0.0,
    /// };
    ///
    /// let texture_format = gctex::TextureFormat::from_u32(tex.format).unwrap();
    /// let raw_rgba_buffer = gctex::decode(&tex.data, tex.width, tex.height, texture_format, &[0], 0);
    ///
    /// assert_eq!(raw_rgba_buffer,
    ///           [0xF7, 0xF7, 0xF7, 0xFF, 0x9F, 0x99, 0x9F, 0xFF, 0x6B, 0x61, 0x6B, 0xFF, 0xF7, 0xF7, 0xF7, 0xFF,
    ///            0xF7, 0xEF, 0xEF, 0xFF, 0xB9, 0xB0, 0xB4, 0xFF, 0xF7, 0xEF, 0xEF, 0xFF, 0xF7, 0xEF, 0xEF, 0xFF,
    ///            0xF7, 0xF7, 0xF7, 0xFF, 0xF7, 0xF7, 0xF7, 0xFF, 0x9F, 0x99, 0x9F, 0xFF, 0xC2, 0xBE, 0xC2, 0xFF,
    ///            0xF7, 0xEF, 0xEF, 0xFF, 0xB9, 0xB0, 0xB4, 0xFF, 0xB9, 0xB0, 0xB4, 0xFF, 0xF7, 0xEF, 0xEF, 0xFF,
    ///            0xF7, 0xF7, 0xF7, 0xFF, 0xF7, 0xF7, 0xF7, 0xFF, 0x9F, 0x99, 0x9F, 0xFF, 0x6B, 0x61, 0x6B, 0xFF,
    ///            0x8F, 0x87, 0x8C, 0xFF, 0x52, 0x49, 0x52, 0xFF, 0xB9, 0xB0, 0xB4, 0xFF, 0xF7, 0xEF, 0xEF, 0xFF,
    ///            0xF7, 0xF7, 0xF7, 0xFF, 0xF7, 0xF7, 0xF7, 0xFF, 0xF7, 0xF7, 0xF7, 0xFF, 0xC2, 0xBE, 0xC2, 0xFF,
    ///            0x8F, 0x87, 0x8C, 0xFF, 0xB9, 0xB0, 0xB4, 0xFF, 0xF7, 0xEF, 0xEF, 0xFF, 0xF7, 0xEF, 0xEF, 0xFF,
    ///            0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF,
    ///            0xEF, 0xEB, 0xE7, 0xFF, 0xEF, 0xEB, 0xE7, 0xFF, 0xEF, 0xEB, 0xE7, 0xFF, 0xEF, 0xEB, 0xE7, 0xFF,
    ///            0xA2, 0x9E, 0xAE, 0xFF, 0xA2, 0x9E, 0xAE, 0xFF, 0xA2, 0x9E, 0xAE, 0xFF, 0xA2, 0x9E, 0xAE, 0xFF,
    ///            0x78, 0x6C, 0x7A, 0xFF, 0x78, 0x6C, 0x7A, 0xFF, 0xA7, 0x9E, 0xA5, 0xFF, 0xEF, 0xEB, 0xE7, 0xFF,
    ///            0x64, 0x60, 0x79, 0xFF, 0x08, 0x04, 0x29, 0xFF, 0x64, 0x60, 0x79, 0xFF, 0xA2, 0x9E, 0xAE, 0xFF,
    ///            0x31, 0x20, 0x39, 0xFF, 0x31, 0x20, 0x39, 0xFF, 0x78, 0x6C, 0x7A, 0xFF, 0xEF, 0xEB, 0xE7, 0xFF,
    ///            0x64, 0x60, 0x79, 0xFF, 0x64, 0x60, 0x79, 0xFF, 0x64, 0x60, 0x79, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF,
    ///            0xA7, 0x9E, 0xA5, 0xFF, 0x31, 0x20, 0x39, 0xFF, 0x78, 0x6C, 0x7A, 0xFF, 0xEF, 0xEB, 0xE7, 0xFF]);
    /// ```
    pub data: Vec<u8>,

    /// Always recomputed on save (currently).
    /// Set to `0.0`.
    pub min_lod: f32,
    /// Always recomputed on save (currently).
    /// Set to `(tex.number_of_images - 1) as f32`.
    pub max_lod: f32,
}

/// Bone (character motion) animation
#[derive(Debug, Clone, PartialEq)]
pub struct ChrData {
    /// Name of this resource.
    pub name: String,

    /// Bones/Joints/Nodes that are being animated. Specifies which attributes of a Bone are animated.
    pub nodes: Vec<ChrNode>,

    /// Actual animation curve data.
    pub tracks: Vec<ChrTrack>,

    pub source_path: String,
    pub frame_duration: u16,
    pub wrap_mode: u32,
    pub scale_rule: u32,
}

/// Describes the animations being applied to a single Bone.
#[derive(Debug, Clone, PartialEq)]
pub struct ChrNode {
    /// Name of the referenced Bone. Case-sensitive?
    pub name: String,

    /// TODO: Should not be exposed to the user.
    pub flags: u32,

    /// You'll need to interpret `flags` to determine which track indices correspond to which attributes, for now.
    pub tracks: Vec<u32>,
}

/// Animation curve data.
#[derive(Debug, Clone, PartialEq)]
pub struct ChrTrack {
    /// How is this curve being stored? Different formats offer different (lossy) compression.
    /// ChrQuantization::Constant is special--when specified only a single keyframe is permitted.
    pub quant: ChrQuantization,
    /// For some animation formats, you will need to compute an optimal scale/offset affine transform that reduces the signed area of the curve.
    pub scale: f32,
    /// For some animation formats, you will need to compute an optimal scale/offset affine transform that reduces the signed area of the curve.
    pub offset: f32,
    /// Keyframes for the Curve data.
    pub frames_data: Vec<ChrFrame>,
}

/// Hermine spline point in an animation curve. We use f64 because the quantized fixed-point numbers have far more precision than f32 allows (and without this, we wouldn't currently support 1:1 matching on encode-decode.)
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ChrFrame {
    /// x: Position of the current keyframe (in time)
    pub frame: f64,
    /// f(x): Curve evaluated at the frame
    pub value: f64,
    /// f'(x): Slope of curve at the frame
    pub slope: f64,
}

// Useful structure for dumping blobs and keeping track of indices.
struct JsonWriteCtx {
    buffers: Vec<Vec<u8>>,
}

impl JsonWriteCtx {
    fn new() -> Self {
        JsonWriteCtx {
            buffers: Vec::new(),
        }
    }

    fn save_buffer_with_move(&mut self, buf: Vec<u8>) -> usize {
        self.buffers.push(buf);
        self.buffers.len() - 1
    }

    fn save_buffer_with_copy<T: AsRef<[u8]>>(&mut self, buf: T) -> usize {
        let tmp: Vec<u8> = buf.as_ref().to_vec();
        self.save_buffer_with_move(tmp)
    }
}

impl Archive {
    fn from_json(archive: JsonArchive, buffers: Vec<Vec<u8>>) -> Self {
        Self {
            chrs: archive
                .chrs
                .into_iter()
                .map(|m| ChrData::from_json(m, &buffers))
                .collect(),
            clrs: archive.clrs,
            models: archive
                .models
                .into_iter()
                .map(|m| Model::from_json(m, &buffers))
                .collect(),
            pats: archive.pats,
            srts: archive.srts,
            textures: archive
                .textures
                .into_iter()
                .map(|t| Texture::from_json(t, &buffers))
                .collect(),
            viss: archive.viss,
        }
    }

    pub fn get_model(&self, name: &str) -> Option<&Model> {
        self.models.iter().find(|model| model.name == name)
    }

    pub fn get_texture(&self, name: &str) -> Option<&Texture> {
        self.textures.iter().find(|texture| texture.name == name)
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonArchive {
        JsonArchive {
            chrs: self.chrs.iter().map(|c| c.to_json(ctx)).collect(),
            clrs: self.clrs.clone(),
            models: self.models.iter().map(|m| m.to_json(ctx)).collect(),
            pats: self.pats.clone(),
            srts: self.srts.clone(),
            textures: self.textures.iter().map(|t| t.to_json(ctx)).collect(),
            viss: self.viss.clone(),
        }
    }
}

impl Model {
    fn from_json(model: JsonModel, buffers: &[Vec<u8>]) -> Self {
        Self {
            bones: model.bones,
            materials: model.materials,
            matrices: model.matrices,
            meshes: model
                .meshes
                .into_iter()
                .map(|m| Mesh::from_json(m, buffers))
                .collect(),
            name: model.name,
            info: model.info,
            positions: model
                .positions
                .into_iter()
                .map(|m| VertexPositionBuffer::from_json(m, buffers))
                .collect(),
            normals: model
                .normals
                .into_iter()
                .map(|m| VertexNormalBuffer::from_json(m, buffers))
                .collect(),
            colors: model
                .colors
                .into_iter()
                .map(|m| VertexColorBuffer::from_json(m, buffers))
                .collect(),
            texcoords: model
                .texcoords
                .into_iter()
                .map(|m| VertexTextureCoordinateBuffer::from_json(m, buffers))
                .collect(),
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonModel {
        JsonModel {
            name: self.name.clone(),
            info: self.info.clone(),
            bones: self.bones.clone(),
            materials: self.materials.clone(),
            matrices: self.matrices.clone(),
            meshes: self.meshes.iter().map(|m| m.to_json(ctx)).collect(),
            positions: self.positions.iter().map(|p| p.to_json(ctx)).collect(),
            normals: self.normals.iter().map(|n| n.to_json(ctx)).collect(),
            colors: self.colors.iter().map(|c| c.to_json(ctx)).collect(),
            texcoords: self.texcoords.iter().map(|t| t.to_json(ctx)).collect(),
        }
    }
}

impl Mesh {
    fn from_json(json_mesh: JsonMesh, buffers: &[Vec<u8>]) -> Self {
        Self {
            clr_buffer: json_mesh.clr_buffer,
            current_matrix: json_mesh.current_matrix,
            mprims: json_mesh
                .mprims
                .into_iter()
                .map(|p| MatrixPrimitive::from_json(p, buffers))
                .collect(),
            name: json_mesh.name,
            nrm_buffer: json_mesh.nrm_buffer,
            pos_buffer: json_mesh.pos_buffer,
            uv_buffer: json_mesh.uv_buffer,
            vcd: json_mesh.vcd,
            visible: json_mesh.visible,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonMesh {
        JsonMesh {
            clr_buffer: self.clr_buffer.clone(),
            current_matrix: self.current_matrix,
            mprims: self.mprims.iter().map(|p| p.to_json(ctx)).collect(),
            name: self.name.clone(),
            nrm_buffer: self.nrm_buffer.clone(),
            pos_buffer: self.pos_buffer.clone(),
            uv_buffer: self.uv_buffer.clone(),
            vcd: self.vcd,
            visible: self.visible,
        }
    }
}

impl MatrixPrimitive {
    fn from_json(json_primitive: JsonPrimitive, buffers: &[Vec<u8>]) -> Self {
        let vertex_data_buffer = buffers
            .get(json_primitive.vertexDataBufferId as usize)
            .cloned()
            .unwrap_or_else(Vec::new);

        Self {
            matrices: json_primitive.matrices,
            num_prims: json_primitive.num_prims,
            vertex_data_buffer,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonPrimitive {
        let buffer_id = ctx.save_buffer_with_copy(&self.vertex_data_buffer);

        JsonPrimitive {
            matrices: self.matrices.clone(),
            num_prims: self.num_prims,
            vertexDataBufferId: buffer_id as i32,
        }
    }
}

impl VertexPositionBuffer {
    fn from_json(buffer_data: JsonBufferData<[f32; 3]>, buffers: &[Vec<u8>]) -> Self {
        let data = buffers
            .get(buffer_data.dataBufferId as usize)
            .expect("Invalid buffer ID");
        let elem_count = data.len() / std::mem::size_of::<[f32; 3]>();
        let data: Vec<[f32; 3]> = unsafe {
            std::slice::from_raw_parts(data.as_ptr() as *const [f32; 3], elem_count).to_vec()
        };

        let cached_minmax = if let (Some(cached_min), Some(cached_max)) =
            (buffer_data.cached_min, buffer_data.cached_max)
        {
            Some((cached_min, cached_max))
        } else {
            None
        };

        Self {
            id: buffer_data.id,
            name: buffer_data.name,
            q_comp: buffer_data.q_comp,
            q_divisor: buffer_data.q_divisor,
            q_stride: buffer_data.q_stride,
            q_type: buffer_data.q_type,
            data,
            cached_minmax,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonBufferData<[f32; 3]> {
        let buffer_id = ctx.save_buffer_with_copy(bytemuck::cast_slice(&self.data));

        JsonBufferData {
            dataBufferId: buffer_id as i32,
            id: self.id,
            name: self.name.clone(),
            q_comp: self.q_comp,
            q_divisor: self.q_divisor,
            q_stride: self.q_stride,
            q_type: self.q_type,
            cached_min: self.cached_minmax.map(|(min, _)| min),
            cached_max: self.cached_minmax.map(|(_, max)| max),
        }
    }
}

impl VertexNormalBuffer {
    fn from_json(buffer_data: JsonBufferData<[f32; 3]>, buffers: &[Vec<u8>]) -> Self {
        let data = buffers
            .get(buffer_data.dataBufferId as usize)
            .expect("Invalid buffer ID");
        let elem_count = data.len() / std::mem::size_of::<[f32; 3]>();
        let data: Vec<[f32; 3]> = unsafe {
            std::slice::from_raw_parts(data.as_ptr() as *const [f32; 3], elem_count).to_vec()
        };

        let cached_minmax = if let (Some(cached_min), Some(cached_max)) =
            (buffer_data.cached_min, buffer_data.cached_max)
        {
            Some((cached_min, cached_max))
        } else {
            None
        };

        Self {
            id: buffer_data.id,
            name: buffer_data.name,
            q_comp: buffer_data.q_comp,
            q_divisor: buffer_data.q_divisor,
            q_stride: buffer_data.q_stride,
            q_type: buffer_data.q_type,
            data,
            cached_minmax,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonBufferData<[f32; 3]> {
        let buffer_id = ctx.save_buffer_with_copy(bytemuck::cast_slice(&self.data));

        JsonBufferData {
            dataBufferId: buffer_id as i32,
            id: self.id,
            name: self.name.clone(),
            q_comp: self.q_comp,
            q_divisor: self.q_divisor,
            q_stride: self.q_stride,
            q_type: self.q_type,
            cached_min: self.cached_minmax.map(|(min, _)| min),
            cached_max: self.cached_minmax.map(|(_, max)| max),
        }
    }
}

impl VertexColorBuffer {
    fn from_json(buffer_data: JsonBufferData<[u8; 4]>, buffers: &[Vec<u8>]) -> Self {
        let data = buffers
            .get(buffer_data.dataBufferId as usize)
            .expect("Invalid buffer ID");
        let elem_count = data.len() / std::mem::size_of::<[u8; 4]>();
        let data: Vec<[u8; 4]> = unsafe {
            std::slice::from_raw_parts(data.as_ptr() as *const [u8; 4], elem_count).to_vec()
        };

        let cached_minmax = if let (Some(cached_min), Some(cached_max)) =
            (buffer_data.cached_min, buffer_data.cached_max)
        {
            Some((cached_min, cached_max))
        } else {
            None
        };

        Self {
            id: buffer_data.id,
            name: buffer_data.name,
            q_comp: buffer_data.q_comp,
            q_divisor: buffer_data.q_divisor,
            q_stride: buffer_data.q_stride,
            q_type: buffer_data.q_type,
            data,
            cached_minmax,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonBufferData<[u8; 4]> {
        let buffer_id = ctx.save_buffer_with_copy(bytemuck::cast_slice(&self.data));

        JsonBufferData {
            dataBufferId: buffer_id as i32,
            id: self.id,
            name: self.name.clone(),
            q_comp: self.q_comp,
            q_divisor: self.q_divisor,
            q_stride: self.q_stride,
            q_type: self.q_type,
            cached_min: self.cached_minmax.map(|(min, _)| min),
            cached_max: self.cached_minmax.map(|(_, max)| max),
        }
    }
}

impl VertexTextureCoordinateBuffer {
    fn from_json(buffer_data: JsonBufferData<[f32; 2]>, buffers: &[Vec<u8>]) -> Self {
        let data = buffers
            .get(buffer_data.dataBufferId as usize)
            .expect("Invalid buffer ID");
        let elem_count = data.len() / std::mem::size_of::<[f32; 2]>();
        let data: Vec<[f32; 2]> = unsafe {
            std::slice::from_raw_parts(data.as_ptr() as *const [f32; 2], elem_count).to_vec()
        };

        let cached_minmax = if let (Some(cached_min), Some(cached_max)) =
            (buffer_data.cached_min, buffer_data.cached_max)
        {
            Some((cached_min, cached_max))
        } else {
            None
        };

        Self {
            id: buffer_data.id,
            name: buffer_data.name,
            q_comp: buffer_data.q_comp,
            q_divisor: buffer_data.q_divisor,
            q_stride: buffer_data.q_stride,
            q_type: buffer_data.q_type,
            data,
            cached_minmax,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonBufferData<[f32; 2]> {
        let buffer_id = ctx.save_buffer_with_copy(bytemuck::cast_slice(&self.data));

        JsonBufferData {
            dataBufferId: buffer_id as i32,
            id: self.id,
            name: self.name.clone(),
            q_comp: self.q_comp,
            q_divisor: self.q_divisor,
            q_stride: self.q_stride,
            q_type: self.q_type,
            cached_min: self.cached_minmax.map(|(min, _)| min),
            cached_max: self.cached_minmax.map(|(_, max)| max),
        }
    }
}

impl Texture {
    fn from_json(texture: JsonTexture, buffers: &[Vec<u8>]) -> Self {
        let data = buffers
            .get(texture.dataBufferId as usize)
            .map(|buffer| buffer.clone())
            .unwrap_or_else(Vec::new);

        Self {
            data,
            format: texture.format,
            height: texture.height,
            max_lod: texture.maxLod,
            min_lod: texture.minLod,
            name: texture.name,
            number_of_images: texture.number_of_images,
            width: texture.width,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JsonTexture {
        let buffer_id = ctx.save_buffer_with_copy(&self.data);

        JsonTexture {
            dataBufferId: buffer_id as i32,
            format: self.format,
            height: self.height,
            maxLod: self.max_lod,
            minLod: self.min_lod,
            name: self.name.clone(),
            number_of_images: self.number_of_images,
            width: self.width,
            sourcePath: "".to_string(),
        }
    }
}

impl ChrData {
    fn from_json(json_data: JSONChrData, buffers: &[Vec<u8>]) -> Self {
        let nodes = json_data
            .nodes
            .into_iter()
            .map(ChrNode::from_json)
            .collect();
        let tracks = json_data
            .tracks
            .into_iter()
            .map(|json_track| ChrTrack::from_json(json_track, buffers))
            .collect();

        Self {
            nodes,
            tracks,
            name: json_data.name,
            source_path: json_data.sourcePath,
            frame_duration: json_data.frameDuration,
            wrap_mode: json_data.wrapMode,
            scale_rule: json_data.scaleRule,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JSONChrData {
        let nodes = self.nodes.iter().map(ChrNode::to_json).collect();
        let tracks = self.tracks.iter().map(|track| track.to_json(ctx)).collect();

        JSONChrData {
            nodes,
            tracks,
            name: self.name.clone(),
            sourcePath: self.source_path.clone(),
            frameDuration: self.frame_duration,
            wrapMode: self.wrap_mode,
            scaleRule: self.scale_rule,
        }
    }
}

impl ChrNode {
    fn from_json(json_node: JSONChrNode) -> Self {
        Self {
            name: json_node.name,
            flags: json_node.flags,
            tracks: json_node.tracks,
        }
    }

    fn to_json(&self) -> JSONChrNode {
        JSONChrNode {
            name: self.name.clone(),
            flags: self.flags,
            tracks: self.tracks.clone(),
        }
    }
}

impl ChrTrack {
    fn from_json(json_track: JSONChrTrack, buffers: &[Vec<u8>]) -> Self {
        let data = buffers
            .get(json_track.framesDataBufferId as usize)
            .expect("Invalid buffer ID");
        let frames_data = ChrFramePacker::unpack(data, json_track.numKeyFrames as usize);

        Self {
            quant: json_track.quant,
            scale: json_track.scale,
            offset: json_track.offset,
            frames_data,
        }
    }

    fn to_json(&self, ctx: &mut JsonWriteCtx) -> JSONChrTrack {
        let buffer_id = ctx.save_buffer_with_move(ChrFramePacker::pack(&self.frames_data));

        JSONChrTrack {
            quant: self.quant,
            scale: self.scale,
            offset: self.offset,
            framesDataBufferId: buffer_id as u32,
            numKeyFrames: self.frames_data.len() as u32,
        }
    }
}

struct ChrFramePacker;

impl ChrFramePacker {
    const CHR_FRAME_SIZE: usize = 8 * 3;

    fn pack(frames: &[ChrFrame]) -> Vec<u8> {
        let mut buffer = Vec::with_capacity(frames.len() * Self::CHR_FRAME_SIZE);
        for frame in frames {
            buffer.extend_from_slice(&frame.frame.to_le_bytes());
            buffer.extend_from_slice(&frame.value.to_le_bytes());
            buffer.extend_from_slice(&frame.slope.to_le_bytes());
        }
        buffer
    }

    fn unpack(bytes: &[u8], num_keyframes: usize) -> Vec<ChrFrame> {
        let mut frames = Vec::with_capacity(num_keyframes);
        for i in 0..num_keyframes {
            let offset = i * Self::CHR_FRAME_SIZE;
            let frame = f64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap());
            let value = f64::from_le_bytes(bytes[offset + 8..offset + 16].try_into().unwrap());
            let slope = f64::from_le_bytes(bytes[offset + 16..offset + 24].try_into().unwrap());
            frames.push(ChrFrame {
                frame,
                value,
                slope,
            });
        }
        frames
    }
}

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

    #[test]
    fn test_archive() {
        let file_path = "dummy.json";
        match read_json(file_path) {
            Ok(json_archive) => {
                // Assuming buffers are loaded here
                let buffers = buffers::read_buffer(&fs::read("dummy.bin").unwrap());
                let archive = Archive::from_json(json_archive, buffers);
                // Add more tests to validate Archive methods
                assert!(archive.get_model("example").is_some());
                assert!(archive.get_texture("human_A").is_some());
            }
            Err(e) => panic!("Error reading JSON file: {}", e),
        }
    }
}

fn create_archive(json_str: &str, raw_buffer: &[u8]) -> anyhow::Result<Archive> {
    // Decode the JSON string to JsonArchive
    let json_archive: JsonArchive = serde_json::from_str(json_str)?;

    // Convert the raw buffer to Vec<Vec<u8>> using read_buffer
    let buffers = buffers::read_buffer(raw_buffer);

    // Create and return the Archive
    Ok(Archive::from_json(json_archive, buffers))
}

fn create_json(archive: &Archive) -> anyhow::Result<(String, Vec<u8>)> {
    let mut ctx = JsonWriteCtx::new();
    let json_archive = archive.to_json(&mut ctx);
    let json_str = serde_json::to_string_pretty(&json_archive)?;
    let blob = buffers::collate_buffers(&ctx.buffers);

    Ok((json_str, blob))
}

/// Read a .brres file from memory
fn read_raw_brres(brres: &[u8]) -> anyhow::Result<Archive> {
    let tmp = ffi::CBrresWrapper::from_bytes(brres)?;

    create_archive(&tmp.json_metadata, &tmp.buffer_data)
}

/// Write a .brres to memory
fn write_raw_brres(archive: &Archive) -> anyhow::Result<Vec<u8>> {
    let (json, blob) = create_json(&archive)?;

    let ffi_obj = ffi::CBrresWrapper::write_bytes(&json, &blob)?;

    // This is a copy we could avoid by returning the CBrresWrapper iteslf--but this
    // avoids exposing a dependency and keeps the API simple.
    Ok(ffi_obj.buffer_data.to_vec())
}

/// Read a .mdl0mat preset folder
/// TODO: Add test
pub fn read_mdl0mat_preset_folder(folder: &std::path::Path) -> anyhow::Result<Archive> {
    let folder_str = folder.to_str().ok_or(anyhow!("Failed to stringify path"))?;
    let ffi_obj = ffi::CBrresWrapper::read_preset_folder(folder_str)?;

    Ok(read_raw_brres(&ffi_obj.buffer_data)?)
}

impl Archive {
    /// Read a .brres file from a raw slice of bytes.
    ///
    /// ```
    /// let raw_bytes = std::fs::read("kuribo.brres").expect("Expected kuribo :)");
    ///
    /// let archive = brres::Archive::from_memory(&raw_bytes).unwrap();
    /// assert!(archive.models[1].name == "kuribo");
    ///
    /// println!("{:#?}", archive.get_model("kuribo").unwrap().meshes[0]);
    /// ```
    pub fn from_memory(buffer: &[u8]) -> anyhow::Result<Archive> {
        read_raw_brres(&buffer)
    }

    /// Read a .brres file from a path on the filesystem.
    ///
    /// ```
    /// let archive = brres::Archive::from_path("kuribo.brres").unwrap();
    /// assert!(archive.models[1].name == "kuribo");
    ///
    /// println!("{:#?}", archive.get_model("kuribo").unwrap().meshes[0]);
    /// ```
    pub fn from_path<P: AsRef<Path>>(path: P) -> anyhow::Result<Archive> {
        let buf = std::fs::read(path)?;

        read_raw_brres(&buf)
    }

    /// Write a .brres file to a raw vector of bytes.
    ///
    /// ```
    /// let kuribo = brres::Archive::from_path("kuribo.brres").unwrap();
    /// let buf = kuribo.write_memory().unwrap();
    /// std::fs::write("kuribo_modified.brres", buf).unwrap();
    /// ```
    pub fn write_memory(self: &Self) -> anyhow::Result<Vec<u8>> {
        write_raw_brres(self)
    }

    /// Write a .brres file to a file.
    ///
    /// ```
    /// let kuribo = brres::Archive::from_path("kuribo.brres").unwrap();
    /// let buf = kuribo.write_path("kuribo_modified.brres").unwrap();
    /// ```
    pub fn write_path<P: AsRef<Path>>(self: &Self, path: P) -> anyhow::Result<()> {
        let buf = write_raw_brres(self)?;
        std::fs::write(path, buf)?;

        Ok(())
    }
}

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

    #[test]
    fn test_read_raw_brres() {
        // Read the sea.brres file into a byte array
        let brres_data =
            fs::read("../../tests/samples/sea.brres").expect("Failed to read sea.brres file");

        // Call the read_raw_brres function
        match read_raw_brres(&brres_data) {
            Ok(archive) => {
                println!("{:#?}", archive.get_model("sea").unwrap().meshes[0]);
                println!("{:#?}", archive.get_model("sea").unwrap().materials[0]);
            }
            Err(e) => {
                panic!("Error reading brres file: {:#?}", e);
            }
        }
    }

    #[test]
    fn test_validate_json_is_lossless_sea() {
        // Read the sea.brres file into a byte array
        let brres_data =
            fs::read("../../tests/samples/sea.brres").expect("Failed to read sea.brres file");

        // Call the read_raw_brres function to create the initial Archive
        let initial_archive = read_raw_brres(&brres_data).expect("Failed to read brres file");

        // Convert the initial Archive to a JSON string
        let (json_str, blob) =
            create_json(&initial_archive).expect("Failed to create JSON from Archive");

        // Create a new Archive from the JSON string
        let new_archive =
            create_archive(&json_str, &blob).expect("Failed to create Archive from JSON");

        // new_archive.models[0].name = "lol".to_string();

        // Compare the initial and new Archives (you might need to implement PartialEq for Archive)
        assert_eq!(
            initial_archive, new_archive,
            "Archives do not match after JSON roundtrip"
        );

        // Print some debug information if needed
        println!("{:#?}", initial_archive.get_model("sea").unwrap().meshes[0]);
        println!(
            "{:#?}",
            initial_archive.get_model("sea").unwrap().materials[0]
        );
    }
    fn assert_buffers_equal(encoded_image: &[u8], cached_image: &[u8], format: &str) {
        if encoded_image != cached_image {
            let diff_count = encoded_image
                .iter()
                .zip(cached_image.iter())
                .filter(|(a, b)| a != b)
                .count();
            println!("Mismatch for {:?} - {} bytes differ", format, diff_count);

            // Print some example differences (up to 10)
            let mut diff_examples = vec![];
            for (i, (a, b)) in encoded_image.iter().zip(cached_image.iter()).enumerate() {
                if a != b {
                    diff_examples.push((i, *a, *b));
                    if diff_examples.len() >= 10 {
                        break;
                    }
                }
            }

            println!("Example differences (up to 10):");
            for (i, a, b) in diff_examples {
                println!("Byte {}: encoded = {}, cached = {}", i, a, b);
            }

            println!(
                "Size of left: {}, size of right: {}",
                encoded_image.len(),
                cached_image.len()
            );
            panic!("Buffers are not equal");
        }
    }
    fn test_validate_binary_is_lossless(path: &str, passes: bool) {
        let name = std::path::Path::new(path)
            .file_name()
            .unwrap()
            .to_str()
            .unwrap();
        let brres_data = fs::read(path).expect("Failed to read brres file");
        let archive = read_raw_brres(&brres_data).expect("Error reading brres file");
        let written_data = write_raw_brres(&archive).expect("Error writing brres file");

        if passes {
            if &brres_data != &written_data {
                fs::write(format!("{name}_good.brres"), &brres_data);
                fs::write(format!("{name}_bad.brres"), &written_data);
            }
            assert_buffers_equal(&brres_data, &written_data, path);
        } else {
            assert!(&brres_data != &written_data)
        }
    }
    #[test]
    fn test_validate_binary_is_lossless_walk() {
        let brres_data = fs::read("../../tests/samples/human_walk.brres")
            .expect("Failed to read human_walk.brres file");
        let archive = read_raw_brres(&brres_data).expect("Error reading brres file");
        let written_data = write_raw_brres(&archive).expect("Error writing brres file");

        fs::write("Invalid_human_walk.brres", &written_data).unwrap();

        // panic!("{:#?}", archive.get_model("human_walk").unwrap().materials[0]);

        assert_buffers_equal(&brres_data, &written_data, "human_walk.brres");
    }
    #[test]
    fn test_validate_binary_is_lossless_sea() {
        test_validate_binary_is_lossless("../../tests/samples/sea.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_srt() {
        test_validate_binary_is_lossless("../../tests/samples/srt.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_rPB() {
        test_validate_binary_is_lossless("../../tests/samples/rPB.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_MashBalloonGC() {
        test_validate_binary_is_lossless("../../tests/samples/MashBalloonGC.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_human_walk_env() {
        test_validate_binary_is_lossless("../../tests/samples/human_walk_env.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_map_model() {
        test_validate_binary_is_lossless("../../tests/samples/map_model.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_kuribo() {
        // CHR0
        test_validate_binary_is_lossless("../../tests/samples/kuribo.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_human_walk_chr0() {
        test_validate_binary_is_lossless("../../tests/samples/human_walk_chr0.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_driver_model() {
        test_validate_binary_is_lossless("../../tests/samples/driver_model.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_mariotreeGC() {
        test_validate_binary_is_lossless("../../tests/samples/mariotreeGC.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_fur_rabbits_chr0() {
        test_validate_binary_is_lossless("../../tests/samples/fur_rabbits-chr0.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_luigi_circuit() {
        // PAT0
        test_validate_binary_is_lossless("../../tests/samples/luigi_circuit.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_pocha_nomodel() {
        // CHR0, CLR0, SRT0
        test_validate_binary_is_lossless("../../tests/samples/pocha_nomodel.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_pocha() {
        // Desync: Draw order
        test_validate_binary_is_lossless("../../tests/samples/pocha.brres", false)
    }
    #[test]
    fn test_validate_binary_is_lossless_smooth_rtpa() {
        // PAT0
        test_validate_binary_is_lossless("../../tests/samples/smooth_rtpa.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_smooth_rcla() {
        // CLR0
        test_validate_binary_is_lossless("../../tests/samples/smooth_rcla.brres", true)
    }
    #[test]
    fn test_validate_binary_is_lossless_brvia() {
        test_validate_binary_is_lossless("../../tests/samples/brvia.brres", true)
    }
    #[test]
    fn test_driver_model() {
        // Bunch of CHR0
        test_validate_binary_is_lossless("../../tests/samples/driver_model.brres", true)
    }
}