ssbh_data 0.19.0

High level data access layer for SSBH formats
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
//! Types for working with [Anim] data in .nuanmb files.
//!
//! # Examples
//! Animation data is stored in a hierarchy.
//! Values for each frame are stored at the [TrackData] level.
/*!

```rust no_run
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use ssbh_data::prelude::*;

let anim = AnimData::from_file("model.nuanmb")?;

for group in anim.groups {
    for node in group.nodes {
        for track in node.tracks {
            println!("Frame Count: {}", track.values.len());
        }
    }
}
# Ok(()) }
```
 */
//!
//! # Compression
//! Compressed animations use lossy compression for all data types except [TrackValues::Boolean].
//! Float compression encodes values using a configurable number of
//! values between two floating point endpoints.
//! Depending on the endpoints and number of bits, the encoded values
//! between the two endpoints may not be representable by 32 bit floating point.
//! This means that decompression may introduce some error, so compressing an animation
//! again with the same settings may produce slightly different compressed data.
//!
//! # File Differences
//! Unmodified files are not guaranteed to be binary identical after saving.
//! Compressed animations use lossy compression for all data types except [TrackValues::Boolean].
//! When converting to [Anim], compression is enabled for a track if compression would save space.
//! This may produce differences with the original due to compression differences.
//! These errors are small in practice but may cause gameplay differences such as online desyncs.
use binrw::io::{Cursor, Seek, Write};
use binrw::{BinRead, BinReaderExt};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
pub use ssbh_lib::formats::anim::GroupType;
use ssbh_lib::formats::anim::TrackTypeV1;
use ssbh_lib::{
    formats::anim::{
        Anim, CompressionType, Group, Node, TrackFlags, TrackTypeV2, TrackV2,
        TransformFlags as AnimTransformFlags, UnkData,
    },
    SsbhArray, Vector3, Vector4, Version,
};
use ssbh_write::SsbhWrite;
use std::collections::HashMap;
use std::{
    convert::{TryFrom, TryInto},
    error::Error,
};

mod buffers;
use buffers::*;
mod bitutils;
mod compression;

/// Data associated with an [Anim] file.
/// Supported versions are 2.0 and 2.1.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, PartialEq, Clone)]
pub struct AnimData {
    pub major_version: u16,
    pub minor_version: u16,

    /// The index of the last frame in the animation,
    /// which is calculated as `(frame_count - 1) as f32`.
    ///
    /// Constant animations will last for final_frame_index + 1 many frames.
    ///
    /// Frames use floating point to allow the rendering speed to differ from the animation speed.
    /// For example, some animations in Smash Ultimate interpolate when playing the game at 60fps but 1/4 speed.
    pub final_frame_index: f32,
    pub groups: Vec<GroupData>,
}

// TODO: Test these conversions.
impl TryFrom<Anim> for AnimData {
    type Error = Box<dyn Error>;

    fn try_from(anim: Anim) -> Result<Self, Self::Error> {
        (&anim).try_into()
    }
}

impl TryFrom<&Anim> for AnimData {
    type Error = Box<dyn Error>;

    fn try_from(anim: &Anim) -> Result<Self, Self::Error> {
        let (major_version, minor_version) = anim.major_minor_version();
        Ok(Self {
            major_version,
            minor_version,
            final_frame_index: match &anim {
                Anim::V12 {
                    final_frame_index, ..
                } => *final_frame_index,
                Anim::V20 {
                    final_frame_index, ..
                } => *final_frame_index,
                Anim::V21 {
                    final_frame_index, ..
                } => *final_frame_index,
            },
            groups: read_anim_groups(anim)?,
        })
    }
}

impl TryFrom<AnimData> for Anim {
    type Error = error::Error;

    fn try_from(data: AnimData) -> Result<Self, Self::Error> {
        create_anim(&data)
    }
}

impl TryFrom<&AnimData> for Anim {
    type Error = error::Error;

    fn try_from(data: &AnimData) -> Result<Self, Self::Error> {
        create_anim(data)
    }
}

pub mod error {
    use super::*;
    use thiserror::Error;

