Skip to main content

sim_engine/renderer/
mesh3d_surface.rs

1//! Bounded homogeneous surface clipping and its authoritative frame preflight.
2
3use super::*;
4
5#[cfg(test)]
6#[path = "mesh3d_surface_tests.rs"]
7mod gpu_tests;
8
9#[cfg(test)]
10#[path = "mesh3d_surface_red_tests.rs"]
11mod red_tests;
12
13#[cfg(test)]
14pub(super) use gpu_tests::{
15    assert_gpu_clipped_recovery, assert_gpu_surface_contract, read_pixels as test_read_pixels,
16    target as test_target,
17};
18
19/// Limits additional clip-space surface topology generated during one 3D draw.
20///
21/// Retained, wholly inside objects need no generated vertices. A crossing
22/// object's surfaces are transformed and clipped together so one draw preserves
23/// their shared depth interpolation. Limits apply before GPU writes or clearing
24/// the target, and may be zero to disallow generated topology.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct Mesh3dRenderBudget {
27    max_generated_vertices: usize,
28    max_generated_triangles: usize,
29    max_generated_upload_bytes: usize,
30}
31
32impl Mesh3dRenderBudget {
33    /// Sets exact generated surface vertex, triangle, and total upload-byte
34    /// ceilings. Upload bytes include canonical display-edge endpoints.
35    pub const fn new(vertices: usize, triangles: usize, upload_bytes: usize) -> Self {
36        Self {
37            max_generated_vertices: vertices,
38            max_generated_triangles: triangles,
39            max_generated_upload_bytes: upload_bytes,
40        }
41    }
42
43    /// Returns the maximum generated clip-space vertices in one frame.
44    pub const fn max_generated_vertices(self) -> usize {
45        self.max_generated_vertices
46    }
47
48    /// Returns the maximum generated triangle-list primitives in one frame.
49    pub const fn max_generated_triangles(self) -> usize {
50        self.max_generated_triangles
51    }
52
53    /// Returns maximum bytes uploaded for generated surfaces and their edges.
54    pub const fn max_generated_upload_bytes(self) -> usize {
55        self.max_generated_upload_bytes
56    }
57}
58
59impl Default for Mesh3dRenderBudget {
60    fn default() -> Self {
61        Self::new(1_048_575, 349_525, 16_777_200)
62    }
63}
64
65/// Non-mutating preflight counts for the exact scene, camera, target and budget.
66#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
67pub struct Mesh3dPreflightReport {
68    pub(super) generated_vertices: usize,
69    pub(super) generated_triangles: usize,
70    pub(super) generated_upload_bytes: usize,
71    pub(super) generated_edges: usize,
72    pub(super) clipped_source_triangles: usize,
73    pub(super) discarded_source_triangles: usize,
74}
75
76impl Mesh3dPreflightReport {
77    /// Returns uploaded clip-space vertices, including unchanged triangles in
78    /// objects that also contain crossing triangles.
79    pub const fn generated_vertex_count(self) -> usize {
80        self.generated_vertices
81    }
82
83    /// Returns generated triangle-list primitives submitted to the GPU.
84    pub const fn generated_triangle_count(self) -> usize {
85        self.generated_triangles
86    }
87
88    /// Returns exact additional surface and display-edge upload bytes.
89    pub const fn generated_upload_bytes(self) -> usize {
90        self.generated_upload_bytes
91    }
92
93    /// Returns canonical clip-space display edges uploaded for crossing objects.
94    /// Their two endpoints share the surface's CPU-defined transform so legal
95    /// shader dot associations cannot shift edges away from their own faces.
96    pub const fn generated_edge_count(self) -> usize {
97        self.generated_edges
98    }
99
100    /// Returns original triangles that intersect the frustum boundary and
101    /// produce a nonempty clipped polygon.
102    pub const fn clipped_source_triangle_count(self) -> usize {
103        self.clipped_source_triangles
104    }
105
106    /// Returns original triangles proven entirely outside the frustum.
107    pub const fn discarded_source_triangle_count(self) -> usize {
108        self.discarded_source_triangles
109    }
110}
111
112#[repr(C)]
113#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
114pub(super) struct SurfaceClipVertex {
115    pub(super) clip: [f32; 4],
116    pub(super) uv: [f32; 2],
117}
118
119impl SurfaceClipVertex {
120    const ATTRIBUTES: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x4];
121    pub(super) const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
122        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
123        step_mode: wgpu::VertexStepMode::Vertex,
124        attributes: &Self::ATTRIBUTES,
125    };
126    const TEXTURED_ATTRIBUTES: [wgpu::VertexAttribute; 2] =
127        wgpu::vertex_attr_array![0 => Float32x4, 5 => Float32x2];
128    pub(super) const TEXTURED_LAYOUT: wgpu::VertexBufferLayout<'static> =
129        wgpu::VertexBufferLayout {
130            array_stride: std::mem::size_of::<Self>() as u64,
131            step_mode: wgpu::VertexStepMode::Vertex,
132            attributes: &Self::TEXTURED_ATTRIBUTES,
133        };
134}
135
136pub(super) struct SurfaceFrame {
137    pub(super) report: Mesh3dPreflightReport,
138    pub(super) vertices: Vec<SurfaceClipVertex>,
139    pub(super) edges: Vec<SurfaceClipEdge>,
140    pub(super) objects: Vec<SurfaceObject>,
141}
142
143pub(super) struct SurfaceObject {
144    pub(super) generated: Option<std::ops::Range<u32>>,
145    pub(super) model_rows: [[f32; 4]; 3],
146    pub(super) generated_edges: Option<std::ops::Range<u32>>,
147}
148
149#[repr(C)]
150#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
151pub(super) struct SurfaceClipEdge {
152    pub(super) start: [f32; 4],
153    pub(super) end: [f32; 4],
154}
155
156impl SurfaceClipEdge {
157    const ATTRIBUTES: [wgpu::VertexAttribute; 2] =
158        wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4];
159    pub(super) const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
160        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
161        step_mode: wgpu::VertexStepMode::Instance,
162        attributes: &Self::ATTRIBUTES,
163    };
164}
165
166pub(super) fn preflight(
167    renderer_identity: &Arc<()>,
168    scene: &Scene3d,
169    camera: Camera3dUniform,
170    budget: Mesh3dRenderBudget,
171    max_buffer_size: u64,
172) -> Result<SurfaceFrame, Mesh3dRenderError> {
173    let capacity_error = Mesh3dRenderError::GeneratedGeometryCapacityTooLarge;
174    let visible_count = scene.visible_object_count();
175    let object_bytes = visible_count
176        .checked_mul(std::mem::size_of::<SurfaceObject>())
177        .ok_or(Mesh3dRenderError::InstanceCapacityTooLarge)?;
178    if u64::try_from(object_bytes).map_or(true, |bytes| bytes > max_buffer_size) {
179        return Err(Mesh3dRenderError::InstanceCapacityTooLarge);
180    }
181    let mut frame = SurfaceFrame {
182        report: Mesh3dPreflightReport::default(),
183        vertices: Vec::new(),
184        edges: Vec::new(),
185        objects: Vec::new(),
186    };
187    frame
188        .objects
189        .try_reserve_exact(visible_count)
190        .map_err(|_| Mesh3dRenderError::InstanceCapacityTooLarge)?;
191    for instance in scene.instances().iter().filter(|instance| instance.visible) {
192        validate_mesh_identity(renderer_identity, &instance.mesh)?;
193        let object_result = (|| {
194            let model = instance
195                .transform
196                .model_rows()
197                .map_err(|_| Mesh3dRenderError::InvalidGeometryTransform)?;
198            validate_shader_points(instance.mesh.source(), model, camera.rows())?;
199            if let Some(style) = instance.wireframe() {
200                validate_edge_projection(
201                    instance.mesh.source(),
202                    model,
203                    camera.rows(),
204                    style,
205                    camera.viewport,
206                )?;
207            }
208            let mut crossing = false;
209            let mut vertex_count = 0usize;
210            if instance.style.surface_style().is_some() {
211                classify_surface(
212                    instance.mesh.source(),
213                    model,
214                    camera.rows(),
215                    |_, vertices, clipped| {
216                        crossing |= clipped;
217                        vertex_count = vertex_count
218                            .checked_add(vertices.len())
219                            .ok_or(capacity_error)?;
220                        if vertices.is_empty() {
221                            frame.report.discarded_source_triangles = frame
222                                .report
223                                .discarded_source_triangles
224                                .checked_add(1)
225                                .ok_or(capacity_error)?;
226                        } else if clipped {
227                            frame.report.clipped_source_triangles = frame
228                                .report
229                                .clipped_source_triangles
230                                .checked_add(1)
231                                .ok_or(capacity_error)?;
232                        }
233                        Ok(())
234                    },
235                )?;
236            }
237            if crossing {
238                let start = frame.report.generated_vertices;
239                let count = start.checked_add(vertex_count).ok_or(capacity_error)?;
240                let vertex_bytes = count
241                    .checked_mul(std::mem::size_of::<SurfaceClipVertex>())
242                    .ok_or(capacity_error)?;
243                let edge_start = frame.report.generated_edges;
244                let edge_count = if instance.wireframe().is_some() {
245                    instance.mesh.source().display_edges().len()
246                } else {
247                    0
248                };
249                let edge_end = edge_start.checked_add(edge_count).ok_or(capacity_error)?;
250                let edge_bytes = edge_end
251                    .checked_mul(std::mem::size_of::<SurfaceClipEdge>())
252                    .ok_or(capacity_error)?;
253                let bytes = vertex_bytes.checked_add(edge_bytes).ok_or(capacity_error)?;
254                if count > budget.max_generated_vertices
255                    || count / 3 > budget.max_generated_triangles
256                    || bytes > budget.max_generated_upload_bytes
257                    || u64::try_from(vertex_bytes.max(edge_bytes))
258                        .map_or(true, |bytes| bytes > max_buffer_size)
259                    || count > u32::MAX as usize
260                    || edge_end > u32::MAX as usize
261                {
262                    return Err(capacity_error);
263                }
264                frame.report.generated_vertices = count;
265                frame.report.generated_triangles = count / 3;
266                frame.report.generated_upload_bytes = bytes;
267                frame.report.generated_edges = edge_end;
268                frame.objects.push(SurfaceObject {
269                    generated: Some(start as u32..count as u32),
270                    model_rows: model,
271                    generated_edges: Some(edge_start as u32..edge_end as u32),
272                });
273            } else {
274                frame.objects.push(SurfaceObject {
275                    generated: None,
276                    model_rows: model,
277                    generated_edges: None,
278                });
279            }
280            Ok(())
281        })();
282        object_result.map_err(|error: Mesh3dRenderError| error.for_object(instance.id))?;
283    }
284    // All source proofs and exact aggregate capacities succeeded. This private
285    // scratch is discarded on failure and never publishes a partial target.
286    frame
287        .vertices
288        .try_reserve_exact(frame.report.generated_vertices)
289        .map_err(|_| capacity_error)?;
290    frame
291        .edges
292        .try_reserve_exact(frame.report.generated_edges)
293        .map_err(|_| capacity_error)?;
294    for (instance, object) in scene
295        .instances()
296        .iter()
297        .filter(|instance| instance.visible)
298        .zip(&frame.objects)
299    {
300        if object.generated.is_none() {
301            continue;
302        }
303        classify_surface(
304            instance.mesh.source(),
305            object.model_rows,
306            camera.rows(),
307            |_, vertices, _| {
308                frame.vertices.extend_from_slice(vertices);
309                Ok(())
310            },
311        )
312        .map_err(|error| error.for_object(instance.id))?;
313        if instance.wireframe().is_some() {
314            for edge in instance.mesh.source().display_edges() {
315                let endpoints = [edge.start(), edge.end()];
316                let mut clips = [[0.0; 4]; 2];
317                for (clip, vertex) in clips.iter_mut().zip(endpoints) {
318                    *clip = shader_clip_point_ranges(
319                        instance.mesh.source().vertices()[vertex as usize],
320                        object.model_rows,
321                        camera.rows(),
322                    )
323                    .map_err(|error| error.for_object(instance.id))?
324                    .map(|component| component.fixed);
325                }
326                frame.edges.push(SurfaceClipEdge {
327                    start: clips[0],
328                    end: clips[1],
329                });
330            }
331        }
332    }
333    Ok(frame)
334}
335
336// A triangle intersected with six convex half-spaces has at most nine vertices.
337const MAX_POLYGON_VERTICES: usize = 9;
338
339#[derive(Clone, Copy)]
340struct ClipVertex {
341    ranges: [ShaderValueRange; 4],
342    planes: u8,
343    provenance: u8,
344    uv: [f32; 2],
345}
346
347impl ClipVertex {
348    fn same_proven_vertex(self, other: Self) -> bool {
349        self.provenance == other.provenance
350            && self.planes == other.planes
351            && self.uv == other.uv
352            && self
353                .ranges
354                .into_iter()
355                .zip(other.ranges)
356                .all(|(left, right)| {
357                    left.fixed == right.fixed
358                        && left.minimum == right.minimum
359                        && left.maximum == right.maximum
360                })
361    }
362    fn plane_range(self, plane: usize) -> Result<(f64, f64), Mesh3dRenderError> {
363        if self.planes & (1 << plane) != 0 {
364            Ok((0.0, 0.0))
365        } else {
366            clip_plane_ranges(self.ranges).map(|ranges| ranges[plane])
367        }
368    }
369
370    fn plane_value(self, plane: usize) -> f64 {
371        if self.planes & (1 << plane) != 0 {
372            return 0.0;
373        }
374        let [x, y, z, w] = self.ranges.map(|range| f64::from(range.fixed));
375        [w + x, w - x, w + y, w - y, z, w - z][plane]
376    }
377}
378
379#[derive(Clone, Copy)]
380struct ClippedTriangle {
381    vertices: [ClipVertex; MAX_POLYGON_VERTICES],
382    count: usize,
383    crossing: bool,
384}
385
386fn inside(vertex: ClipVertex, plane: usize) -> Result<bool, Mesh3dRenderError> {
387    let range = vertex.plane_range(plane)?;
388    if range.0 >= 0.0 {
389        Ok(true)
390    } else if range.1 <= -f64::from(f32::MIN_POSITIVE) {
391        Ok(false)
392    } else {
393        Err(Mesh3dRenderError::UnportableSurfaceTopology)
394    }
395}
396
397fn intersection(
398    start: ClipVertex,
399    end: ClipVertex,
400    plane: usize,
401    provenance: u8,
402) -> Result<ClipVertex, Mesh3dRenderError> {
403    let error = Mesh3dRenderError::UnportableSurfaceTopology;
404    let start_distance = start.plane_range(plane)?;
405    let end_distance = end.plane_range(plane)?;
406    if start_distance == (0.0, 0.0) {
407        return Ok(start);
408    }
409    if end_distance == (0.0, 0.0) {
410        return Ok(end);
411    }
412    let denominator = rounded_f32_add_range(start_distance, end_distance, true).ok_or(error)?;
413    let amount = wgsl_signed_division_range(start_distance, denominator).ok_or(error)?;
414    if amount.0 < 0.0 || amount.1 > 1.0 {
415        return Err(error);
416    }
417    // The emitted position has a single CPU-defined representation. Intervals
418    // still prove topology for all legal transform associations, so baking the
419    // position is not permission to accept an ambiguous source triangle.
420    let distance = start.plane_value(plane);
421    let fixed_amount = distance / (distance - end.plane_value(plane));
422    let mut ranges = [ShaderValueRange::exact(0.0); 4];
423    for (axis, range) in ranges.iter_mut().enumerate() {
424        let left = start.ranges[axis];
425        let right = end.ranges[axis];
426        let (minimum, maximum) = interval_lerp_range(
427            (left.minimum, left.maximum),
428            (right.minimum, right.maximum),
429            amount,
430        )
431        .ok_or(error)?;
432        let fixed = (f64::from(left.fixed)
433            + (f64::from(right.fixed) - f64::from(left.fixed)) * fixed_amount)
434            as f32;
435        if !is_portable_shader_source(fixed) {
436            return Err(error);
437        }
438        *range = ShaderValueRange {
439            fixed,
440            minimum: minimum.min(f64::from(fixed)),
441            maximum: maximum.max(f64::from(fixed)),
442        };
443    }
444    let planes = (start.planes & end.planes) | (1 << plane);
445    let uv = std::array::from_fn(|axis| {
446        (f64::from(start.uv[axis])
447            + (f64::from(end.uv[axis]) - f64::from(start.uv[axis])) * fixed_amount) as f32
448    });
449    if uv
450        .into_iter()
451        .any(|value| !is_portable_shader_source(value) || !(0.0..=1.0).contains(&value))
452    {
453        return Err(error);
454    }
455    // Preserve the exact plane relation, including corners shared by two
456    // previously clipped planes. This prevents a second hardware clip caused
457    // only by independently rounding x and w at the boundary.
458    for boundary in 0..6 {
459        if planes & (1 << boundary) == 0 {
460            continue;
461        }
462        let w = ranges[3];
463        let (axis, negative) = match boundary {
464            0 => (0, true),
465            1 => (0, false),
466            2 => (1, true),
467            3 => (1, false),
468            4 => {
469                ranges[2] = ShaderValueRange::exact(0.0);
470                continue;
471            }
472            _ => (2, false),
473        };
474        ranges[axis] = if negative {
475            ShaderValueRange {
476                fixed: -w.fixed,
477                minimum: -w.maximum,
478                maximum: -w.minimum,
479            }
480        } else {
481            w
482        };
483    }
484    Ok(ClipVertex {
485        ranges,
486        planes,
487        provenance,
488        uv,
489    })
490}
491
492#[cfg(test)]
493fn clipped_triangle(
494    clips: [[ShaderValueRange; 4]; 3],
495) -> Result<ClippedTriangle, Mesh3dRenderError> {
496    clipped_triangle_with_uv(clips, [[0.0; 2]; 3])
497}
498
499fn clipped_triangle_with_uv(
500    clips: [[ShaderValueRange; 4]; 3],
501    uv: [[f32; 2]; 3],
502) -> Result<ClippedTriangle, Mesh3dRenderError> {
503    let empty = ClipVertex {
504        ranges: [ShaderValueRange::exact(0.0); 4],
505        planes: 0,
506        provenance: 0,
507        uv: [0.0; 2],
508    };
509    let mut result = ClippedTriangle {
510        vertices: [empty; MAX_POLYGON_VERTICES],
511        count: 3,
512        crossing: false,
513    };
514    for (provenance, (destination, ranges)) in result.vertices.iter_mut().zip(clips).enumerate() {
515        let plane_ranges = clip_plane_ranges(ranges)?;
516        let planes = plane_ranges
517            .iter()
518            .enumerate()
519            .fold(0, |mask, (plane, range)| {
520                mask | if *range == (0.0, 0.0) { 1 << plane } else { 0 }
521            });
522        *destination = ClipVertex {
523            ranges,
524            planes,
525            provenance: provenance as u8,
526            uv: uv[provenance],
527        };
528    }
529    // Common-plane rejection does not need a projected orientation proof.
530    let mut next_provenance = 3u8;
531    for plane in 0..6 {
532        if result.vertices[..3]
533            .iter()
534            .all(|vertex| vertex.plane_range(plane).is_ok_and(|range| range.1 < 0.0))
535        {
536            result.count = 0;
537            return Ok(result);
538        }
539    }
540    for plane in 0..6 {
541        if result.count == 0 {
542            break;
543        }
544        let input = result;
545        result.count = 0;
546        let mut previous = input.vertices[input.count - 1];
547        let mut previous_inside = inside(previous, plane)?;
548        for current in input.vertices[..input.count].iter().copied() {
549            let current_inside = inside(current, plane)?;
550            let intersection = if previous_inside != current_inside {
551                let intersection = intersection(previous, current, plane, next_provenance)?;
552                next_provenance += 1;
553                Some(intersection)
554            } else {
555                None
556            };
557            result.crossing |= !current_inside;
558            for vertex in intersection
559                .into_iter()
560                .chain(current_inside.then_some(current))
561            {
562                if result.count > 0
563                    && result.vertices[result.count - 1]
564                        .ranges
565                        .map(|value| value.fixed)
566                        == vertex.ranges.map(|value| value.fixed)
567                {
568                    // Only identical, proven boundary endpoints may collapse.
569                    // An uncertainty envelope is never discarded as zero area.
570                    if !result.vertices[result.count - 1].same_proven_vertex(vertex) {
571                        return Err(Mesh3dRenderError::UnportableSurfaceTopology);
572                    }
573                    continue;
574                }
575                if result.count == MAX_POLYGON_VERTICES {
576                    return Err(Mesh3dRenderError::UnportableSurfaceTopology);
577                }
578                result.vertices[result.count] = vertex;
579                result.count += 1;
580            }
581            previous = current;
582            previous_inside = current_inside;
583        }
584        if result.count > 1
585            && result.vertices[0].ranges.map(|value| value.fixed)
586                == result.vertices[result.count - 1]
587                    .ranges
588                    .map(|value| value.fixed)
589        {
590            if !result.vertices[0].same_proven_vertex(result.vertices[result.count - 1]) {
591                return Err(Mesh3dRenderError::UnportableSurfaceTopology);
592            }
593            result.count -= 1;
594        }
595    }
596    if result.count > 0 && result.count < 3 {
597        return Err(Mesh3dRenderError::UnportableSurfaceTopology);
598    }
599    for index in 1..result.count.saturating_sub(1) {
600        let vertices = [
601            result.vertices[0],
602            result.vertices[index],
603            result.vertices[index + 1],
604        ];
605        for vertex in vertices {
606            if vertex.ranges[3].minimum < f64::from(f32::MIN_POSITIVE) {
607                return Err(Mesh3dRenderError::UnportableSurfaceTopology);
608            }
609            for plane in 0..6 {
610                if !inside(vertex, plane)? || vertex.plane_value(plane) < 0.0 {
611                    return Err(Mesh3dRenderError::UnportableSurfaceTopology);
612                }
613            }
614        }
615        validate_projected_triangle_orientation(vertices.map(|vertex| vertex.ranges))?;
616    }
617    Ok(result)
618}
619
620pub(super) fn classify_surface(
621    mesh: &Mesh3d,
622    model_rows: [[f32; 4]; 3],
623    camera_rows: [[f32; 4]; 4],
624    mut visit: impl FnMut(usize, &[SurfaceClipVertex], bool) -> Result<(), Mesh3dRenderError>,
625) -> Result<(), Mesh3dRenderError> {
626    for (index, triangle) in mesh.triangle_indices().chunks_exact(3).enumerate() {
627        let mut clips = [[ShaderValueRange::exact(0.0); 4]; 3];
628        for (destination, vertex) in clips.iter_mut().zip(triangle) {
629            *destination = shader_clip_point_ranges(
630                mesh.vertices()[*vertex as usize],
631                model_rows,
632                camera_rows,
633            )?;
634        }
635        let uv = std::array::from_fn(|index| {
636            mesh.texture_coordinates()
637                .get(triangle[index] as usize)
638                .map_or([0.0, 0.0], |coordinate| [coordinate.u(), coordinate.v()])
639        });
640        let polygon = clipped_triangle_with_uv(clips, uv)?;
641        let mut emitted = [SurfaceClipVertex {
642            clip: [0.0; 4],
643            uv: [0.0; 2],
644        }; 21];
645        let mut count = 0;
646        for fan in 1..polygon.count.saturating_sub(1) {
647            for vertex in [
648                polygon.vertices[0],
649                polygon.vertices[fan],
650                polygon.vertices[fan + 1],
651            ] {
652                emitted[count] = SurfaceClipVertex {
653                    clip: vertex.ranges.map(|range| range.fixed),
654                    uv: vertex.uv,
655                };
656                count += 1;
657            }
658        }
659        visit(index, &emitted[..count], polygon.crossing)?;
660    }
661    Ok(())
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667
668    fn exact(points: [[f32; 4]; 3]) -> [[ShaderValueRange; 4]; 3] {
669        points.map(|point| point.map(ShaderValueRange::exact))
670    }
671
672    #[test]
673    fn surface_clips_every_frustum_plane_in_both_windings() {
674        let base = [
675            [-0.4, -0.3, 0.4, 1.0],
676            [0.5, -0.2, 0.6, 1.0],
677            [0.1, 0.5, 0.5, 1.0],
678        ];
679        for plane in 0..6 {
680            let mut points = base;
681            match plane {
682                0 => points[0][0] = -2.0,
683                1 => points[0][0] = 2.0,
684                2 => points[0][1] = -2.0,
685                3 => points[0][1] = 2.0,
686                4 => points[0][2] = -0.5,
687                _ => points[0][2] = 1.5,
688            }
689            for reverse in [false, true] {
690                let mut input = points;
691                if reverse {
692                    input.swap(1, 2);
693                }
694                let result = clipped_triangle(exact(input))
695                    .unwrap_or_else(|error| panic!("plane={plane} reverse={reverse}: {error}"));
696                assert!(result.crossing);
697                assert_eq!(result.count, 4);
698                for vertex in &result.vertices[..result.count] {
699                    assert!(vertex.ranges[3].fixed > 0.0);
700                    for boundary in 0..6 {
701                        assert!(vertex.plane_value(boundary) >= 0.0);
702                    }
703                }
704            }
705        }
706    }
707
708    #[test]
709    fn surface_clipping_handles_camera_plane_and_multi_plane_corners() {
710        for points in [
711            [
712                [-0.1, -0.2, -0.1, 0.0],
713                [0.5, -0.2, 0.5, 1.0],
714                [0.1, 0.5, 0.5, 1.0],
715            ],
716            [
717                [-0.1, -0.2, -0.1, f32::MIN_POSITIVE],
718                [0.5, -0.2, 0.5, 1.0],
719                [0.1, 0.5, 0.5, 1.0],
720            ],
721            [
722                [-2.0, -1.5, 0.5, 1.0],
723                [2.0, -0.7, 0.5, 1.0],
724                [0.1, 2.0, 0.5, 1.0],
725            ],
726        ] {
727            let result = clipped_triangle(exact(points)).unwrap();
728            assert!(result.crossing);
729            assert!(result.count >= 3 && result.count <= MAX_POLYGON_VERTICES);
730        }
731    }
732
733    #[test]
734    fn surface_clipping_keeps_ambiguous_and_edge_on_rejections() {
735        let edge_on = exact([
736            [-0.5, 0.0, 0.2, 1.0],
737            [0.0, 0.0, 0.5, 1.0],
738            [0.5, 0.0, 0.8, 1.0],
739        ]);
740        assert!(matches!(
741            clipped_triangle(edge_on),
742            Err(Mesh3dRenderError::UnportableSurfaceTopology)
743        ));
744        let mut grazing = exact([
745            [-1.0, -0.3, 0.4, 1.0],
746            [0.5, -0.2, 0.6, 1.0],
747            [0.1, 0.5, 0.5, 1.0],
748        ]);
749        grazing[0][0].minimum = -1.000001;
750        grazing[0][0].maximum = -0.999999;
751        assert!(matches!(
752            clipped_triangle(grazing),
753            Err(Mesh3dRenderError::UnportableSurfaceTopology)
754        ));
755        let outside = exact([
756            [-2.0, 0.0, 0.5, 1.0],
757            [-2.5, 0.0, 0.5, 1.0],
758            [-3.0, 0.0, 0.5, 1.0],
759        ]);
760        assert_eq!(clipped_triangle(outside).unwrap().count, 0);
761    }
762}