Skip to main content

yog_body/
model.rs

1//! A `.ymodel` made ready to draw: its bones in order, each cube baked into
2//! the quads vanilla's `ModelPart.Cube` makes (same corners, same box-UV,
3//! same mirroring) — so a model drawn here looks as one drawn by the game.
4
5use crate::format::{CubeDef, ModelFile};
6use crate::math::{Mat4, Vec3, rad};
7
8/// One four-cornered face: corners, their UVs (0–1), its normal.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Quad {
11    pub pos: [Vec3; 4],
12    pub uv: [[f32; 2]; 4],
13    pub normal: Vec3,
14}
15
16impl Quad {
17    /// This quad moved by `m`.
18    pub fn transformed(&self, m: &Mat4) -> Quad {
19        Quad {
20            pos: self.pos.map(|p| m.transform_point(p)),
21            uv: self.uv,
22            normal: m.transform_normal(self.normal),
23        }
24    }
25
26    /// The middle of its corners.
27    pub fn center(&self) -> Vec3 {
28        (self.pos[0] + self.pos[1] + self.pos[2] + self.pos[3]) * 0.25
29    }
30}
31
32/// A bone, ready.
33#[derive(Debug, Clone)]
34pub struct Bone {
35    pub name: String,
36    /// Index of its parent in [`Model::bones`] (always before it).
37    pub parent: Option<usize>,
38    /// Pixels.
39    pub pivot: Vec3,
40    /// Radians.
41    pub rotation: Vec3,
42    /// Its cubes' faces, in its own space (pixels).
43    pub quads: Vec<Quad>,
44    pub locators: Vec<(String, Vec3)>,
45}
46
47/// A model, ready.
48#[derive(Debug, Clone)]
49pub struct Model {
50    /// The texture as the host loads it (`ns:textures/….png`).
51    pub texture: String,
52    pub bones: Vec<Bone>,
53}
54
55impl Model {
56    /// Builds `file`; `namespace` completes a texture given as a path.
57    /// Errors name what's wrong (an unknown or later parent, a repeated
58    /// name).
59    pub fn new(file: &ModelFile, namespace: &str) -> Result<Model, String> {
60        let texture = texture_id(&file.texture, namespace);
61        let [tw, th] = file.texture_size.map(|n| n.max(1) as f32);
62        let mut bones: Vec<Bone> = Vec::with_capacity(file.bones.len());
63        for b in &file.bones {
64            if bones.iter().any(|o| o.name == b.name) {
65                return Err(format!("bone `{}` comes twice", b.name));
66            }
67            let parent = match &b.parent {
68                None => None,
69                Some(p) => Some(
70                    bones
71                        .iter()
72                        .position(|o| &o.name == p)
73                        .ok_or_else(|| format!("bone `{}`: its parent `{p}` must come before it", b.name))?,
74                ),
75            };
76            bones.push(Bone {
77                name: b.name.clone(),
78                parent,
79                pivot: Vec3::from_array(b.pivot),
80                rotation: rad(Vec3::from_array(b.rotation)),
81                quads: b.cubes.iter().flat_map(|c| cube(c, tw, th)).collect(),
82                locators: b.locators.0.iter().map(|(n, p)| (n.clone(), Vec3::from_array(*p))).collect(),
83            });
84        }
85        Ok(Model { texture, bones })
86    }
87
88    pub fn bone(&self, name: &str) -> Option<usize> {
89        self.bones.iter().position(|b| b.name == name)
90    }
91}
92
93/// `entity/x.png` in mod `ns` → `ns:textures/entity/x.png`; a full id stays.
94pub fn texture_id(texture: &str, namespace: &str) -> String {
95    if texture.contains(':') {
96        texture.to_owned()
97    } else {
98        format!("{namespace}:textures/{}", texture.trim_start_matches('/'))
99    }
100}
101
102/// `ModelPart.Cube`'s six faces.
103pub fn cube(c: &CubeDef, tex_w: f32, tex_h: f32) -> [Quad; 6] {
104    let [x, y, z] = c.origin;
105    let [w, h, d] = c.size;
106    let [u, v] = c.uv;
107    let g = c.inflate;
108    let (mut x0, y0, z0) = (x - g, y - g, z - g);
109    let (mut x1, y1, z1) = (x + w + g, y + h + g, z + d + g);
110    if c.mirror {
111        std::mem::swap(&mut x0, &mut x1);
112    }
113    let p = |x, y, z| Vec3::new(x, y, z);
114    let (v7, v0, v1, v2) = (p(x0, y0, z0), p(x1, y0, z0), p(x1, y1, z0), p(x0, y1, z0));
115    let (v3, v4, v5, v6) = (p(x0, y0, z1), p(x1, y0, z1), p(x1, y1, z1), p(x0, y1, z1));
116    let (u0, u1, u2, u3, u4, u5) = (u, u + d, u + d + w, u + d + w + w, u + d + w + d, u + d + w + d + w);
117    let (t0, t1, t2) = (v, v + d, v + d + h);
118    let face = |corners: [Vec3; 4], ua: f32, va: f32, ub: f32, vb: f32, normal: Vec3| {
119        let mut pos = corners;
120        let mut uv = [[ub / tex_w, va / tex_h], [ua / tex_w, va / tex_h], [ua / tex_w, vb / tex_h], [ub / tex_w, vb / tex_h]];
121        let mut n = normal;
122        if c.mirror {
123            pos.reverse();
124            uv.reverse();
125            n.x = -n.x;
126        }
127        Quad { pos, uv, normal: n }
128    };
129    [
130        face([v4, v3, v7, v0], u1, t0, u2, t1, Vec3::new(0.0, -1.0, 0.0)),
131        face([v1, v2, v6, v5], u2, t1, u3, t0, Vec3::new(0.0, 1.0, 0.0)),
132        face([v7, v3, v6, v2], u0, t1, u1, t2, Vec3::new(-1.0, 0.0, 0.0)),
133        face([v0, v7, v2, v1], u1, t1, u2, t2, Vec3::new(0.0, 0.0, -1.0)),
134        face([v4, v0, v1, v5], u2, t1, u4, t2, Vec3::new(1.0, 0.0, 0.0)),
135        face([v3, v4, v5, v6], u4, t1, u5, t2, Vec3::new(0.0, 0.0, 1.0)),
136    ]
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    fn wing() -> CubeDef {
144        CubeDef { origin: [-10.0, 0.0, 0.0], size: [10.0, 20.0, 2.0], uv: [22.0, 0.0], inflate: 1.0, mirror: false }
145    }
146
147    #[test]
148    fn a_cube_is_vanillas() {
149        let q = cube(&wing(), 64.0, 32.0);
150        // DOWN: v4, v3, v7, v0 with UVs from (d, 0) to (d + w, d).
151        assert_eq!(q[0].pos[0], Vec3::new(1.0, -1.0, 3.0));
152        assert_eq!(q[0].uv[0], [34.0 / 64.0, 0.0]);
153        assert_eq!(q[0].uv[1], [24.0 / 64.0, 0.0]);
154        assert_eq!(q[3].normal, Vec3::new(0.0, 0.0, -1.0));
155    }
156
157    #[test]
158    fn a_mirrored_cube_turns_its_faces() {
159        let mut c = wing();
160        c.mirror = true;
161        let q = cube(&c, 64.0, 32.0);
162        assert_eq!(q[2].normal, Vec3::new(1.0, 0.0, 0.0));
163        assert_eq!(q[0].pos[3], Vec3::new(-11.0, -1.0, 3.0));
164    }
165
166    #[test]
167    fn textures_get_the_namespace() {
168        assert_eq!(texture_id("misc/a.png", "hex"), "hex:textures/misc/a.png");
169        assert_eq!(texture_id("minecraft:textures/x.png", "hex"), "minecraft:textures/x.png");
170    }
171}