    /// Errors while creating an [Anim] from [AnimData].
    #[derive(Debug, Error)]
    pub enum Error {
        /// Creating an [Anim] file for the given version is not supported.
        #[error(
            "creating a version {}.{} anim is not supported",
            major_version,
            minor_version
        )]
        UnsupportedVersion {
            major_version: u16,
            minor_version: u16,
        },

        /// The final frame index is negative or smaller than the
        // index of the final frame in the longest track.
        #[error(
            "final frame index {} must be non negative and at least as 
             large as the index of the final frame in the longest track",
            final_frame_index
        )]
        InvalidFinalFrameIndex { final_frame_index: f32 },

        /// An error occurred while writing data to a buffer.
        #[error(transparent)]
        Io(#[from] std::io::Error),

        /// An error occurred while reading data from a buffer.
        #[error(transparent)]
        BinRead(#[from] binrw::error::Error),

        /// An error occurred while reading compressed data from a buffer.
        #[error(transparent)]
        BitError(#[from] bitutils::BitReadError),

        #[error(
            "compressed header bits per entry of {} does not match expected value of {}",
            actual,
            expected
        )]
        UnexpectedBitCount { expected: usize, actual: usize },

        #[error(
            "track data range {0}..{0}+{1} is out of range for a buffer of size {2}",
            start,
            size,
            buffer_size
        )]
        InvalidTrackDataRange {
            start: usize,
            size: usize,
            buffer_size: usize,
        },

        /// The buffer index is not valid for a version 1.2 anim file.
        #[error(
            "buffer index {} is out of range for a buffer collection of size {}",
            buffer_index,
            buffer_count
        )]
        BufferIndexOutOfRange {
            buffer_index: usize,
            buffer_count: usize,
        },

        /// An error occurred while reading the compressed header for version 2.0 or later.
        #[error("the track data compression header is malformed and cannot be read")]
        MalformedCompressionHeader,
    }
}

enum AnimVersion {
    Version20,
    Version21,
}

// TODO: Test this for a small example?
fn create_anim(data: &AnimData) -> Result<Anim, error::Error> {
    let version = match (data.major_version, data.minor_version) {
        (2, 0) => Ok(AnimVersion::Version20),
        (2, 1) => Ok(AnimVersion::Version21),
        _ => Err(error::Error::UnsupportedVersion {
            major_version: data.major_version,
            minor_version: data.minor_version,
        }),
    }?;

    let mut buffer = Cursor::new(Vec::new());

    let animations = data
        .groups
        .iter()
        .map(|g| create_anim_group(g, &mut buffer))
        .collect::<Result<Vec<_>, _>>()?;

    let max_frame_count = animations
        .iter()
        .filter_map(|a| {
            a.nodes
                .elements
                .iter()
                .filter_map(|n| n.tracks.elements.iter().map(|t| t.frame_count).max())
                .max()
        })
        .max()
        .unwrap_or(0);

    // Make sure the final frame index is at least as large as the final frame of the longest animation.
    let final_frame_index = if data.final_frame_index >= 0.0
        && data.final_frame_index >= max_frame_count as f32 - 1.0
    {
        Ok(data.final_frame_index)
    } else {
        Err(error::Error::InvalidFinalFrameIndex {
            final_frame_index: data.final_frame_index,
        })
    }?;

    match version {
        AnimVersion::Version20 => Ok(Anim::V20 {
            final_frame_index,
            unk1: 1,
            unk2: 3,
            name: "".into(), // TODO: this is usually based on file name?
            groups: animations.into(),
            buffer: buffer.into_inner().into(),
        }),
        AnimVersion::Version21 => Ok(Anim::V21 {
            final_frame_index,
            unk1: 1,
            unk2: 3,
            name: "".into(), // TODO: this is usually based on file name?
            groups: animations.into(),
            buffer: buffer.into_inner().into(),
            // TODO: Research how to rebuild the extra header data.
            unk_data: UnkData {
                unk1: SsbhArray::new(),
                unk2: SsbhArray::new(),
            },
        }),
    }
}

fn create_anim_group(g: &GroupData, buffer: &mut Cursor<Vec<u8>>) -> Result<Group, error::Error> {
    Ok(Group {
        group_type: g.group_type,
        nodes: g
            .nodes
            .iter()
            .map(|n| create_anim_node(n, buffer))
            .collect::<Result<Vec<_>, _>>()?
            .into(),
    })
}

fn create_anim_node(n: &NodeData, buffer: &mut Cursor<Vec<u8>>) -> Result<Node, error::Error> {
    Ok(Node {
        name: n.name.as_str().into(), // TODO: Make a convenience method for this?
        tracks: n
            .tracks
            .iter()
            .map(|t| create_anim_track_v2(buffer, t))
            .collect::<Result<Vec<_>, _>>()?
            .into(),
    })
}

