From 562e7c1f004b931d0b054b03cc4474cf200b7e3d Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:24:04 +0000 Subject: [PATCH 1/6] Recompiler: watertight ray/triangle test for BVH triangle nodes The triangle node was emulated with Moller-Trumbore in the CPU reference (gpu/bvh.rs), the HLSL prelude (bvh_intersect) and the DXIL lowering. Its inside test is not consistent between two triangles that share an edge, so a ray exactly through the edge can miss both: holes in traced shadows and visibility. The new test is the watertight one (Woop, Benthin, Wald, JCGT 2013): shear so the ray runs along its largest axis, then the signs of the three edge functions decide. A shared edge's function is exactly negated in the other triangle, so at least one of them hits. Adapted from victory-fork (GPL-3.0-or-later), which follows Mesa RADV's software emulation of the instruction (MIT). The result encoding is unchanged (t*det, det, I*det, J*det, miss = inf, 1, 0, 0); edge-on and NaN still miss and t is still not tested in the node. HLSL uses precise and DXIL requires DisableMathRefactoring so no product is fused. Tests: shared edge and shared vertex rays along every axis and both ray signs (fails with the old test), agreement with Moller-Trumbore on random rays, degenerate / in-plane / NaN rays, and a GPU test of a triangle pair's shared edge. --- THIRD_PARTY.md | 1 + crates/xcl/src/gpu/bvh.rs | 180 ++++++++++++++++++++++++- crates/xcl/src/gpu/dxil/lower_image.rs | 105 +++++++++------ crates/xcl/src/gpu/recomp/emit.rs | 34 ++++- crates/xcl/src/gpu/recomp/tests.rs | 68 ++++++++++ 5 files changed, 343 insertions(+), 45 deletions(-) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index db38e8a443..68a86f9a00 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -11,6 +11,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | +| [victory-fork](https://github.com/fxceless/victory-fork) | GPL-3.0-or-later | watertight ray/triangle test of the BVH triangle node (`gpu/bvh.rs` `triangle_hit`, the HLSL `bvh_intersect` in `gpu/recomp/emit.rs`, `gpu/dxil/lower_image.rs`): after its `crates/victory-shader/src/bvh.rs` `triangle`, which follows Mesa RADV's software emulation of the instruction (MIT; Woop, Benthin, Wald, JCGT 2013) | port with annotation | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index 5ff20d8911..0574e9c8ee 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -247,15 +247,53 @@ fn world_to_object(m: &[[f32; 4]; 3]) -> [f32; 12] { fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { [a[0] - b[0], a[1] - b[1], a[2] - b[2]] } +#[cfg(test)] fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] } +#[cfg(test)] fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } -/// Möller–Trumbore as the triangle node returns it: (t·det, det, i·det, j·det), `None` = miss +/// The triangle node's test as it returns it: (t·det, det, i·det, j·det), `None` = miss. +/// Watertight (Woop, Benthin, Wald, "Watertight Ray/Triangle Intersection", JCGT 2013): the +/// vertices are sheared so the ray runs along its largest axis and the signs of the three edge +/// functions decide, so a ray through an edge two triangles share hits at least one of them +/// (both when the edge function is exactly 0; the console's rule for that tie is not known). +/// Edge-on (det = 0) and NaN miss; t is not tested here (the traversal does). The HLSL prelude +/// (`recomp/emit.rs` `bvh_intersect`) and the DXIL lowering (`dxil/lower_image.rs`) do the same +/// operations in the same order. +/// +/// Adapted from victory-fork (https://github.com/fxceless/victory-fork, GPL-3.0-or-later), +/// `crates/victory-shader/src/bvh.rs` `triangle`, which follows the software emulation of this +/// instruction in Mesa RADV (https://gitlab.freedesktop.org/mesa/mesa, MIT). Changed 2026-11: +/// no t sign test, XCL's result encoding. pub fn triangle_hit(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { + let a = d.map(f32::abs); + // largest axis, then the other two in the order that keeps the winding + let kz = if a[0] >= a[1] { if a[0] >= a[2] { 0 } else { 2 } } else if a[1] >= a[2] { 1 } else { 2 }; + let (kx, ky) = if d[kz] < 0.0 { ((kz + 2) % 3, (kz + 1) % 3) } else { ((kz + 1) % 3, (kz + 2) % 3) }; + let sz = 1.0 / d[kz]; + let (sx, sy) = (d[kx] * sz, d[ky] * sz); + let shear = |p: [f32; 3]| { + let r = sub(p, o); + [r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz]] + }; + let (p0, p1, p2) = (shear(v[0]), shear(v[1]), shear(v[2])); + // edge functions: the barycentric numerators of v0, v1, v2 + let u = p2[0] * p1[1] - p2[1] * p1[0]; + let i = p0[0] * p2[1] - p0[1] * p2[0]; + let j = p1[0] * p0[1] - p1[1] * p0[0]; + let mixed = (u < 0.0 || i < 0.0 || j < 0.0) && (u > 0.0 || i > 0.0 || j > 0.0); + let det = u + (i + j); + let t = (u * p0[2] + i * p1[2]) + j * p2[2]; + (!mixed && (det > 0.0 || det < 0.0)).then_some([t, det, i, j]) +} + +/// The Möller–Trumbore test XCL used before the watertight one (tests compare against it). +#[cfg(test)] +fn triangle_hit_mt(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { let (e1, e2) = (sub(v[1], v[0]), sub(v[2], v[0])); let p = cross(d, e2); let det = dot(e1, p); @@ -1139,4 +1177,144 @@ pub(crate) mod tests { let got_o = intersect_node(&data, BOX32, 100.0, [f32::NAN, 0.5, 0.5], [1.0, 0.0, 0.0], [1.0, f32::INFINITY, f32::INFINITY], true); assert_eq!(got_o, [INVALID; 4], "a ray with NaN origin must miss"); } + + /// `p` rotated so that its axis 2 becomes `axis`, mirrored when `flip` + fn place(p: [f32; 3], axis: usize, flip: bool) -> [f32; 3] { + let mut r = [0.0; 3]; + for k in 0..3 { + r[(axis + 1 + k) % 3] = p[k]; + } + if flip { + r[axis] = -r[axis]; + } + r + } + + /// hits among `tris` for a ray from `o` along `d` + fn hits(tris: &[Triangle], o: [f32; 3], d: [f32; 3]) -> usize { + tris.iter().filter(|t| triangle_hit(t, o, d).is_some()).count() + } + + /// Rays exactly through the edge two triangles share and through the vertex a fan shares: + /// at least one triangle hits, along every dominant axis, both ray signs and windings. + #[test] + fn triangle_hit_is_watertight_at_shared_edges_and_vertices() { + let mut r = rng(11); + let mut checked = 0; + for axis in 0..3 { + for flip in [false, true] { + for _ in 0..200 { + // a quad split along a random diagonal, in a plane across the ray's main axis + let z = r(-2.0, 2.0); + let (a, b) = ([r(-3.0, -1.0), r(-1.0, 1.0), z], [r(1.0, 3.0), r(-1.0, 1.0), z]); + let (c, e) = ([r(-3.0, 3.0), r(8.0, 10.0), z + r(-0.5, 0.5)], [r(-3.0, 3.0), r(-10.0, -8.0), z + r(-0.5, 0.5)]); + let pair = [[a, b, c], [b, a, e]].map(|t| t.map(|p| place(p, axis, flip))); + let s = r(0.0, 1.0); + let on = [0, 1, 2].map(|k| a[k] + s * (b[k] - a[k])); + // ray from below, tilted but still mostly along the axis + let dir = [r(-0.3, 0.3), r(-0.3, 0.3), if r(0.0, 1.0) < 0.5 { 1.0 } else { -1.0 }]; + let o = [0, 1, 2].map(|k| on[k] - 4.0 * dir[k]); + let (o, dir) = (place(o, axis, flip), place(dir, axis, flip)); + assert!(hits(&pair, o, dir) >= 1, "edge: axis {axis} flip {flip} {pair:?} o {o:?} d {dir:?}"); + // fan of 6 around a shared vertex, ray straight through it + let v = [r(-1.0, 1.0), r(-1.0, 1.0), z]; + let ring: Vec<[f32; 3]> = (0..6) + .map(|k| { + let ang = k as f32 * std::f32::consts::TAU / 6.0 + r(0.0, 0.3); + [v[0] + 2.0 * ang.cos(), v[1] + 2.0 * ang.sin(), z + r(-0.5, 0.5)] + }) + .collect(); + let fan: Vec = (0..6).map(|k| [v, ring[k], ring[(k + 1) % 6]].map(|p| place(p, axis, flip))).collect(); + let o = [0, 1, 2].map(|k| v[k] - 4.0 * dir_local(dir, axis, flip)[k]); + let o = place(o, axis, flip); + assert!(hits(&fan, o, dir) >= 1, "vertex: axis {axis} flip {flip} o {o:?} d {dir:?}"); + checked += 1; + } + } + } + assert_eq!(checked, 1200); + } + + /// inverse of `place` for a direction + fn dir_local(d: [f32; 3], axis: usize, flip: bool) -> [f32; 3] { + let mut d = d; + if flip { + d[axis] = -d[axis]; + } + [0, 1, 2].map(|k| d[(axis + 1 + k) % 3]) + } + + /// Away from edges the watertight test agrees with the old Möller–Trumbore one: same hit / + /// miss, same sign of det (facing), t and barycentrics within rounding. + #[test] + fn triangle_hit_agrees_with_moller_trumbore_on_generic_rays() { + for seed in 0..8u64 { + let tris = random_tris(50, 200 + seed); + let mut r = rng(300 + seed); + let mut both = 0; + for _ in 0..2000 { + let o = [r(-12.0, 12.0), r(-12.0, 12.0), r(-12.0, 12.0)]; + let to = [r(-8.0, 8.0), r(-8.0, 8.0), r(-8.0, 8.0)]; + let d = sub(to, o); + for t in &tris { + let (w, m) = (triangle_hit(t, o, d), triangle_hit_mt(t, o, d)); + let Some(m) = m else { + if let Some(w) = w { + // only a ray within rounding of an edge may differ + assert!([w[2], w[3], w[1] - w[2] - w[3]].iter().any(|x| (x / w[1]).abs() < 1e-4), "{t:?} {o:?} {d:?}: {w:?}"); + } + continue; + }; + let Some(w) = w else { + assert!([m[2], m[3], m[1] - m[2] - m[3]].iter().any(|x| (x / m[1]).abs() < 1e-4), "{t:?} {o:?} {d:?}: {m:?}"); + continue; + }; + assert_eq!(w[1] > 0.0, m[1] > 0.0, "facing"); + for k in [0, 2, 3] { + assert!((w[k] / w[1] - m[k] / m[1]).abs() < 1e-4, "{k}: {w:?} vs {m:?}"); + } + both += 1; + } + } + assert!(both > 100, "seed {seed}: {both} hits"); + } + } + + /// Degenerate triangles, rays in the triangle's plane, a zero direction and NaN miss. + #[test] + fn triangle_hit_degenerate_and_parallel_miss() { + let d = [0.0, 0.0, 1.0]; + let o = [0.2, 0.2, -1.0]; + let tri = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + let degenerate: [Triangle; 3] = [ + [[0.0; 3], [0.0; 3], [0.0; 3]], + [[0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [2.0, 2.0, 0.0]], + [[0.2, 0.2, 0.0], [0.2, 0.2, 0.0], [1.0, 0.0, 0.0]], + ]; + for t in °enerate { + assert!(triangle_hit(t, o, d).is_none(), "{t:?}"); + } + // in the plane, along each in-plane axis and a diagonal + for d in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 0.0, 0.0]] { + assert!(triangle_hit(&tri, [-1.0, 0.2, 0.0], d).is_none(), "{d:?}"); + } + assert!(triangle_hit(&tri, o, [0.0; 3]).is_none()); + assert!(triangle_hit(&tri, o, [f32::NAN, 0.0, 1.0]).is_none()); + assert!(triangle_hit(&tri, [f32::NAN, 0.2, -1.0], d).is_none()); + let mut nan = tri; + nan[1][0] = f32::NAN; + assert!(triangle_hit(&nan, o, d).is_none()); + // the node returns its miss encoding, never a NaN + for t in degenerate.iter().chain([&nan]) { + let mut data = vec![0u8; 64]; + for (k, p) in t.iter().enumerate() { + for a in 0..3 { + data[12 * k + 4 * a..12 * k + 4 * a + 4].copy_from_slice(&p[a].to_le_bytes()); + } + } + data[60..64].copy_from_slice(&TRI_ID_PLAIN.to_le_bytes()); + let r = intersect_node(&data, 0, 100.0, o, d, d.map(|x| 1.0 / x), false).map(f32::from_bits); + assert_eq!(r, [f32::INFINITY, 1.0, 0.0, 0.0]); + } + } } diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index ba7a38ddba..d117f465fc 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -63,23 +63,6 @@ impl Lw { fn f3(&mut self, a: [Value; 3], b: [Value; 3], op: fn(&mut Lw, Value, Value) -> Value) -> [Value; 3] { [op(self, a[0], b[0]), op(self, a[1], b[1]), op(self, a[2], b[2])] } - fn cross(&mut self, a: [Value; 3], b: [Value; 3]) -> [Value; 3] { - let x0 = self.fmul(a[1], b[2]); - let x1 = self.fmul(a[2], b[1]); - let x = self.fsub(x0, x1); - let y0 = self.fmul(a[2], b[0]); - let y1 = self.fmul(a[0], b[2]); - let y = self.fsub(y0, y1); - let z0 = self.fmul(a[0], b[1]); - let z1 = self.fmul(a[1], b[0]); - let z = self.fsub(z0, z1); - [x, y, z] - } - /// HLSL `dot(float3, float3)` = `Dot3`. - fn dot3(&mut self, a: [Value; 3], b: [Value; 3]) -> Value { - let f32 = self.s.m.f32(); - self.s.op(55, "dot3", Some(f32), f32, &[a[0], a[1], a[2], b[0], b[1], b[2]], super::module::FnAttrs::ReadNone) - } /// Move a finite float32 upward toward +inf by `g` ULPs (leaving NaN/Inf/g=0 unchanged). fn bvh_grow_hi(&mut self, x: Value, g: Value) -> Value { @@ -284,31 +267,77 @@ impl Lw { let v1 = [lw.f(words[3]), lw.f(words[4]), lw.f(words[5])]; let v2 = [lw.f(words[6]), lw.f(words[7]), lw.f(words[8])]; let tw = words[9]; - let e1 = lw.f3(v1, v0, Lw::fsub); - let e2 = lw.f3(v2, v0, Lw::fsub); - let p = lw.cross(dir, e2); - let det = lw.dot3(e1, p); - let sv = lw.f3(o, v0, Lw::fsub); - let q = lw.cross(sv, e1); - let i = lw.dot3(sv, p); - let j = lw.dot3(dir, q); - let t = lw.dot3(e2, q); + // watertight test as gpu::bvh::triangle_hit and the HLSL prelude (Woop, Benthin, Wald + // 2013; adapted from victory-fork, https://github.com/fxceless/victory-fork, + // GPL-3.0-or-later, after Mesa RADV, MIT); no fused products, so a shared edge's + // function is exactly negated in the other triangle + lw.s.require(super::shader::Feature::DisableMathRefactoring); + let ad = [lw.fabs(dir[0]), lw.fabs(dir[1]), lw.fabs(dir[2])]; + let xy = lw.fcmp(Pred::FOGe, ad[0], ad[1]); + let xz = lw.fcmp(Pred::FOGe, ad[0], ad[2]); + let yz = lw.fcmp(Pred::FOGe, ad[1], ad[2]); + let nxy = lw.lnot(xy); + let kz0 = lw.land(xy, xz); + let kz1 = lw.land(nxy, yz); + // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 + let perm = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { + let x = lw.sel(kz1, v[2], v[0]); + let x = lw.sel(kz0, v[1], x); + let y = lw.sel(kz1, v[0], v[1]); + let y = lw.sel(kz0, v[2], y); + let z = lw.sel(kz1, v[1], v[2]); + let z = lw.sel(kz0, v[0], z); + [x, y, z] + }; + let pd = perm(lw, dir); let z = lw.fc(0.0); + let sw = lw.fcmp(Pred::FOLt, pd[2], z); + let swap = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { [lw.sel(sw, v[1], v[0]), lw.sel(sw, v[0], v[1]), v[2]] }; + let pd = swap(lw, pd); + let one = lw.fc(1.0); + let sz = lw.fdiv(one, pd[2]); + let sx = lw.fmul(pd[0], sz); + let sy = lw.fmul(pd[1], sz); + let mut sh = [[z; 3]; 3]; + for (k, v) in [v0, v1, v2].into_iter().enumerate() { + let r = lw.f3(v, o, Lw::fsub); + let r = perm(lw, r); + let r = swap(lw, r); + let ax = lw.fmul(sx, r[2]); + let ay = lw.fmul(sy, r[2]); + sh[k] = [lw.fsub(r[0], ax), lw.fsub(r[1], ay), lw.fmul(sz, r[2])]; + } + let [p0, p1, p2] = sh; + let edge = |lw: &mut Lw, a: [Value; 3], b: [Value; 3]| { + let m0 = lw.fmul(a[0], b[1]); + let m1 = lw.fmul(a[1], b[0]); + lw.fsub(m0, m1) + }; + let u = edge(lw, p2, p1); + let i = edge(lw, p0, p2); + let j = edge(lw, p1, p0); + let mut neg = lw.fcmp(Pred::FOLt, u, z); + let mut pos = lw.fcmp(Pred::FOGt, u, z); + for e in [i, j] { + let n = lw.fcmp(Pred::FOLt, e, z); + neg = lw.lor(neg, n); + let p = lw.fcmp(Pred::FOGt, e, z); + pos = lw.lor(pos, p); + } + let mixed = lw.land(neg, pos); let ij = lw.fadd(i, j); + let det = lw.fadd(u, ij); + let tu = lw.fmul(u, p0[2]); + let ti = lw.fmul(i, p1[2]); + let tj = lw.fmul(j, p2[2]); + let t = lw.fadd(tu, ti); + let t = lw.fadd(t, tj); + // edge-on (det = 0) and NaN miss let dpos = lw.fcmp(Pred::FOGt, det, z); - let c1 = lw.fcmp(Pred::FOGe, i, z); - let c2 = lw.fcmp(Pred::FOGe, j, z); - let c3 = lw.fcmp(Pred::FOLe, ij, det); - let hp = lw.land(c1, c2); - let hp = lw.land(hp, c3); let dneg = lw.fcmp(Pred::FOLt, det, z); - let n1 = lw.fcmp(Pred::FOLe, i, z); - let n2 = lw.fcmp(Pred::FOLe, j, z); - let n3 = lw.fcmp(Pred::FOGe, ij, det); - let hn = lw.land(dneg, n1); - let hn = lw.land(hn, n2); - let hn = lw.land(hn, n3); - let hit = lw.sel(dpos, hp, hn); + let dnz = lw.lor(dpos, dneg); + let inside = lw.lnot(mixed); + let hit = lw.land(inside, dnz); let di = lw.fsub(det, i); let b0 = lw.fsub(di, j); let bc = [b0, i, j, z]; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 1c51cfd0e2..d437164aed 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -6360,12 +6360,34 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i uint o1 = type == 0u ? 12u : (type == 3u ? 48u : 36u); uint o2 = type <= 1u ? 24u : (type == 2u ? 48u : 0u); float3 v0 = asfloat(mem.Load3(at + o0)), v1 = asfloat(mem.Load3(at + o1)), v2 = asfloat(mem.Load3(at + o2)); - float3 e1 = v1 - v0, e2 = v2 - v0, p = cross(d, e2); - float det = dot(e1, p); - float3 sv = o - v0, q = cross(sv, e1); - float i = dot(sv, p), j = dot(d, q), t = dot(e2, q); - // inside when i, j, 1 - i - j >= 0 relative to det (either winding); avoid det * det underflow/overflow - bool hit = det > 0.0f ? (i >= 0.0f && j >= 0.0f && i + j <= det) : (det < 0.0f && i <= 0.0f && j <= 0.0f && i + j >= det); + // watertight test as gpu::bvh::triangle_hit (Woop, Benthin, Wald 2013; adapted from + // victory-fork, https://github.com/fxceless/victory-fork, GPL-3.0-or-later, after Mesa + // RADV, MIT): shear so the ray runs along its largest axis, signs of the edge functions + // decide; `precise` so that no product is fused and a shared edge's function is exactly + // negated in the other triangle + float3 ad = abs(d); + uint kz = ad.x >= ad.y ? (ad.x >= ad.z ? 0u : 2u) : (ad.y >= ad.z ? 1u : 2u); + // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 + float3 pd = kz == 0u ? d.yzx : (kz == 1u ? d.zxy : d.xyz); + bool sw = pd.z < 0.0f; + pd = sw ? pd.yxz : pd; + precise float sz = 1.0f / pd.z; + precise float sx = pd.x * sz, sy = pd.y * sz; + float3 r0 = v0 - o, r1 = v1 - o, r2 = v2 - o; + r0 = kz == 0u ? r0.yzx : (kz == 1u ? r0.zxy : r0); r0 = sw ? r0.yxz : r0; + r1 = kz == 0u ? r1.yzx : (kz == 1u ? r1.zxy : r1); r1 = sw ? r1.yxz : r1; + r2 = kz == 0u ? r2.yzx : (kz == 1u ? r2.zxy : r2); r2 = sw ? r2.yxz : r2; + precise float3 p0 = float3(r0.x - sx * r0.z, r0.y - sy * r0.z, sz * r0.z); + precise float3 p1 = float3(r1.x - sx * r1.z, r1.y - sy * r1.z, sz * r1.z); + precise float3 p2 = float3(r2.x - sx * r2.z, r2.y - sy * r2.z, sz * r2.z); + precise float u = p2.x * p1.y - p2.y * p1.x; + precise float i = p0.x * p2.y - p0.y * p2.x; + precise float j = p1.x * p0.y - p1.y * p0.x; + bool mixed = (u < 0.0f || i < 0.0f || j < 0.0f) && (u > 0.0f || i > 0.0f || j > 0.0f); + precise float det = u + (i + j); + precise float t = (u * p0.z + i * p1.z) + j * p2.z; + // edge-on (det = 0) and NaN miss + bool hit = !mixed && (det > 0.0f || det < 0.0f); // barycentrics back to the original vertex order: triangle id @60, per triangle I / J source uint4 bc = asuint(float4(det - i - j, i, j, 0.0f)); uint tw = mem.Load(at + 60u); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index d23899a80f..460923aeb1 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6323,6 +6323,74 @@ fn gpu_triangle_pair_and_box16_nodes() { assert!(checked > 5, "{checked} triangle hits"); } +/// Watertight triangle test on the GPU: rays exactly through the edge a triangle pair shares +/// (type 0 = (v0, v1, v2) and type 1 = (v1, v3, v2) share v1–v2), along each axis and both +/// signs. Each ray goes to both triangles in neighbouring lanes: at least one hits, and hit / +/// miss is the CPU's. +#[test] +fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { + use crate::gpu::bvh; + if !gpu_ready() { + return; + } + let base = 0x1000usize; + let mut mem = vec![0u32; 0x2000 / 4]; + let w = |mem: &mut Vec, at: usize, vals: &[u32]| mem[(base + at) / 4..(base + at) / 4 + vals.len()].copy_from_slice(vals); + let ff = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + // one skewed quad across each axis: v1 = (-1.3, 0.7), v2 = (1.1, -0.9) in the other two axes + let quad = [[-1.7f32, -1.9, 0.0], [-1.3, 0.7, 0.2], [1.1, -0.9, -0.1], [1.6, 1.8, 0.3]]; + let at = |axis: usize, p: [f32; 3]| { + let mut r = [0.0f32; 3]; + r[(axis + 1) % 3] = p[0]; + r[(axis + 2) % 3] = p[1]; + r[axis] = 5.0 + p[2]; + r + }; + for axis in 0..3 { + let verts: Vec = quad.iter().flat_map(|&p| at(axis, p)).collect(); + w(&mut mem, 0x40 * (axis + 1), &ff(&verts)); + w(&mut mem, 0x40 * (axis + 1) + 48, &[0x80, 0, 1, 0x0909]); + } + let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 1 << 24]); // word 3 bit 24: barycentric result (mode 1) + let mut r = bvh::tests::rng(23); + let mut rays = vec![]; + let mut ray = ([0.0f32; 3], [0.0f32; 3], 0usize); + for (l, v) in st.vgpr.iter_mut().enumerate() { + if l % 2 == 0 { + let axis = (l / 2) % 3; + let s = r(0.0, 1.0); + let (v1, v2) = (at(axis, quad[1]), at(axis, quad[2])); + let on = [0, 1, 2].map(|a| v1[a] + s * (v2[a] - v1[a])); + let mut d = [r(-0.4, 0.4), r(-0.4, 0.4), r(-0.4, 0.4)]; + d[axis] = if (l / 6) % 2 == 0 { 1.0 } else { -1.0 }; + ray = ([0, 1, 2].map(|a| on[a] - 3.0 * d[a]), d, axis); + } + let (o, d, axis) = ray; + let inv = d.map(|x| 1.0 / x); + let node = ((0x40 * (axis as u32 + 1)) >> 3) | (l as u32 % 2); + v[0] = node; + for (k, x) in [100.0f32, o[0], o[1], o[2], d[0], d[1], d[2], inv[0], inv[1], inv[2]].iter().enumerate() { + v[1 + k] = x.to_bits(); + } + rays.push((node, o, d, inv)); + } + let res = runner::run_code(&code, &st, &mem).unwrap(); + let data: Vec = mem[base / 4..].iter().flat_map(|x| x.to_le_bytes()).collect(); + // GPU and CPU may round 1 / d differently, so on the edge each is checked on its own + let (mut gh, mut ch) = ([false; 2], [false; 2]); + for (l, &(node, o, d, inv)) in rays.iter().enumerate() { + gh[l % 2] = f32::from_bits(res.vgpr[l][100]).is_finite(); + ch[l % 2] = f32::from_bits(bvh::intersect_node(&data, node, 100.0, o, d, inv, true)[0]).is_finite(); + if l % 2 == 1 { + assert!(gh[0] || gh[1], "lanes {} and {l}: GPU ray through the shared edge missed both", l - 1); + assert!(ch[0] || ch[1], "lanes {} and {l}: CPU ray through the shared edge missed both", l - 1); + } + } +} + /// Multi-window `image_bvh64_intersect_ray` (full 64-bit node pointer into UMA window 1 with /// base = 0, plus 48-bit base in window 1) and axis-aligned grazing ray / NaN-disabled box. #[test] From 8a7c6045b79fcbfb7928769bc01e1e93b9b54320 Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:31:53 +0000 Subject: [PATCH 2/6] Recompiler: keep the BVH triangle result scale and pin watertight cases Follow-up to the watertight triangle test. The sheared determinant is Moller-Trumbore's divided by |d[kz]|: t, det and the barycentric numerators are now multiplied back by |d[kz]| after the hit decision in the CPU reference, the HLSL prelude and the DXIL lowering, so the four dwords keep the scale XCL returned before (checked against the old test on random rays). A non-finite t or det (tiny d[kz], huge shear) is a miss. Tests: exact dyadic rays through a shared edge (both vertex orders) and a fan's shared vertex on every axis and sign; a pinned ray through a shared edge that Moller-Trumbore misses in both triangles; axis choice on ties; non-finite t. With the old test the pinned, random-edge and non-finite tests fail; the exact dyadic cases pass with both. Limit: the DXIL module drops DisableMathRefactoring when it also uses FMad, and a driver may then fuse the edge-function products, which loses the exact negation across a shared edge (no worse than before). Provenance: Mesa RADV src/amd/vulkan/nir/radv_nir_rt_common.c intersect_ray_amd_software_tri (MIT), via victory-fork (GPL-3.0-or-later). --- THIRD_PARTY.md | 3 +- crates/xcl/src/gpu/bvh.rs | 114 ++++++++++++++++++++++--- crates/xcl/src/gpu/dxil/lower_image.rs | 17 +++- crates/xcl/src/gpu/recomp/emit.rs | 11 ++- crates/xcl/src/gpu/recomp/tests.rs | 4 +- 5 files changed, 129 insertions(+), 20 deletions(-) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 68a86f9a00..30ec8aa49d 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -11,7 +11,8 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | -| [victory-fork](https://github.com/fxceless/victory-fork) | GPL-3.0-or-later | watertight ray/triangle test of the BVH triangle node (`gpu/bvh.rs` `triangle_hit`, the HLSL `bvh_intersect` in `gpu/recomp/emit.rs`, `gpu/dxil/lower_image.rs`): after its `crates/victory-shader/src/bvh.rs` `triangle`, which follows Mesa RADV's software emulation of the instruction (MIT; Woop, Benthin, Wald, JCGT 2013) | port with annotation | +| [victory-fork](https://github.com/fxceless/victory-fork) | GPL-3.0-or-later | watertight ray/triangle test of the BVH triangle node (`gpu/bvh.rs` `triangle_hit`, the HLSL `bvh_intersect` in `gpu/recomp/emit.rs`, `gpu/dxil/lower_image.rs`): after its `crates/victory-shader/src/bvh.rs` `triangle` | port with annotation | +| [Mesa RADV](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/vulkan) (Mesa) | MIT | the same triangle test, through victory-fork: `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri` (Woop, Benthin, Wald, JCGT 2013) | logic ported with annotation | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index 0574e9c8ee..0bad3c04f6 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -261,18 +261,19 @@ fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { /// vertices are sheared so the ray runs along its largest axis and the signs of the three edge /// functions decide, so a ray through an edge two triangles share hits at least one of them /// (both when the edge function is exactly 0; the console's rule for that tie is not known). -/// Edge-on (det = 0) and NaN miss; t is not tested here (the traversal does). The HLSL prelude -/// (`recomp/emit.rs` `bvh_intersect`) and the DXIL lowering (`dxil/lower_image.rs`) do the same -/// operations in the same order. +/// Edge-on (det = 0), NaN and a non-finite t or det miss; t's sign is not tested here (the +/// traversal does). The four values have the Möller–Trumbore scale XCL returned before. The +/// HLSL prelude (`recomp/emit.rs` `bvh_intersect`) and the DXIL lowering +/// (`dxil/lower_image.rs`) do the same operations in the same order. /// /// Adapted from victory-fork (https://github.com/fxceless/victory-fork, GPL-3.0-or-later), -/// `crates/victory-shader/src/bvh.rs` `triangle`, which follows the software emulation of this -/// instruction in Mesa RADV (https://gitlab.freedesktop.org/mesa/mesa, MIT). Changed 2026-11: -/// no t sign test, XCL's result encoding. +/// `crates/victory-shader/src/bvh.rs` `triangle`, which follows Mesa RADV +/// (https://gitlab.freedesktop.org/mesa/mesa, MIT, © 2021 Google): +/// `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri`. Changed 2026-11: +/// f32 edge functions (Mesa computes them in f64), no t sign test, XCL's result scale (Mesa +/// returns t / |det| and the sign of det). pub fn triangle_hit(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { - let a = d.map(f32::abs); - // largest axis, then the other two in the order that keeps the winding - let kz = if a[0] >= a[1] { if a[0] >= a[2] { 0 } else { 2 } } else if a[1] >= a[2] { 1 } else { 2 }; + let kz = dominant_axis(d); let (kx, ky) = if d[kz] < 0.0 { ((kz + 2) % 3, (kz + 1) % 3) } else { ((kz + 1) % 3, (kz + 2) % 3) }; let sz = 1.0 / d[kz]; let (sx, sy) = (d[kx] * sz, d[ky] * sz); @@ -288,7 +289,17 @@ pub fn triangle_hit(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> let mixed = (u < 0.0 || i < 0.0 || j < 0.0) && (u > 0.0 || i > 0.0 || j > 0.0); let det = u + (i + j); let t = (u * p0[2] + i * p1[2]) + j * p2[2]; - (!mixed && (det > 0.0 || det < 0.0)).then_some([t, det, i, j]) + // back to Möller–Trumbore's scale (the sheared determinant is its det / |d[kz]|), after + // the decision; a non-finite t or det (tiny d[kz], huge shear) misses + let s = d[kz].abs(); + let r = [t * s, det * s, i * s, j * s]; + (!mixed && (det > 0.0 || det < 0.0) && r[0].is_finite() && r[1].is_finite()).then_some(r) +} + +/// The ray's largest axis (ties: x before y before z), along which `triangle_hit` shears. +fn dominant_axis(d: [f32; 3]) -> usize { + let a = d.map(f32::abs); + if a[0] >= a[1] { if a[0] >= a[2] { 0 } else { 2 } } else if a[1] >= a[2] { 1 } else { 2 } } /// The Möller–Trumbore test XCL used before the watertight one (tests compare against it). @@ -1195,8 +1206,8 @@ pub(crate) mod tests { tris.iter().filter(|t| triangle_hit(t, o, d).is_some()).count() } - /// Rays exactly through the edge two triangles share and through the vertex a fan shares: - /// at least one triangle hits, along every dominant axis, both ray signs and windings. + /// Random rays from a point on the edge two triangles share and on the vertex a fan shares + /// (rounded, so near, not exactly on it): at least one triangle hits, every axis and sign. #[test] fn triangle_hit_is_watertight_at_shared_edges_and_vertices() { let mut r = rng(11); @@ -1270,6 +1281,7 @@ pub(crate) mod tests { continue; }; assert_eq!(w[1] > 0.0, m[1] > 0.0, "facing"); + assert!((w[1] - m[1]).abs() <= 1e-3 * m[1].abs(), "det scale: {w:?} vs {m:?}"); for k in [0, 2, 3] { assert!((w[k] / w[1] - m[k] / m[1]).abs() < 1e-4, "{k}: {w:?} vs {m:?}"); } @@ -1280,6 +1292,84 @@ pub(crate) mod tests { } } + /// Dyadic coordinates, so the ray passes exactly through the shared edge / vertex: at least + /// one triangle hits, along every dominant axis, both signs, the shared edge listed in + /// opposite orders (consistent winding) and in the same order. + #[test] + fn triangle_hit_exact_shared_edge_and_vertex() { + let (a, b) = ([-1.0, -0.5, 1.0], [1.5, 1.0, 1.0]); + let (c, e) = ([-2.0, 3.0, 1.5], [2.0, -3.0, 0.5]); + let pairs: [[Triangle; 2]; 2] = [[[a, b, c], [b, a, e]], [[a, b, c], [a, b, e]]]; + let v = [0.25, -0.5, 1.0]; + let ring = [[2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [-2.0, 2.0], [-2.0, 0.0], [-2.0, -2.0], [0.0, -2.0], [2.0, -2.0]]; + let fan: Vec = (0..8) + .map(|k| { + let p = |k: usize| [v[0] + ring[k % 8][0], v[1] + ring[k % 8][1], 1.0 + 0.25 * (k % 2) as f32]; + [v, p(k), p(k + 1)] + }) + .collect(); + let dirs = [[0.0, 0.0, 1.0], [0.25, -0.5, 1.0], [-0.375, 0.125, 1.0], [0.5, 0.5, -1.0], [-0.75, 0.25, -1.0]]; + for axis in 0..3 { + for flip in [false, true] { + for dl in dirs { + let d = place(dl, axis, flip); + for s in [0.25f32, 0.5, 0.75] { + let on = [0, 1, 2].map(|k| a[k] + s * (b[k] - a[k])); + let o = place([0, 1, 2].map(|k| on[k] - 2.0 * dl[k]), axis, flip); + for pair in &pairs { + let pair = pair.map(|t| t.map(|p| place(p, axis, flip))); + assert!(hits(&pair, o, d) >= 1, "edge: axis {axis} flip {flip} s {s} d {d:?} {pair:?}"); + } + } + let o = place([0, 1, 2].map(|k| v[k] - 2.0 * dl[k]), axis, flip); + let fan: Vec = fan.iter().map(|t| t.map(|p| place(p, axis, flip))).collect(); + assert!(hits(&fan, o, d) >= 1, "vertex: axis {axis} flip {flip} d {d:?}"); + } + } + } + } + + /// Found by `triangle_hit_is_watertight_at_shared_edges_and_vertices` (seed 11, first case): + /// a ray through the edge (1.911541, -2.025442, 0.78372467)–(1.911541, 2.740394, -0.50947857) + /// that Möller–Trumbore misses in both triangles; the watertight test hits at least one. + #[test] + fn triangle_hit_pinned_shared_edge_moller_trumbore_misses() { + let (a, b) = ([1.911541f32, -2.025442, 0.78372467], [1.911541f32, 2.740394, -0.50947857]); + let pair = [[a, b, [2.1104007, -1.6796683, 9.487581]], [b, a, [1.5455573, 0.7414906, -8.11272]]]; + let (o, d) = ([5.911541f32, -0.8080063, 0.59203976], [-1.0f32, -0.13060194, 0.000772506]); + assert_eq!(pair.iter().filter(|t| triangle_hit_mt(t, o, d).is_some()).count(), 0); + assert!(hits(&pair, o, d) >= 1); + } + + /// Equal largest components pick the first axis (x before y before z), as in the HLSL and + /// DXIL `kz` selection. + #[test] + fn triangle_hit_dominant_axis_ties() { + assert_eq!(dominant_axis([1.0, -1.0, 0.5]), 0); + assert_eq!(dominant_axis([-1.0, 1.0, 1.0]), 0); + assert_eq!(dominant_axis([0.5, 1.0, -1.0]), 1); + assert_eq!(dominant_axis([0.5, -0.25, 1.0]), 2); + assert_eq!(dominant_axis([0.0, 0.0, 0.0]), 0); + } + + /// A tiny largest component with a far triangle overflows the sheared depth: the node + /// returns its miss encoding, not an infinite or NaN t with a finite det. + #[test] + fn triangle_hit_non_finite_t_misses() { + let tri = [[5.0, 0.0, 0.0], [5.0, 1.0, 0.0], [5.0, 0.0, 1.0]]; + let (o, d) = ([0.0, 0.2, 0.2], [1e-38f32, 0.0, 0.0]); + assert!(triangle_hit(&tri, o, d).is_none()); + let mut data = vec![0u8; 64]; + for (k, p) in tri.iter().enumerate() { + for x in 0..3 { + data[12 * k + 4 * x..12 * k + 4 * x + 4].copy_from_slice(&p[x].to_le_bytes()); + } + } + data[60..64].copy_from_slice(&TRI_ID_PLAIN.to_le_bytes()); + let r = intersect_node(&data, 0, 100.0, o, d, d.map(|x| 1.0 / x), false).map(f32::from_bits); + assert_eq!(r, [f32::INFINITY, 1.0, 0.0, 0.0]); + } + /// Degenerate triangles, rays in the triangle's plane, a zero direction and NaN miss. #[test] fn triangle_hit_degenerate_and_parallel_miss() { diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index d117f465fc..668dbda7ee 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -270,7 +270,9 @@ impl Lw { // watertight test as gpu::bvh::triangle_hit and the HLSL prelude (Woop, Benthin, Wald // 2013; adapted from victory-fork, https://github.com/fxceless/victory-fork, // GPL-3.0-or-later, after Mesa RADV, MIT); no fused products, so a shared edge's - // function is exactly negated in the other triangle + // function is exactly negated in the other triangle. Limit: the module drops + // DisableMathRefactoring when it also uses FMad (shader.rs), and a driver may then + // fuse these products, which loses the exact negation (no worse than before) lw.s.require(super::shader::Feature::DisableMathRefactoring); let ad = [lw.fabs(dir[0]), lw.fabs(dir[1]), lw.fabs(dir[2])]; let xy = lw.fcmp(Pred::FOGe, ad[0], ad[1]); @@ -332,12 +334,23 @@ impl Lw { let tj = lw.fmul(j, p2[2]); let t = lw.fadd(tu, ti); let t = lw.fadd(t, tj); - // edge-on (det = 0) and NaN miss + // back to Möller–Trumbore's scale after the decision; edge-on (det = 0), NaN and a + // non-finite t or det miss let dpos = lw.fcmp(Pred::FOGt, det, z); let dneg = lw.fcmp(Pred::FOLt, det, z); let dnz = lw.lor(dpos, dneg); let inside = lw.lnot(mixed); let hit = lw.land(inside, dnz); + let s = lw.fabs(pd[2]); + let (t, det, i, j) = (lw.fmul(t, s), lw.fmul(det, s), lw.fmul(i, s), lw.fmul(j, s)); + let pinf = lw.fc(f32::INFINITY); + let mut hit = hit; + for x in [t, det] { + // |x| < inf is false for inf and NaN + let ax = lw.fabs(x); + let fin = lw.fcmp(Pred::FOLt, ax, pinf); + hit = lw.land(hit, fin); + } let di = lw.fsub(det, i); let b0 = lw.fsub(di, j); let bc = [b0, i, j, z]; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index d437164aed..22891d85a4 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -6364,7 +6364,8 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i // victory-fork, https://github.com/fxceless/victory-fork, GPL-3.0-or-later, after Mesa // RADV, MIT): shear so the ray runs along its largest axis, signs of the edge functions // decide; `precise` so that no product is fused and a shared edge's function is exactly - // negated in the other triangle + // negated in the other triangle (DXC marks them so in the DXIL; a driver that fuses + // anyway loses that) float3 ad = abs(d); uint kz = ad.x >= ad.y ? (ad.x >= ad.z ? 0u : 2u) : (ad.y >= ad.z ? 1u : 2u); // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 @@ -6386,8 +6387,12 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i bool mixed = (u < 0.0f || i < 0.0f || j < 0.0f) && (u > 0.0f || i > 0.0f || j > 0.0f); precise float det = u + (i + j); precise float t = (u * p0.z + i * p1.z) + j * p2.z; - // edge-on (det = 0) and NaN miss - bool hit = !mixed && (det > 0.0f || det < 0.0f); + // back to Möller–Trumbore's scale after the decision; edge-on (det = 0), NaN and a + // non-finite t or det miss + precise float s = abs(pd.z); + t = t * s; precise float dets = det * s; i = i * s; j = j * s; + bool hit = !mixed && (det > 0.0f || det < 0.0f) && !isinf(t) && !isnan(t) && !isinf(dets) && !isnan(dets); + det = dets; // barycentrics back to the original vertex order: triangle id @60, per triangle I / J source uint4 bc = asuint(float4(det - i - j, i, j, 0.0f)); uint tw = mem.Load(at + 60u); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 460923aeb1..510230ada3 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6325,8 +6325,8 @@ fn gpu_triangle_pair_and_box16_nodes() { /// Watertight triangle test on the GPU: rays exactly through the edge a triangle pair shares /// (type 0 = (v0, v1, v2) and type 1 = (v1, v3, v2) share v1–v2), along each axis and both -/// signs. Each ray goes to both triangles in neighbouring lanes: at least one hits, and hit / -/// miss is the CPU's. +/// signs. Each ray goes to both triangles in neighbouring lanes: at least one hits on the GPU, +/// and at least one in the CPU reference (each checked on its own). #[test] fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { use crate::gpu::bvh; From 7071a3650d187fbac6a4c749003cb4bf274861c1 Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:54:32 +0000 Subject: [PATCH 3/6] Recompiler: put the watertight BVH triangle test behind XCL_BVH_WATERTIGHT The watertight test changes what a title's ray tracing sees, so as #3011 asks for a port it is now behind a switch, off by default: XCL_BVH_WATERTIGHT=1 selects it, otherwise the CPU reference, the HLSL prelude and the DXIL lowering use Moller-Trumbore exactly as before. The switch is read once (gpu::bvh::watertight). The HLSL gets it as a positions; the translated cache's identity (recomp::pso) gets a tag when it is on, so the existing entries stay valid with it off and a stored watertight translation is never taken for a Moller-Trumbore one. Tests set it per thread (carried over to the DXIL translator's thread), never through the process environment. Tests: the pinned shared-edge ray misses both triangles with the switch off and hits with it on; the emitted HLSL and the direct DXIL differ between the two positions. Provenance: victory-fork 9a9091d (fxceless), after Mesa RADV intersect_ray_amd_software_tri (Copyright 2021 Google, MIT); README documents the switch. --- README.md | 4 ++ THIRD_PARTY.md | 4 +- crates/xcl/src/gpu/bvh.rs | 68 +++++++++++++++++++------- crates/xcl/src/gpu/dxil/kernel.rs | 6 +++ crates/xcl/src/gpu/dxil/lower_image.rs | 49 ++++++++++++++++++- crates/xcl/src/gpu/recomp/emit.rs | 12 +++++ crates/xcl/src/gpu/recomp/pso.rs | 2 + crates/xcl/src/gpu/recomp/tests.rs | 23 ++++++++- 8 files changed, 145 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 0dc65fb2e9..43418ad902 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,10 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o split-wave64 programs that access LDS stay on the HLSL path to preserve instruction order between their two hardware wave32 halves. Test results on other GPUs: [#42](https://github.com/xcl-dev/xcl/issues/42). +- **`XCL_BVH_WATERTIGHT=1`** (off by default): the ray/triangle test of `image_bvh_intersect_ray` + becomes watertight, so a ray exactly through an edge two triangles share hits one of them instead + of possibly missing both. Changes the translated shaders (they get their own cache entries). + Ported from victory-fork, after Mesa RADV (see `THIRD_PARTY.md`). ```powershell cargo build --release --workspace # target\release\xcl.exe diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 30ec8aa49d..93a8c5d390 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -11,8 +11,8 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | -| [victory-fork](https://github.com/fxceless/victory-fork) | GPL-3.0-or-later | watertight ray/triangle test of the BVH triangle node (`gpu/bvh.rs` `triangle_hit`, the HLSL `bvh_intersect` in `gpu/recomp/emit.rs`, `gpu/dxil/lower_image.rs`): after its `crates/victory-shader/src/bvh.rs` `triangle` | port with annotation | -| [Mesa RADV](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/vulkan) (Mesa) | MIT | the same triangle test, through victory-fork: `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri` (Woop, Benthin, Wald, JCGT 2013) | logic ported with annotation | +| [victory-fork](https://github.com/fxceless/victory-fork) | GPL-3.0-or-later | watertight ray/triangle test of the BVH triangle node (`gpu/bvh.rs` `triangle_hit`, the HLSL `bvh_intersect` in `gpu/recomp/emit.rs`, `gpu/dxil/lower_image.rs`, behind `XCL_BVH_WATERTIGHT=1`): after its `crates/victory-shader/src/bvh.rs` `triangle` at `9a9091d` (fxceless), changed 2026-11-27 | port with annotation | +| [Mesa RADV](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/vulkan) (Mesa) | MIT | the same triangle test, through victory-fork: `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri` (Copyright © 2021 Google, SPDX MIT; Woop, Benthin, Wald, JCGT 2013) | logic ported with annotation | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index 0bad3c04f6..36e26d4c70 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -247,16 +247,32 @@ fn world_to_object(m: &[[f32; 4]; 3]) -> [f32; 12] { fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { [a[0] - b[0], a[1] - b[1], a[2] - b[2]] } -#[cfg(test)] fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] } -#[cfg(test)] fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } /// The triangle node's test as it returns it: (t·det, det, i·det, j·det), `None` = miss. +pub fn triangle_hit(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { + if watertight() { triangle_hit_watertight(v, o, d) } else { triangle_hit_mt(v, o, d) } +} + +/// `XCL_BVH_WATERTIGHT=1` (off by default): the triangle node uses the watertight test in the CPU +/// reference, the HLSL prelude and the DXIL lowering; otherwise Möller–Trumbore as before. Read +/// once; a test sets it for its own thread only (`tests::with_watertight`). The HLSL has it as a +/// `#define` (so in DXC's cache key) and the translated cache's identity has it (`recomp::pso`). +pub fn watertight() -> bool { + #[cfg(test)] + if let Some(w) = tests::WATERTIGHT.with(|c| c.get()) { + return w; + } + static W: std::sync::OnceLock = std::sync::OnceLock::new(); + *W.get_or_init(|| std::env::var("XCL_BVH_WATERTIGHT").is_ok_and(|v| v == "1")) +} + +/// The watertight test of `triangle_hit`: /// Watertight (Woop, Benthin, Wald, "Watertight Ray/Triangle Intersection", JCGT 2013): the /// vertices are sheared so the ray runs along its largest axis and the signs of the three edge /// functions decide, so a ray through an edge two triangles share hits at least one of them @@ -267,12 +283,12 @@ fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { /// (`dxil/lower_image.rs`) do the same operations in the same order. /// /// Adapted from victory-fork (https://github.com/fxceless/victory-fork, GPL-3.0-or-later), -/// `crates/victory-shader/src/bvh.rs` `triangle`, which follows Mesa RADV +/// commit `9a9091d`, `crates/victory-shader/src/bvh.rs` `triangle` (by fxceless), which follows Mesa RADV /// (https://gitlab.freedesktop.org/mesa/mesa, MIT, © 2021 Google): -/// `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri`. Changed 2026-11: +/// `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri`. Changed 2026-11-27: /// f32 edge functions (Mesa computes them in f64), no t sign test, XCL's result scale (Mesa /// returns t / |det| and the sign of det). -pub fn triangle_hit(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { +fn triangle_hit_watertight(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { let kz = dominant_axis(d); let (kx, ky) = if d[kz] < 0.0 { ((kz + 2) % 3, (kz + 1) % 3) } else { ((kz + 1) % 3, (kz + 2) % 3) }; let sz = 1.0 / d[kz]; @@ -302,8 +318,7 @@ fn dominant_axis(d: [f32; 3]) -> usize { if a[0] >= a[1] { if a[0] >= a[2] { 0 } else { 2 } } else if a[1] >= a[2] { 1 } else { 2 } } -/// The Möller–Trumbore test XCL used before the watertight one (tests compare against it). -#[cfg(test)] +/// The Möller–Trumbore test XCL used before the watertight one (`XCL_BVH_WATERTIGHT` unset). fn triangle_hit_mt(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { let (e1, e2) = (sub(v[1], v[0]), sub(v[2], v[0])); let p = cross(d, e2); @@ -1203,7 +1218,7 @@ pub(crate) mod tests { /// hits among `tris` for a ray from `o` along `d` fn hits(tris: &[Triangle], o: [f32; 3], d: [f32; 3]) -> usize { - tris.iter().filter(|t| triangle_hit(t, o, d).is_some()).count() + tris.iter().filter(|t| triangle_hit_watertight(t, o, d).is_some()).count() } /// Random rays from a point on the edge two triangles share and on the vertex a fan shares @@ -1268,7 +1283,7 @@ pub(crate) mod tests { let to = [r(-8.0, 8.0), r(-8.0, 8.0), r(-8.0, 8.0)]; let d = sub(to, o); for t in &tris { - let (w, m) = (triangle_hit(t, o, d), triangle_hit_mt(t, o, d)); + let (w, m) = (triangle_hit_watertight(t, o, d), triangle_hit_mt(t, o, d)); let Some(m) = m else { if let Some(w) = w { // only a ray within rounding of an edge may differ @@ -1339,6 +1354,10 @@ pub(crate) mod tests { let (o, d) = ([5.911541f32, -0.8080063, 0.59203976], [-1.0f32, -0.13060194, 0.000772506]); assert_eq!(pair.iter().filter(|t| triangle_hit_mt(t, o, d).is_some()).count(), 0); assert!(hits(&pair, o, d) >= 1); + // the switch: off (the default) = Möller–Trumbore, misses both; on = watertight + let n = |on| with_watertight(on, || pair.iter().filter(|t| triangle_hit(t, o, d).is_some()).count()); + assert_eq!(n(false), 0); + assert!(n(true) >= 1); } /// Equal largest components pick the first axis (x before y before z), as in the HLSL and @@ -1358,7 +1377,7 @@ pub(crate) mod tests { fn triangle_hit_non_finite_t_misses() { let tri = [[5.0, 0.0, 0.0], [5.0, 1.0, 0.0], [5.0, 0.0, 1.0]]; let (o, d) = ([0.0, 0.2, 0.2], [1e-38f32, 0.0, 0.0]); - assert!(triangle_hit(&tri, o, d).is_none()); + assert!(triangle_hit_watertight(&tri, o, d).is_none()); let mut data = vec![0u8; 64]; for (k, p) in tri.iter().enumerate() { for x in 0..3 { @@ -1366,7 +1385,7 @@ pub(crate) mod tests { } } data[60..64].copy_from_slice(&TRI_ID_PLAIN.to_le_bytes()); - let r = intersect_node(&data, 0, 100.0, o, d, d.map(|x| 1.0 / x), false).map(f32::from_bits); + let r = with_watertight(true, || intersect_node(&data, 0, 100.0, o, d, d.map(|x| 1.0 / x), false)).map(f32::from_bits); assert_eq!(r, [f32::INFINITY, 1.0, 0.0, 0.0]); } @@ -1382,18 +1401,18 @@ pub(crate) mod tests { [[0.2, 0.2, 0.0], [0.2, 0.2, 0.0], [1.0, 0.0, 0.0]], ]; for t in °enerate { - assert!(triangle_hit(t, o, d).is_none(), "{t:?}"); + assert!(triangle_hit_watertight(t, o, d).is_none(), "{t:?}"); } // in the plane, along each in-plane axis and a diagonal for d in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 0.0, 0.0]] { - assert!(triangle_hit(&tri, [-1.0, 0.2, 0.0], d).is_none(), "{d:?}"); + assert!(triangle_hit_watertight(&tri, [-1.0, 0.2, 0.0], d).is_none(), "{d:?}"); } - assert!(triangle_hit(&tri, o, [0.0; 3]).is_none()); - assert!(triangle_hit(&tri, o, [f32::NAN, 0.0, 1.0]).is_none()); - assert!(triangle_hit(&tri, [f32::NAN, 0.2, -1.0], d).is_none()); + assert!(triangle_hit_watertight(&tri, o, [0.0; 3]).is_none()); + assert!(triangle_hit_watertight(&tri, o, [f32::NAN, 0.0, 1.0]).is_none()); + assert!(triangle_hit_watertight(&tri, [f32::NAN, 0.2, -1.0], d).is_none()); let mut nan = tri; nan[1][0] = f32::NAN; - assert!(triangle_hit(&nan, o, d).is_none()); + assert!(triangle_hit_watertight(&nan, o, d).is_none()); // the node returns its miss encoding, never a NaN for t in degenerate.iter().chain([&nan]) { let mut data = vec![0u8; 64]; @@ -1403,8 +1422,21 @@ pub(crate) mod tests { } } data[60..64].copy_from_slice(&TRI_ID_PLAIN.to_le_bytes()); - let r = intersect_node(&data, 0, 100.0, o, d, d.map(|x| 1.0 / x), false).map(f32::from_bits); + let r = with_watertight(true, || intersect_node(&data, 0, 100.0, o, d, d.map(|x| 1.0 / x), false)).map(f32::from_bits); assert_eq!(r, [f32::INFINITY, 1.0, 0.0, 0.0]); } } + + thread_local! { + /// `watertight()` for this test thread only (`None`: `XCL_BVH_WATERTIGHT`) + pub(crate) static WATERTIGHT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// `f` with the triangle test switched `on` / off on this thread, restored after + pub(crate) fn with_watertight(on: bool, f: impl FnOnce() -> R) -> R { + let old = WATERTIGHT.with(|c| c.replace(Some(on))); + let r = f(); + WATERTIGHT.with(|c| c.set(old)); + r + } } diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 8e01ef00a4..8ef7c73951 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -252,12 +252,18 @@ fn translate_entry_with( let code = code.to_vec(); #[cfg(test)] let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); + // a test's `XCL_BVH_WATERTIGHT` setting is per thread: carried over to the translator's + #[cfg(test)] + let wt = crate::gpu::bvh::watertight(); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) .spawn(move || { #[cfg(test)] super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); + #[cfg(test)] + return crate::gpu::bvh::tests::with_watertight(wt, || translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask)); + #[cfg(not(test))] translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask) }) .map_err(|e| format!("translator thread: {e}"))? diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index 668dbda7ee..afeda4712a 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -63,6 +63,23 @@ impl Lw { fn f3(&mut self, a: [Value; 3], b: [Value; 3], op: fn(&mut Lw, Value, Value) -> Value) -> [Value; 3] { [op(self, a[0], b[0]), op(self, a[1], b[1]), op(self, a[2], b[2])] } + fn cross(&mut self, a: [Value; 3], b: [Value; 3]) -> [Value; 3] { + let x0 = self.fmul(a[1], b[2]); + let x1 = self.fmul(a[2], b[1]); + let x = self.fsub(x0, x1); + let y0 = self.fmul(a[2], b[0]); + let y1 = self.fmul(a[0], b[2]); + let y = self.fsub(y0, y1); + let z0 = self.fmul(a[0], b[1]); + let z1 = self.fmul(a[1], b[0]); + let z = self.fsub(z0, z1); + [x, y, z] + } + /// HLSL `dot(float3, float3)` = `Dot3`. + fn dot3(&mut self, a: [Value; 3], b: [Value; 3]) -> Value { + let f32 = self.s.m.f32(); + self.s.op(55, "dot3", Some(f32), f32, &[a[0], a[1], a[2], b[0], b[1], b[2]], super::module::FnAttrs::ReadNone) + } /// Move a finite float32 upward toward +inf by `g` ULPs (leaving NaN/Inf/g=0 unchanged). fn bvh_grow_hi(&mut self, x: Value, g: Value) -> Value { @@ -267,6 +284,9 @@ impl Lw { let v1 = [lw.f(words[3]), lw.f(words[4]), lw.f(words[5])]; let v2 = [lw.f(words[6]), lw.f(words[7]), lw.f(words[8])]; let tw = words[9]; + let z = lw.fc(0.0); + // `XCL_BVH_WATERTIGHT` (`gpu::bvh::watertight`); the direct translator's cache identity has it + let (t, det, i, j, hit) = if crate::gpu::bvh::watertight() { // watertight test as gpu::bvh::triangle_hit and the HLSL prelude (Woop, Benthin, Wald // 2013; adapted from victory-fork, https://github.com/fxceless/victory-fork, // GPL-3.0-or-later, after Mesa RADV, MIT); no fused products, so a shared edge's @@ -292,7 +312,6 @@ impl Lw { [x, y, z] }; let pd = perm(lw, dir); - let z = lw.fc(0.0); let sw = lw.fcmp(Pred::FOLt, pd[2], z); let swap = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { [lw.sel(sw, v[1], v[0]), lw.sel(sw, v[0], v[1]), v[2]] }; let pd = swap(lw, pd); @@ -351,6 +370,34 @@ impl Lw { let fin = lw.fcmp(Pred::FOLt, ax, pinf); hit = lw.land(hit, fin); } + (t, det, i, j, hit) + } else { + // Möller–Trumbore, the test before XCL_BVH_WATERTIGHT + let e1 = lw.f3(v1, v0, Lw::fsub); + let e2 = lw.f3(v2, v0, Lw::fsub); + let p = lw.cross(dir, e2); + let det = lw.dot3(e1, p); + let sv = lw.f3(o, v0, Lw::fsub); + let q = lw.cross(sv, e1); + let i = lw.dot3(sv, p); + let j = lw.dot3(dir, q); + let t = lw.dot3(e2, q); + let ij = lw.fadd(i, j); + let dpos = lw.fcmp(Pred::FOGt, det, z); + let c1 = lw.fcmp(Pred::FOGe, i, z); + let c2 = lw.fcmp(Pred::FOGe, j, z); + let c3 = lw.fcmp(Pred::FOLe, ij, det); + let hp = lw.land(c1, c2); + let hp = lw.land(hp, c3); + let dneg = lw.fcmp(Pred::FOLt, det, z); + let n1 = lw.fcmp(Pred::FOLe, i, z); + let n2 = lw.fcmp(Pred::FOLe, j, z); + let n3 = lw.fcmp(Pred::FOGe, ij, det); + let hn = lw.land(dneg, n1); + let hn = lw.land(hn, n2); + let hn = lw.land(hn, n3); + (t, det, i, j, lw.sel(dpos, hp, hn)) + }; let di = lw.fsub(det, i); let b0 = lw.fsub(di, j); let bc = [b0, i, j, z]; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 22891d85a4..8fae53a6e0 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5031,6 +5031,8 @@ static uint xcl_cap = 1u << 16; } let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); + // the BVH triangle test (`gpu::bvh::watertight`): part of the text, so of the DXC cache key + let _ = writeln!(h, "#define XCL_BVH_WATERTIGHT {}", crate::gpu::bvh::watertight() as u8); h.push_str(PRELUDE_MEM); if self.uses_scratch { h.push_str(PRELUDE_SCRATCH); @@ -6360,6 +6362,7 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i uint o1 = type == 0u ? 12u : (type == 3u ? 48u : 36u); uint o2 = type <= 1u ? 24u : (type == 2u ? 48u : 0u); float3 v0 = asfloat(mem.Load3(at + o0)), v1 = asfloat(mem.Load3(at + o1)), v2 = asfloat(mem.Load3(at + o2)); +#if XCL_BVH_WATERTIGHT // watertight test as gpu::bvh::triangle_hit (Woop, Benthin, Wald 2013; adapted from // victory-fork, https://github.com/fxceless/victory-fork, GPL-3.0-or-later, after Mesa // RADV, MIT): shear so the ray runs along its largest axis, signs of the edge functions @@ -6393,6 +6396,15 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i t = t * s; precise float dets = det * s; i = i * s; j = j * s; bool hit = !mixed && (det > 0.0f || det < 0.0f) && !isinf(t) && !isnan(t) && !isinf(dets) && !isnan(dets); det = dets; +#else + // Möller–Trumbore, the test before XCL_BVH_WATERTIGHT + float3 e1 = v1 - v0, e2 = v2 - v0, p = cross(d, e2); + float det = dot(e1, p); + float3 sv = o - v0, q = cross(sv, e1); + float i = dot(sv, p), j = dot(d, q), t = dot(e2, q); + // inside when i, j, 1 - i - j >= 0 relative to det (either winding); avoid det * det underflow/overflow + bool hit = det > 0.0f ? (i >= 0.0f && j >= 0.0f && i + j <= det) : (det < 0.0f && i <= 0.0f && j <= 0.0f && i + j >= det); +#endif // barycentrics back to the original vertex order: triangle id @60, per triangle I / J source uint4 bc = asuint(float4(det - i - j, i, j, 0.0f)); uint tw = mem.Load(at + 60u); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index cd7b234bf8..89de9d0a87 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -382,6 +382,8 @@ mod translated { } else { id }; // `XCL_X_LDS_ORDER=0`: the split wave64 form without its LDS order, in both translators let id = if crate::gpu::recomp::emit::lds_order_wanted() { id } else { identity_for(&id.to_string(), "xcl-x-lds-order-0") }; + // `XCL_BVH_WATERTIGHT=1`: another BVH triangle test in the HLSL and the DXIL (off keeps the identity) + let id = if crate::gpu::bvh::watertight() { identity_for(&id.to_string(), "xcl-bvh-watertight") } else { id }; // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity if Backend::current() != Backend::Hlsl && crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 510230ada3..88c19dca61 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6377,13 +6377,13 @@ fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { } rays.push((node, o, d, inv)); } - let res = runner::run_code(&code, &st, &mem).unwrap(); + let res = bvh::tests::with_watertight(true, || runner::run_code(&code, &st, &mem)).unwrap(); let data: Vec = mem[base / 4..].iter().flat_map(|x| x.to_le_bytes()).collect(); // GPU and CPU may round 1 / d differently, so on the edge each is checked on its own let (mut gh, mut ch) = ([false; 2], [false; 2]); for (l, &(node, o, d, inv)) in rays.iter().enumerate() { gh[l % 2] = f32::from_bits(res.vgpr[l][100]).is_finite(); - ch[l % 2] = f32::from_bits(bvh::intersect_node(&data, node, 100.0, o, d, inv, true)[0]).is_finite(); + ch[l % 2] = f32::from_bits(bvh::tests::with_watertight(true, || bvh::intersect_node(&data, node, 100.0, o, d, inv, true))[0]).is_finite(); if l % 2 == 1 { assert!(gh[0] || gh[1], "lanes {} and {l}: GPU ray through the shared edge missed both", l - 1); assert!(ch[0] || ch[1], "lanes {} and {l}: CPU ray through the shared edge missed both", l - 1); @@ -6391,6 +6391,25 @@ fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { } } +/// `XCL_BVH_WATERTIGHT` selects the triangle test in the HLSL (a `#define`, so the text and +/// DXC's cache key differ) and in the direct DXIL (other bytes); off is Möller–Trumbore. +#[test] +fn bvh_watertight_switch_changes_the_hlsl_and_the_dxil() { + use crate::gpu::bvh::tests::with_watertight; + let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let hlsl = |on| with_watertight(on, || translate(&code, &Options::default()).unwrap().hlsl); + let (off, on) = (hlsl(false), hlsl(true)); + assert!(off.contains("#define XCL_BVH_WATERTIGHT 0") && on.contains("#define XCL_BVH_WATERTIGHT 1")); + assert!(off.contains("#if XCL_BVH_WATERTIGHT") && off.contains("p = cross(d, e2)")); + assert_ne!(off, on); + let dxil = |on| with_watertight(on, || runner::direct_kernel(&code, true)); + match (dxil(false), dxil(true)) { + (Ok(off), Ok(on)) => assert_ne!(off, on, "direct DXIL is the same with and without the switch"), + (a, b) => panic!("direct DXIL: {:?} / {:?}", a.err(), b.err()), + } +} + /// Multi-window `image_bvh64_intersect_ray` (full 64-bit node pointer into UMA window 1 with /// base = 0, plus 48-bit base in window 1) and axis-aligned grazing ray / NaN-disabled box. #[test] From 1da3ec3b42da701c0e0c388ce7f3eba6f8a4ea62 Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:06:36 +0000 Subject: [PATCH 4/6] Recompiler: keep the HLSL unchanged with XCL_BVH_WATERTIGHT off With the switch off the emitted HLSL is now byte for byte what it was before: the #define and the #if/#else in the BVH prelude went into every shader's text, so every DXC cache key changed and every user would have compiled all shaders again. The watertight triangle block now replaces Moller-Trumbore's in the prelude text in Rust, only when the switch is on and only for programs that call bvh_intersect. The DXIL lowering creates its zero constant where it did before in the Moller-Trumbore branch. Tests: the off HLSL has no trace of the switch and holds the old triangle block, a program without BVH is the same in both positions; the GPU test adds the pinned pair Moller-Trumbore misses in both triangles, so a GPU hit there shows the switch reached the translation. The random near-edge test is dropped (the exact and pinned cases cover it) and three small CPU tests are merged into one. The provenance note moves to the file headers. --- crates/xcl/src/gpu/bvh.rs | 146 +++++++------------------ crates/xcl/src/gpu/dxil/lower_image.rs | 22 ++-- crates/xcl/src/gpu/recomp/emit.rs | 98 ++++++++++------- crates/xcl/src/gpu/recomp/tests.rs | 34 ++++-- 4 files changed, 138 insertions(+), 162 deletions(-) diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index 36e26d4c70..142116892c 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -28,6 +28,14 @@ //! //! Top-down build: median split of the leaf box centroids on the longest axis, twice per box //! node (4 children), one triangle / instance per leaf. +//! +//! `triangle_hit_watertight` (`XCL_BVH_WATERTIGHT=1`) is adapted from victory-fork +//! (https://github.com/fxceless/victory-fork, GPL-3.0-or-later) commit `9a9091d`, +//! `crates/victory-shader/src/bvh.rs` `triangle` (by fxceless), which follows Mesa RADV +//! (https://gitlab.freedesktop.org/mesa/mesa, MIT, Copyright © 2021 Google) +//! `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri`. Changed +//! 2026-11-27: f32 edge functions (Mesa computes them in f64), no t sign test, XCL's result +//! scale (Mesa returns t / |det| and the sign of det). pub const BOX32: u32 = 5; pub const INSTANCE: u32 = 6; @@ -261,8 +269,9 @@ pub fn triangle_hit(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> /// `XCL_BVH_WATERTIGHT=1` (off by default): the triangle node uses the watertight test in the CPU /// reference, the HLSL prelude and the DXIL lowering; otherwise Möller–Trumbore as before. Read -/// once; a test sets it for its own thread only (`tests::with_watertight`). The HLSL has it as a -/// `#define` (so in DXC's cache key) and the translated cache's identity has it (`recomp::pso`). +/// once; a test sets it for its own thread only (`tests::with_watertight`). Off, the HLSL is the +/// text it was before; on, a program calling `bvh_intersect` gets other text (so another DXC +/// cache key), and the translated cache's identity gets a tag (`recomp::pso`). pub fn watertight() -> bool { #[cfg(test)] if let Some(w) = tests::WATERTIGHT.with(|c| c.get()) { @@ -280,14 +289,8 @@ pub fn watertight() -> bool { /// Edge-on (det = 0), NaN and a non-finite t or det miss; t's sign is not tested here (the /// traversal does). The four values have the Möller–Trumbore scale XCL returned before. The /// HLSL prelude (`recomp/emit.rs` `bvh_intersect`) and the DXIL lowering -/// (`dxil/lower_image.rs`) do the same operations in the same order. -/// -/// Adapted from victory-fork (https://github.com/fxceless/victory-fork, GPL-3.0-or-later), -/// commit `9a9091d`, `crates/victory-shader/src/bvh.rs` `triangle` (by fxceless), which follows Mesa RADV -/// (https://gitlab.freedesktop.org/mesa/mesa, MIT, © 2021 Google): -/// `src/amd/vulkan/nir/radv_nir_rt_common.c` `intersect_ray_amd_software_tri`. Changed 2026-11-27: -/// f32 edge functions (Mesa computes them in f64), no t sign test, XCL's result scale (Mesa -/// returns t / |det| and the sign of det). +/// (`dxil/lower_image.rs`) do the same operations in the same order. Ported code: see the file +/// header. fn triangle_hit_watertight(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> { let kz = dominant_axis(d); let (kx, ky) = if d[kz] < 0.0 { ((kz + 2) % 3, (kz + 1) % 3) } else { ((kz + 1) % 3, (kz + 2) % 3) }; @@ -1221,55 +1224,6 @@ pub(crate) mod tests { tris.iter().filter(|t| triangle_hit_watertight(t, o, d).is_some()).count() } - /// Random rays from a point on the edge two triangles share and on the vertex a fan shares - /// (rounded, so near, not exactly on it): at least one triangle hits, every axis and sign. - #[test] - fn triangle_hit_is_watertight_at_shared_edges_and_vertices() { - let mut r = rng(11); - let mut checked = 0; - for axis in 0..3 { - for flip in [false, true] { - for _ in 0..200 { - // a quad split along a random diagonal, in a plane across the ray's main axis - let z = r(-2.0, 2.0); - let (a, b) = ([r(-3.0, -1.0), r(-1.0, 1.0), z], [r(1.0, 3.0), r(-1.0, 1.0), z]); - let (c, e) = ([r(-3.0, 3.0), r(8.0, 10.0), z + r(-0.5, 0.5)], [r(-3.0, 3.0), r(-10.0, -8.0), z + r(-0.5, 0.5)]); - let pair = [[a, b, c], [b, a, e]].map(|t| t.map(|p| place(p, axis, flip))); - let s = r(0.0, 1.0); - let on = [0, 1, 2].map(|k| a[k] + s * (b[k] - a[k])); - // ray from below, tilted but still mostly along the axis - let dir = [r(-0.3, 0.3), r(-0.3, 0.3), if r(0.0, 1.0) < 0.5 { 1.0 } else { -1.0 }]; - let o = [0, 1, 2].map(|k| on[k] - 4.0 * dir[k]); - let (o, dir) = (place(o, axis, flip), place(dir, axis, flip)); - assert!(hits(&pair, o, dir) >= 1, "edge: axis {axis} flip {flip} {pair:?} o {o:?} d {dir:?}"); - // fan of 6 around a shared vertex, ray straight through it - let v = [r(-1.0, 1.0), r(-1.0, 1.0), z]; - let ring: Vec<[f32; 3]> = (0..6) - .map(|k| { - let ang = k as f32 * std::f32::consts::TAU / 6.0 + r(0.0, 0.3); - [v[0] + 2.0 * ang.cos(), v[1] + 2.0 * ang.sin(), z + r(-0.5, 0.5)] - }) - .collect(); - let fan: Vec = (0..6).map(|k| [v, ring[k], ring[(k + 1) % 6]].map(|p| place(p, axis, flip))).collect(); - let o = [0, 1, 2].map(|k| v[k] - 4.0 * dir_local(dir, axis, flip)[k]); - let o = place(o, axis, flip); - assert!(hits(&fan, o, dir) >= 1, "vertex: axis {axis} flip {flip} o {o:?} d {dir:?}"); - checked += 1; - } - } - } - assert_eq!(checked, 1200); - } - - /// inverse of `place` for a direction - fn dir_local(d: [f32; 3], axis: usize, flip: bool) -> [f32; 3] { - let mut d = d; - if flip { - d[axis] = -d[axis]; - } - [0, 1, 2].map(|k| d[(axis + 1 + k) % 3]) - } - /// Away from edges the watertight test agrees with the old Möller–Trumbore one: same hit / /// miss, same sign of det (facing), t and barycentrics within rounding. #[test] @@ -1344,7 +1298,7 @@ pub(crate) mod tests { } } - /// Found by `triangle_hit_is_watertight_at_shared_edges_and_vertices` (seed 11, first case): + /// Found by a random near-edge search (seed 11, first case): /// a ray through the edge (1.911541, -2.025442, 0.78372467)–(1.911541, 2.740394, -0.50947857) /// that Möller–Trumbore misses in both triangles; the watertight test hits at least one. #[test] @@ -1360,48 +1314,38 @@ pub(crate) mod tests { assert!(n(true) >= 1); } - /// Equal largest components pick the first axis (x before y before z), as in the HLSL and - /// DXIL `kz` selection. - #[test] - fn triangle_hit_dominant_axis_ties() { - assert_eq!(dominant_axis([1.0, -1.0, 0.5]), 0); - assert_eq!(dominant_axis([-1.0, 1.0, 1.0]), 0); - assert_eq!(dominant_axis([0.5, 1.0, -1.0]), 1); - assert_eq!(dominant_axis([0.5, -0.25, 1.0]), 2); - assert_eq!(dominant_axis([0.0, 0.0, 0.0]), 0); - } - - /// A tiny largest component with a far triangle overflows the sheared depth: the node - /// returns its miss encoding, not an infinite or NaN t with a finite det. + /// The watertight test's edge cases: degenerate triangles, rays in the triangle's plane, a + /// zero direction and NaN miss; a tiny largest component with a far triangle overflows the + /// sheared depth and misses; the node then returns its miss encoding, never a NaN. Equal + /// largest components pick the first axis (x before y before z), as the HLSL and DXIL `kz`. #[test] - fn triangle_hit_non_finite_t_misses() { - let tri = [[5.0, 0.0, 0.0], [5.0, 1.0, 0.0], [5.0, 0.0, 1.0]]; - let (o, d) = ([0.0, 0.2, 0.2], [1e-38f32, 0.0, 0.0]); - assert!(triangle_hit_watertight(&tri, o, d).is_none()); - let mut data = vec![0u8; 64]; - for (k, p) in tri.iter().enumerate() { - for x in 0..3 { - data[12 * k + 4 * x..12 * k + 4 * x + 4].copy_from_slice(&p[x].to_le_bytes()); + fn triangle_hit_degenerate_non_finite_and_axis_ties() { + let node = |t: &Triangle| { + let mut data = vec![0u8; 64]; + for (k, p) in t.iter().enumerate() { + for a in 0..3 { + data[12 * k + 4 * a..12 * k + 4 * a + 4].copy_from_slice(&p[a].to_le_bytes()); + } } - } - data[60..64].copy_from_slice(&TRI_ID_PLAIN.to_le_bytes()); - let r = with_watertight(true, || intersect_node(&data, 0, 100.0, o, d, d.map(|x| 1.0 / x), false)).map(f32::from_bits); - assert_eq!(r, [f32::INFINITY, 1.0, 0.0, 0.0]); - } - - /// Degenerate triangles, rays in the triangle's plane, a zero direction and NaN miss. - #[test] - fn triangle_hit_degenerate_and_parallel_miss() { + data[60..64].copy_from_slice(&TRI_ID_PLAIN.to_le_bytes()); + data + }; + let miss = [f32::INFINITY, 1.0, 0.0, 0.0]; + let at = |t: &Triangle, o: [f32; 3], d: [f32; 3]| with_watertight(true, || intersect_node(&node(t), 0, 100.0, o, d, d.map(|x| 1.0 / x), false)).map(f32::from_bits); let d = [0.0, 0.0, 1.0]; let o = [0.2, 0.2, -1.0]; let tri = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; - let degenerate: [Triangle; 3] = [ + let mut nan = tri; + nan[1][0] = f32::NAN; + let degenerate: [Triangle; 4] = [ [[0.0; 3], [0.0; 3], [0.0; 3]], [[0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [2.0, 2.0, 0.0]], [[0.2, 0.2, 0.0], [0.2, 0.2, 0.0], [1.0, 0.0, 0.0]], + nan, ]; for t in °enerate { assert!(triangle_hit_watertight(t, o, d).is_none(), "{t:?}"); + assert_eq!(at(t, o, d), miss, "{t:?}"); } // in the plane, along each in-plane axis and a diagonal for d in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 0.0, 0.0]] { @@ -1410,20 +1354,12 @@ pub(crate) mod tests { assert!(triangle_hit_watertight(&tri, o, [0.0; 3]).is_none()); assert!(triangle_hit_watertight(&tri, o, [f32::NAN, 0.0, 1.0]).is_none()); assert!(triangle_hit_watertight(&tri, [f32::NAN, 0.2, -1.0], d).is_none()); - let mut nan = tri; - nan[1][0] = f32::NAN; - assert!(triangle_hit_watertight(&nan, o, d).is_none()); - // the node returns its miss encoding, never a NaN - for t in degenerate.iter().chain([&nan]) { - let mut data = vec![0u8; 64]; - for (k, p) in t.iter().enumerate() { - for a in 0..3 { - data[12 * k + 4 * a..12 * k + 4 * a + 4].copy_from_slice(&p[a].to_le_bytes()); - } - } - data[60..64].copy_from_slice(&TRI_ID_PLAIN.to_le_bytes()); - let r = with_watertight(true, || intersect_node(&data, 0, 100.0, o, d, d.map(|x| 1.0 / x), false)).map(f32::from_bits); - assert_eq!(r, [f32::INFINITY, 1.0, 0.0, 0.0]); + let far = [[5.0, 0.0, 0.0], [5.0, 1.0, 0.0], [5.0, 0.0, 1.0]]; + let (fo, fd) = ([0.0, 0.2, 0.2], [1e-38f32, 0.0, 0.0]); + assert!(triangle_hit_watertight(&far, fo, fd).is_none()); + assert_eq!(at(&far, fo, fd), miss); + for (d, k) in [([1.0, -1.0, 0.5], 0), ([-1.0, 1.0, 1.0], 0), ([0.5, 1.0, -1.0], 1), ([0.5, -0.25, 1.0], 2), ([0.0; 3], 0)] { + assert_eq!(dominant_axis(d), k, "{d:?}"); } } diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index afeda4712a..72a6afdf7a 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -4,6 +4,11 @@ //! `image_bvh(64)_intersect_ray` on the flat memory (port of //! `recomp/emit.rs` `mimg` and `bvh_intersect`; compute rules: no implicit //! derivatives, so implicit-LOD samples take LOD 0 / the bias). +//! +//! The watertight BVH triangle test (`XCL_BVH_WATERTIGHT=1`) is adapted from victory-fork +//! (https://github.com/fxceless/victory-fork, GPL-3.0-or-later) `9a9091d`, +//! `crates/victory-shader/src/bvh.rs` `triangle`, after Mesa RADV (MIT, Copyright © 2021 Google) +//! `intersect_ray_amd_software_tri`; changed 2026-11-27 (see `gpu/bvh.rs`). use super::lower::{err, LResult, Lw, VAR_VGPR, VAR_WIN}; use super::module::{BinOp, Pred, Value}; @@ -284,15 +289,12 @@ impl Lw { let v1 = [lw.f(words[3]), lw.f(words[4]), lw.f(words[5])]; let v2 = [lw.f(words[6]), lw.f(words[7]), lw.f(words[8])]; let tw = words[9]; - let z = lw.fc(0.0); - // `XCL_BVH_WATERTIGHT` (`gpu::bvh::watertight`); the direct translator's cache identity has it - let (t, det, i, j, hit) = if crate::gpu::bvh::watertight() { - // watertight test as gpu::bvh::triangle_hit and the HLSL prelude (Woop, Benthin, Wald - // 2013; adapted from victory-fork, https://github.com/fxceless/victory-fork, - // GPL-3.0-or-later, after Mesa RADV, MIT); no fused products, so a shared edge's + // `XCL_BVH_WATERTIGHT=1` (`gpu::bvh::watertight`): the watertight test as + // gpu::bvh::triangle_hit_watertight and the HLSL prelude; no fused products, so a shared edge's // function is exactly negated in the other triangle. Limit: the module drops // DisableMathRefactoring when it also uses FMad (shader.rs), and a driver may then // fuse these products, which loses the exact negation (no worse than before) + let (t, det, i, j, hit, z) = if crate::gpu::bvh::watertight() { lw.s.require(super::shader::Feature::DisableMathRefactoring); let ad = [lw.fabs(dir[0]), lw.fabs(dir[1]), lw.fabs(dir[2])]; let xy = lw.fcmp(Pred::FOGe, ad[0], ad[1]); @@ -312,6 +314,7 @@ impl Lw { [x, y, z] }; let pd = perm(lw, dir); + let z = lw.fc(0.0); let sw = lw.fcmp(Pred::FOLt, pd[2], z); let swap = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { [lw.sel(sw, v[1], v[0]), lw.sel(sw, v[0], v[1]), v[2]] }; let pd = swap(lw, pd); @@ -370,9 +373,8 @@ impl Lw { let fin = lw.fcmp(Pred::FOLt, ax, pinf); hit = lw.land(hit, fin); } - (t, det, i, j, hit) + (t, det, i, j, hit, z) } else { - // Möller–Trumbore, the test before XCL_BVH_WATERTIGHT let e1 = lw.f3(v1, v0, Lw::fsub); let e2 = lw.f3(v2, v0, Lw::fsub); let p = lw.cross(dir, e2); @@ -382,6 +384,7 @@ impl Lw { let i = lw.dot3(sv, p); let j = lw.dot3(dir, q); let t = lw.dot3(e2, q); + let z = lw.fc(0.0); let ij = lw.fadd(i, j); let dpos = lw.fcmp(Pred::FOGt, det, z); let c1 = lw.fcmp(Pred::FOGe, i, z); @@ -396,7 +399,8 @@ impl Lw { let hn = lw.land(dneg, n1); let hn = lw.land(hn, n2); let hn = lw.land(hn, n3); - (t, det, i, j, lw.sel(dpos, hp, hn)) + let hit = lw.sel(dpos, hp, hn); + (t, det, i, j, hit, z) }; let di = lw.fsub(det, i); let b0 = lw.fsub(di, j); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8fae53a6e0..b58607d81f 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1,4 +1,8 @@ //! Instruction semantics: one RDNA2 instruction → HLSL statements. +//! +//! `BVH_TRIANGLE_WATERTIGHT` is adapted from victory-fork (https://github.com/fxceless/victory-fork, +//! GPL-3.0-or-later) `9a9091d`, `crates/victory-shader/src/bvh.rs` `triangle`, after Mesa RADV +//! (MIT, Copyright © 2021 Google) `intersect_ray_amd_software_tri`; changed 2026-11-27 (see `gpu/bvh.rs`). use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; @@ -5031,9 +5035,11 @@ static uint xcl_cap = 1u << 16; } let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); - // the BVH triangle test (`gpu::bvh::watertight`): part of the text, so of the DXC cache key - let _ = writeln!(h, "#define XCL_BVH_WATERTIGHT {}", crate::gpu::bvh::watertight() as u8); - h.push_str(PRELUDE_MEM); + if crate::gpu::bvh::watertight() && body.contains("bvh_intersect(") { + h.push_str(&bvh_watertight_prelude_mem()); + } else { + h.push_str(PRELUDE_MEM); + } if self.uses_scratch { h.push_str(PRELUDE_SCRATCH); } @@ -6256,6 +6262,55 @@ void scr_st(uint a, uint v, uint n) { } "#; +/// `bvh_intersect`'s Möller–Trumbore triangle test in `PRELUDE_MEM` (`XCL_BVH_WATERTIGHT` off). +pub(super) const BVH_TRIANGLE_MT: &str = r#" float3 e1 = v1 - v0, e2 = v2 - v0, p = cross(d, e2); + float det = dot(e1, p); + float3 sv = o - v0, q = cross(sv, e1); + float i = dot(sv, p), j = dot(d, q), t = dot(e2, q); + // inside when i, j, 1 - i - j >= 0 relative to det (either winding); avoid det * det underflow/overflow + bool hit = det > 0.0f ? (i >= 0.0f && j >= 0.0f && i + j <= det) : (det < 0.0f && i <= 0.0f && j <= 0.0f && i + j >= det); +"#; + +/// The watertight test that replaces `BVH_TRIANGLE_MT` with `XCL_BVH_WATERTIGHT=1`, as +/// `gpu::bvh::triangle_hit_watertight` (provenance in this file's header): shear so the ray runs +/// along its largest axis, signs of the edge functions decide; `precise` so that no product is +/// fused and a shared edge's function is exactly negated in the other triangle (a driver that +/// fuses anyway loses that). +const BVH_TRIANGLE_WATERTIGHT: &str = r#" float3 ad = abs(d); + uint kz = ad.x >= ad.y ? (ad.x >= ad.z ? 0u : 2u) : (ad.y >= ad.z ? 1u : 2u); + // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 + float3 pd = kz == 0u ? d.yzx : (kz == 1u ? d.zxy : d.xyz); + bool sw = pd.z < 0.0f; + pd = sw ? pd.yxz : pd; + precise float sz = 1.0f / pd.z; + precise float sx = pd.x * sz, sy = pd.y * sz; + float3 r0 = v0 - o, r1 = v1 - o, r2 = v2 - o; + r0 = kz == 0u ? r0.yzx : (kz == 1u ? r0.zxy : r0); r0 = sw ? r0.yxz : r0; + r1 = kz == 0u ? r1.yzx : (kz == 1u ? r1.zxy : r1); r1 = sw ? r1.yxz : r1; + r2 = kz == 0u ? r2.yzx : (kz == 1u ? r2.zxy : r2); r2 = sw ? r2.yxz : r2; + precise float3 p0 = float3(r0.x - sx * r0.z, r0.y - sy * r0.z, sz * r0.z); + precise float3 p1 = float3(r1.x - sx * r1.z, r1.y - sy * r1.z, sz * r1.z); + precise float3 p2 = float3(r2.x - sx * r2.z, r2.y - sy * r2.z, sz * r2.z); + precise float u = p2.x * p1.y - p2.y * p1.x; + precise float i = p0.x * p2.y - p0.y * p2.x; + precise float j = p1.x * p0.y - p1.y * p0.x; + bool mixed = (u < 0.0f || i < 0.0f || j < 0.0f) && (u > 0.0f || i > 0.0f || j > 0.0f); + precise float det = u + (i + j); + precise float t = (u * p0.z + i * p1.z) + j * p2.z; + // back to Möller–Trumbore's scale after the decision; edge-on (det = 0), NaN and a + // non-finite t or det miss + precise float s = abs(pd.z); + t = t * s; precise float dets = det * s; i = i * s; j = j * s; + bool hit = !mixed && (det > 0.0f || det < 0.0f) && !isinf(t) && !isnan(t) && !isinf(dets) && !isnan(dets); + det = dets; +"#; + +/// `PRELUDE_MEM` with the watertight triangle test (only for shaders that call `bvh_intersect`). +fn bvh_watertight_prelude_mem() -> String { + assert!(PRELUDE_MEM.contains(BVH_TRIANGLE_MT), "PRELUDE_MEM lost its triangle test"); + PRELUDE_MEM.replacen(BVH_TRIANGLE_MT, BVH_TRIANGLE_WATERTIGHT, 1) +} + const PRELUDE_MEM: &str = r#" uint4 ld_raw(uint a) { // one Load4 + one Load (with several memory windows each is a switch) and no branch @@ -6362,49 +6417,12 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i uint o1 = type == 0u ? 12u : (type == 3u ? 48u : 36u); uint o2 = type <= 1u ? 24u : (type == 2u ? 48u : 0u); float3 v0 = asfloat(mem.Load3(at + o0)), v1 = asfloat(mem.Load3(at + o1)), v2 = asfloat(mem.Load3(at + o2)); -#if XCL_BVH_WATERTIGHT - // watertight test as gpu::bvh::triangle_hit (Woop, Benthin, Wald 2013; adapted from - // victory-fork, https://github.com/fxceless/victory-fork, GPL-3.0-or-later, after Mesa - // RADV, MIT): shear so the ray runs along its largest axis, signs of the edge functions - // decide; `precise` so that no product is fused and a shared edge's function is exactly - // negated in the other triangle (DXC marks them so in the DXIL; a driver that fuses - // anyway loses that) - float3 ad = abs(d); - uint kz = ad.x >= ad.y ? (ad.x >= ad.z ? 0u : 2u) : (ad.y >= ad.z ? 1u : 2u); - // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 - float3 pd = kz == 0u ? d.yzx : (kz == 1u ? d.zxy : d.xyz); - bool sw = pd.z < 0.0f; - pd = sw ? pd.yxz : pd; - precise float sz = 1.0f / pd.z; - precise float sx = pd.x * sz, sy = pd.y * sz; - float3 r0 = v0 - o, r1 = v1 - o, r2 = v2 - o; - r0 = kz == 0u ? r0.yzx : (kz == 1u ? r0.zxy : r0); r0 = sw ? r0.yxz : r0; - r1 = kz == 0u ? r1.yzx : (kz == 1u ? r1.zxy : r1); r1 = sw ? r1.yxz : r1; - r2 = kz == 0u ? r2.yzx : (kz == 1u ? r2.zxy : r2); r2 = sw ? r2.yxz : r2; - precise float3 p0 = float3(r0.x - sx * r0.z, r0.y - sy * r0.z, sz * r0.z); - precise float3 p1 = float3(r1.x - sx * r1.z, r1.y - sy * r1.z, sz * r1.z); - precise float3 p2 = float3(r2.x - sx * r2.z, r2.y - sy * r2.z, sz * r2.z); - precise float u = p2.x * p1.y - p2.y * p1.x; - precise float i = p0.x * p2.y - p0.y * p2.x; - precise float j = p1.x * p0.y - p1.y * p0.x; - bool mixed = (u < 0.0f || i < 0.0f || j < 0.0f) && (u > 0.0f || i > 0.0f || j > 0.0f); - precise float det = u + (i + j); - precise float t = (u * p0.z + i * p1.z) + j * p2.z; - // back to Möller–Trumbore's scale after the decision; edge-on (det = 0), NaN and a - // non-finite t or det miss - precise float s = abs(pd.z); - t = t * s; precise float dets = det * s; i = i * s; j = j * s; - bool hit = !mixed && (det > 0.0f || det < 0.0f) && !isinf(t) && !isnan(t) && !isinf(dets) && !isnan(dets); - det = dets; -#else - // Möller–Trumbore, the test before XCL_BVH_WATERTIGHT float3 e1 = v1 - v0, e2 = v2 - v0, p = cross(d, e2); float det = dot(e1, p); float3 sv = o - v0, q = cross(sv, e1); float i = dot(sv, p), j = dot(d, q), t = dot(e2, q); // inside when i, j, 1 - i - j >= 0 relative to det (either winding); avoid det * det underflow/overflow bool hit = det > 0.0f ? (i >= 0.0f && j >= 0.0f && i + j <= det) : (det < 0.0f && i <= 0.0f && j <= 0.0f && i + j >= det); -#endif // barycentrics back to the original vertex order: triangle id @60, per triangle I / J source uint4 bc = asuint(float4(det - i - j, i, j, 0.0f)); uint tw = mem.Load(at + 60u); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 88c19dca61..8ca1b1a8f1 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6351,6 +6351,14 @@ fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { w(&mut mem, 0x40 * (axis + 1), &ff(&verts)); w(&mut mem, 0x40 * (axis + 1) + 48, &[0x80, 0, 1, 0x0909]); } + // nodes 4 and 5: the pinned pair of `bvh.rs` that Möller–Trumbore misses in both triangles, + // each as type 0 in the same vertex order (so the old test rounds as there), last two lanes + let (pa, pb) = ([1.911541f32, -2.025442, 0.78372467], [1.911541f32, 2.740394, -0.50947857]); + for (n, tri) in [[pa, pb, [2.1104007, -1.6796683, 9.487581]], [pb, pa, [1.5455573, 0.7414906, -8.11272]]].iter().enumerate() { + w(&mut mem, 0x100 + 0x40 * n, &ff(&tri.concat())); + w(&mut mem, 0x100 + 0x40 * n + 48, &[0, 0, 1, 0x0909]); + } + let pinned_ray = ([5.911541f32, -0.8080063, 0.59203976], [-1.0f32, -0.13060194, 0.000772506], 3usize); let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap(); code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let mut st = KernelState::default(); @@ -6368,9 +6376,12 @@ fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { d[axis] = if (l / 6) % 2 == 0 { 1.0 } else { -1.0 }; ray = ([0, 1, 2].map(|a| on[a] - 3.0 * d[a]), d, axis); } + if l >= 62 { + ray = pinned_ray; + } let (o, d, axis) = ray; let inv = d.map(|x| 1.0 / x); - let node = ((0x40 * (axis as u32 + 1)) >> 3) | (l as u32 % 2); + let node = if axis == 3 { (0x100 + 0x40 * (l as u32 % 2)) >> 3 } else { ((0x40 * (axis as u32 + 1)) >> 3) | (l as u32 % 2) }; v[0] = node; for (k, x) in [100.0f32, o[0], o[1], o[2], d[0], d[1], d[2], inv[0], inv[1], inv[2]].iter().enumerate() { v[1 + k] = x.to_bits(); @@ -6389,20 +6400,27 @@ fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { assert!(ch[0] || ch[1], "lanes {} and {l}: CPU ray through the shared edge missed both", l - 1); } } + // the pinned lanes separate the tests: the old one (switch off) misses both there + let ((n0, o, d, inv), n1) = (rays[62], rays[63].0); + let mt = |n| f32::from_bits(bvh::tests::with_watertight(false, || bvh::intersect_node(&data, n, 100.0, o, d, inv, true))[0]); + assert!(mt(n0).is_infinite() && mt(n1).is_infinite(), "Möller–Trumbore hits the pinned pair"); } -/// `XCL_BVH_WATERTIGHT` selects the triangle test in the HLSL (a `#define`, so the text and -/// DXC's cache key differ) and in the direct DXIL (other bytes); off is Möller–Trumbore. +/// `XCL_BVH_WATERTIGHT` selects the triangle test in the HLSL and in the direct DXIL. Off, the +/// HLSL has main's Möller–Trumbore text and nothing of the switch (DXC cache keys unchanged); +/// on, only a program that calls `bvh_intersect` changes. #[test] fn bvh_watertight_switch_changes_the_hlsl_and_the_dxil() { use crate::gpu::bvh::tests::with_watertight; let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap(); code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); - let hlsl = |on| with_watertight(on, || translate(&code, &Options::default()).unwrap().hlsl); - let (off, on) = (hlsl(false), hlsl(true)); - assert!(off.contains("#define XCL_BVH_WATERTIGHT 0") && on.contains("#define XCL_BVH_WATERTIGHT 1")); - assert!(off.contains("#if XCL_BVH_WATERTIGHT") && off.contains("p = cross(d, e2)")); - assert_ne!(off, on); + let hlsl = |code: &[u8], on| with_watertight(on, || translate(code, &Options::default()).unwrap().hlsl); + let (off, on) = (hlsl(&code, false), hlsl(&code, true)); + assert!(!off.contains("XCL_BVH_WATERTIGHT") && !on.contains("XCL_BVH_WATERTIGHT")); + assert!(off.contains(super::emit::BVH_TRIANGLE_MT) && !off.contains("precise float sz")); + assert!(on.contains("precise float sz") && !on.contains("p = cross(d, e2)")); + let plain = prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None)]); + assert_eq!(hlsl(&plain, false), hlsl(&plain, true), "a program without BVH changed"); let dxil = |on| with_watertight(on, || runner::direct_kernel(&code, true)); match (dxil(false), dxil(true)) { (Ok(off), Ok(on)) => assert_ne!(off, on, "direct DXIL is the same with and without the switch"), From 7865254e68c30bea88b05888e079c37a556b6493 Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:59:50 +0000 Subject: [PATCH 5/6] Recompiler: indent the two BVH triangle branches in the DXIL lowering --- crates/xcl/src/gpu/dxil/lower_image.rs | 210 ++++++++++++------------- 1 file changed, 105 insertions(+), 105 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index 72a6afdf7a..430e74c31d 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -295,112 +295,112 @@ impl Lw { // DisableMathRefactoring when it also uses FMad (shader.rs), and a driver may then // fuse these products, which loses the exact negation (no worse than before) let (t, det, i, j, hit, z) = if crate::gpu::bvh::watertight() { - lw.s.require(super::shader::Feature::DisableMathRefactoring); - let ad = [lw.fabs(dir[0]), lw.fabs(dir[1]), lw.fabs(dir[2])]; - let xy = lw.fcmp(Pred::FOGe, ad[0], ad[1]); - let xz = lw.fcmp(Pred::FOGe, ad[0], ad[2]); - let yz = lw.fcmp(Pred::FOGe, ad[1], ad[2]); - let nxy = lw.lnot(xy); - let kz0 = lw.land(xy, xz); - let kz1 = lw.land(nxy, yz); - // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 - let perm = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { - let x = lw.sel(kz1, v[2], v[0]); - let x = lw.sel(kz0, v[1], x); - let y = lw.sel(kz1, v[0], v[1]); - let y = lw.sel(kz0, v[2], y); - let z = lw.sel(kz1, v[1], v[2]); - let z = lw.sel(kz0, v[0], z); - [x, y, z] - }; - let pd = perm(lw, dir); - let z = lw.fc(0.0); - let sw = lw.fcmp(Pred::FOLt, pd[2], z); - let swap = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { [lw.sel(sw, v[1], v[0]), lw.sel(sw, v[0], v[1]), v[2]] }; - let pd = swap(lw, pd); - let one = lw.fc(1.0); - let sz = lw.fdiv(one, pd[2]); - let sx = lw.fmul(pd[0], sz); - let sy = lw.fmul(pd[1], sz); - let mut sh = [[z; 3]; 3]; - for (k, v) in [v0, v1, v2].into_iter().enumerate() { - let r = lw.f3(v, o, Lw::fsub); - let r = perm(lw, r); - let r = swap(lw, r); - let ax = lw.fmul(sx, r[2]); - let ay = lw.fmul(sy, r[2]); - sh[k] = [lw.fsub(r[0], ax), lw.fsub(r[1], ay), lw.fmul(sz, r[2])]; - } - let [p0, p1, p2] = sh; - let edge = |lw: &mut Lw, a: [Value; 3], b: [Value; 3]| { - let m0 = lw.fmul(a[0], b[1]); - let m1 = lw.fmul(a[1], b[0]); - lw.fsub(m0, m1) - }; - let u = edge(lw, p2, p1); - let i = edge(lw, p0, p2); - let j = edge(lw, p1, p0); - let mut neg = lw.fcmp(Pred::FOLt, u, z); - let mut pos = lw.fcmp(Pred::FOGt, u, z); - for e in [i, j] { - let n = lw.fcmp(Pred::FOLt, e, z); - neg = lw.lor(neg, n); - let p = lw.fcmp(Pred::FOGt, e, z); - pos = lw.lor(pos, p); - } - let mixed = lw.land(neg, pos); - let ij = lw.fadd(i, j); - let det = lw.fadd(u, ij); - let tu = lw.fmul(u, p0[2]); - let ti = lw.fmul(i, p1[2]); - let tj = lw.fmul(j, p2[2]); - let t = lw.fadd(tu, ti); - let t = lw.fadd(t, tj); - // back to Möller–Trumbore's scale after the decision; edge-on (det = 0), NaN and a - // non-finite t or det miss - let dpos = lw.fcmp(Pred::FOGt, det, z); - let dneg = lw.fcmp(Pred::FOLt, det, z); - let dnz = lw.lor(dpos, dneg); - let inside = lw.lnot(mixed); - let hit = lw.land(inside, dnz); - let s = lw.fabs(pd[2]); - let (t, det, i, j) = (lw.fmul(t, s), lw.fmul(det, s), lw.fmul(i, s), lw.fmul(j, s)); - let pinf = lw.fc(f32::INFINITY); - let mut hit = hit; - for x in [t, det] { - // |x| < inf is false for inf and NaN - let ax = lw.fabs(x); - let fin = lw.fcmp(Pred::FOLt, ax, pinf); - hit = lw.land(hit, fin); - } - (t, det, i, j, hit, z) + lw.s.require(super::shader::Feature::DisableMathRefactoring); + let ad = [lw.fabs(dir[0]), lw.fabs(dir[1]), lw.fabs(dir[2])]; + let xy = lw.fcmp(Pred::FOGe, ad[0], ad[1]); + let xz = lw.fcmp(Pred::FOGe, ad[0], ad[2]); + let yz = lw.fcmp(Pred::FOGe, ad[1], ad[2]); + let nxy = lw.lnot(xy); + let kz0 = lw.land(xy, xz); + let kz1 = lw.land(nxy, yz); + // (kz + 1, kz + 2, kz), the first two swapped when d[kz] < 0 + let perm = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { + let x = lw.sel(kz1, v[2], v[0]); + let x = lw.sel(kz0, v[1], x); + let y = lw.sel(kz1, v[0], v[1]); + let y = lw.sel(kz0, v[2], y); + let z = lw.sel(kz1, v[1], v[2]); + let z = lw.sel(kz0, v[0], z); + [x, y, z] + }; + let pd = perm(lw, dir); + let z = lw.fc(0.0); + let sw = lw.fcmp(Pred::FOLt, pd[2], z); + let swap = |lw: &mut Lw, v: [Value; 3]| -> [Value; 3] { [lw.sel(sw, v[1], v[0]), lw.sel(sw, v[0], v[1]), v[2]] }; + let pd = swap(lw, pd); + let one = lw.fc(1.0); + let sz = lw.fdiv(one, pd[2]); + let sx = lw.fmul(pd[0], sz); + let sy = lw.fmul(pd[1], sz); + let mut sh = [[z; 3]; 3]; + for (k, v) in [v0, v1, v2].into_iter().enumerate() { + let r = lw.f3(v, o, Lw::fsub); + let r = perm(lw, r); + let r = swap(lw, r); + let ax = lw.fmul(sx, r[2]); + let ay = lw.fmul(sy, r[2]); + sh[k] = [lw.fsub(r[0], ax), lw.fsub(r[1], ay), lw.fmul(sz, r[2])]; + } + let [p0, p1, p2] = sh; + let edge = |lw: &mut Lw, a: [Value; 3], b: [Value; 3]| { + let m0 = lw.fmul(a[0], b[1]); + let m1 = lw.fmul(a[1], b[0]); + lw.fsub(m0, m1) + }; + let u = edge(lw, p2, p1); + let i = edge(lw, p0, p2); + let j = edge(lw, p1, p0); + let mut neg = lw.fcmp(Pred::FOLt, u, z); + let mut pos = lw.fcmp(Pred::FOGt, u, z); + for e in [i, j] { + let n = lw.fcmp(Pred::FOLt, e, z); + neg = lw.lor(neg, n); + let p = lw.fcmp(Pred::FOGt, e, z); + pos = lw.lor(pos, p); + } + let mixed = lw.land(neg, pos); + let ij = lw.fadd(i, j); + let det = lw.fadd(u, ij); + let tu = lw.fmul(u, p0[2]); + let ti = lw.fmul(i, p1[2]); + let tj = lw.fmul(j, p2[2]); + let t = lw.fadd(tu, ti); + let t = lw.fadd(t, tj); + // back to Möller–Trumbore's scale after the decision; edge-on (det = 0), NaN and a + // non-finite t or det miss + let dpos = lw.fcmp(Pred::FOGt, det, z); + let dneg = lw.fcmp(Pred::FOLt, det, z); + let dnz = lw.lor(dpos, dneg); + let inside = lw.lnot(mixed); + let hit = lw.land(inside, dnz); + let s = lw.fabs(pd[2]); + let (t, det, i, j) = (lw.fmul(t, s), lw.fmul(det, s), lw.fmul(i, s), lw.fmul(j, s)); + let pinf = lw.fc(f32::INFINITY); + let mut hit = hit; + for x in [t, det] { + // |x| < inf is false for inf and NaN + let ax = lw.fabs(x); + let fin = lw.fcmp(Pred::FOLt, ax, pinf); + hit = lw.land(hit, fin); + } + (t, det, i, j, hit, z) } else { - let e1 = lw.f3(v1, v0, Lw::fsub); - let e2 = lw.f3(v2, v0, Lw::fsub); - let p = lw.cross(dir, e2); - let det = lw.dot3(e1, p); - let sv = lw.f3(o, v0, Lw::fsub); - let q = lw.cross(sv, e1); - let i = lw.dot3(sv, p); - let j = lw.dot3(dir, q); - let t = lw.dot3(e2, q); - let z = lw.fc(0.0); - let ij = lw.fadd(i, j); - let dpos = lw.fcmp(Pred::FOGt, det, z); - let c1 = lw.fcmp(Pred::FOGe, i, z); - let c2 = lw.fcmp(Pred::FOGe, j, z); - let c3 = lw.fcmp(Pred::FOLe, ij, det); - let hp = lw.land(c1, c2); - let hp = lw.land(hp, c3); - let dneg = lw.fcmp(Pred::FOLt, det, z); - let n1 = lw.fcmp(Pred::FOLe, i, z); - let n2 = lw.fcmp(Pred::FOLe, j, z); - let n3 = lw.fcmp(Pred::FOGe, ij, det); - let hn = lw.land(dneg, n1); - let hn = lw.land(hn, n2); - let hn = lw.land(hn, n3); - let hit = lw.sel(dpos, hp, hn); - (t, det, i, j, hit, z) + let e1 = lw.f3(v1, v0, Lw::fsub); + let e2 = lw.f3(v2, v0, Lw::fsub); + let p = lw.cross(dir, e2); + let det = lw.dot3(e1, p); + let sv = lw.f3(o, v0, Lw::fsub); + let q = lw.cross(sv, e1); + let i = lw.dot3(sv, p); + let j = lw.dot3(dir, q); + let t = lw.dot3(e2, q); + let z = lw.fc(0.0); + let ij = lw.fadd(i, j); + let dpos = lw.fcmp(Pred::FOGt, det, z); + let c1 = lw.fcmp(Pred::FOGe, i, z); + let c2 = lw.fcmp(Pred::FOGe, j, z); + let c3 = lw.fcmp(Pred::FOLe, ij, det); + let hp = lw.land(c1, c2); + let hp = lw.land(hp, c3); + let dneg = lw.fcmp(Pred::FOLt, det, z); + let n1 = lw.fcmp(Pred::FOLe, i, z); + let n2 = lw.fcmp(Pred::FOLe, j, z); + let n3 = lw.fcmp(Pred::FOGe, ij, det); + let hn = lw.land(dneg, n1); + let hn = lw.land(hn, n2); + let hn = lw.land(hn, n3); + let hit = lw.sel(dpos, hp, hn); + (t, det, i, j, hit, z) }; let di = lw.fsub(det, i); let b0 = lw.fsub(di, j); From 5b45711dde12f3877d669bea5200a24c0c2b800e Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:34:00 +0000 Subject: [PATCH 6/6] Recompiler: watertight BVH triangle misses coplanar rays and zero denominators Three finite binary32 inputs from the #3038 review, reproduced on the CPU reference, the HLSL and the direct DXIL before this change: - coplanar ray (Moller-Trumbore det exactly 0, rounded sheared det -2^-23): returned a hit. The hit now also needs Moller-Trumbore's det of the original ray and plane (f32, same operation order in all three) to have the sheared det's sign. - tiny d[kz] (2^-60): u*p0.z etc. overflowed and a finite interior hit (-2^80, -1, -1/4, -1/4) was lost. The weighted depths now use the unscaled axial distances and only d[kz]'s sign is applied (exact), which is t*det at Moller-Trumbore's scale without the 1/d[kz] and |d[kz]| round trip. Now returns Moller-Trumbore's values bit for bit. - encoded det = sheared det * |d[kz]| rounding to 0 (-2^-80 * 2^-80): returned a hit with denominator -0. The encoded det must now be a normal number, so it is never 0, also on a GPU that flushes subnormals. The edge functions and their sign decision are unchanged, so the shared edge property is the same. Default path (XCL_BVH_WATERTIGHT off) untouched. --- crates/xcl/src/gpu/bvh.rs | 61 +++++++++++++++++++++++--- crates/xcl/src/gpu/dxil/lower_image.rs | 35 ++++++++++++--- crates/xcl/src/gpu/recomp/emit.rs | 22 +++++++--- crates/xcl/src/gpu/recomp/tests.rs | 46 +++++++++++++++++++ 4 files changed, 143 insertions(+), 21 deletions(-) diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index 142116892c..cd4a85d15e 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -296,9 +296,10 @@ fn triangle_hit_watertight(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f3 let (kx, ky) = if d[kz] < 0.0 { ((kz + 2) % 3, (kz + 1) % 3) } else { ((kz + 1) % 3, (kz + 2) % 3) }; let sz = 1.0 / d[kz]; let (sx, sy) = (d[kx] * sz, d[ky] * sz); + // (x, y) sheared, z the unscaled axial distance from the origin let shear = |p: [f32; 3]| { let r = sub(p, o); - [r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz]] + [r[kx] - sx * r[kz], r[ky] - sy * r[kz], r[kz]] }; let (p0, p1, p2) = (shear(v[0]), shear(v[1]), shear(v[2])); // edge functions: the barycentric numerators of v0, v1, v2 @@ -307,12 +308,24 @@ fn triangle_hit_watertight(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f3 let j = p1[0] * p0[1] - p1[1] * p0[0]; let mixed = (u < 0.0 || i < 0.0 || j < 0.0) && (u > 0.0 || i > 0.0 || j > 0.0); let det = u + (i + j); - let t = (u * p0[2] + i * p1[2]) + j * p2[2]; + // Möller–Trumbore's t·det is the depth sum over the sheared det times |d[kz]| / d[kz]: + // with the unscaled depths only d[kz]'s sign is left (exact), so nothing overflows that + // the old t·det does not + let tz = (u * p0[2] + i * p1[2]) + j * p2[2]; + let t = if d[kz] < 0.0 { -tz } else { tz }; // back to Möller–Trumbore's scale (the sheared determinant is its det / |d[kz]|), after - // the decision; a non-finite t or det (tiny d[kz], huge shear) misses + // the decision let s = d[kz].abs(); - let r = [t * s, det * s, i * s, j * s]; - (!mixed && (det > 0.0 || det < 0.0) && r[0].is_finite() && r[1].is_finite()).then_some(r) + let r = [t, det * s, i * s, j * s]; + // the plane's own orientation (Möller–Trumbore's det, as `triangle_hit_mt`) must agree with + // the sheared det's sign: a ray in (or within rounding of) the plane misses even when the + // rounded sheared det is not 0 + let mt = dot(sub(v[1], v[0]), cross(d, sub(v[2], v[0]))); + let facing = (det > 0.0 && mt > 0.0) || (det < 0.0 && mt < 0.0); + // the traversal divides by the encoded det: a normal number, so never 0 (also where a GPU + // flushes subnormals); a non-finite t or det misses + let normal = r[1].abs() >= f32::MIN_POSITIVE; + (!mixed && facing && normal && r[0].is_finite() && r[1].is_finite()).then_some(r) } /// The ray's largest axis (ties: x before y before z), along which `triangle_hit` shears. @@ -1315,8 +1328,8 @@ pub(crate) mod tests { } /// The watertight test's edge cases: degenerate triangles, rays in the triangle's plane, a - /// zero direction and NaN miss; a tiny largest component with a far triangle overflows the - /// sheared depth and misses; the node then returns its miss encoding, never a NaN. Equal + /// zero direction and NaN miss; a tiny largest component (1e-38) gives a subnormal + /// encoded det and misses; the node then returns its miss encoding, never a NaN. Equal /// largest components pick the first axis (x before y before z), as the HLSL and DXIL `kz`. #[test] fn triangle_hit_degenerate_non_finite_and_axis_ties() { @@ -1363,6 +1376,40 @@ pub(crate) mod tests { } } + /// Review cases of #3038 (finite binary32 inputs; `p` = 2^p): + /// 1. a ray in the triangle's plane (Möller–Trumbore's det is exactly 0) whose rounded + /// sheared determinant is not 0 misses; + /// 2. a finite interior hit whose weighted sheared depths overflow (tiny d[kz]) still hits, + /// with Möller–Trumbore's values; + /// 3. a hit whose encoded determinant (sheared det · |d[kz]|) rounds to 0 misses, so the + /// traversal never divides by a zero denominator. + pub(crate) fn review_cases() -> [(Triangle, [f32; 3], [f32; 3]); 3] { + let p = |e: i32| 2f32.powi(e); + [ + ([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [4.0, 5.0, 6.0]], [-1.0, -2.0, -3.0], [1.0, 2.0, 3.0]), + ([[0.0, 0.0, p(20)], [p(30), 0.0, p(20)], [0.0, p(30), p(20)]], [p(28), p(28), 0.0], [0.0, 0.0, p(-60)]), + ([[0.0, 0.0, 1.0], [p(-40), 0.0, 1.0], [0.0, p(-40), 1.0]], [p(-42), p(-42), 0.0], [0.0, 0.0, p(-80)]), + ] + } + + #[test] + fn triangle_hit_review_cases_coplanar_overflow_zero_denominator() { + let [c1, c2, c3] = review_cases(); + for (k, (t, o, d)) in review_cases().iter().enumerate() { + eprintln!("case {}: watertight {:?} mt {:?}", k + 1, triangle_hit_watertight(t, *o, *d), triangle_hit_mt(t, *o, *d)); + } + assert_eq!(triangle_hit_mt(&c1.0, c1.1, c1.2), None); + assert_eq!(triangle_hit_watertight(&c1.0, c1.1, c1.2), None, "coplanar ray"); + let p = |e: i32| 2f32.powi(e); + assert_eq!(triangle_hit_mt(&c2.0, c2.1, c2.2), Some([-p(80), -1.0, -0.25, -0.25])); + assert_eq!(triangle_hit_watertight(&c2.0, c2.1, c2.2), Some([-p(80), -1.0, -0.25, -0.25]), "overflowed depth"); + assert_eq!(triangle_hit_watertight(&c3.0, c3.1, c3.2), None, "zero denominator"); + // the same small triangle with a unit direction is a valid hit and still hits + let unit = [0.0, 0.0, 1.0]; + assert_eq!(triangle_hit_watertight(&c3.0, c3.1, unit), triangle_hit_mt(&c3.0, c3.1, unit)); + assert!(triangle_hit_watertight(&c3.0, c3.1, unit).is_some()); + } + thread_local! { /// `watertight()` for this test thread only (`None`: `XCL_BVH_WATERTIGHT`) pub(crate) static WATERTIGHT: std::cell::Cell> = const { std::cell::Cell::new(None) }; diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index 430e74c31d..29f5badf4a 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -329,7 +329,8 @@ impl Lw { let r = swap(lw, r); let ax = lw.fmul(sx, r[2]); let ay = lw.fmul(sy, r[2]); - sh[k] = [lw.fsub(r[0], ax), lw.fsub(r[1], ay), lw.fmul(sz, r[2])]; + // (x, y) sheared, z the unscaled axial distance from the origin + sh[k] = [lw.fsub(r[0], ax), lw.fsub(r[1], ay), r[2]]; } let [p0, p1, p2] = sh; let edge = |lw: &mut Lw, a: [Value; 3], b: [Value; 3]| { @@ -356,17 +357,37 @@ impl Lw { let tj = lw.fmul(j, p2[2]); let t = lw.fadd(tu, ti); let t = lw.fadd(t, tj); - // back to Möller–Trumbore's scale after the decision; edge-on (det = 0), NaN and a - // non-finite t or det miss + // Möller–Trumbore's t·det: the unscaled depth sum with d[kz]'s sign + let tn = lw.fneg(t); + let t = lw.sel(sw, tn, t); + // the plane's orientation (Möller–Trumbore's det, gpu::bvh order) must agree + // with the sheared det's sign; edge-on, NaN miss + let e1 = lw.f3(v1, v0, Lw::fsub); + let e2 = lw.f3(v2, v0, Lw::fsub); + let c = lw.cross(dir, e2); + let m0 = lw.fmul(e1[0], c[0]); + let m1 = lw.fmul(e1[1], c[1]); + let m2 = lw.fmul(e1[2], c[2]); + let mt = lw.fadd(m0, m1); + let mt = lw.fadd(mt, m2); let dpos = lw.fcmp(Pred::FOGt, det, z); let dneg = lw.fcmp(Pred::FOLt, det, z); - let dnz = lw.lor(dpos, dneg); + let mpos = lw.fcmp(Pred::FOGt, mt, z); + let mneg = lw.fcmp(Pred::FOLt, mt, z); + let fp = lw.land(dpos, mpos); + let fneg = lw.land(dneg, mneg); + let facing = lw.lor(fp, fneg); let inside = lw.lnot(mixed); - let hit = lw.land(inside, dnz); + let hit = lw.land(inside, facing); + // back to Möller–Trumbore's scale after the decision; the encoded det is a normal + // number (never 0 for the traversal), a non-finite t or det misses let s = lw.fabs(pd[2]); - let (t, det, i, j) = (lw.fmul(t, s), lw.fmul(det, s), lw.fmul(i, s), lw.fmul(j, s)); + let (det, i, j) = (lw.fmul(det, s), lw.fmul(i, s), lw.fmul(j, s)); + let adet = lw.fabs(det); + let fmin = lw.fc(f32::MIN_POSITIVE); + let normal = lw.fcmp(Pred::FOGe, adet, fmin); let pinf = lw.fc(f32::INFINITY); - let mut hit = hit; + let mut hit = lw.land(hit, normal); for x in [t, det] { // |x| < inf is false for inf and NaN let ax = lw.fabs(x); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index b58607d81f..35444c8e25 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -6288,20 +6288,28 @@ const BVH_TRIANGLE_WATERTIGHT: &str = r#" float3 ad = abs(d); r0 = kz == 0u ? r0.yzx : (kz == 1u ? r0.zxy : r0); r0 = sw ? r0.yxz : r0; r1 = kz == 0u ? r1.yzx : (kz == 1u ? r1.zxy : r1); r1 = sw ? r1.yxz : r1; r2 = kz == 0u ? r2.yzx : (kz == 1u ? r2.zxy : r2); r2 = sw ? r2.yxz : r2; - precise float3 p0 = float3(r0.x - sx * r0.z, r0.y - sy * r0.z, sz * r0.z); - precise float3 p1 = float3(r1.x - sx * r1.z, r1.y - sy * r1.z, sz * r1.z); - precise float3 p2 = float3(r2.x - sx * r2.z, r2.y - sy * r2.z, sz * r2.z); + // (x, y) sheared, z the unscaled axial distance from the origin + precise float3 p0 = float3(r0.x - sx * r0.z, r0.y - sy * r0.z, r0.z); + precise float3 p1 = float3(r1.x - sx * r1.z, r1.y - sy * r1.z, r1.z); + precise float3 p2 = float3(r2.x - sx * r2.z, r2.y - sy * r2.z, r2.z); precise float u = p2.x * p1.y - p2.y * p1.x; precise float i = p0.x * p2.y - p0.y * p2.x; precise float j = p1.x * p0.y - p1.y * p0.x; bool mixed = (u < 0.0f || i < 0.0f || j < 0.0f) && (u > 0.0f || i > 0.0f || j > 0.0f); precise float det = u + (i + j); + // Möller–Trumbore's t·det: the unscaled depth sum with d[kz]'s sign precise float t = (u * p0.z + i * p1.z) + j * p2.z; - // back to Möller–Trumbore's scale after the decision; edge-on (det = 0), NaN and a - // non-finite t or det miss + t = pd.z < 0.0f ? -t : t; + // the plane's orientation (Möller–Trumbore's det) must agree with the sheared det's sign + precise float3 e1 = v1 - v0, e2 = v2 - v0; + precise float3 c = float3(d.y * e2.z - d.z * e2.y, d.z * e2.x - d.x * e2.z, d.x * e2.y - d.y * e2.x); + precise float mt = (e1.x * c.x + e1.y * c.y) + e1.z * c.z; + bool facing = (det > 0.0f && mt > 0.0f) || (det < 0.0f && mt < 0.0f); + // back to Möller–Trumbore's scale after the decision; the encoded det is a normal + // number (never 0 for the traversal), a non-finite t or det misses precise float s = abs(pd.z); - t = t * s; precise float dets = det * s; i = i * s; j = j * s; - bool hit = !mixed && (det > 0.0f || det < 0.0f) && !isinf(t) && !isnan(t) && !isinf(dets) && !isnan(dets); + precise float dets = det * s; i = i * s; j = j * s; + bool hit = !mixed && facing && abs(dets) >= 1.17549435e-38f && !isinf(t) && !isnan(t) && !isinf(dets) && !isnan(dets); det = dets; "#; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 8ca1b1a8f1..84d5abca18 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6406,6 +6406,52 @@ fn gpu_bvh_triangle_pair_shared_edge_is_watertight() { assert!(mt(n0).is_infinite() && mt(n1).is_infinite(), "Möller–Trumbore hits the pinned pair"); } +/// The #3038 review cases (`bvh::tests::review_cases`: coplanar ray, overflowing sheared depth, +/// zero encoded denominator) plus the small triangle with a unit direction, one per lane, with +/// the watertight test on the GPU (HLSL, or the direct DXIL with `XCL_DIRECT_DXIL=1`): the node +/// result is the CPU reference's bit for bit, and hit / miss is as the review expects. +#[test] +fn gpu_bvh_watertight_review_cases_match_the_cpu() { + use crate::gpu::bvh; + if !gpu_ready() { + return; + } + let base = 0x1000usize; + let mut mem = vec![0u32; 0x2000 / 4]; + let w = |mem: &mut Vec, at: usize, vals: &[u32]| mem[(base + at) / 4..(base + at) / 4 + vals.len()].copy_from_slice(vals); + let [c1, c2, c3] = bvh::tests::review_cases(); + let cases = [(c1, false), (c2, true), (c3, false), ((c3.0, c3.1, [0.0, 0.0, 1.0]), true)]; + for (k, ((tri, _, _), _)) in cases.iter().enumerate() { + let v: Vec = tri.concat().iter().map(|x| x.to_bits()).collect(); + w(&mut mem, 0x40 * (k + 1), &v); + w(&mut mem, 0x40 * (k + 1) + 48, &[0, 0, 1, 0x0909]); + } + let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 1 << 24]); // word 3 bit 24: barycentric result (mode 1) + let lane = |l: usize| (l % cases.len(), (0x40 * (l % cases.len() as usize + 1) as u32) >> 3); + for (l, v) in st.vgpr.iter_mut().enumerate() { + let (k, node) = lane(l); + let ((_, o, d), _) = cases[k]; + let inv = d.map(|x| 1.0 / x); + v[0] = node; + for (n, x) in [f32::MAX, o[0], o[1], o[2], d[0], d[1], d[2], inv[0], inv[1], inv[2]].iter().enumerate() { + v[1 + n] = x.to_bits(); + } + } + let res = bvh::tests::with_watertight(true, || runner::run_code(&code, &st, &mem)).unwrap(); + let data: Vec = mem[base / 4..].iter().flat_map(|x| x.to_le_bytes()).collect(); + for l in 0..cases.len() { + let (k, node) = lane(l); + let ((_, o, d), hit) = cases[k]; + let cpu = bvh::tests::with_watertight(true, || bvh::intersect_node(&data, node, f32::MAX, o, d, d.map(|x| 1.0 / x), true)); + let gpu: [u32; 4] = res.vgpr[l][100..104].try_into().unwrap(); + assert_eq!(gpu, cpu, "case {}: GPU {:?} CPU {:?}", k + 1, gpu.map(f32::from_bits), cpu.map(f32::from_bits)); + assert_eq!(f32::from_bits(cpu[0]).is_finite(), hit, "case {}: {:?}", k + 1, cpu.map(f32::from_bits)); + } +} + /// `XCL_BVH_WATERTIGHT` selects the triangle test in the HLSL and in the direct DXIL. Off, the /// HLSL has main's Möller–Trumbore text and nothing of the switch (DXC cache keys unchanged); /// on, only a program that calls `bvh_intersect` changes.