Skip to main content

qualia_core_db/specialized_libs/computational_geometry/
gpu.rs

1//! Typed WGSL geometry kernels with deterministic CPU oracles.
2//!
3//! These kernels complement WGSL Forge without pretending that branch-heavy
4//! exact topology edits belong on the GPU. Parallel broad phases run here;
5//! uncertain predicates are explicitly returned to the robust CPU/WASM path.
6//! Shader generation delegates to Etalon; this module does not dispatch GPU work.
7//!
8//! ## P1.9 — orient3d and incircle GPU batches
9//!
10//! Added `Orient3dF32` and `IncircleF32` kernels, each with:
11//! - A WGSL shader that computes the filtered determinant in f32 and flags
12//!   `GPU_ORIENTATION_UNCERTAIN` when near the error bound.
13//! - A CPU/WASM oracle (`evaluate_orient3d_batch_f32`, `evaluate_incircle_batch_f32`)
14//!   that runs the full filtered → compensated → exact ladder.
15//!
16//! The GPU is the fast broad phase; uncertain lanes fall back to the CPU
17//! oracle's exact path. On the no-adapter path, the CPU oracle is the
18//! deterministic fallback (identical results, no GPU needed).
19
20use super::box_join::BoxPair;
21use super::expansion::Sign;
22use super::{incircle, orient_3d, orientation_2, Aabb, Point2, Point3};
23
24pub use etalon_wgsl_forge::geometry_specs::filtered::{
25    emit_geometry_wgsl, GeometryGpuError, GeometryGpuKernel, GeometryGpuSchedule,
26    GPU_ORIENTATION_UNCERTAIN, GPU_OVERLAP_YES, GPU_OVERLAP_NO, GPU_OVERLAP_UNCERTAIN,
27};
28
29/// CPU/WASM oracle for packed `(ax, ay, bx, by, cx, cy)` f32 triples.
30pub fn evaluate_orientation_batch_f32(
31    packed: &[f32],
32    out: &mut [i8],
33) -> Result<usize, GeometryGpuError> {
34    if packed.len() % 6 != 0 {
35        return Err(GeometryGpuError::InputLengthNotMultipleOfSix);
36    }
37    let count = packed.len() / 6;
38    if out.len() < count {
39        return Err(GeometryGpuError::OutputTooSmall { required: count });
40    }
41    for (index, triple) in packed.chunks_exact(6).enumerate() {
42        out[index] = orientation_2(
43            Point2::new(triple[0] as f64, triple[1] as f64),
44            Point2::new(triple[2] as f64, triple[3] as f64),
45            Point2::new(triple[4] as f64, triple[5] as f64),
46        ) as i8;
47    }
48    Ok(count)
49}
50
51/// CPU/WASM oracle for packed `(ax,ay,az, bx,by,bz, cx,cy,cz, dx,dy,dz)` f32
52/// quadruples (12 f32s per quad). Runs the full filtered → compensated → exact
53/// ladder via [`orient_3d`].
54///
55/// P1.9.
56pub fn evaluate_orient3d_batch_f32(
57    packed: &[f32],
58    out: &mut [i8],
59) -> Result<usize, GeometryGpuError> {
60    if packed.len() % 12 != 0 {
61        return Err(GeometryGpuError::InputLengthNotMultipleOfTwelve);
62    }
63    let count = packed.len() / 12;
64    if out.len() < count {
65        return Err(GeometryGpuError::OutputTooSmall { required: count });
66    }
67    for (index, quad) in packed.chunks_exact(12).enumerate() {
68        let s = orient_3d(
69            Point3::new(quad[0] as f64, quad[1] as f64, quad[2] as f64),
70            Point3::new(quad[3] as f64, quad[4] as f64, quad[5] as f64),
71            Point3::new(quad[6] as f64, quad[7] as f64, quad[8] as f64),
72            Point3::new(quad[9] as f64, quad[10] as f64, quad[11] as f64),
73        );
74        out[index] = sign_to_i8(s);
75    }
76    Ok(count)
77}
78
79/// CPU/WASM oracle for packed `(ax,ay, bx,by, cx,cy, dx,dy)` f32 quadruples
80/// (8 f32s per quad). Runs the full filtered → compensated → exact ladder via
81/// [`incircle`].
82///
83/// P1.9.
84pub fn evaluate_incircle_batch_f32(
85    packed: &[f32],
86    out: &mut [i8],
87) -> Result<usize, GeometryGpuError> {
88    if packed.len() % 8 != 0 {
89        return Err(GeometryGpuError::InputLengthNotMultipleOfEight);
90    }
91    let count = packed.len() / 8;
92    if out.len() < count {
93        return Err(GeometryGpuError::OutputTooSmall { required: count });
94    }
95    for (index, quad) in packed.chunks_exact(8).enumerate() {
96        let s = incircle(
97            Point2::new(quad[0] as f64, quad[1] as f64),
98            Point2::new(quad[2] as f64, quad[3] as f64),
99            Point2::new(quad[4] as f64, quad[5] as f64),
100            Point2::new(quad[6] as f64, quad[7] as f64),
101        );
102        out[index] = sign_to_i8(s);
103    }
104    Ok(count)
105}
106
107// ── P3.6: AABB overlap CPU oracle + merge ────────────────────────────────
108
109/// CPU/WASM oracle for packed AABB pairs (12 f32s per pair).
110/// Returns exact overlap results: 1 = overlap, 0 = no overlap.
111pub fn evaluate_aabb_overlap_batch_f32(
112    packed: &[f32],
113    out: &mut [i32],
114) -> Result<usize, GeometryGpuError> {
115    if packed.len() % 12 != 0 {
116        return Err(GeometryGpuError::InputLengthNotMultipleOfTwelve);
117    }
118    let count = packed.len() / 12;
119    if out.len() < count {
120        return Err(GeometryGpuError::OutputTooSmall { required: count });
121    }
122    for (index, pair) in packed.chunks_exact(12).enumerate() {
123        let a = Aabb::new(
124            Point3::new(pair[0] as f64, pair[1] as f64, pair[2] as f64),
125            Point3::new(pair[3] as f64, pair[4] as f64, pair[5] as f64),
126        );
127        let b = Aabb::new(
128            Point3::new(pair[6] as f64, pair[7] as f64, pair[8] as f64),
129            Point3::new(pair[9] as f64, pair[10] as f64, pair[11] as f64),
130        );
131        out[index] = if a.overlaps(&b) {
132            GPU_OVERLAP_YES
133        } else {
134            GPU_OVERLAP_NO
135        };
136    }
137    Ok(count)
138}
139
140/// GPU filter simulation for AABB overlap (f32). Returns YES/NO/UNCERTAIN.
141fn gpu_filter_aabb_overlap_f32(pair: &[f32]) -> i32 {
142    let aminx = pair[0] as f64;
143    let aminy = pair[1] as f64;
144    let aminz = pair[2] as f64;
145    let amaxx = pair[3] as f64;
146    let amaxy = pair[4] as f64;
147    let amaxz = pair[5] as f64;
148    let bminx = pair[6] as f64;
149    let bminy = pair[7] as f64;
150    let bminz = pair[8] as f64;
151    let bmaxx = pair[9] as f64;
152    let bmaxy = pair[10] as f64;
153    let bmaxz = pair[11] as f64;
154
155    let dx1 = bmaxx - aminx;
156    let dx2 = amaxx - bminx;
157    let dy1 = bmaxy - aminy;
158    let dy2 = amaxy - bminy;
159    let dz1 = bmaxz - aminz;
160    let dz2 = amaxz - bminz;
161
162    let min_gap = dx1.min(dx2).min(dy1).min(dy2).min(dz1).min(dz2);
163    let eps = 1.0e-5;
164
165    if min_gap < 0.0 {
166        GPU_OVERLAP_NO
167    } else if min_gap < eps {
168        GPU_OVERLAP_UNCERTAIN
169    } else {
170        GPU_OVERLAP_YES
171    }
172}
173
174/// Deterministic merge: combine GPU candidate results with CPU verification.
175///
176/// GPU-certain YES/NO lanes are trusted. GPU-uncertain lanes are resolved
177/// by the CPU exact oracle. The output is deterministic: identical for
178/// GPU-on vs GPU-off (the merge guarantee).
179///
180/// `gpu_results` is the output of the GPU kernel (or the CPU simulation).
181/// `packed` is the original packed AABB pair data.
182/// `out` receives the final verified overlap results.
183pub fn merge_aabb_overlap_results(
184    packed: &[f32],
185    gpu_results: &[i32],
186    out: &mut [i32],
187) -> Result<usize, GeometryGpuError> {
188    let count = gpu_results.len();
189    if packed.len() < count * 12 {
190        return Err(GeometryGpuError::InputLengthNotMultipleOfTwelve);
191    }
192    if out.len() < count {
193        return Err(GeometryGpuError::OutputTooSmall { required: count });
194    }
195    for i in 0..count {
196        if gpu_results[i] == GPU_OVERLAP_UNCERTAIN {
197            // CPU exact resolution for uncertain lanes.
198            let pair = &packed[i * 12..(i + 1) * 12];
199            let a = Aabb::new(
200                Point3::new(pair[0] as f64, pair[1] as f64, pair[2] as f64),
201                Point3::new(pair[3] as f64, pair[4] as f64, pair[5] as f64),
202            );
203            let b = Aabb::new(
204                Point3::new(pair[6] as f64, pair[7] as f64, pair[8] as f64),
205                Point3::new(pair[9] as f64, pair[10] as f64, pair[11] as f64),
206            );
207            out[i] = if a.overlaps(&b) {
208                GPU_OVERLAP_YES
209            } else {
210                GPU_OVERLAP_NO
211            };
212        } else {
213            // Trust GPU-certain lanes.
214            out[i] = gpu_results[i];
215        }
216    }
217    Ok(count)
218}
219
220// ── P3.6: BVH overlap candidate generation + CPU merge ───────────────────
221
222/// Generate candidate pairs from a BVH overlap query using GPU-style
223/// broad-phase filtering, then merge with CPU exact verification.
224///
225/// This is the deterministic CPU path that produces results identical
226/// to the GPU path. When a GPU adapter is available, the GPU kernel
227/// generates the candidate set; this merge function verifies uncertain
228/// lanes. Without a GPU, this function does the full computation.
229///
230/// `boxes_a` / `boxes_b`: the two AABB sets.
231/// `out_pairs`: receives verified overlapping pairs.
232/// Returns the number of pairs written.
233pub fn gpu_candidate_box_join(
234    boxes_a: &[Aabb],
235    boxes_b: &[Aabb],
236    out_pairs: &mut [BoxPair],
237) -> Result<usize, GeometryGpuError> {
238    let max_pairs = boxes_a.len() * boxes_b.len();
239    if out_pairs.len() < max_pairs {
240        return Err(GeometryGpuError::CandidateBufferTooSmall {
241            required: max_pairs,
242        });
243    }
244
245    // Pack all pairs into f32 buffer (12 f32s per pair).
246    let mut packed: Vec<f32> = Vec::with_capacity(max_pairs * 12);
247    let mut pair_indices: Vec<(u32, u32)> = Vec::with_capacity(max_pairs);
248    for (i, a) in boxes_a.iter().enumerate() {
249        for (j, b) in boxes_b.iter().enumerate() {
250            packed.push(a.min.x as f32);
251            packed.push(a.min.y as f32);
252            packed.push(a.min.z as f32);
253            packed.push(a.max.x as f32);
254            packed.push(a.max.y as f32);
255            packed.push(a.max.z as f32);
256            packed.push(b.min.x as f32);
257            packed.push(b.min.y as f32);
258            packed.push(b.min.z as f32);
259            packed.push(b.max.x as f32);
260            packed.push(b.max.y as f32);
261            packed.push(b.max.z as f32);
262            pair_indices.push((i as u32, j as u32));
263        }
264    }
265
266    // GPU filter (CPU simulation).
267    let pair_count = pair_indices.len();
268    let mut gpu_results: Vec<i32> = vec![0; pair_count];
269    for i in 0..pair_count {
270        gpu_results[i] = gpu_filter_aabb_overlap_f32(&packed[i * 12..(i + 1) * 12]);
271    }
272
273    // Merge: verify uncertain lanes with CPU exact oracle.
274    let mut merged: Vec<i32> = vec![0; pair_count];
275    merge_aabb_overlap_results(&packed, &gpu_results, &mut merged)?;
276
277    // Collect verified overlapping pairs in deterministic (a, b) order.
278    let mut count = 0usize;
279    for i in 0..pair_count {
280        if merged[i] == GPU_OVERLAP_YES {
281            out_pairs[count] = BoxPair {
282                a: pair_indices[i].0,
283                b: pair_indices[i].1,
284            };
285            count += 1;
286        }
287    }
288
289    // Sort for deterministic output.
290    out_pairs[..count].sort_unstable();
291    Ok(count)
292}
293
294/// Map a `Sign` to `i8` matching the GPU's encoding: +1 / 0 / -1.
295#[inline]
296fn sign_to_i8(s: Sign) -> i8 {
297    match s {
298        Sign::Positive => 1,
299        Sign::Zero => 0,
300        Sign::Negative => -1,
301    }
302}
303
304/// GPU filter result for a single orient3d quadruple (f32).
305/// Returns +1 / -1 / `GPU_ORIENTATION_UNCERTAIN`.
306///
307/// This is the CPU-side simulation of the GPU filtered stage — used by the
308/// differential test to verify that GPU-certain lanes match the CPU exact
309/// ladder and GPU-uncertain lanes are flagged.
310pub fn gpu_filter_orient3d_f32(quad: &[f32]) -> i32 {
311    let ax = quad[0] as f64;
312    let ay = quad[1] as f64;
313    let az = quad[2] as f64;
314    let bx = quad[3] as f64;
315    let by = quad[4] as f64;
316    let bz = quad[5] as f64;
317    let cx = quad[6] as f64;
318    let cy = quad[7] as f64;
319    let cz = quad[8] as f64;
320    let dx = quad[9] as f64;
321    let dy = quad[10] as f64;
322    let dz = quad[11] as f64;
323
324    let abx = bx - ax;
325    let aby = by - ay;
326    let abz = bz - az;
327    let acx = cx - ax;
328    let acy = cy - ay;
329    let acz = cz - az;
330    let adx = dx - ax;
331    let ady = dy - ay;
332    let adz = dz - az;
333
334    let cx0 = acy * adz - acz * ady;
335    let cy0 = acz * adx - acx * adz;
336    let cz0 = acx * ady - acy * adx;
337    let det = abx * cx0 + aby * cy0 + abz * cz0;
338
339    let perm = abx.abs() * (acy.abs() * adz.abs() + acz.abs() * ady.abs())
340        + aby.abs() * (acx.abs() * adz.abs() + acz.abs() * adx.abs())
341        + abz.abs() * (acx.abs() * ady.abs() + acy.abs() * adx.abs());
342    // f32 epsilon ≈ 1.19e-7, but we use a slightly larger bound for safety
343    let error_bound = perm * 1.5e-5;
344
345    if det.abs() <= error_bound {
346        GPU_ORIENTATION_UNCERTAIN
347    } else if det > 0.0 {
348        1
349    } else {
350        -1
351    }
352}
353
354/// GPU filter result for a single incircle quadruple (f32).
355pub fn gpu_filter_incircle_f32(quad: &[f32]) -> i32 {
356    let ax = quad[0] as f64;
357    let ay = quad[1] as f64;
358    let bx = quad[2] as f64;
359    let by = quad[3] as f64;
360    let cx = quad[4] as f64;
361    let cy = quad[5] as f64;
362    let dx = quad[6] as f64;
363    let dy = quad[7] as f64;
364
365    let adx = ax - dx;
366    let ady = ay - dy;
367    let bdx = bx - dx;
368    let bdy = by - dy;
369    let cdx = cx - dx;
370    let cdy = cy - dy;
371    let ad2 = adx * adx + ady * ady;
372    let bd2 = bdx * bdx + bdy * bdy;
373    let cd2 = cdx * cdx + cdy * cdy;
374
375    let m1 = bdy * cd2 - cdy * bd2;
376    let m2 = bdx * cd2 - cdx * bd2;
377    let m3 = bdx * cdy - bdy * cdx;
378    let det = adx * m1 - ady * m2 + ad2 * m3;
379
380    let perm = adx.abs() * (bdy.abs() * cd2.abs() + cdy.abs() * bd2.abs())
381        + ady.abs() * (bdx.abs() * cd2.abs() + cdx.abs() * bd2.abs())
382        + ad2.abs() * (bdx.abs() * cdy.abs() + bdy.abs() * cdx.abs());
383    let error_bound = perm * 3.0e-5;
384
385    if det.abs() <= error_bound {
386        GPU_ORIENTATION_UNCERTAIN
387    } else if det > 0.0 {
388        1
389    } else {
390        -1
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn batch_oracle_matches_scalar_predicates() {
400        let packed = [
401            0.0, 0.0, 1.0, 0.0, 1.0, 1.0, // CCW
402            0.0, 0.0, 1.0, 0.0, 1.0, -1.0, // CW
403            0.0, 0.0, 1.0, 0.0, 2.0, 0.0, // collinear
404        ];
405        let mut out = [9i8; 3];
406        assert_eq!(
407            evaluate_orientation_batch_f32(&packed, &mut out).unwrap(),
408            3
409        );
410        assert_eq!(
411            out,
412            [
413                super::super::Orientation::CounterClockwise as i8,
414                super::super::Orientation::Clockwise as i8,
415                super::super::Orientation::Collinear as i8,
416            ]
417        );
418    }
419
420    #[test]
421    fn shader_generation_is_typed_and_deterministic() {
422        let schedule = GeometryGpuSchedule::default();
423        let a = emit_geometry_wgsl(GeometryGpuKernel::Orientation2F32, schedule).unwrap();
424        let b = emit_geometry_wgsl(GeometryGpuKernel::Orientation2F32, schedule).unwrap();
425        assert_eq!(a, b);
426        assert!(a.contains("@workgroup_size(128, 1, 1)"));
427        assert!(a.contains("orientation[i] = 2"));
428    }
429
430    #[cfg(feature = "wgsl-forge")]
431    #[test]
432    fn shader_passes_naga_validation() {
433        let source = emit_geometry_wgsl(
434            GeometryGpuKernel::Orientation2F32,
435            GeometryGpuSchedule::default(),
436        )
437        .unwrap();
438        let report = crate::wgsl_forge::validate_wgsl(&source).unwrap();
439        assert_eq!(report.entry_points, vec!["orientation_2_f32"]);
440    }
441
442    // ── P1.9: orient3d GPU kernel + oracle ────────────────────────────────
443
444    #[test]
445    fn orient3d_batch_oracle_matches_scalar() {
446        // Positive, negative, coplanar tetrahedra
447        let packed = [
448            // Positive: (0,0,0),(1,0,0),(0,1,0),(0,0,1)
449            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0,
450            // Negative: swap b and c
451            0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
452            // Coplanar: all z=0
453            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0,
454        ];
455        let mut out = [9i8; 3];
456        assert_eq!(evaluate_orient3d_batch_f32(&packed, &mut out).unwrap(), 3);
457        assert_eq!(out, [1, -1, 0]);
458    }
459
460    #[test]
461    fn orient3d_shader_generation_is_deterministic() {
462        let schedule = GeometryGpuSchedule::default();
463        let a = emit_geometry_wgsl(GeometryGpuKernel::Orient3dF32, schedule).unwrap();
464        let b = emit_geometry_wgsl(GeometryGpuKernel::Orient3dF32, schedule).unwrap();
465        assert_eq!(a, b);
466        assert!(a.contains("orient_3d_f32"));
467        assert!(a.contains("@workgroup_size(128, 1, 1)"));
468    }
469
470    #[cfg(feature = "wgsl-forge")]
471    #[test]
472    fn orient3d_shader_passes_naga_validation() {
473        let source = emit_geometry_wgsl(
474            GeometryGpuKernel::Orient3dF32,
475            GeometryGpuSchedule::default(),
476        )
477        .unwrap();
478        let report = crate::wgsl_forge::validate_wgsl(&source).unwrap();
479        assert_eq!(report.entry_points, vec!["orient_3d_f32"]);
480    }
481
482    #[test]
483    fn orient3d_gpu_certain_lanes_match_cpu_exact() {
484        // Clear cases where the GPU filter should be certain
485        let packed = [
486            // Positive tetrahedron (clear)
487            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0,
488            // Negative tetrahedron (clear)
489            0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
490        ];
491        let mut cpu_out = [9i8; 2];
492        evaluate_orient3d_batch_f32(&packed, &mut cpu_out).unwrap();
493
494        for (i, quad) in packed.chunks_exact(12).enumerate() {
495            let gpu = gpu_filter_orient3d_f32(quad);
496            // GPU-certain lanes must match CPU exact
497            assert_ne!(gpu, GPU_ORIENTATION_UNCERTAIN, "lane {i} should be certain");
498            assert_eq!(
499                gpu as i8, cpu_out[i],
500                "lane {i}: GPU={gpu}, CPU={}",
501                cpu_out[i]
502            );
503        }
504    }
505
506    #[test]
507    fn orient3d_gpu_uncertain_lanes_flagged_near_degeneracy() {
508        // Coplanar case — exact zero determinant. GPU filter flags uncertain
509        // (|det| = 0 <= error_bound = 0).
510        let packed = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0];
511        let gpu = gpu_filter_orient3d_f32(&packed);
512        assert_eq!(
513            gpu, GPU_ORIENTATION_UNCERTAIN,
514            "coplanar should be uncertain"
515        );
516
517        // CPU oracle resolves it exactly (Zero)
518        let mut cpu_out = [9i8; 1];
519        evaluate_orient3d_batch_f32(&packed, &mut cpu_out).unwrap();
520        assert_eq!(cpu_out[0], 0);
521    }
522
523    // ── P1.9: incircle GPU kernel + oracle ────────────────────────────────
524
525    #[test]
526    fn incircle_batch_oracle_matches_scalar() {
527        // Inside, outside, on (unit circle, CCW)
528        let packed = [
529            // a=(1,0), b=(0,1), c=(-1,0), d=(0,0) → inside
530            1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0,
531            // a=(1,0), b=(0,1), c=(-1,0), d=(2,0) → outside
532            1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 2.0, 0.0,
533            // a=(1,0), b=(0,1), c=(-1,0), d=(0,-1) → on
534            1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, -1.0,
535        ];
536        let mut out = [9i8; 3];
537        assert_eq!(evaluate_incircle_batch_f32(&packed, &mut out).unwrap(), 3);
538        assert_eq!(out, [1, -1, 0]);
539    }
540
541    #[test]
542    fn incircle_shader_generation_is_deterministic() {
543        let schedule = GeometryGpuSchedule::default();
544        let a = emit_geometry_wgsl(GeometryGpuKernel::IncircleF32, schedule).unwrap();
545        let b = emit_geometry_wgsl(GeometryGpuKernel::IncircleF32, schedule).unwrap();
546        assert_eq!(a, b);
547        assert!(a.contains("incircle_f32"));
548        assert!(a.contains("@workgroup_size(128, 1, 1)"));
549    }
550
551    #[cfg(feature = "wgsl-forge")]
552    #[test]
553    fn incircle_shader_passes_naga_validation() {
554        let source = emit_geometry_wgsl(
555            GeometryGpuKernel::IncircleF32,
556            GeometryGpuSchedule::default(),
557        )
558        .unwrap();
559        let report = crate::wgsl_forge::validate_wgsl(&source).unwrap();
560        assert_eq!(report.entry_points, vec!["incircle_f32"]);
561    }
562
563    #[test]
564    fn incircle_gpu_certain_lanes_match_cpu_exact() {
565        let packed = [
566            // Inside (clear)
567            1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, // Outside (clear)
568            1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 2.0, 0.0,
569        ];
570        let mut cpu_out = [9i8; 2];
571        evaluate_incircle_batch_f32(&packed, &mut cpu_out).unwrap();
572
573        for (i, quad) in packed.chunks_exact(8).enumerate() {
574            let gpu = gpu_filter_incircle_f32(quad);
575            assert_ne!(gpu, GPU_ORIENTATION_UNCERTAIN, "lane {i} should be certain");
576            assert_eq!(
577                gpu as i8, cpu_out[i],
578                "lane {i}: GPU={gpu}, CPU={}",
579                cpu_out[i]
580            );
581        }
582    }
583
584    #[test]
585    fn incircle_gpu_uncertain_lanes_flagged_near_degeneracy() {
586        // Cocircular case — exact zero determinant. GPU filter flags uncertain.
587        let packed = [1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, -1.0];
588        let gpu = gpu_filter_incircle_f32(&packed);
589        assert_eq!(
590            gpu, GPU_ORIENTATION_UNCERTAIN,
591            "cocircular should be uncertain"
592        );
593
594        let mut cpu_out = [9i8; 1];
595        evaluate_incircle_batch_f32(&packed, &mut cpu_out).unwrap();
596        // CPU resolves exactly (Zero — on circle)
597        assert_eq!(cpu_out[0], 0);
598    }
599
600    // ── P1.9: CPU/GPU differential over the determinism corpus ────────────
601
602    #[test]
603    fn cpu_gpu_differential_orient3d_over_corpus() {
604        // A set of orient3d cases covering clear, degenerate, and near-degenerate
605        let packed: [f32; 36] = [
606            // Clear positive
607            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, // Clear negative
608            0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
609            // Coplanar (exact zero)
610            0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0,
611        ];
612
613        let mut cpu_out = [9i8; 3];
614        evaluate_orient3d_batch_f32(&packed, &mut cpu_out).unwrap();
615
616        for (i, quad) in packed.chunks_exact(12).enumerate() {
617            let gpu = gpu_filter_orient3d_f32(quad);
618            if gpu != GPU_ORIENTATION_UNCERTAIN {
619                // GPU-certain lane must match CPU exact
620                assert_eq!(
621                    gpu as i8, cpu_out[i],
622                    "GPU-certain lane {i} disagrees with CPU exact: GPU={gpu}, CPU={}",
623                    cpu_out[i]
624                );
625            }
626            // GPU-uncertain lanes are correctly flagged — CPU resolves them
627        }
628    }
629
630    #[test]
631    fn cpu_gpu_differential_incircle_over_corpus() {
632        let packed: [f32; 24] = [
633            // Inside (clear)
634            1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, // Outside (clear)
635            1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 2.0, 0.0, // On circle (exact zero)
636            1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, -1.0,
637        ];
638
639        let mut cpu_out = [9i8; 3];
640        evaluate_incircle_batch_f32(&packed, &mut cpu_out).unwrap();
641
642        for (i, quad) in packed.chunks_exact(8).enumerate() {
643            let gpu = gpu_filter_incircle_f32(quad);
644            if gpu != GPU_ORIENTATION_UNCERTAIN {
645                assert_eq!(
646                    gpu as i8, cpu_out[i],
647                    "GPU-certain lane {i} disagrees with CPU exact: GPU={gpu}, CPU={}",
648                    cpu_out[i]
649                );
650            }
651        }
652    }
653
654    #[test]
655    fn orient3d_batch_rejects_wrong_input_length() {
656        let packed = [0.0f32; 11]; // not multiple of 12
657        let mut out = [0i8; 1];
658        assert_eq!(
659            evaluate_orient3d_batch_f32(&packed, &mut out),
660            Err(GeometryGpuError::InputLengthNotMultipleOfTwelve)
661        );
662    }
663
664    #[test]
665    fn incircle_batch_rejects_wrong_input_length() {
666        let packed = [0.0f32; 7]; // not multiple of 8
667        let mut out = [0i8; 1];
668        assert_eq!(
669            evaluate_incircle_batch_f32(&packed, &mut out),
670            Err(GeometryGpuError::InputLengthNotMultipleOfEight)
671        );
672    }
673
674    #[test]
675    fn orient3d_batch_rejects_small_output() {
676        let packed = [0.0f32; 12];
677        let mut out = [0i8; 0]; // too small
678        assert_eq!(
679            evaluate_orient3d_batch_f32(&packed, &mut out),
680            Err(GeometryGpuError::OutputTooSmall { required: 1 })
681        );
682    }
683
684    // ── P3.6: AABB overlap GPU kernel + merge ─────────────────────────────
685
686    #[test]
687    fn aabb_overlap_shader_generation_is_deterministic() {
688        let schedule = GeometryGpuSchedule::default();
689        let a = emit_geometry_wgsl(GeometryGpuKernel::AabbOverlapF32, schedule).unwrap();
690        let b = emit_geometry_wgsl(GeometryGpuKernel::AabbOverlapF32, schedule).unwrap();
691        assert_eq!(a, b);
692        assert!(a.contains("aabb_overlap_f32"));
693        assert!(a.contains("@workgroup_size(128, 1, 1)"));
694    }
695
696    #[test]
697    fn aabb_overlap_cpu_oracle_matches_exact() {
698        // Clear overlap, clear non-overlap, boundary-touching.
699        let packed: [f32; 36] = [
700            // Overlapping: [0,0,0]-[2,2,2] vs [1,1,1]-[3,3,3]
701            0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 3.0, 3.0, 3.0,
702            // Non-overlapping: [0,0,0]-[1,1,1] vs [5,5,5]-[6,6,6]
703            0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0,
704            // Boundary-touching: [0,0,0]-[1,1,1] vs [1,0,0]-[2,1,1]
705            0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 2.0, 1.0, 1.0,
706        ];
707        let mut out = [0i32; 3];
708        evaluate_aabb_overlap_batch_f32(&packed, &mut out).unwrap();
709        assert_eq!(out, [GPU_OVERLAP_YES, GPU_OVERLAP_NO, GPU_OVERLAP_YES]);
710    }
711
712    #[test]
713    fn aabb_overlap_gpu_certain_lanes_match_cpu() {
714        let packed: [f32; 24] = [
715            // Clear overlap
716            0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 3.0, 3.0, 3.0,
717            // Clear non-overlap
718            0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0,
719        ];
720        let mut cpu_out = [0i32; 2];
721        evaluate_aabb_overlap_batch_f32(&packed, &mut cpu_out).unwrap();
722        for (i, pair) in packed.chunks_exact(12).enumerate() {
723            let gpu = gpu_filter_aabb_overlap_f32(pair);
724            assert_ne!(gpu, GPU_OVERLAP_UNCERTAIN, "lane {i} should be certain");
725            assert_eq!(gpu, cpu_out[i], "lane {i}: GPU={gpu}, CPU={}", cpu_out[i]);
726        }
727    }
728
729    #[test]
730    fn aabb_overlap_merge_produces_identical_results() {
731        // The merge guarantee: GPU-on vs GPU-off produce identical results.
732        let packed: [f32; 36] = [
733            // Clear overlap
734            0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 3.0, 3.0, 3.0,
735            // Clear non-overlap
736            0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0,
737            // Boundary-touching (may be uncertain)
738            0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 2.0, 1.0, 1.0,
739        ];
740
741        // Path 1: GPU filter + merge.
742        let mut gpu_results = [0i32; 3];
743        for i in 0..3 {
744            gpu_results[i] = gpu_filter_aabb_overlap_f32(&packed[i * 12..(i + 1) * 12]);
745        }
746        let mut merged = [0i32; 3];
747        merge_aabb_overlap_results(&packed, &gpu_results, &mut merged).unwrap();
748
749        // Path 2: CPU exact only (no GPU).
750        let mut cpu_only = [0i32; 3];
751        evaluate_aabb_overlap_batch_f32(&packed, &mut cpu_only).unwrap();
752
753        // Merge guarantee: identical results.
754        assert_eq!(merged, cpu_only);
755    }
756
757    #[test]
758    fn gpu_candidate_box_join_matches_brute_force() {
759        let boxes_a: Vec<Aabb> = vec![
760            Aabb::new(Point3::new(0.0, 0.0, 0.0), Point3::new(2.0, 2.0, 2.0)),
761            Aabb::new(Point3::new(3.0, 3.0, 3.0), Point3::new(5.0, 5.0, 5.0)),
762            Aabb::new(Point3::new(1.0, 1.0, 1.0), Point3::new(4.0, 4.0, 4.0)),
763        ];
764        let boxes_b: Vec<Aabb> = vec![
765            Aabb::new(Point3::new(1.5, 1.5, 1.5), Point3::new(3.5, 3.5, 3.5)),
766            Aabb::new(Point3::new(10.0, 10.0, 10.0), Point3::new(11.0, 11.0, 11.0)),
767        ];
768
769        let max_pairs = boxes_a.len() * boxes_b.len();
770        let mut gpu_out = vec![BoxPair { a: 0, b: 0 }; max_pairs];
771        let gpu_count = gpu_candidate_box_join(&boxes_a, &boxes_b, &mut gpu_out).unwrap();
772
773        let mut brute_out = vec![BoxPair { a: 0, b: 0 }; max_pairs];
774        let brute_count =
775            super::super::box_join::box_join_brute_force(&boxes_a, &boxes_b, &mut brute_out)
776                .unwrap();
777
778        assert_eq!(gpu_count, brute_count);
779        let mut gpu_sorted = gpu_out[..gpu_count].to_vec();
780        gpu_sorted.sort_unstable();
781        let mut brute_sorted = brute_out[..brute_count].to_vec();
782        brute_sorted.sort_unstable();
783        assert_eq!(gpu_sorted, brute_sorted);
784    }
785
786    #[test]
787    fn gpu_candidate_box_join_deterministic() {
788        let boxes_a: Vec<Aabb> = vec![
789            Aabb::new(Point3::new(0.0, 0.0, 0.0), Point3::new(2.0, 2.0, 2.0)),
790            Aabb::new(Point3::new(1.0, 1.0, 1.0), Point3::new(3.0, 3.0, 3.0)),
791        ];
792        let boxes_b: Vec<Aabb> = vec![Aabb::new(
793            Point3::new(1.5, 0.0, 0.0),
794            Point3::new(2.5, 1.0, 1.0),
795        )];
796
797        let run = || {
798            let mut out = vec![BoxPair { a: 0, b: 0 }; boxes_a.len() * boxes_b.len()];
799            let count = gpu_candidate_box_join(&boxes_a, &boxes_b, &mut out).unwrap();
800            (count, out)
801        };
802
803        let (c1, o1) = run();
804        let (c2, o2) = run();
805        assert_eq!(c1, c2);
806        assert_eq!(o1[..c1], o2[..c2]);
807    }
808
809    #[test]
810    fn point_aabb_dist_sq_shader_generation_is_deterministic() {
811        let schedule = GeometryGpuSchedule::default();
812        let a = emit_geometry_wgsl(GeometryGpuKernel::PointAabbDistSqF32, schedule).unwrap();
813        let b = emit_geometry_wgsl(GeometryGpuKernel::PointAabbDistSqF32, schedule).unwrap();
814        assert_eq!(a, b);
815        assert!(a.contains("point_aabb_dist_sq_f32"));
816    }
817}