Repository navigation
Description
Decision needed
May solidcraft-gpu contain one unsafe expression, so that the GPU path tracer can use hardware ray tracing? The expression is unsafe { wgpu::ExperimentalFeatures::enabled() }, the token wgpu 30 requires before a device can request Features::EXPERIMENTAL_RAY_QUERY.
Today the workspace has unsafe_code = "forbid". AGENTS.md lists three exceptions, all in the app crate, each because no safe API exists. This would be a fourth exception of the same kind: no safe API exists for this either.
Why it matters
The path tracer (#2067, #2191) traces rays through a software BVH in a WGSL compute shader. Ray traversal dominates render time: on an NVIDIA GB10, the 1080p coffee-machine scene with glass takes about 50 s at 256 spp. Every NVIDIA RTX, AMD RDNA2+ and recent Intel Arc GPU has dedicated ray tracing hardware that we leave idle.
Hardware ray queries are item 5 of the 1.0 must-haves in the roadmap (#3151). They are also the foundation of its 2.0 real-time ray-traced viewport (item 22). We expect a large speed-up, but we'll measure it in the prototype rather than promise it here.
What exactly needs unsafe (wgpu 30.0.1)
wgpu::ExperimentalFeatures::enabled()is aconst unsafe fn. It returns the token passed inDeviceDescriptor::experimental_features, and every feature namedEXPERIMENTAL_*is refused without it.- Its documented safety contract is: "You acknowledge that there may be UB-containing bugs in these APIs and those may be hit by calling otherwise safe code. You agree to report any such bugs to us."
- Everything else is safe Rust:
Device::create_blas,Device::create_tlas,CommandEncoder::build_acceleration_structures, andray_queryin WGSL. - The real risk isn't our unsafe line. It's that wgpu marks the feature experimental, so wgpu or driver bugs on this path could cause undefined behaviour or a GPU fault instead of an error.
Proposal
- Isolate it. One module, e.g.
crates/gpu/src/path/hardware.rs, with#![allow(unsafe_code)]and a module comment explaining the contract, as inapps/solidcraft/src/native_crash.rs.solidcraft-gpuchanges fromforbidtodeny, as the app crate did.- Nothing else in the crate may use
unsafe.
- Off by default, opt-in at runtime. Hardware ray tracing is used only when:
- the adapter reports
EXPERIMENTAL_RAY_QUERY; - the backend is one wgpu supports for it (wgpu 30 documents ray queries for Vulkan);
- a setting or environment variable enables it.
Otherwise, and on any device or pipeline error, the existing software BVH path runs, unchanged. A bad driver costs speed, never a render.
- the adapter reports
- Same results.
- The hardware path must pass the existing oracle tests: glass, MIS, shadows and denoiser.
- Closed-glass robustness depends on our exact-arithmetic hit ordering. So for transmissive bodies the hardware traversal may only return candidate hits, and the existing precise tie-breaking decides between them. A failing glass test blocks shipping.
- CI. Tests run where the hardware exists, on the GB10 and RTX 4090 self-hosted runners. Lavapipe keeps testing the software path. Whether lavapipe's own ray-query support is good enough to test against is checked during the prototype.
- Revisit the opt-in when wgpu drops the
EXPERIMENTAL_prefix and the token. At that point theunsafegoes away.
Related decision (optional, same reasoning)
Device::create_pipeline_cache is also unsafe in wgpu 30. A persistent pipeline cache would avoid recompiling the path shader at every launch, which would help both #3217 (about 2 h FXC compiles on DX12) and CI. If the maintainers accept item 1 for ray queries, they could allow pipeline caching in the same isolated module.
Asks for the maintainers
- Accept or reject the exception in
solidcraft-gpuforExperimentalFeatures::enabled(). - Optional: also accept
create_pipeline_cache. - Agree that it ships off by default, behind an opt-in.
If it's accepted, the next step is a prototype PR stacked on #2191: hardware traversal for opaque geometry first, benchmarked on the GB10 and RTX 4090, interleaved against the software path.
🤖 Generated with Claude Code
Activity
bluecmd commentedon Oct 19, 2026
Measured: hardware ray queries vs the software BVH (NVIDIA GB10)
Summary: with the one
unsafeopt-in, the opaque coffee-machine render at 1080p and 64 spp drops from 8.80 s to 2.18 s, 4.0× faster overall. That's 6.5× per sample (122 ms → 18.8 ms), with images matching the software render to 85.6 dB PSNR.Setup
b209c11b.examples/studio/coffee-exploded-sweep.json: 58,362 triangles, 1920×1080, three area lights, maximum depth 12.bluecmd/solidcraft@hwrt-prototype. It's evidence only and not for merging: it allowsunsafe. Seetools/hwrt-bench/README.md.1. Full renders through the production job path
The prototype (
SC_HWRT=1) replaces onlytrace_ordered_within, the f32 BVH traversal used for opaque launches and shadows, with a wgpu ray query on one BLAS/TLAS. Shading, sampling, light selection and tone mapping are unchanged. Runs were interleaved, three repeats each, after one warm-up per mode.render_and_encode_secondsThe 1-spp time is mostly fixed cost: the BVH, readback and PNG encode. The hardware path also replaces the 230 ms CPU BVH build with a BLAS build of a few milliseconds on the GPU. The prototype still builds the software BVH as well, so the 1-spp numbers don't show that saving.
Images: software vs hardware at 64 spp, same seeds:
Two software runs are bit-identical. The few differing pixels come from hits that differ at f32 precision.
2. Traversal only: the renderer's rays without shading
tools/hwrt-benchloads the buffers a real job uploads (SC_DUMP). It traces each pixel's path with the renderer's own WGSL traversal over its own BVH, and again with hardware ray queries. Each path is a camera ray, then per surface vertex one shadow ray per area light and a cosine bounce, launched exactly assample_pathlaunches opaque rays.Both tracers produce the same 3,659,154 surface vertices and the same 1,346,263 occluded shadow rays for 15.66 M rays. The table shows the median of 3 runs × 20 dispatches, timed with GPU timestamps:
3. Single ray sets (2,073,600 rays each, read from and written to buffers)
What this does not cover yet
trace_precise_withinprovides. The prototype leaves those on the software path, so the physical-glass scenes weren't measured. That's the design point raised in the proposal above.🤖 Generated with Claude Code
https://claude.ai/code/session_01J4cQstyRPcLFCDRPjxBuFS
bluecmd commentedon Oct 19, 2026
RTX 4090 (Vulkan) results: same branch, scene and parameters
Setup: NVIDIA GeForce RTX 4090, Windows 11, driver 616.56, Vulkan. The code is
hwrt-prototype@a3ffd067, with the GB10 render parameters verbatim (SHA-256 matches). The GPU was otherwise idle.Full renders, interleaved, three repeats after one warm-up per mode (
render_and_encode_seconds):At 64 spp that's 3.05× overall; the GB10 gave 4.0×.
The software path is already about 2.4× faster on the 4090 than on the GB10. With hardware traversal, the remaining 1.23 s is mostly shading, accumulation, readback and encoding.
Images: software vs hardware at 64 spp, in each of the three pairs:
Repeats within each mode are bit-identical.
Traversal-only paths:
On the GB10 this was 17–18×.
Single ray sets (2.07 M rays):
Cold start: the first hardware pipeline compile on this driver took 364 s, against 0.06 s for the already-cached software pipeline. After that, setup took 0.06–0.08 s in both modes. A shipping implementation would need to account for this, as #3217 does for DX12: keep the software path available while the hardware pipeline compiles, or compile it in the background.
Overall, on both GPUs:
🤖 Generated with Claude Code
https://claude.ai/code/session_01J4cQstyRPcLFCDRPjxBuFS
wdunn001 commentedon Oct 20, 2026
Yes to hardware ray queries. The measurements above justify the work on their own. The proposal as written puts the capability in the wrong crate. I want the decision recorded with constraints about where it lives.
The exception is wider than one expression
unsafe_code = "forbid"is set twice for this crate: once in the workspace lints and again at the crate root incrates/gpu/src/lib.rs. Aforbidcannot be lifted by an#[allow]. Accepting the proposal as written means demoting both todeny. Our existing exceptions are all platform FFI boundaries with no safe API: the 3Dconnexiondlopen, the Objective-C document hooks, the Windows crash filter, and the Windows window procedure.ExperimentalFeatures::enabled()is a different kind of thing. It is an acknowledgement token for an experimental API surface.solidcraft-gpushould keepforbid.WebGPU is a shipping target
solidcraft-gpuis in thecargo xtask wasmcrate set. The browser build is WebGPU-first (apps/solidcraft-web/src/main.rs), with WebGL2 as the fallback. WebGPU has no ray query API. The software WGSL traversal therefore stays the baseline that every target runs. Hardware traversal has to be a swappable implementation behind that baseline, selected per adapter at runtime.Proposal: the same seam we use everywhere else
Make ray traversal a backend behind an interface. The repo already works this way elsewhere:
crates/engine/src/capture.rsholds an installed renderer trait object. EveryPicturenames the backend that drew it.crates/gpu/src/select.rsis a purePolicy/Tier/Landingladder driven bySOLIDCRAFT_GPU, unit tested without a GPU.tessellation()incrates/gpu/src/view.rsis a capability probe returningOption<TessGpu>, with a driver denylist and an env kill switch, whereNonemeans the CPU path runs.crates/mcp/src/backend.rsis one trait with remote and headless implementations.Concretely:
TraceBackendseam with the existing software BVH traversal as the default implementation. Selection goes through a policy in the shape ofselect.rs, for exampleSOLIDCRAFT_TRACE=auto|rayquery|bvh.unsafetoken lives in a new leaf crate, for examplesolidcraft-gpu-rayquery, withunsafe_code = "deny"and one#![allow(unsafe_code)]module carrying the contract comment, exactly asnative_crash.rsdoes. The leaf crate is native-only and stays out of thextask wasmcrate set.crates/render/src/backend.rs, answeringAvailability::Unavailable { reason }on adapters withoutEXPERIMENTAL_RAY_QUERY.docs/render-backends.mdalready names acceleration structures as a host admission concern.indexed_raycast_answers_as_the_scan_doesincrates/geom/src/bvh_tests.rs: the hardware query and the software BVH must return the same nearest hit across the oracle scenes. Transmissive bodies keep the exact-arithmetic ordering on the software path, as proposed.Where this is heading
docs/web-runtime.mdalready commits us to thecraft-gpuprovider model:GpuProviderandProviderRegistrycontracts, withcraft-gpu-wgpusupplying WebGPU on wasm32 and Vulkan, DX12, or Metal on desktop. storytold/craft-libs#160 lands those crates with zerounsafe. Its error boundary lets no wgpu types cross. A traversal backend shaped as above can later become a provider there without redesign.Answers to the asks
solidcraft-gpukeepsforbid.create_pipeline_cachegets the same answer: same leaf crate, same module. The 364 s cold compile measured on the 4090 makes it worth doing together.The next step stands as proposed: a prototype PR stacked on #2191, opaque geometry first, with the backend seam in place from the first commit.
bluecmd commentedon Oct 20, 2026
Thanks, I agree with this shape and will build it that way.
solidcraft-gpukeepsforbid(unsafe_code), and the software BVH stays the baseline on every target. Here is the plan, with two corrections from measurements made since.Correction 1: pipeline caches only help Vulkan. In wgpu 30,
create_pipeline_cacheis implemented for Vulkan only; D3D12 and Metal ignore it. A cache in the leaf crate will remove the ~364–375 s cold Vulkan compile on the 4090 (the driver's own cache already makes repeat runs ~2 s). It does nothing for D3D12. #3306 handles D3D12 separately: x64 builds link DXC, which takes the compile from ~2 h with FXC to ~82 s, paid once per process. The cache module still goes in the leaf crate as you say. It just won't change the D3D12 numbers.Correction 2: the parity gate compares nearest hits with a tolerance. Hardware traversal runs in f32 with the driver's own watertightness rules. It can choose the other triangle across a shared edge, or move
tby a few ulps. So the differential test, in the shape ofindexed_raycast_answers_as_the_scan_does, asserts per ray:twithin a relative ε;The test reports the mismatch fraction and fails above zero outside those edge cases.
Plan
TraceBackendseam insolidcraft-gpu, from the first commit. A backend supplies the WGSL nearest-hit/any-hit functions the integrator calls (today'strace_ordered_withinand the shadow query), its extra bind group layout, and the per-scene build, with an upload and BLAS/TLAS for ray queries. The software BVH is the default backend and keeps the exact-ordered precise path for glass, which always stays software. No wgpu types cross the seam's public surface, so it can later become acraft-gpuprovider.select.rs:SOLIDCRAFT_TRACE=auto|rayquery|bvh, unit-tested without a GPU.autostaysbvhuntil the parity gate and driver coverage justify changing the default. A bad driver only ever costs speed.crates/gpu-rayquery(solidcraft-gpu-rayquery): a native-only leaf withunsafe_code = "deny"and one#![allow(unsafe_code)]module with the contract comment. It exposes two safe functions: open a device withEXPERIMENTAL_RAY_QUERYand the minimum acceleration-structure limits, and create the Vulkan pipeline cache.solidcraft-gpudepends on it only undercfg(not(target_arch = "wasm32")). It stays out of thextask wasmset and gets a layers entry ordered beforegpu.crates/render/src/backend.rs. WithSOLIDCRAFT_TRACE=rayqueryon an adapter without ray queries, gpu-path reportsAvailability::Unavailable { reason }. Underautoit falls back tobvhand logs that it did.tools/hwrt-benchnumbers (Decision: allow one unsafe opt-in in solidcraft-gpu for hardware ray tracing (wgpu ExperimentalFeatures) #3236 comments: GB10 6.5×, 4090 4.5× per sample) rerun through the seam, plus the parity test on GB10 and the 4090.Order: #2191, #2780 and #3306 land first. They fix today's launch stalls: the synchronous setup and the FXC compile. Then a prototype PR stacked on #2191 with opaque geometry only. The
hwrt-prototypebranch stays evidence only and won't be merged.I'll keep this issue open until the prototype PR links back to it.
🤖 Generated with Claude Code
https://claude.ai/code/session_01J4cQstyRPcLFCDRPjxBuFS
ablasik commentedon Oct 27, 2026
A data point for the "we'll measure it in the prototype" part, from Metal rather than Vulkan.
I built a local prototype on top of #7185 (path tracer on Metal), using
EXPERIMENTAL_RAY_QUERYbehind theExperimentalFeaturestoken as proposed here. On an Apple M3 Max, wgpu 30 exposes ray queries on Metal as well, so item 2's "Vulkan only" can probably include Metal.Scene: an e-bike battery design, 32 bodies, 57,786 triangles, no glass, 1080p. Render time in seconds, 3 runs each, median shown:
The images match the software path within 6/255 per channel.
So on Apple silicon the gain is modest, about 15–20%, not the large step one would expect on RTX hardware. Shading and sampling still dominate here once traversal gets cheaper. The GB10 and RTX numbers will decide whether it pays off. I can push the prototype branch if that helps with the RTX measurement.
bluecmd commentedon Oct 27, 2026
Thanks @ablasik. That's a useful data point, and the first one from Metal.
We already have GB10 and RTX 4090 numbers from the Vulkan prototype, posted above (GB10, RTX 4090): the coffee machine, 58,362 triangles, 1080p, no glass, close to your scene's size:
Traversal alone was 17–25× faster on the two NVIDIA GPUs, so most of the remaining time there is shading, accumulation and readback. Your 1.2× on Apple silicon fits your reading: once traversal is cheap, shading dominates. It could also be that Metal's ray query path is less mature. A traversal-only measurement would separate the two;
tools/hwrt-benchon thehwrt-prototypebranch has one.Yes, please push the prototype branch. Running your branch on the 4090 with your battery scene would give a direct Metal-vs-Vulkan comparison of the same code. I can't give a date: our GB10 machines are unavailable for now, and the 4090 runs when we have capacity.
On scope: the path tracer is currently Vulkan-only, with Metal listed as "later" in #3151. Whether #7183 brings Metal in is for the maintainers to decide there; this thread only records the measurements.
🤖 Generated with Claude Code