Skip to main content

unbanished_terrain/
query.rs

1//! Gameplay queries on the saved height grid: the vertical ray cast that gives the ground height
2//! and normal anywhere on the map, and the natural cell type derived from it.
3//!
4//! Positions are map-centred: cell `(i, j)` covers `[i - size/2, i - size/2 + 1)` and likewise for
5//! `y`. Float operations follow the disassembly so results are bit-exact.
6//!
7//! Original: `FUN_1400b6460`, `FUN_1400afef0`, `FUN_1400afce0`, `FUN_1400a3790`.
8
9use super::mesh::HeightGrid;
10
11type Vec3 = [f32; 3];
12
13fn sub(a: Vec3, b: Vec3) -> Vec3 {
14    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
15}
16
17/// `Math::Vector3::Cross`.
18fn cross(a: Vec3, b: Vec3) -> Vec3 {
19    [
20        a[1] * b[2] - a[2] * b[1],
21        b[0] * a[2] - a[0] * b[2],
22        a[0] * b[1] - b[0] * a[1],
23    ]
24}
25
26fn dot(a: Vec3, b: Vec3) -> f32 {
27    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
28}
29
30/// `Math::Vector3::Normalize` (by value): `v * (1 / |v|)`, unchanged when zero.
31fn normalize(v: Vec3) -> Vec3 {
32    let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
33    if len == 0.0 {
34        return v;
35    }
36    let inv = 1.0 / len;
37    [v[0] * inv, v[1] * inv, v[2] * inv]
38}
39
40const EPSILON: f32 = -1e-4;
41const RAY_TOP: f32 = 100.0;
42const RAY_LENGTH: f32 = 200.0;
43
44/// `FUN_1400afce0`: ray/triangle test. `t` is written once the barycentric tests pass, even when
45/// it is then rejected by the range test, as in the original.
46#[allow(clippy::too_many_arguments, clippy::neg_cmp_op_on_partial_ord)]
47fn ray_triangle(
48    origin: Vec3,
49    dir: Vec3,
50    tmax: f32,
51    v0: Vec3,
52    v1: Vec3,
53    v2: Vec3,
54    t: &mut f32,
55    normal: &mut Vec3,
56) -> bool {
57    let e1 = sub(v1, v0);
58    let e2 = sub(v2, v0);
59    let p = cross(dir, e2);
60    let det = dot(e1, p);
61    let s = sub(origin, v0);
62    let q = cross(s, e1);
63    let u = dot(s, p);
64    let v = dot(dir, q);
65    // comiss branches: each rejection is taken when the comparison holds (NaN passes through).
66    if !(det > 0.0) || EPSILON > u || u > det || EPSILON > v || v + u > det {
67        return false;
68    }
69    let hit = 1.0 / det * dot(e2, q);
70    *t = hit;
71    // jb at 0x1400afe71 and 0x1400afe7b: a NaN distance is rejected.
72    if !(hit >= 0.0) || !(tmax >= hit) {
73        return false;
74    }
75    *normal = normalize(cross(e1, e2));
76    true
77}
78
79impl HeightGrid<'_> {
80    /// Where a ray first hits the ground, no farther than `maximum`: the distance and the point.
81    /// The game uses it to stop picking at the ground.
82    ///
83    /// Deviation: the port tests every cell in the rectangle the ray crosses, where the original
84    /// walks the cells along the ray.
85    ///
86    /// Original: `FUN_1400afef0`; its walk along the ray is `FUN_1400afa00`.
87    pub fn intersect(&self, origin: Vec3, direction: Vec3, maximum: f32) -> Option<(f32, Vec3)> {
88        let n = self.width as i32 - 1;
89        let half = n >> 1;
90        let end = [
91            origin[0] + direction[0] * maximum,
92            origin[1] + direction[1] * maximum,
93        ];
94        let lo = std::array::from_fn::<_, 2, _>(|k| {
95            ((origin[k].min(end[k]) + half as f32).floor() as i32 - 1).clamp(0, n - 1)
96        });
97        let hi = std::array::from_fn::<_, 2, _>(|k| {
98            ((origin[k].max(end[k]) + half as f32).floor() as i32 + 1).clamp(0, n - 1)
99        });
100        let mut limit = maximum;
101        let mut found = false;
102        let mut normal = [0.; 3];
103        for y in lo[1]..=hi[1] {
104            for x in lo[0]..=hi[0] {
105                let [a, b, c, d] = [
106                    self.corner(x, y, half),
107                    self.corner(x + 1, y, half),
108                    self.corner(x + 1, y + 1, half),
109                    self.corner(x, y + 1, half),
110                ];
111                let triangles = if (x + y) & 1 == 0 {
112                    [[a, b, d], [b, c, d]]
113                } else {
114                    [[a, b, c], [a, c, d]]
115                };
116                for [a, b, c] in triangles {
117                    let mut t = limit;
118                    if ray_triangle(origin, direction, limit, a, b, c, &mut t, &mut normal) {
119                        limit = t;
120                        found = true;
121                    }
122                }
123            }
124        }
125        found.then(|| {
126            (
127                limit,
128                [
129                    origin[0] + direction[0] * limit,
130                    origin[1] + direction[1] * limit,
131                    origin[2] + direction[2] * limit,
132                ],
133            )
134        })
135    }
136
137    fn corner(&self, x: i32, y: i32, half: i32) -> Vec3 {
138        let hi = self.width as i32 - 1;
139        let h = self.heights[y.clamp(0, hi) as usize * self.width + x.clamp(0, hi) as usize];
140        [
141            (x - half) as f32,
142            (y - half) as f32,
143            h as i32 as f32 * 0.00390625,
144        ]
145    }
146
147    /// `FUN_1400afef0`: cast a ray against the two triangles of cell `(x, y)`. Returns whether
148    /// either triangle was hit and the last `t` written; `normal` takes the last hit's normal.
149    fn raycast_cell(
150        &self,
151        x: i32,
152        y: i32,
153        dir: Vec3,
154        origin: Vec3,
155        tmax: f32,
156        normal: &mut Vec3,
157    ) -> (bool, f32) {
158        let half = (self.width as i32 - 1) >> 1;
159        let a = self.corner(x, y, half);
160        let b = self.corner(x + 1, y, half);
161        let c = self.corner(x + 1, y + 1, half);
162        let d = self.corner(x, y + 1, half);
163        let (first, second) = if (x + y) & 1 == 0 {
164            ([a, b, d], [b, c, d])
165        } else {
166            ([a, b, c], [a, c, d])
167        };
168        let mut limit = tmax;
169        let mut t = 0.0f32;
170        let mut hit = false;
171        if ray_triangle(
172            origin, dir, limit, first[0], first[1], first[2], &mut t, normal,
173        ) {
174            limit = t;
175            hit = true;
176        }
177        if ray_triangle(
178            origin, dir, limit, second[0], second[1], second[2], &mut t, normal,
179        ) {
180            hit = true;
181        }
182        (hit, t)
183    }
184
185    /// The normal of the ground under `(x, y)`: a ray straight down from height `top`, at most
186    /// `length` long. It is zero when the ray hits nothing.
187    ///
188    /// Original: `FUN_1400afef0`.
189    pub fn normal_below(&self, x: f32, y: f32, top: f32, length: f32) -> [f32; 3] {
190        let half = ((self.width as i32 - 1) >> 1) as f32;
191        let mut normal = [0.0; 3];
192        self.raycast_cell(
193            (x + half) as i32,
194            (y + half) as i32,
195            [0.0, 0.0, -1.0],
196            [x, y, top],
197            length,
198            &mut normal,
199        );
200        normal
201    }
202
203    /// Ground height at a map position (0 when no triangle is hit). `normal` receives the hit
204    /// triangle's normal and is left unchanged otherwise.
205    ///
206    /// Original: `FUN_1400b6460`.
207    pub fn ground(&self, x: f32, y: f32, normal: &mut [f32; 3]) -> f32 {
208        let half = ((self.width as i32 - 1) >> 1) as f32;
209        let ix = (x + half) as i32;
210        let iy = (y + half) as i32;
211        let dir = [0.0, 0.0, -1.0];
212        let origin = [x, y, RAY_TOP];
213        let (hit, t) = self.raycast_cell(ix, iy, dir, origin, RAY_LENGTH, normal);
214        if hit {
215            t * dir[2] + origin[2]
216        } else {
217            0.0
218        }
219    }
220
221    /// The natural type of gameplay map cell `index` (row-major over `map_size²`). The gameplay map
222    /// is `n × n` cells centred on the `2n`-cell terrain.
223    ///
224    /// Original: `FUN_1400a3790`.
225    pub fn natural_cell_type(&self, map_size: usize, index: usize) -> CellType {
226        let size = map_size as i32;
227        let index = index as i32;
228        let offset = (size >> 1) as f32 - 0.5;
229        let x = (index % size) as f32 - offset;
230        let y = (index / size) as f32 - offset;
231        let mut normal = [0.0; 3];
232        let h = self.ground(x, y, &mut normal);
233        CellType::classify(h, normal[2])
234    }
235}
236
237// Byte +0x29 of the 48-byte map cell.
238/// The type of a map cell. Types 5 to 8 block movement (the mask `0x1e0`); the others can be
239/// walked on (the mask `0xe1f`). Types whose meaning is not confirmed have no name.
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub struct CellType(pub u8);
242
243impl CellType {
244    /// Flat ground where buildings can go.
245    pub const GROUND: CellType = CellType(2);
246    /// High ground. It blocks movement.
247    pub const HIGH: CellType = CellType(6);
248    /// Shallow water. It blocks movement.
249    pub const SHALLOW_WATER: CellType = CellType(7);
250    /// Deep water. It blocks movement.
251    pub const DEEP_WATER: CellType = CellType(8);
252    /// Rough ground: walkable, but not buildable.
253    pub const ROUGH: CellType = CellType(10);
254
255    /// The natural type of a cell from the ground height and the up component of its normal:
256    /// deep water below -1.4, shallow water below -0.25, ground from -0.25 to 0.75 when the
257    /// ground is flat (`up ≥ 0.9`), rough ground below 2.0, and high ground above.
258    ///
259    /// Original: `FUN_1400a3790`.
260    pub fn classify(height: f32, up: f32) -> CellType {
261        if height < -1.4 {
262            return CellType::DEEP_WATER;
263        }
264        if height < -0.25 {
265            return CellType::SHALLOW_WATER;
266        }
267        if (-0.25..=0.75).contains(&height) && 0.9 <= up {
268            return CellType::GROUND;
269        }
270        if height < 2.0 {
271            CellType::ROUGH
272        } else {
273            CellType::HIGH
274        }
275    }
276
277    /// Whether walkers cannot enter a cell of this type.
278    pub fn blocks_movement(self) -> bool {
279        (1u32 << self.0) & 0x1e0 != 0
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    /// `FUN_1400afce0`: a ray that meets a triangle at a NaN distance is rejected (`jb` at
288    /// 0x1400afe71), but the NaN is still written to `t`.
289    #[test]
290    fn a_nan_distance_misses_the_triangle() {
291        let (v0, v1, v2) = ([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
292        let down = [0.0, 0.0, -1.0];
293        let (mut t, mut normal) = (0.0, [0.0; 3]);
294        assert!(ray_triangle(
295            [0.25, 0.25, 1.0],
296            down,
297            10.0,
298            v0,
299            v1,
300            v2,
301            &mut t,
302            &mut normal
303        ));
304        assert_eq!(t, 1.0);
305        let origin = [0.25, 0.25, f32::NAN];
306        assert!(!ray_triangle(
307            origin,
308            down,
309            10.0,
310            v0,
311            v1,
312            v2,
313            &mut t,
314            &mut normal
315        ));
316        assert!(t.is_nan());
317    }
318}