Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions THIRD_PARTY.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +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`, 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 |
Expand Down
285 changes: 284 additions & 1 deletion crates/xcl/src/gpu/bvh.rs

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"))?
Expand Down
164 changes: 139 additions & 25 deletions crates/xcl/src/gpu/dxil/lower_image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -284,31 +289,140 @@ 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);
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);
// `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]);
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]);
// (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]| {
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);
// 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 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, 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 (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 = lw.land(hit, normal);
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 di = lw.fsub(det, i);
let b0 = lw.fsub(di, j);
let bc = [b0, i, j, z];
Expand Down
67 changes: 66 additions & 1 deletion crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
@@ -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 _;
Expand Down Expand Up @@ -5031,7 +5035,11 @@ static uint xcl_cap = 1u << 16;
}
let infos: Vec<String> = (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(", "));
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);
}
Expand Down Expand Up @@ -6254,6 +6262,63 @@ 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;
// (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;
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);
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;
"#;

/// `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
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")))
Expand Down
Loading
Loading