Skip to main content

source_vmf/
transform.rs

1//! Placement of a `func_instance`: rotation by its `angles`, then translation by its `origin`
2
3use std::ops::Mul;
4
5use crate::vmf::entities::Entity;
6use crate::vmf::world::{Side, Solid};
7
8/// Rotation followed by translation, in Source's axis conventions
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Transform {
11    pub origin: [f64; 3],
12    /// Columns are forward, left and up, like Source's `matrix3x4_t`
13    pub rot: [[f64; 3]; 3],
14}
15
16impl Transform {
17    pub const IDENTITY: Self = Self {
18        origin: [0.0; 3],
19        rot: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
20    };
21
22    /// Reads the entity's `origin` and `angles` keys, missing ones count as zero
23    pub fn from_entity(ent: &Entity) -> Self {
24        Self {
25            origin: vec3(ent, "origin"),
26            rot: angle_matrix(vec3(ent, "angles")),
27        }
28    }
29
30    /// Maps a point from local space to the parent space
31    pub fn point(&self, p: [f64; 3]) -> [f64; 3] {
32        let r = self.rotate(p);
33        std::array::from_fn(|i| round(r[i] + self.origin[i]))
34    }
35
36    /// Rotates a direction, translation doesn't apply
37    pub fn vector(&self, v: [f64; 3]) -> [f64; 3] {
38        self.rotate(v).map(round)
39    }
40
41    /// Maps entity `angles` (pitch yaw roll, in degrees) from local space to the parent space
42    pub fn angles(&self, local: [f64; 3]) -> [f64; 3] {
43        matrix_angles(mat_mul(&self.rot, &angle_matrix(local))).map(round)
44    }
45
46    /// Maps the parent space back to local space
47    pub fn inverse(&self) -> Self {
48        let rot = std::array::from_fn(|i| std::array::from_fn(|j| self.rot[j][i]));
49        let back = Self { origin: [0.0; 3], rot };
50        Self {
51            origin: back.vector(self.origin.map(|v| -v)),
52            rot,
53        }
54    }
55
56    /// Moves a brush: plane points, texture axes and displacement data
57    pub fn apply_solid(&self, solid: &mut Solid) {
58        // didn't move? then not a single byte gets reformatted either
59        if *self == Self::IDENTITY {
60            return;
61        }
62        for side in &mut solid.sides {
63            self.apply_side(side);
64        }
65    }
66
67    /// Moves an entity's `origin`, turns its `angles` and moves its brushes.
68    /// Other keys that only the FGD knows to be positions or angles (`movedir`, the `pitch` of lights) stay as they are
69    pub fn apply_entity(&self, ent: &mut Entity) {
70        if *self == Self::IDENTITY {
71            return;
72        }
73
74        if ent.get("origin").is_some() {
75            let origin = self.point(vec3(ent, "origin"));
76            ent.set("origin".to_string(), fmt_vec3(origin));
77        }
78
79        // VBSP doesn't touch angles of an unrotated instance either, no "0 270 0" -> "0 -90 0" churn
80        if ent.get("angles").is_some() && self.rot != Self::IDENTITY.rot {
81            let angles = self.angles(vec3(ent, "angles"));
82            ent.set("angles".to_string(), fmt_vec3(angles));
83        }
84
85        for solid in ent.solids.iter_mut().flatten() {
86            self.apply_solid(solid);
87        }
88    }
89
90    fn apply_side(&self, side: &mut Side) {
91        if let Some(p) = parse::<9>(&side.plane) {
92            let [a, b, c] = [0, 3, 6].map(|i| fmt_vec3(self.point([p[i], p[i + 1], p[i + 2]])));
93            side.plane = format!("({a}) ({b}) ({c})");
94        }
95        self.apply_axis(&mut side.u_axis);
96        self.apply_axis(&mut side.v_axis);
97
98        let Some(disp) = &mut side.dispinfo else {
99            return;
100        };
101
102        if let Some(start) = parse::<3>(&disp.start_position) {
103            disp.start_position = format!("[{}]", fmt_vec3(self.point(start)));
104        }
105
106        // VBSP moves startposition and NEVER turns these (MergeBrushSides), so disps in rotated instances should come out bent in game prob?
107        // Hammer draws them turned, we go with Hammer
108        for rows in [&mut disp.normals, &mut disp.offsets, &mut disp.offset_normals] {
109            for row in &mut rows.rows {
110                self.apply_row(row);
111            }
112        }
113    }
114
115    /// `[x y z shift] scale`, a point lands on texel `dot(p, xyz) / scale + shift`
116    fn apply_axis(&self, axis: &mut String) {
117        let Some([x, y, z, shift, scale]) = parse::<5>(axis).filter(|&[.., scale]| scale != 0.0) else {
118            return;
119        };
120        let dir = self.vector([x, y, z]);
121        
122        // shift is in TEXELS, so the origin has to go through `/ scale` too, same as VBSP MergeBrushSides
123        let shift = round(shift - dot(self.origin, dir) / scale);
124        *axis = format!("[{} {shift}] {scale}", fmt_vec3(dir));
125    }
126
127    fn apply_row(&self, row: &mut String) {
128        let values: Option<Vec<f64>> = row.split_whitespace().map(|v| v.parse().ok()).collect();
129        let Some(values) = values.filter(|v| v.len() % 3 == 0) else {
130            return;
131        };
132
133        *row = values
134            .chunks_exact(3)
135            .map(|v| fmt_vec3(self.vector([v[0], v[1], v[2]])))
136            .collect::<Vec<_>>()
137            .join(" ");
138    }
139
140    fn rotate(&self, v: [f64; 3]) -> [f64; 3] {
141        self.rot.map(|row| dot(row, v))
142    }
143}
144
145/// `parent * child` maps points from the child's local space straight to the parent's parent space
146impl Mul for Transform {
147    type Output = Self;
148
149    fn mul(self, child: Self) -> Self {
150        Self {
151            origin: self.point(child.origin),
152            rot: mat_mul(&self.rot, &child.rot),
153        }
154    }
155}
156
157fn round(v: f64) -> f64 {
158    (v * 1e6).round() / 1e6 + 0.0
159}
160
161fn vec3(ent: &Entity, key: &str) -> [f64; 3] {
162    let mut out = [0.0; 3];
163    if let Some(value) = ent.get(key) {
164        for (slot, part) in out.iter_mut().zip(value.split_whitespace()) {
165            *slot = part.parse().unwrap_or(0.0);
166        }
167    }
168
169    out
170}
171
172/// Exactly `N` numbers of a VMF value, brackets ignored: `(0 64 64) (64 64 64) (64 0 64)`, `[1 0 0 0] 0.25`
173fn parse<const N: usize>(value: &str) -> Option<[f64; N]> {
174    let mut parts = value
175        .split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']'))
176        .filter(|part| !part.is_empty());
177    let mut out = [0.0; N];
178    
179    for slot in &mut out {
180        *slot = parts.next()?.parse().ok()?;
181    }
182
183    parts.next().is_none().then_some(out)
184}
185
186fn fmt_vec3(v: [f64; 3]) -> String {
187    format!("{} {} {}", v[0], v[1], v[2])
188}
189
190fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
191    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
192}
193
194fn mat_mul(a: &[[f64; 3]; 3], b: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
195    std::array::from_fn(|i| std::array::from_fn(|j| (0..3).map(|k| a[i][k] * b[k][j]).sum()))
196}
197
198/// Port of mathlib `AngleMatrix`
199fn angle_matrix([pitch, yaw, roll]: [f64; 3]) -> [[f64; 3]; 3] {
200    let (sp, cp) = pitch.to_radians().sin_cos();
201    let (sy, cy) = yaw.to_radians().sin_cos();
202    let (sr, cr) = roll.to_radians().sin_cos();
203
204    [
205        [cp * cy, sp * sr * cy - cr * sy, sp * cr * cy + sr * sy],
206        [cp * sy, sp * sr * sy + cr * cy, sp * cr * sy - sr * cy],
207        [-sp, sr * cp, cr * cp],
208    ]
209}
210
211/// Port of mathlib `MatrixAngles`
212fn matrix_angles(m: [[f64; 3]; 3]) -> [f64; 3] {
213    let xy = m[0][0].hypot(m[1][0]);
214    let pitch = (-m[2][0]).atan2(xy);
215
216    let (yaw, roll) = if xy > 0.001 {
217        (m[1][0].atan2(m[0][0]), m[2][1].atan2(m[2][2]))
218    } else {
219        ((-m[0][1]).atan2(m[1][1]), 0.0)
220    };
221    
222    [pitch, yaw, roll].map(f64::to_degrees)
223}