fn create_anim_track_v2(
    buffer: &mut Cursor<Vec<u8>>,
    t: &TrackData,
) -> Result<TrackV2, error::Error> {
    let compression_type = infer_optimal_compression_type(&t.values);

    // The current stream position matches the offsets used for Smash Ultimate's anim files.
    // This assumes we traverse the hierarchy (group -> node -> track) in DFS order.
    let pos_before = buffer.stream_position()?;

    // Pointers for compressed data are relative to the start of the track's data.
    // This requires using a second writer due to how SsbhWrite is implemented.
    let mut track_data = Cursor::new(Vec::new());

    // TODO: Add tests for preserving scale compensation?.
    t.values
        .write(&mut track_data, compression_type, t.compensate_scale)?;

    buffer.write_all(&track_data.into_inner())?;
    let pos_after = buffer.stream_position()?;

    Ok(TrackV2 {
        name: t.name.as_str().into(),
        flags: TrackFlags {
            track_type: t.values.track_type(),
            compression_type,
        },
        frame_count: t.values.len() as u32,
        transform_flags: t.transform_flags.into(),
        data_offset: pos_before as u32,
        data_size: pos_after - pos_before,
    })
}

fn infer_optimal_compression_type(values: &TrackValues) -> CompressionType {
    match (values, values.len()) {
        // Single frame animations use a special compression type.
        (TrackValues::Transform(_), 0..=1) => CompressionType::ConstTransform,
        (_, 0..=1) => CompressionType::Constant,
        _ => {
            // The compressed header adds some overhead, so we need to also check frame count.
            // Once there are enough elements to exceed the header size, compression starts to save space.

            // TODO: Is integer division correct here?
            let uncompressed_frames_per_header =
                values.compressed_overhead_in_bytes() / values.data_size_in_bytes();

            // Some tracks overlap the default data with the compression to save space.
            // This calculation assumes we aren't performing that optimization.
            if values.len() > uncompressed_frames_per_header as usize + 1 {
                CompressionType::Compressed
            } else {
                CompressionType::Direct
            }
        }
    }
}

// TODO: Test conversions from anim?
fn read_anim_groups(anim: &Anim) -> Result<Vec<GroupData>, error::Error> {
    match anim {
        // TODO: Create fake groups for version 1.0?
        ssbh_lib::prelude::Anim::V12 {
            tracks, buffers, ..
        } => {
            // TODO: Group by type?
            // TODO: Assign a single node to each track with the track name as the name?
            // TODO: Use the track type as the track name like "Transform"?
            read_groups_v12(&tracks.elements, &buffers.elements)
        }
        ssbh_lib::formats::anim::Anim::V20 { groups, buffer, .. } => {
            read_groups_v20(&groups.elements, &buffer.elements)
        }
        ssbh_lib::formats::anim::Anim::V21 { groups, buffer, .. } => {
            read_groups_v20(&groups.elements, &buffer.elements)
        }
    }
}

fn group_type_v12(track_type: TrackTypeV1) -> GroupType {
    match track_type {
        TrackTypeV1::Transform => GroupType::Transform,
        TrackTypeV1::UvTransform => GroupType::Material,
        TrackTypeV1::Visibility => GroupType::Visibility,
    }
}

fn read_groups_v12(
    tracks: &[ssbh_lib::formats::anim::TrackV1],
    buffers: &[ssbh_lib::SsbhByteBuffer],
) -> Result<Vec<GroupData>, error::Error> {
    // Group by the track type.
    let mut tracks_by_type = HashMap::new();

    // TODO: Avoid unwrap.
    // Node names like bones names are set at the track level for anim 1.2.
    // Save the track name to use for the nodes later.
    for track in tracks {
        let group_type = group_type_v12(track.track_type);
        let track_data = create_track_data_v12(track, buffers).unwrap();
        tracks_by_type
            .entry(group_type)
            .or_insert(Vec::new())
            .push((track.name.to_string_lossy(), track_data));
    }

    // Use the grouping conventions for version 2.0+ anims.
    // TODO: Will this preserve data when saving back to 1.2?
    let groups = tracks_by_type
        .into_iter()
        .map(|(group_type, tracks)| GroupData {
            group_type,
            nodes: tracks
                .into_iter()
                .map(|(name, track)| NodeData {
                    name,
                    tracks: vec![track],
                })
                .collect(),
        })
        .collect();

    Ok(groups)
}

