Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_math/
clip_lanes.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! One-plane convex clip of eight-lane `i32` vertices.
3//!
4//! GoldSrc's renderers (Half-Life, Counter-Strike) clip textured polygons
5//! against the view frustum in view space, one plane at a time, carrying
6//! position, colour and UV as eight `i32` lanes: `[x, y, z, r, g, b, u, v]`.
7//! Every plane they use is linear in two of those lanes, and every crossing is
8//! interpolated the same way, so the whole pass is one function of the plane's
9//! four numbers. [`clip_lanes8_plane_reference`] states it with the generic
10//! [`attributed_clip`](crate::attributed_clip) kernel; with the `asm-kernels`
11//! feature on the console, [`clip_lanes8_plane`] runs a hand-scheduled kernel
12//! that produces the same bytes.
13//!
14//! # Definition
15//!
16//! A vertex `v` is inside when
17//! `v[primary_offset / 4] * primary + v[2] * depth + bias >= 0` (wrapping
18//! `i32` arithmetic). The polygon is traversed previous-to-current; each edge
19//! whose endpoints disagree emits a crossing before the current vertex, and an
20//! inside vertex is copied. A crossing orders its endpoints by `(x, y, z)`
21//! (signed, lexicographic) so a shared edge interpolates identically from both
22//! sides, takes `t = ratio_q12_i32(d_a, d_a - d_b)` with the distances in that
23//! order, and sets every lane to [`lerp_q12_i32_wide`] of the two endpoints;
24//! lane 2 is then replaced by `forced_depth` when `force_depth` is non-zero (a
25//! near plane lands exactly on its distance). When `count` vertices would
26//! overflow `capacity` the pass stops and returns `capacity`.
27
28use crate::attributed_clip::{
29    clip_to_plane, lerp_q12_i32_wide, ratio_q12_i32, AttributedClipPlane, ClipTraversal,
30};
31
32/// One vertex: `[x, y, z, r, g, b, u, v]`.
33pub type Lanes8 = [i32; 8];
34
35/// A clip plane over [`Lanes8`] vertices; see the [module](self) definition.
36///
37/// `repr(C)` and read by the assembly kernel field by field.
38#[repr(C)]
39#[derive(Copy, Clone, Debug, PartialEq, Eq)]
40pub struct LanePlane {
41    /// Byte offset of the lane multiplied by `primary`: 0 for x, 4 for y.
42    pub primary_offset: u32,
43    /// Multiplier of the lane at `primary_offset`.
44    pub primary: i32,
45    /// Multiplier of lane 2 (z).
46    pub depth: i32,
47    /// Constant added to the distance.
48    pub bias: i32,
49    /// Non-zero to overwrite lane 2 of every crossing with `forced_depth`.
50    pub force_depth: u32,
51    /// The value for lane 2 of a crossing when `force_depth` is set.
52    pub forced_depth: i32,
53    /// Vertices the destination can hold.
54    pub capacity: u32,
55}
56
57impl LanePlane {
58    /// Signed distance of `vertex` from the plane.
59    #[inline(always)]
60    pub fn distance(&self, vertex: &Lanes8) -> i32 {
61        vertex[(self.primary_offset / 4) as usize]
62            .wrapping_mul(self.primary)
63            .wrapping_add(vertex[2].wrapping_mul(self.depth))
64            .wrapping_add(self.bias)
65    }
66}
67
68struct Adapter<'a>(&'a LanePlane);
69
70impl AttributedClipPlane<Lanes8> for Adapter<'_> {
71    type Distance = i32;
72
73    #[inline(always)]
74    fn distance(&self, _: usize, vertex: &Lanes8) -> i32 {
75        self.0.distance(vertex)
76    }
77
78    #[inline(always)]
79    fn inside(&self, distance: i32) -> bool {
80        distance >= 0
81    }
82
83    #[inline(always)]
84    fn intersection(
85        &self,
86        _: usize,
87        first: &Lanes8,
88        first_distance: i32,
89        _: usize,
90        second: &Lanes8,
91        second_distance: i32,
92    ) -> Lanes8 {
93        let (a, b, da, db) = if (second[0], second[1], second[2]) < (first[0], first[1], first[2]) {
94            (second, first, second_distance, first_distance)
95        } else {
96            (first, second, first_distance, second_distance)
97        };
98        let t = ratio_q12_i32(da, da.wrapping_sub(db));
99        let mut out = [0i32; 8];
100        for lane in 0..8 {
101            out[lane] = lerp_q12_i32_wide(a[lane], b[lane], t);
102        }
103        if self.0.force_depth != 0 {
104            out[2] = self.0.forced_depth;
105        }
106        out
107    }
108}
109
110/// Clip `count` vertices at `src` against `plane` into `dst`, returning how many
111/// were written. The portable definition.
112///
113/// # Safety
114///
115/// `src` must be valid for reads of `count` vertices, `dst` for writes of
116/// `plane.capacity` vertices, and the two ranges must not overlap.
117pub unsafe fn clip_lanes8_plane_reference(
118    src: *const Lanes8,
119    count: usize,
120    dst: *mut Lanes8,
121    plane: &LanePlane,
122) -> usize {
123    let capacity = plane.capacity as usize;
124    // SAFETY: the caller's ranges; `dst` is only written through the slice.
125    let (source, destination) = unsafe {
126        (
127            core::slice::from_raw_parts(src, count),
128            core::slice::from_raw_parts_mut(dst, capacity),
129        )
130    };
131    clip_to_plane(
132        source,
133        destination,
134        &Adapter(plane),
135        ClipTraversal::PreviousToCurrent,
136    )
137    .unwrap_or(capacity)
138}
139
140/// [`clip_lanes8_plane_reference`], or the hand-scheduled kernel on the
141/// console when the `asm-kernels` feature is on. Same safety contract; the
142/// two produce identical bytes (`hello-asmprobe` checks it).
143///
144/// # Safety
145///
146/// As [`clip_lanes8_plane_reference`].
147#[inline(always)]
148pub unsafe fn clip_lanes8_plane(
149    src: *const Lanes8,
150    count: usize,
151    dst: *mut Lanes8,
152    plane: &LanePlane,
153) -> usize {
154    #[cfg(all(target_arch = "mips", feature = "asm-kernels"))]
155    {
156        // SAFETY: forwarded contract.
157        unsafe { crate::asm_kernels::psx_math_clip_lanes8_plane(src, count, dst, plane) }
158    }
159    #[cfg(not(all(target_arch = "mips", feature = "asm-kernels")))]
160    {
161        // SAFETY: forwarded contract.
162        unsafe { clip_lanes8_plane_reference(src, count, dst, plane) }
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    fn plane(primary_offset: u32, primary: i32, depth: i32, bias: i32) -> LanePlane {
171        LanePlane {
172            primary_offset,
173            primary,
174            depth,
175            bias,
176            force_depth: 0,
177            forced_depth: 0,
178            capacity: 8,
179        }
180    }
181
182    #[test]
183    fn an_all_inside_polygon_is_copied() {
184        let near = LanePlane {
185            force_depth: 1,
186            forced_depth: 8,
187            ..plane(0, 0, 1, -8)
188        };
189        let src = [
190            [0, 0, 100, 1, 2, 3, 4, 5],
191            [10, 0, 120, 6, 7, 8, 9, 10],
192            [0, 10, 90, 0, 0, 0, 0, 0],
193        ];
194        let mut dst = [[0i32; 8]; 8];
195        // SAFETY: arrays of the stated sizes, disjoint.
196        let n = unsafe { clip_lanes8_plane_reference(src.as_ptr(), 3, dst.as_mut_ptr(), &near) };
197        assert_eq!(n, 3);
198        assert_eq!(&dst[..3], &src[..]);
199    }
200
201    #[test]
202    fn a_crossing_lands_on_the_plane_and_interpolates_every_lane() {
203        let near = LanePlane {
204            force_depth: 1,
205            forced_depth: 8,
206            ..plane(0, 0, 1, -8)
207        };
208        // One vertex at z = 4 (outside), two at z = 12 (inside): both crossings
209        // sit at t = 0.5 in Q12, and the polygon gains a vertex.
210        let a = [0, 0, 4, 0, 0, 0, 0, 0];
211        let b = [16, 8, 12, 100, 200, 40, 10, 20];
212        let c = [16, -8, 12, 60, 20, 20, 30, 40];
213        let src = [a, b, c];
214        let mut dst = [[0i32; 8]; 8];
215        // SAFETY: as above.
216        let n = unsafe { clip_lanes8_plane_reference(src.as_ptr(), 3, dst.as_mut_ptr(), &near) };
217        assert_eq!(n, 4);
218        assert_eq!(dst[0], [8, -4, 8, 30, 10, 10, 15, 20]);
219        assert_eq!(dst[1], [8, 4, 8, 50, 100, 20, 5, 10]);
220        assert_eq!(dst[2], b);
221        assert_eq!(dst[3], c);
222    }
223
224    #[test]
225    fn a_full_destination_reports_its_capacity() {
226        let always = plane(0, 0, 0, 1);
227        let src = [[1; 8]; 3];
228        let mut dst = [[0i32; 8]; 8];
229        let mut full = always;
230        full.capacity = 2;
231        // SAFETY: as above.
232        let n = unsafe { clip_lanes8_plane_reference(src.as_ptr(), 3, dst.as_mut_ptr(), &full) };
233        assert_eq!(n, 2);
234    }
235}