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
// SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com>
// SPDX-License-Identifier: GPL-3.0-or-later

use std::io::{Cursor, SeekFrom};

use crate::common_file_operations::strings_parser;
use crate::ByteSpan;
use binrw::binread;
use binrw::BinRead;

#[binread]
#[derive(Debug)]
#[br(import { data_offset: i32 })]
#[brw(little)]
#[allow(unused)]
struct RacialDeformer {
    bone_count: i32,

    #[br(count = bone_count)]
    bone_name_offsets: Vec<u16>,

    #[br(args(data_offset as u64, &bone_name_offsets), parse_with = strings_parser)]
    #[br(restore_position)]
    bone_names: Vec<String>,

    #[br(if((bone_count & 1) != 0))]
    #[br(temp)]
    _padding: u16,

    /// 4x3 matrix
    #[br(count = bone_count)]
    #[br(err_context("offset = {} bone count = {}", data_offset, bone_count))]
    transform: Vec<[f32; 12]>,
}

#[binread]
#[derive(Debug)]
#[brw(little)]
struct PreBoneDeformerItem {
    body_id: u16, // the combined body id like 0101
    link_index: i16,
    #[br(pad_after = 4)]
    #[br(temp)]
    data_offset: i32,

    #[br(args { data_offset: data_offset })]
    #[br(seek_before = SeekFrom::Start(data_offset as u64))]
    #[br(restore_position)]
    deformer: RacialDeformer,
}

#[binread]
#[derive(Debug)]
#[brw(little)]
#[allow(dead_code)]
struct PreBoneDeformerLink {
    parent_index: i16,
    first_child_index: i16,
    next_sibling_index: i16,
    deformer_index: u16,
}

#[binread]
#[derive(Debug)]
#[brw(little)]
#[allow(dead_code)]
struct PreBoneDeformerHeader {
    count: i32,

    #[br(count = count)]
    items: Vec<PreBoneDeformerItem>,

    #[br(count = count)]
    links: Vec<PreBoneDeformerLink>,
}

pub struct PreBoneDeformer {
    header: PreBoneDeformerHeader,
}

#[derive(Debug)]
pub struct PreBoneDeformBone {
    /// Name of the affected bone
    pub name: String,
    /// The deform matrix
    pub deform: [f32; 12],
}

#[derive(Debug)]
pub struct PreBoneDeformMatrices {
    /// The prebone deform bones
    pub bones: Vec<PreBoneDeformBone>,
}

impl PreBoneDeformer {
    /// Reads an existing PBD file
    pub fn from_existing(buffer: ByteSpan) -> Option<PreBoneDeformer> {
        let mut cursor = Cursor::new(buffer);
        let header = PreBoneDeformerHeader::read(&mut cursor).ok()?;

        Some(PreBoneDeformer { header })
    }

    /// Calculates the deform matrices between two races
    pub fn get_deform_matrices(
        &self,
        from_body_id: u16,
        to_body_id: u16,
    ) -> Option<PreBoneDeformMatrices> {
        if from_body_id == to_body_id {
            return None;
        }

        let mut item = self
            .header
            .items
            .iter()
            .find(|x| x.body_id == from_body_id)?;
        let mut next = &self.header.links[item.link_index as usize];

        if next.next_sibling_index == -1 {
            return None;
        }

        let mut bones = vec![];

        loop {
            for i in 0..item.deformer.bone_count {
                bones.push(PreBoneDeformBone {
                    name: item.deformer.bone_names[i as usize].clone(),
                    deform: item.deformer.transform[i as usize],
                })
            }

            if next.parent_index == -1 {
                break;
            }

            next = &self.header.links[next.parent_index as usize];
            item = &self.header.items[next.deformer_index as usize];

            if item.body_id == to_body_id {
                break;
            }
        }

        Some(PreBoneDeformMatrices { bones })
    }
}

#[cfg(test)]
mod tests {
    use std::fs::read;
    use std::path::PathBuf;

    use super::*;

    #[test]
    fn test_invalid() {
        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        d.push("resources/tests");
        d.push("random");

        // Feeding it invalid data should not panic
        PreBoneDeformer::from_existing(&read(d).unwrap());
    }
}