fn create_track_data_v12(
    track: &ssbh_lib::formats::anim::TrackV1,
    buffers: &[ssbh_lib::SsbhByteBuffer],
) -> Result<TrackData, error::Error> {
    // TODO: Add tests for this to buffers.rs.
    println!("{:?}", track.name.to_string_lossy());
    for property in &track.properties.elements {
        let data = buffers.get(property.buffer_index as usize).ok_or(
            error::Error::BufferIndexOutOfRange {
                buffer_index: property.buffer_index as usize,
                buffer_count: buffers.len(),
            },
        )?;

        let mut reader = Cursor::new(&data.elements);
        let header: u32 = reader.read_le()?;

        println!("{:?},{:x?}", property.name.to_string_lossy(), header);

        // TODO: Make this an enum?
        // TODO: Is the header multiple fields for const, data type, etc?
        match header {
            0x1003 => {
                println!("{:x?}", reader.read_le::<f32>()?);
            }
            0x2003 => {
                println!("{:?}", reader.read_le::<(f32, f32)>()?);
            }
            0x3003 => {
                println!("{:?}", reader.read_le::<Vector3>()?);
            }
            0x4003 => {
                println!("{:?}", reader.read_le::<Vector4>()?);
            }
            0x1013 => {
                println!("{:x?}", reader.read_le::<u16>()?);
            }
            0x3409 => {
                println!("{:?}", reader.read_le::<V12Test1>()?);
                // Assume the remainder is the compressed buffer.
                println!("Compressed: {:?} bytes", data.elements.len() - 52 - 4);
            }
            0x4308 => {
                println!("{:?}", reader.read_le::<V12Test3>()?);
                // Assume the remainder is the compressed buffer.
                println!("Compressed: {:?} bytes", data.elements.len() - 72 - 4);
            }
            0x4409 => {
                let test = reader.read_le::<V12Test2>()?;
                println!("{test:?}");
                // Assume the remainder is the compressed buffer.
                println!("Compressed: {:?} bytes", data.elements.len() - 64 - 4);
            }
            x => println!("Unrecognized header: {x:?}"),
        }
    }
    println!();

    // TODO: Set the track data based on type?
    // TODO: Set the scale options?
    Ok(TrackData {
        // TODO: Is this the correct naming convention?
        name: match track.track_type {
            TrackTypeV1::Transform => "Transform".to_owned(),
            TrackTypeV1::Visibility => "Visibility".to_owned(),
            TrackTypeV1::UvTransform => "Material".to_owned(),
        },
        compensate_scale: false,
        values: TrackValues::Float(Vec::new()),
        transform_flags: TransformFlags::default(),
    })
}

fn read_groups_v20(
    anim_groups: &[ssbh_lib::formats::anim::Group],
    anim_buffer: &[u8],
) -> Result<Vec<GroupData>, error::Error> {
    let mut groups = Vec::new();

    for anim_group in anim_groups {
        let mut nodes = Vec::new();

        for anim_node in &anim_group.nodes.elements {
            let mut tracks = Vec::new();
            for anim_track in &anim_node.tracks.elements {
                // Find and read the track data.
                let track = create_track_data_v20(anim_track, anim_buffer)?;
                tracks.push(track);
            }

            let node = NodeData {
                name: anim_node.name.to_string_lossy(),
                tracks,
            };
            nodes.push(node);
        }

        let group = GroupData {
            group_type: anim_group.group_type,
            nodes,
        };
        groups.push(group);
    }

    Ok(groups)
}

fn create_track_data_v20(
    track: &ssbh_lib::formats::anim::TrackV2,
    buffer: &[u8],
) -> Result<TrackData, error::Error> {
    let start = track.data_offset as usize;
    let end =
        start
            .checked_add(track.data_size as usize)
            .ok_or(error::Error::InvalidTrackDataRange {
                start: track.data_offset as usize,
                size: track.data_size as usize,
                buffer_size: buffer.len(),
            })?;
    let buffer = buffer
        .get(start..end)
        .ok_or(error::Error::InvalidTrackDataRange {
            start: track.data_offset as usize,
            size: track.data_size as usize,
            buffer_size: buffer.len(),
        })?;

    let (values, compensate_scale) =
        read_track_values(buffer, track.flags, track.frame_count as usize)?;

    // The compensate scale override is included in scale options instead.
    Ok(TrackData {
        name: track.name.to_string_lossy(),
        values,
        compensate_scale,
        transform_flags: track.transform_flags.into(),
    })
}

/// Data associated with a [Group].
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, PartialEq, Clone)]
pub struct GroupData {
    /// The usage type for all the [NodeData] in [nodes](#structfield.nodes)
    pub group_type: GroupType,
    pub nodes: Vec<NodeData>,
}

/// Data associated with a [Node].
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, PartialEq, Clone)]
pub struct NodeData {
    pub name: String,
    pub tracks: Vec<TrackData>,
}

