From 166d470acf97339da15bf58b3598a5ca2586be74 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 21:04:33 -0800 Subject: [PATCH] raster3d: a clipped edge crosses at the same corner in both directions when its distances tie When both corners of an edge lie equally far from a clip plane, crossing_f64 interpolated from whichever corner came first, so the two triangles sharing the edge could get crossings that differ in the last bit and leave a crack between them. A tie now starts from the corner that sorts first by its coordinates and weights. --- crates/raster3d/src/raster.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/raster3d/src/raster.rs b/crates/raster3d/src/raster.rs index bc545a9da2..4f2c1b4121 100644 --- a/crates/raster3d/src/raster.rs +++ b/crates/raster3d/src/raster.rs @@ -140,8 +140,16 @@ fn clip_wide(poly: &[Corner], planes: &[usize]) -> Vec { /// Where the edge from `a` (plane distance `da`) to `b` (`db`) crosses the plane, interpolated in /// `f64` from the corner nearer the plane, so both directions of an edge give the same corner. +/// When both corners are equally near, the interpolation starts from the corner that sorts first +/// by its coordinates and then its weights. fn crossing_f64(a: ([f64; 4], [f64; 3]), b: ([f64; 4], [f64; 3]), da: f64, db: f64) -> ([f64; 4], [f64; 3]) { - let (p, q, t) = if da.abs() <= db.abs() { (a, b, da / (da - db)) } else { (b, a, db / (db - da)) }; + let a_first = if da.abs() == db.abs() { + let order = a.0.iter().chain(&a.1).zip(b.0.iter().chain(&b.1)).map(|(x, y)| x.total_cmp(y)).find(|o| o.is_ne()); + order.is_none_or(std::cmp::Ordering::is_lt) + } else { + da.abs() < db.abs() + }; + let (p, q, t) = if a_first { (a, b, da / (da - db)) } else { (b, a, db / (db - da)) }; let c: [f64; 4] = std::array::from_fn(|k| p.0[k] + (q.0[k] - p.0[k]) * t); let w: [f64; 3] = std::array::from_fn(|k| p.1[k] + (q.1[k] - p.1[k]) * t); (c, w) @@ -699,7 +707,7 @@ pub fn try_render(s: &Scene, limits: &Limits) -> Result { mod tests { use std::sync::atomic::{AtomicU64, Ordering}; - use super::{cover, f32_crossing, fan, project, try_render}; + use super::{cover, crossing_f64, f32_crossing, fan, project, try_render}; use crate::scene::{Material, Scene, Vertex}; use crate::{Limits, RenderError}; @@ -760,4 +768,14 @@ mod tests { assert_eq!(f32_crossing(-3e38, 1e38), (false, 0.75)); assert_eq!(f32_crossing(1e38, -3e38), (false, 0.25)); } + + #[test] + fn both_directions_of_an_edge_cross_at_the_same_corner_when_the_distances_tie() { + let a = ([3.0, 0.1, 0.5, 1.0], [1.0, 0.0, 0.0]); + let b = ([2f64.powi(54), 0.7, 0.5, 1.0], [0.0, 0.3, 0.7]); + let ab = crossing_f64(a, b, 1.0, -1.0); + let ba = crossing_f64(b, a, -1.0, 1.0); + assert_eq!(ab.0.map(f64::to_bits), ba.0.map(f64::to_bits)); + assert_eq!(ab.1.map(f64::to_bits), ba.1.map(f64::to_bits)); + } }