/// The data associated with a [TrackV2].
///
/// # Examples
/// The scale settings and transform flags should usually use their default value.
/**

```rust
use ssbh_data::anim_data::{TrackData, TrackValues, Transform, TransformFlags};

let track = TrackData {
    name: "Transform".to_string(),
    values: TrackValues::Transform(vec![Transform::IDENTITY]),
    compensate_scale: false,
    transform_flags: TransformFlags::default()
};
```
 */
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, PartialEq, Clone)]
pub struct TrackData {
    /// The name of the property to animate.
    ///
    /// For tracks in a group of type [GroupType::Material], this is the name of the material parameter like "CustomVector31".
    /// Other group types tend to use the name of the group type like "Transform" or "Visibility".
    pub name: String,

    /// Revert the scaling of the immediate parent when `true`.
    /// Only applies to [TrackValues::Transform].
    ///
    /// The final scale relative to the parent is `current_scale * (1 / parent_scale)`.
    /// For Smash Ultimate, this is not applied recursively on the parent,
    /// so only the immediate parent's scaling is taken into account.
    /// This matches the behavior of scale compensation in Autodesk Maya.
    pub compensate_scale: bool,

    pub transform_flags: TransformFlags,

    /// The frame values for the property specified by [name](#structfield.name).
    ///
    /// Each element in the [TrackValues] provides the value for a single frame.
    /// If the [TrackValues] contains a single element, this track will be considered constant
    /// and repeat that element for each frame in the animation
    /// up to and including [final_frame_index](struct.AnimData.html#structfield.final_frame_index).
    pub values: TrackValues,
}

/// See [ssbh_lib::formats::anim::TransformFlags].
// Including compensate scale would be redundant with ScaleOptions.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
pub struct TransformFlags {
    pub override_translation: bool,
    pub override_rotation: bool,
    pub override_scale: bool,
    pub override_compensate_scale: bool,
}

impl From<TransformFlags> for AnimTransformFlags {
    fn from(f: TransformFlags) -> Self {
        Self::new()
            .with_override_translation(f.override_translation)
            .with_override_rotation(f.override_rotation)
            .with_override_scale(f.override_scale)
            .with_override_compensate_scale(f.override_compensate_scale)
    }
}

impl From<AnimTransformFlags> for TransformFlags {
    fn from(f: AnimTransformFlags) -> Self {
        Self {
            override_translation: f.override_translation(),
            override_rotation: f.override_rotation(),
            override_scale: f.override_scale(),
            override_compensate_scale: f.override_compensate_scale(),
        }
    }
}

// TODO: Investigate if the names based on the Anim 1.2 property names are accurate.
/// A decomposed 2D transformation for texture coordinates.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, BinRead, PartialEq, SsbhWrite, Default, Clone, Copy)]
pub struct UvTransform {
    pub scale_u: f32,
    pub scale_v: f32,
    pub rotation: f32,
    pub translate_u: f32,
    pub translate_v: f32,
}

/// A decomposed 3D transformation consisting of a scale, rotation, and translation.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub struct Transform {
    /// XYZ scale
    pub scale: Vector3,
    /// An XYZW unit quaternion where XYZ represent the axis component
    /// and w represents the angle component.
    pub rotation: Vector4,
    /// XYZ translation
    pub translation: Vector3,
}

impl Transform {
    /// An identity transformation representing no scale, rotation, or translation.
    pub const IDENTITY: Transform = Transform {
        scale: Vector3 {
            x: 1.0,
            y: 1.0,
            z: 1.0,
        },
        rotation: Vector4 {
            x: 0.0,
            y: 0.0,
            z: 0.0,
            w: 1.0,
        },
        translation: Vector3 {
            x: 0.0,
            y: 0.0,
            z: 0.0,
        },
    };
}

// TODO: Add version 1.2 types.
// TODO: Create runtime errors when saving tracks with incompatible data?
/// A value collection with an element for each frame of the animation.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, PartialEq, Clone)]
pub enum TrackValues {
    /// Transformations used for camera or skeletal animations.
    Transform(Vec<Transform>),
    /// Transformations applied to UV coordinates for texture animations.
    UvTransform(Vec<UvTransform>),
    /// Animated scalar parameter values.
    Float(Vec<f32>),
    // TODO: rename to u32?
    PatternIndex(Vec<u32>),
    /// Visibility animations or animated boolean parameters.
    Boolean(Vec<bool>),
    /// Material animations or animated vector parameters.
    Vector4(Vec<Vector4>),
}

impl TrackValues {
    /// Returns the number of elements, which is equivalent to the number of frames.
    /// # Examples
    /**

    ```rust
    # use ssbh_data::anim_data::TrackValues;
    assert_eq!(3, TrackValues::Boolean(vec![true, false, true]).len());
    ```
     */
    pub fn len(&self) -> usize {
        match self {
            TrackValues::Transform(v) => v.len(),
            TrackValues::UvTransform(v) => v.len(),
            TrackValues::Float(v) => v.len(),
            TrackValues::PatternIndex(v) => v.len(),
            TrackValues::Boolean(v) => v.len(),
            TrackValues::Vector4(v) => v.len(),
        }
    }

    /// Returns `true` there are no elements.
    /**

    ```rust
    # use ssbh_data::anim_data::TrackValues;
    assert!(TrackValues::Transform(Vec::new()).is_empty());
    ```
     */
    pub fn is_empty(&self) -> bool {
        match self {
            TrackValues::Transform(v) => v.is_empty(),
            TrackValues::UvTransform(v) => v.is_empty(),
            TrackValues::Float(v) => v.is_empty(),
            TrackValues::PatternIndex(v) => v.is_empty(),
            TrackValues::Boolean(v) => v.is_empty(),
            TrackValues::Vector4(v) => v.is_empty(),
        }
    }

    fn track_type(&self) -> TrackTypeV2 {
        match self {
            TrackValues::Transform(_) => TrackTypeV2::Transform,
            TrackValues::UvTransform(_) => TrackTypeV2::UvTransform,
            TrackValues::Float(_) => TrackTypeV2::Float,
            TrackValues::PatternIndex(_) => TrackTypeV2::PatternIndex,
            TrackValues::Boolean(_) => TrackTypeV2::Boolean,
            TrackValues::Vector4(_) => TrackTypeV2::Vector4,
        }
    }
}

// TODO: Organize this in compression.rs similar to version 2.0+
// Vector3?
#[allow(dead_code)]
#[derive(Debug, BinRead)]
struct V12Test1 {
    unk0: u32, // frame count?
    unk1: f32,
    unk2: f32,
    unk3: u16, // flags?
    unk4: u16,
    unk5: [Vector3; 3],
    // TODO: Compressed data?
}

// Vector4?
#[allow(dead_code)]
#[derive(Debug, BinRead)]
struct V12Test2 {
    unk0: u32, // frame count?
    unk1: f32,
    unk2: f32,
    unk3: u16, // flags?
    unk4: u16,
    unk5: [Vector4; 3],
    // TODO: Compressed data?
}

#[allow(dead_code)]
#[derive(Debug, BinRead)]
struct V12Test3 {
    frame_count: u32,
    unk1: f32,
    #[br(count = frame_count, align_after = 4)] // align to float boundary
    unk2: Vec<u8>, // TODO: key frames?
    unk3: [Vector3; 3],
    // TODO: Compressed data?
}

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

    // TODO: Test the conversions more thoroughly.

    #[test]
    fn create_empty_anim_v_2_0() {
        let anim = create_anim(&AnimData {
            major_version: 2,
            minor_version: 0,
            final_frame_index: 1.5,
            groups: Vec::new(),
        })
        .unwrap();

        assert!(matches!(
            anim,
            Anim::V20 {
                final_frame_index,
                ..
            } if final_frame_index == 1.5
        ));
    }

    #[test]
    fn create_empty_anim_v_2_1() {
        let anim = create_anim(&AnimData {
            major_version: 2,
            minor_version: 1,
            final_frame_index: 2.5,
            groups: Vec::new(),
        })
        .unwrap();

        assert!(matches!(anim, Anim::V21 {
            final_frame_index, 
            ..
        } if final_frame_index == 2.5));
    }

    #[test]
    fn create_anim_negative_frame_index() {
        let result = create_anim(&AnimData {
            major_version: 2,
            minor_version: 1,
            final_frame_index: -1.0,
            groups: Vec::new(),
        });

        assert!(matches!(
            result,
            Err(error::Error::InvalidFinalFrameIndex {
                final_frame_index
            }) if final_frame_index == -1.0
        ));
    }

    #[test]
    fn create_anim_insufficient_frame_index() {
        let result = create_anim(&AnimData {
            major_version: 2,
            minor_version: 1,
            final_frame_index: 2.0,
            groups: vec![GroupData {
                group_type: GroupType::Visibility,
                nodes: vec![NodeData {
                    name: String::new(),
                    tracks: vec![TrackData {
                        name: String::new(),
                        values: TrackValues::Boolean(vec![true; 4]),
                        compensate_scale: false,
                        transform_flags: TransformFlags::default(),
                    }],
                }],
            }],
        });

        // A value of at least 3.0 is expected.
        assert!(matches!(
            result,
            Err(error::Error::InvalidFinalFrameIndex {
                final_frame_index
            }) if final_frame_index == 2.0
        ));
    }

    #[test]
    fn create_anim_zero_frame_index() {
        let anim = create_anim(&AnimData {
            major_version: 2,
            minor_version: 1,
            final_frame_index: 0.0,
            groups: Vec::new(),
        })
        .unwrap();

        assert!(matches!(anim, Anim::V21 {
            final_frame_index,
            ..
        } if final_frame_index == 0.0));
    }

    #[test]
    fn create_empty_anim_invalid_version() {
        let result = create_anim(&AnimData {
            major_version: 1,
            minor_version: 2,
            final_frame_index: 0.0,
            groups: Vec::new(),
        });

        assert!(matches!(
            result,
            Err(error::Error::UnsupportedVersion {
                major_version: 1,
                minor_version: 2
            })
        ));
    }

    #[test]
    fn create_node_no_tracks() {
        let node = NodeData {
            name: "empty".to_string(),
            tracks: Vec::new(),
        };

        let mut buffer = Cursor::new(Vec::new());

        let anim_node = create_anim_node(&node, &mut buffer).unwrap();
        assert_eq!("empty", anim_node.name.to_str().unwrap());
        assert!(anim_node.tracks.elements.is_empty());
    }

    #[test]
    fn create_node_multiple_tracks() {
        let node = NodeData {
            name: "empty".to_string(),
            tracks: vec![
                TrackData {
                    name: "t1".to_string(),
                    values: TrackValues::Float(vec![1.0, 2.0, 3.0]),
                    compensate_scale: false,
                    transform_flags: TransformFlags::default(),
                },
                TrackData {
                    name: "t2".to_string(),
                    values: TrackValues::PatternIndex(vec![4, 5]),
                    compensate_scale: false,
                    transform_flags: TransformFlags::default(),
                },
            ],
        };

        let mut buffer = Cursor::new(Vec::new());

        let anim_node = create_anim_node(&node, &mut buffer).unwrap();
        assert_eq!("empty", anim_node.name.to_str().unwrap());
        assert_eq!(2, anim_node.tracks.elements.len());

        let t1 = &anim_node.tracks.elements[0];
        assert_eq!("t1", t1.name.to_str().unwrap());
        assert_eq!(
            TrackFlags {
                track_type: TrackTypeV2::Float,
                compression_type: CompressionType::Direct
            },
            t1.flags
        );
        assert_eq!(3, t1.frame_count);
        assert_eq!(0, t1.data_offset);
        assert_eq!(12, t1.data_size);

        let t2 = &anim_node.tracks.elements[1];
        assert_eq!("t2", t2.name.to_str().unwrap());
        assert_eq!(
            TrackFlags {
                track_type: TrackTypeV2::PatternIndex,
                compression_type: CompressionType::Direct
            },
            t2.flags
        );
        assert_eq!(2, t2.frame_count);
        assert_eq!(12, t2.data_offset);
        assert_eq!(8, t2.data_size);
    }

    #[test]
    fn compression_type_empty() {
        assert_eq!(
            CompressionType::ConstTransform,
            infer_optimal_compression_type(&TrackValues::Transform(Vec::new()))
        );
        assert_eq!(
            CompressionType::Constant,
            infer_optimal_compression_type(&TrackValues::UvTransform(Vec::new()))
        );
        assert_eq!(
            CompressionType::Constant,
            infer_optimal_compression_type(&TrackValues::Float(Vec::new()))
        );
        assert_eq!(
            CompressionType::Constant,
            infer_optimal_compression_type(&TrackValues::PatternIndex(Vec::new()))
        );
        assert_eq!(
            CompressionType::Constant,
            infer_optimal_compression_type(&TrackValues::Boolean(Vec::new()))
        );
        assert_eq!(
            CompressionType::Constant,
            infer_optimal_compression_type(&TrackValues::Vector4(Vec::new()))
        );
    }

    #[test]
    fn compression_type_boolean_multiple_frames() {
        // The compression adds 33 bytes of overhead.
        // The uncompressed representation for a bool is 1 byte.
        // We need more than (33 / 1 + 1) frames for compression to save space.
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::Boolean(vec![true; 8]))
        );
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::Boolean(vec![true; 34]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::Boolean(vec![true; 35]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::Boolean(vec![true; 100]))
        );
    }

    #[test]
    fn compression_type_float_multiple_frames() {
        // The compression adds 36 bytes of overhead.
        // The uncompressed representation for a float is 4 bytes.
        // We need more than 10 (36 / 4 + 1) frames for compression to save space.
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::Float(vec![0.0; 8]))
        );
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::Float(vec![0.0; 10]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::Float(vec![0.0; 11]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::Float(vec![0.0; 100]))
        );
    }

    #[test]
    fn compression_type_pattern_index_multiple_frames() {
        // The compression adds 36 bytes of overhead.
        // The uncompressed representation for a float is 4 bytes.
        // We need more than 10 (36 / 4 + 1) frames for compression to save space.
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::PatternIndex(vec![0; 8]))
        );
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::PatternIndex(vec![0; 10]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::PatternIndex(vec![0; 11]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::PatternIndex(vec![0; 100]))
        );
    }

    #[test]
    fn compression_type_uv_transform_multiple_frames() {
        // The compression adds 116 bytes of overhead.
        // The uncompressed representation for a UV transform is 20 bytes.
        // We need more than 6.8 (116 / 20 + 1) frames for compression to save space.
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::UvTransform(vec![
                UvTransform::default();
                3
            ]))
        );
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::UvTransform(vec![
                UvTransform::default();
                6
            ]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::UvTransform(vec![
                UvTransform::default();
                7
            ]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::UvTransform(vec![
                UvTransform::default();
                100
            ]))
        );
    }

    #[test]
    fn compression_type_vector4_multiple_frames() {
        // The compression adds 96 bytes of overhead.
        // The uncompressed representation for a UV transform is 20 bytes.
        // We need more than 7 (96 / 16 + 1) frames for compression to save space.
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::Vector4(vec![Vector4::default(); 3]))
        );
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::Vector4(vec![Vector4::default(); 7]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::Vector4(vec![Vector4::default(); 8]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::Vector4(vec![Vector4::default(); 100]))
        );
    }

    #[test]
    fn compression_type_transform_multiple_frames() {
        // The compression adds 204 bytes of overhead.
        // The uncompressed representation for a transform is 44 bytes.
        // We need more than 5.63 (204 / 44 + 1) frames for compression to save space.
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::Transform(vec![Transform::default(); 3]))
        );
        assert_eq!(
            CompressionType::Direct,
            infer_optimal_compression_type(&TrackValues::Transform(vec![Transform::default(); 5]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::Transform(vec![Transform::default(); 6]))
        );
        assert_eq!(
            CompressionType::Compressed,
            infer_optimal_compression_type(&TrackValues::Transform(vec![
                Transform::default();
                100
            ]))
        );
    }

    #[test]
    fn read_v20_track_invalid_offset() {
        let result = create_track_data_v20(
            &TrackV2 {
                name: "abc".into(),
                flags: TrackFlags {
                    track_type: TrackTypeV2::Transform,
                    compression_type: CompressionType::Compressed,
                },
                frame_count: 2,
                transform_flags: AnimTransformFlags::new(),
                data_offset: 5,
                data_size: 1,
            },
            &[0u8; 4],
        );

        assert!(matches!(
            result,
            Err(error::Error::InvalidTrackDataRange {
                start: 5,
                size: 1,
                buffer_size: 4
            })
        ));
    }

    #[test]
    fn read_v20_track_offset_overflow() {
        let result = create_track_data_v20(
            &TrackV2 {
                name: "abc".into(),
                flags: TrackFlags {
                    track_type: TrackTypeV2::Transform,
                    compression_type: CompressionType::Compressed,
                },
                frame_count: 2,
                transform_flags: AnimTransformFlags::new(),
                data_offset: u32::MAX,
                data_size: 1,
            },
            &[0u8; 4],
        );

        assert!(matches!(
            result,
            Err(error::Error::InvalidTrackDataRange {
                start: 4294967295,
                size: 1,
                buffer_size: 4
            })
        ));
    }

    #[test]
    fn read_v20_track_invalid_size() {
        let result = create_track_data_v20(
            &TrackV2 {
                name: "abc".into(),
                flags: TrackFlags {
                    track_type: TrackTypeV2::Transform,
                    compression_type: CompressionType::Compressed,
                },
                frame_count: 2,
                transform_flags: AnimTransformFlags::new(),
                data_offset: 0,
                data_size: 5,
            },
            &[0u8; 3],
        );

        assert!(matches!(
            result,
            Err(error::Error::InvalidTrackDataRange {
                start: 0,
                size: 5,
                buffer_size: 3
            })
        ));
    }
}