Skip to content

Bake: batch antialiased GPU queries in larger spans - #275

Draft
simonhull wants to merge 12 commits into
storytold:mainfrom
simonhull:perf/bake-gpu-aa-queries
Draft

simonhull wants to merge 12 commits into
storytold:mainfrom
simonhull:perf/bake-gpu-aa-queries

Conversation

@simonhull

@simonhull simonhull commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Draft for discussion. Nobody asked for this, so I've opened it as a draft for you to evaluate, not as a request to merge. If it's useful, I'm happy to rework it, split it up or follow it through; if you'd rather handle this yourselves, or it overlaps something you've started, feel free to close it.

Stacked on #274, the ray-budget PR for #196: review that one first. This PR only touches what runs around the tracer once rays are split between subsamples.

Cause

After the ray-budget fix, an 8×8 bake casts the same hemisphere rays as a 1×1 bake, but on the hilo scene it still took about 6.5× as long on the GPU (29.9 s against 4.6 s), and the GPU spent 2.7× longer in hemispheres for the same rays. I profiled it with GPU timestamp queries, per-phase timers and samply. Per-query setup in the shader is not the cause: with large enough batches the 8×8 hemisphere kernel takes the same time as the 1×1 kernel (3.81 s against 3.88 s). The time went to three other places:

  • Two cores doing the CPU work. A batch is 2^18 subsamples, which at 8×8 and 2048² is only 2 texel rows. bake_rows builds samples, transfer rays and queries and evaluates them with one rayon task per row, so 2 of 12 cores did all of it. samply shows 2 workers busy and 10 mostly idle. This was 12.9 s of the 14 s "other": sample building 3.7 s, evaluation 6.2 s, transfer rays 1.3 s, queries 1.1 s.
  • Batches too small for the GPU. Each batch gives the GPU 2^18 subsamples × 2 rays, against 2^18 × 128 at 1×1. That is 1024 synchronous round trips of a small dispatch instead of 16. The hemisphere kernel took 5.2 s at 8×8 against 3.9 s at 1×1, plus about 1.2 s of submission and copy time beyond the kernels.
  • Query rows copied three times on the way up. hemispheres collected a Vec of rows per query, concatenated them into a second buffer, and write_buffer copied that into wgpu's staging memory on one thread. That is 17 GB of query rows for one 8×8 bake: 1.8 s to build plus about 1.4 s to copy.

Fix

  • bake_rows works on spans of texels instead of whole rows: a span is about 4096 subsamples, so a whole row without antialiasing (up to 4096 texels) and 64 texels at 8×8. Each span keeps its texels' subsamples together, and its outputs are the matching slices of each map row, so per-texel work and order are unchanged.
  • Antialiased batches hold up to 2^18 texels in at most 2^20 subsamples: 2×2 holds as many texels as an unantialiased batch, 4×4 2^16 and 8×8 2^14. 1×1 batches are unchanged, and so is the curvature batch.
  • The GPU tracer builds query and ray rows in parallel. Each thread writes its contiguous range straight into wgpu's staging memory with queue.write_buffer_with, with no intermediate Vec. Each write runs inside its own error scope, because wgpu's error scopes are per thread: a failed upload on a worker is reported and the bake falls back to the CPU, instead of tracing stale rows.
  • GPU threads per query are sized from the bake's subsample count (a new Hemisphere::subsamples), not from the largest share in the batch, so results don't depend on how texels are batched. The hemisphere results are converted in parallel too. GpuScene splits into the scene (roots) and Batches (buffers and run), so the row builder can borrow the roots without a copy.

The output does not change: every map of every configuration below is byte-identical to the base branch, with and without antialiasing.

Measured on current main

Main now bakes curvature from the mesh by default, and mesh curvature runs in small batches, so it dominates an antialiased bake. Apple M3 Pro, material ball, medians of 3 runs, in seconds, on a busy machine. "#274" is the ray-budget PR this is stacked on.

bake #274 this PR
1×1 2048², mesh curvature on (default) 3.9–5.7 3.5–3.8
1×1 2048², mesh curvature off 2.35 2.31
8×8 512², mesh curvature on (default) 9.0–9.4 7.0–7.7
8×8 1024², mesh curvature off 4.6–6.1 2.0–2.1

With mesh curvature off, 8×8 is about 2.2–3× faster and 1×1 is unchanged. With it on (the default), 8×8 is about 1.2–1.3× faster on this Mac. The reviewer saw no 8×8 gain with curvature on, on an RTX 3060.

Measured at the time (normal-map curvature, then the default)

Apple M3 Pro, 2048², default maps (AO and thickness at 64 rays, plus normal, ID and the other transfers). hilo is the 4,096-triangle low poly baked from a 4.2M-triangle high poly. ball is the material ball (22,016 triangles) with no high poly. Medians of 3 runs, in seconds, before and after run back to back on a quiet machine.

scene tracer AA before after
hilo GPU 1×1 4.64 4.42
hilo GPU 8×8 29.93 14.19 (2.1×)
hilo CPU 8×8 59.71 49.56 (−17%)
ball GPU 1×1 2.39 2.34
ball GPU 8×8 20.69 8.66 (2.4×)
ball CPU 8×8 31.53 23.61 (−25%)
  • hilo GPU 8×8: CPU-side "other" time dropped from 14.1 s to 5.6 s, and hemisphere tracing from 12.7 s to 6.7 s. The hemisphere kernel now matches 1×1 (3.81 s against 3.88 s, GPU timestamps).
  • The CPU tracer gains only the "other" part: its tracing time is unchanged.
  • 1×1 changes are within run-to-run noise (only the parallel row upload touches that path).
  • Peak RSS at 8×8: hilo 2.94 → 2.99 GB, ball 1.61 → 1.56 GB (one sample each; repeated runs spread by ±0.3 GB). In a batch-size sweep on hilo 8×8 (before the span change), 2^20-subsample batches raised peak RSS by about 0.5 GB over 2^18, 2^19 by 0.15 GB, and 2^21 was no faster than 2^20.
  • What 8×8 still costs over 1×1 on the GPU (about 9.8 s on hilo) is per-subsample work: building and evaluating 64× the samples on all cores (about 4.7 s), 64× the transfer rays (1.9 s), and moving 96 bytes per subsample to and from the GPU (about 2.8 s). Packing a texel's subsamples into one query would save only the 16 shared bytes of a 64-byte row, since position, normals and key differ per subsample. I left it out.

Verified

  • New test antialiased_batches_hold_more_subsamples_up_to_a_cap (crates/bake/src/tests.rs) counts batches through the public Tracer trait. At 512² a 1×1 bake is one batch of 2^18 queries, and a 2×2 bake is one batch of 2^20 instead of four of 2^18. At 8×8, 256² is four batches of 2^20. With the old batch rule it fails: left: (4, 262144), right: (1, 1048576).
  • antialiased_spans_write_each_texel_in_place checks a row with a full span and a partial one. Shifting the second span by one texel fails it.
  • a_failed_upload_is_an_error fails without the per-thread error scope.
  • gpu_hemisphere_results_do_not_depend_on_batching: a batch of only small shares gives the same bytes as those shares inside a mixed batch. Sizing threads from the batch's largest share fails it.
  • Byte-identical to the base branch: all 7 maps, full data, hashed, on hilo and ball, GPU 1×1, GPU 8×8 and CPU 8×8.
  • Rebased onto the ray-budget PR's bent-normal fix: all ten maps are still byte-identical to the base branch at 8×8 (512², hilo and ball, CPU and GPU), and at 1×1 to main (2048²). The analytic reference scenes (Bake: analytic reference scenes for the mesh-map baker #279) pass on both tracers, with the same bent-normal errors as the base branch at 2×2, 4×4 and 8×8. GPU 8×8 on hilo, run alternately with the build before the rebase: 14.24 s against 14.31 s (medians of 3), so the table holds.
  • gpu_bake_matches_the_cpu and gpu_respects_secondary_ray_filters_and_ground_plane pass, and so do all 58 bake tests, including the ray-budget PR's tests.
  • cargo +1.96.0 xtask ci passed before the review changes. Since then I've run the bake, render and engine bake tests, clippy, fmt and cargo xtask wasm.

Not changed

  • GPU dispatch size: each dispatch is still capped at RAYS_PER_DISPATCH (2^24 rays), so the longest single piece of GPU work, which is what a driver watchdog such as Windows TDR times, is the same as before. An 8×8 batch now encodes more of those dispatches into one submission, so each blocking wait is longer. That hasn't been tested on a slow GPU. Each of a batch's buffers stays under wgpu's default 128 MiB binding limit (64 MiB of query rows and up to 96 MiB of results at 2^20 subsamples), about 256 MiB in all with the staging copy (from the buffer sizing code, not measured). The existing buffer-limit check still applies. Dispatches are sized from the largest share (from Bake: split each texel's rays between its antialiasing subsamples #274), so a batch of large shares can't exceed the per-dispatch ray budget.
  • Shader and buffer layout. bake.wgsl, Query, Params and the 64-byte query row are untouched.
  • Mesh-curvature batches stay at 2^15 subsamples for progress and cancellation.
  • CPU/GPU overlap. RayScene is still a synchronous batch call, so the CPU waits while the GPU traces (about 5.5 s on hilo at 8×8). Overlapping them needs a double-buffered or async RayScene: a larger change for another PR.

@coderabbitai

coderabbitai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@SteamSmith

Copy link
Copy Markdown
Collaborator

I'm taking this one for review.

With antialiasing on, every subsample of a texel cast the full ray count
of ambient occlusion, bent normal and thickness, so 8x8 cast 64 times the
configured rays per texel and a default 8K bake took over an hour on the
GPU (storytold#196).

A texel's covered subsamples now take interleaved shares of one stratified
pattern of max(rays, subsamples) directions, rotated by the texel's seed:
a texel casts the configured rays however finely it is sampled, and its
directions stay as well spread as a 1x1 bake's. Query carries the share;
the CPU tracer and the GPU shader walk it with a stride.

A share holds only a band of the pattern's elevations (its rays share
their low index bits, and elevation comes from the reversed bits), so a
bent normal normalized per share and then averaged leaned up to 11.6
degrees off. A subsample of a split texel returns the unnormalized sum
of its open directions instead, and the texel normalizes the sum of its
subsamples' once: its bent normal is the one its whole pattern gives. A
share whose rays all fall below the surface reports NaN and the texel
skips it, as a texel skips its rejected rays. Single-ray transfers still
run once per subsample, and a 1x1 bake is bit-identical to before.
With rays split between subsamples, an 8x8 bake spent most of its time
outside ray tracing. A batch held 2^18 subsamples, which at 8x8 is only
two texel rows: bake_rows built and evaluated samples one row per task,
so two cores did the work, and each batch gave the GPU about 2 rays per
subsample, too little to fill it between the synchronous round trips.
The GPU tracer also built each batch's query rows on the side, copied
them into one buffer and then into wgpu's upload buffer on one thread.

bake_rows now works on spans of texels: whole rows without antialiasing,
runs of 64 texels at 8x8. Antialiased batches hold as many texels as
unantialiased ones, up to 2^20 subsamples. The GPU tracer builds query
and ray rows in parallel straight into its upload writes. Per-texel work
is unchanged, so every map is bit-identical to before at 1x1 and with
antialiasing.
@simonhull
simonhull force-pushed the perf/bake-gpu-aa-queries branch from 34aa22e to 4036655 Compare November 10, 2026 16:06
@SteamSmith

Copy link
Copy Markdown
Collaborator

Review notes (prepared with Claude Code)

PR #275

Verdict: merge after rework, and after #274. The work is grouped differently but each texel is computed as before. One real bug, and two claims in the description need correcting.

What I checked

  • bake_rows now works on spans of 4096 subsamples, antialiased batches are min(2^18 * subsamples, 2^20), and query and ray rows are uploaded in parallel. A new test shows the spans write each texel in its place (it fails if the second span is shifted by one texel). Reverting the batch rule fails the PR's batch test.
  • Seeds and query order are unchanged. On the material ball (256 squared, all default maps, 1x1, 2x2 and 8x8, CPU and GPU) every map hashes identically to Bake: split each texel's rays between its antialiasing subsamples #274.

Changes requested

  1. Failed GPU uploads are lost. wgpu error scopes are per thread. The scope is pushed on the calling thread but write_buffer now runs on rayon workers, so a failed write (for example out of memory) goes to the baker's no-op uncaptured-error handler. The batch then traces stale rows, where before the error led to a CPU fallback. Reproduced on an RTX 3060: an overrunning write on the scoping thread is caught, the same write made on a worker is not. Wrapping each worker's write in its own scope fixes it at no measurable cost (7.80 s vs 7.72 s); patch 1 includes a_failed_upload_is_an_error, which fails without it.
  2. "Output is unchanged" needs a qualifier. On a scene with a quad plus thin UV slivers (256 squared, 8x8, GPU), a few partly covered texels differ by float rounding between Bake: split each texel's rays between its antialiasing subsamples #274 and Bake: batch antialiased GPU queries in larger spans #275: 14-15 AO values by at most 1.2e-7, up to 499 bent-normal values by at most 4.8e-7, and 2-12 thickness values by 0.125-0.25 (a nearly flat map, so min/max normalisation blows a rounding step up). The cause is that threads per query are sized from the largest subset count in the batch, and Bake: batch antialiased GPU queries in larger spans #275 changes the batches. Sizing them from the bake's subsample count (known in the bake context) would make results independent of batching. The CPU tracer and 2x2 are byte-identical.
  3. The speed-up only applies with mesh curvature off. Main now enables mesh curvature by default ("Bake curvature from the mesh by default", after this PR's base, which defaulted to the normal-map method that traces no curvature), so your 2.1-2.4x table was right for your base. On current main, with the default map set, mesh curvature is enabled, the whole bake uses the small curvature batch, and 8x8 shows no gain (about 90 s on both builds, on a busy machine) while 1x1 was 14-20% slower over three rounds. With curvature off, 8x8 went from 12.5 s to 7.9 s (1.58x) and 1x1 was about 5% faster. The 1x1 slowdown is probably the extra copy of every ray into a per-thread Vec before the staging buffer (I did not profile it); writing cast_slice(&rays[range]) per thread directly would avoid it. (The description says rows are written with no intermediate Vec; upload does use a per-thread one.)
  4. Batch size. The test name antialiased_batches_hold_as_many_texels_as_unantialiased_ones overstates it: only 2x2 batches hold 2^18 texels; 4x4 holds 2^16 and 8x8 holds 2^14 (the 2^20 cap). GPU batch buffers grow from about 48 MiB to about 192 MiB (from reading the buffer sizing code, not measured).
  5. Dispatch size. Larger batches raise the worst-case rays per dispatch for pathological layouts at 4096 rays (analysis only): 4x4 goes from 4x to 16x the 2^24 budget. Sizing dispatches from the smallest subset count bounds it, so it should land with this. Patches 3 and 4 below are the two Bake: split each texel's rays between its antialiasing subsamples #274 fixes (thickness fallback and dispatch sizing) adapted to this branch.
  6. Constants. AA_BATCH, SPAN_SAMPLES and FILL_CHUNK are named but nothing says why that value; one line each please. Sizing threads per query from the bake's subsample count (item 2) needs a field on Hemisphere, because RayScene::hemispheres cannot see the bake context.

Patch 2 below is a test that checks a row with a full span and a partial one.

Notes

  • I reviewed this on main before you rebased; the change is the same and all four patches below apply, in order, to the rebased branch. Open .spp projects and .spsm, .spmsk and .sbsar files #360 replaces the same batch constants and conflicts with this PR in lib.rs.
  • Not run: 8K and UDIM memory (computed from the code), a slow-GPU watchdog test, cargo xtask ci.

Patch 1: catch upload errors on the threads that write

The changes described above, as a patch you can apply (git apply), against the head of this PR as reviewed. If you would rather have them as a PR against your branch, say so.

Show the patch
From b632f824a75bd7cdff90ce3e91c2889d73404db5 Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 07:22:23 -0500
Subject: [PATCH 1/3] fix(275): catch upload errors on the threads that write

wgpu's error scopes are per thread, so the batch's scope on the calling
thread never saw a failed write_buffer from a rayon worker: the error went
to the no-op uncaptured handler and the batch ran on stale rows. Each
worker's write now runs in a scope of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 crates/render/src/gpu_bake.rs | 24 ++++++++++++++++++++----
 1 file changed, 20 insertions(+), 4 deletions(-)

diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs
index 86263ff..33d608f 100644
--- a/crates/render/src/gpu_bake.rs
+++ b/crates/render/src/gpu_bake.rs
@@ -281,7 +281,7 @@ impl Batches<'_> {
         let io = self.io(in_bytes, out_bytes, blocks.len() as u64)?;
         let dev = &g.device;
         scoped(dev, "GPU baking: dispatch", || {
-            upload(&g.queue, &io.items, n, item)?;
+            upload(dev, &g.queue, &io.items, n, item)?;
             g.queue.write_buffer(&io.params, 0, &blocks);
             let mut enc = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_bake") });
             {
@@ -313,8 +313,11 @@ impl Batches<'_> {
 }
 
 /// Upload `item(i)` as the `i`-th `N`-byte row of `buffer`: built and written in parallel, each
-/// thread a contiguous range of rows.
+/// thread a contiguous range of rows. wgpu's error scopes are per thread, so each write runs in a
+/// scope of its own on the thread that makes it: a failed write (out of memory, say) is an error
+/// here rather than lost to the uncaptured-error handler.
 fn upload<const N: usize>(
+    device: &wgpu::Device,
     queue: &wgpu::Queue,
     buffer: &wgpu::Buffer,
     n: usize,
@@ -327,8 +330,7 @@ fn upload<const N: usize>(
         for i in start..start.saturating_add(chunk).min(n) {
             bytes.extend_from_slice(&item(i)?);
         }
-        queue.write_buffer(buffer, start.saturating_mul(N) as u64, bytes);
-        Ok(())
+        scoped(device, "GPU baking: upload", || queue.write_buffer(buffer, start.saturating_mul(N) as u64, bytes)).map_err(BakeError::Tracer)
     })
 }
 
@@ -416,6 +418,20 @@ mod tests {
 
     use super::*;
 
+    /// A write that fails while a batch uploads on worker threads is reported (wgpu's error scopes
+    /// are per thread, so the caller's scope never sees a worker's error), not silently dropped.
+    #[test]
+    fn a_failed_upload_is_an_error() {
+        let Some(baker) = gpu() else { return };
+        let g = baker.gpu().unwrap();
+        let usage = wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST;
+        let small = g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("tc_bake_test"), size: 256, usage, mapped_at_creation: false });
+        // Every write runs on a worker of its own pool, as in a bake, and runs past the buffer's end
+        let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap();
+        let caught = scoped(&g.device, "test upload", || pool.install(|| upload(&g.device, &g.queue, &small, 4 * FILL_CHUNK, |_| Ok([0u8; 64]))));
+        assert!(!matches!(caught, Ok(Ok(()))), "an overrunning upload was reported as written");
+    }
+
     /// The GPU baker, or None (test skipped) without a hardware adapter.
     fn gpu() -> Option<GpuBaker> {
         let g = GpuBaker::new();
-- 
2.55.0.windows.5

Patch 2: test that antialiased spans write each texel in place

The changes described above, as a patch you can apply (git apply), against the head of this PR as reviewed. If you would rather have them as a PR against your branch, say so.

Show the patch
From 0aaebdf261aac79b78de640f345abbe88a92da9b Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 08:49:24 -0500
Subject: [PATCH] test(275): antialiased spans write each texel in place

A 96-texel 8x8 row is one full 64-texel span and a partial one; the
position and world-normal maps must match the 1x1 bake texel for texel.
Fails when a span's output is shifted by one texel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 crates/bake/tests/antialiased_spans_test.rs | 49 +++++++++++++++++++++
 1 file changed, 49 insertions(+)
 create mode 100644 crates/bake/tests/antialiased_spans_test.rs

diff --git a/crates/bake/tests/antialiased_spans_test.rs b/crates/bake/tests/antialiased_spans_test.rs
new file mode 100644
index 0000000..0a43d25
--- /dev/null
+++ b/crates/bake/tests/antialiased_spans_test.rs
@@ -0,0 +1,49 @@
+//! Antialiased rows are baked in spans of texels (64 at 8×8): every texel still lands in place.
+
+use texturecraft_bake::{BakeOutput, BakeRequest, Progress, bake};
+use texturecraft_core::{BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CommonBakeSettings, PositionMode, PositionSettings};
+use texturecraft_geom::glam::{Vec2, Vec3};
+use texturecraft_geom::{Bvh, Mesh};
+
+/// The unit quad over all of UV space.
+fn quad() -> Mesh {
+    Mesh::from_parts(
+        vec![Vec3::new(-1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(-1.0, 0.0, 1.0)],
+        Some(vec![Vec3::Y; 4]),
+        vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 1.0)],
+        vec![0, 2, 1, 0, 3, 2],
+        "Quad",
+    )
+    .unwrap()
+}
+
+/// Position and world normal of `mesh` over three 32-texel UV tiles in a row (96 × 32 texels).
+fn bake_three_tiles(mesh: &Mesh, antialiasing: BakeAntialiasing) -> BakeOutput {
+    let mut s = BakeSettings::default();
+    s.common = CommonBakeSettings { resolution: BakeResolution::R32, antialiasing, dilation: 0, apply_diffusion: false, ..s.common };
+    s.maps.position.parameters = PositionSettings { normalization: PositionMode::BoundingBox, ..s.maps.position.parameters };
+    s.maps.select([BakedMap::Position, BakedMap::WorldNormal]);
+    let bvh = Bvh::new(mesh);
+    let req =
+        BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, cage_paint: None, tiles: (3, 1) };
+    bake(&req, &Progress::new()).unwrap()
+}
+
+/// A 96-texel 8×8 row is one full span of 64 texels and a partial one of 32. The position map is
+/// linear across the quad, so each texel's 8×8 average equals its 1×1 centre sample (a whole-row
+/// span): a texel written to the wrong place, or a span out of order, shows up at once.
+#[test]
+fn antialiased_spans_write_each_texel_in_place() {
+    let m = quad();
+    let (plain, antialiased) = (bake_three_tiles(&m, BakeAntialiasing::None), bake_three_tiles(&m, BakeAntialiasing::Subsampling8x8));
+    assert_eq!((antialiased.resolution, antialiased.height), (96, 32));
+    for map in [BakedMap::Position, BakedMap::WorldNormal] {
+        let (a, b) = (&plain.maps[&map], &antialiased.maps[&map]);
+        assert_eq!(a.len(), b.len());
+        let worst = a.iter().zip(b).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
+        assert!(worst < 1e-4, "{map:?}: an 8×8 texel differs from the 1×1 one by {worst}");
+    }
+    // The positions really vary along the row (a constant map would hide misplaced texels)
+    let position = &plain.maps[&BakedMap::Position];
+    assert!((position[95 * 3] - position[0]).abs() > 0.5, "{} vs {}", position[95 * 3], position[0]);
+}
-- 
2.55.0.windows.5

Patch 3: thickness fallback (the first fix on #274, adapted to this branch)

The changes described above, as a patch you can apply (git apply), against the head of this PR as reviewed. If you would rather have them as a PR against your branch, say so.

Show the patch
From 3e0cd40407bb40de50e2dea14ed79d35b9c4eeba Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 07:08:01 -0500
Subject: [PATCH] fix(274): a split texel with no accepted ray keeps the
 unantialiased value

When every ray subset of an antialiased texel fell below the surface, the
texel got the map's display neutral (raw thickness 1.0) where a 1x1 bake
gives the maximum ray distance, an outlier for min/max normalization.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 crates/bake/src/lib.rs                     | 19 +++++--
 crates/bake/tests/antialiasing_fallback.rs | 61 ++++++++++++++++++++++
 2 files changed, 77 insertions(+), 3 deletions(-)
 create mode 100644 crates/bake/tests/antialiasing_fallback.rs

diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs
index 65fb261..8590674 100644
--- a/crates/bake/src/lib.rs
+++ b/crates/bake/src/lib.rs
@@ -399,6 +399,8 @@ fn bake_rows(
     let (occlusion_results, separate_bent_results, thickness) =
         (next(context.ao.is_some()), next(separate_bent_pass.is_some()), next(context.thickness.is_some()));
     let bent_results = if separate_bent_pass.is_some() { &separate_bent_results } else { &occlusion_results };
+    // What a thickness query with no accepted ray reports (Hemisphere::evaluate)
+    let thickness_dmax = context.thickness.map_or(1.0, |pass| pass.dmax);
 
     // Each span's slice of every map, in span order
     let mut outputs: Vec<OutRow> = Vec::with_capacity(spans.len());
@@ -413,16 +415,19 @@ fn bake_rows(
         let mut span_sample_index = 0;
         for x in span.x..span.x + span.width {
             let texel_samples = samples.get(span_sample_index..).unwrap_or_default().iter().take_while(|sample| sample.x == x).count();
-            let bent = texel_bent_normal(bent_results, first + span_sample_index..first + span_sample_index + texel_samples);
+            let texel = first + span_sample_index..first + span_sample_index + texel_samples;
+            let bent = texel_bent_normal(bent_results, texel.clone());
+            // A split texel none of whose rays was accepted reports what one query with no accepted ray does
+            let (ao_unset, thickness_unset) = (no_accepted_ray(&occlusion_results, texel.clone()), no_accepted_ray(&thickness, texel));
             // Per map: a subsample without a finite value (a ray subset with no accepted ray) is skipped
             let mut accumulated = [[0.0f32; 3]; BakedMap::ALL.len()];
             let mut counts = [0u32; BakedMap::ALL.len()];
             while let Some(sample) = samples.get(span_sample_index).filter(|sample| sample.x == x) {
                 let sample_index = first + span_sample_index;
                 let traced = map::Traced {
-                    ao: occlusion_results.get(sample_index).map_or(1.0, |value| value[0]),
+                    ao: occlusion_results.get(sample_index).map_or(1.0, |value| if ao_unset { 1.0 } else { value[0] }),
                     bent,
-                    thickness: thickness.get(sample_index).map_or(1.0, |value| value[0]),
+                    thickness: thickness.get(sample_index).map_or(1.0, |value| if thickness_unset { thickness_dmax } else { value[0] }),
                     curvature: curvature.get(sample_index).copied().unwrap_or(0.5),
                 };
                 context.evaluate(maps, &sample.surface, sample.bary, transfer(sample_index), &traced, &mut sample_values);
@@ -449,6 +454,14 @@ fn bake_rows(
     Ok(())
 }
 
+/// Whether the texel whose subsamples have these hemisphere results split its rays and none of them
+/// was accepted (every subset reported NaN). Such a texel takes the value a single query with no
+/// accepted ray gives (unoccluded, or the maximum ray distance), as it would without antialiasing,
+/// rather than the map's display neutral. A texel traced as one query never reports NaN.
+fn no_accepted_ray(results: &[[f32; 4]], texel: std::ops::Range<usize>) -> bool {
+    results.get(texel).is_some_and(|values| values.len() > 1 && values.iter().all(|value| value[0].is_nan()))
+}
+
 /// The bent normal of the texel whose subsamples have these hemisphere results. A texel traced as one
 /// query has its own; subsamples that split a texel's rays hold unnormalized sums of open directions
 /// (NaN for a subset with no accepted ray), normalized here once for the texel. None (each subsample
diff --git a/crates/bake/tests/antialiasing_fallback.rs b/crates/bake/tests/antialiasing_fallback.rs
new file mode 100644
index 0000000..5d44512
--- /dev/null
+++ b/crates/bake/tests/antialiasing_fallback.rs
@@ -0,0 +1,61 @@
+//! Antialiased texels whose rays all fall below the surface (#274 review).
+#![allow(clippy::unwrap_used)]
+
+use texturecraft_bake::{BakeOutput, BakeRequest, Progress, bake};
+use texturecraft_core::{BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, RaySettings, ThicknessNormalization};
+use texturecraft_geom::glam::{Vec2, Vec3};
+use texturecraft_geom::{Bvh, Mesh};
+
+/// A flat square in y = 0 whose shading normals are all `n`.
+fn plane(n: Vec3) -> Mesh {
+    Mesh::from_parts(
+        vec![Vec3::new(-1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(-1.0, 0.0, 1.0)],
+        Some(vec![n; 4]),
+        vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 1.0)],
+        vec![0, 2, 1, 0, 3, 2],
+        "Plane",
+    )
+    .unwrap()
+}
+
+/// Bakes `mesh` on the CPU tracer.
+fn run(mesh: &Mesh, s: &BakeSettings) -> BakeOutput {
+    let bvh = Bvh::new(mesh);
+    let request =
+        BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1) };
+    bake(&request, &Progress::new()).unwrap()
+}
+
+/// The mean of a map's first component over all texels (the plane covers every texel).
+fn mean(out: &BakeOutput, map: BakedMap) -> f32 {
+    let values: Vec<f32> = out.maps[&map].iter().step_by(map.components()).copied().collect();
+    values.iter().sum::<f32>() / values.len() as f32
+}
+
+/// A texel whose every ray falls below the surface gets the same raw thickness and occlusion with
+/// antialiasing as without it (the maximum ray distance, and unoccluded), not the map's display
+/// neutral: a raw thickness of 1 would be an outlier for min/max normalization.
+#[test]
+fn antialiasing_gives_a_texel_with_no_accepted_ray_the_unantialiased_value() {
+    // Shading normals lying in the face and a zero spread: every ray grazes the face and is rejected
+    let m = plane(Vec3::X);
+    let mut base = BakeSettings::default();
+    base.common.resolution = BakeResolution::R16;
+    base.common.dilation = 0;
+    base.common.apply_diffusion = false;
+    base.maps.select([BakedMap::Thickness, BakedMap::AmbientOcclusion]);
+    base.maps.thickness.parameters.normalization = ThicknessNormalization::None;
+    for r in [&mut base.maps.thickness.parameters.rays, &mut base.maps.ao.parameters.rays] {
+        *r = RaySettings { rays: 4, max_distance: 0.1, spread: 0.0, ..*r };
+    }
+    let plain = run(&m, &base);
+    for antialiasing in [BakeAntialiasing::Subsampling2x2, BakeAntialiasing::Subsampling8x8] {
+        let mut s = base.clone();
+        s.common.antialiasing = antialiasing;
+        let smooth = run(&m, &s);
+        for map in [BakedMap::Thickness, BakedMap::AmbientOcclusion] {
+            let (plain, smooth) = (mean(&plain, map), mean(&smooth, map));
+            assert!((plain - smooth).abs() < 1e-6, "{antialiasing:?} {map:?}: {plain} without antialiasing, {smooth} with it");
+        }
+    }
+}
-- 
2.55.0.windows.5

Patch 4: dispatch sizing (the optional fix on #274, adapted to this branch)

The changes described above, as a patch you can apply (git apply), against the head of this PR as reviewed. If you would rather have them as a PR against your branch, say so.

Show the patch
From bb9805c516711b8654bd6e37298544bafc1d23e1 Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 07:08:02 -0500
Subject: [PATCH] fix(274): size hemisphere dispatches for the largest ray
 share

Lanes are sized for a full texel's share, but an edge texel with few
covered subsamples casts more rays per query, so a dispatch sized by the
smallest share could cast up to 64 times RAYS_PER_DISPATCH rays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 crates/render/src/gpu_bake.rs | 37 ++++++++++++++++++++++++++++++-----
 1 file changed, 32 insertions(+), 5 deletions(-)

diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs
index 33d608f..370eff6 100644
--- a/crates/render/src/gpu_bake.rs
+++ b/crates/render/src/gpu_bake.rs
@@ -334,6 +334,16 @@ fn upload<const N: usize>(
     })
 }
 
+/// Threads per query and queries per dispatch of a hemisphere pass of `rays` rays per texel, for
+/// queries that split their texel's rays into between `fewest` and `most` subsets. A query's rays
+/// spread over `lanes` threads of a workgroup (a power of two), sized for the usual full texel's
+/// share; a dispatch holds as many queries as keep it under RAYS_PER_DISPATCH even if they all cast
+/// the largest share (an edge texel with few covered subsamples casts more rays per query).
+fn hemisphere_sizes(rays: u32, (fewest, most): (u32, u32)) -> (u32, usize) {
+    let lanes = rays.div_ceil(most.max(1)).clamp(1, WORKGROUP).next_power_of_two();
+    (lanes, RAYS_PER_DISPATCH / rays.div_ceil(fewest.max(1)).max(1) as usize)
+}
+
 /// A row of `v` (as bits) and `w`.
 fn row(v: Vec3, w: u32) -> [u32; 4] {
     [v.x.to_bits(), v.y.to_bits(), v.z.to_bits(), w]
@@ -361,14 +371,15 @@ impl RayScene for GpuScene<'_> {
             let rows = [row(q.pos, q.rot[0].to_bits()), row(q.nrm, q.rot[1].to_bits()), row(q.geo, q.key), [root, q.subset, q.subsets.max(1), 0]];
             Ok(bytemuck::cast::<[[u32; 4]; 4], [u8; 64]>(rows))
         };
-        // Antialiased texels split their rays between subsamples: size the lanes for a full texel's share.
+        // Antialiased texels split their rays between subsamples: size the lanes for a full texel's share,
+        // and the dispatches for the largest share (an edge texel's few subsamples cast more rays each),
+        // so that no dispatch casts more than RAYS_PER_DISPATCH rays.
         let subsets = queries.par_iter().map(|q| q.subsets).max().unwrap_or(1).max(1);
+        let fewest_subsets = queries.par_iter().map(|q| q.subsets).min().unwrap_or(1).max(1);
         let passes: Vec<Pass> = passes
             .iter()
             .map(|h| {
-                // A query's rays spread over `lanes` threads of a workgroup (a power of two).
-                let rays = h.rays.div_ceil(subsets);
-                let lanes = rays.clamp(1, WORKGROUP).next_power_of_two();
+                let (lanes, per_dispatch) = hemisphere_sizes(h.rays, (fewest_subsets, subsets));
                 let flags =
                     [(h.uniform, UNIFORM), (h.ground_height.is_some(), 8), (h.same_key, SAME_KEY)].iter().filter(|(on, _)| *on).fold(0, |f, (_, b)| f | b);
                 let params = Params {
@@ -394,7 +405,7 @@ impl RayScene for GpuScene<'_> {
                     lanes,
                     ..Params::default()
                 };
-                Pass { params, per_dispatch: RAYS_PER_DISPATCH / rays.max(1) as usize, per_group: (WORKGROUP / lanes) as usize }
+                Pass { params, per_dispatch, per_group: (WORKGROUP / lanes) as usize }
             })
             .collect();
         let gpu = self.gpu;
@@ -432,6 +443,22 @@ mod tests {
         assert!(!matches!(caught, Ok(Ok(()))), "an overrunning upload was reported as written");
     }
 
+    /// However a batch mixes fully and partly covered antialiased texels, no hemisphere dispatch casts
+    /// more than RAYS_PER_DISPATCH rays (the driver-watchdog bound), and unsplit queries are sized as
+    /// before rays were split.
+    #[test]
+    fn hemisphere_dispatches_stay_under_the_ray_budget() {
+        for rays in [1, 7, 64, 1000, 4096] {
+            for (fewest, most) in [(1, 1), (1, 4), (1, 64), (3, 16), (64, 64)] {
+                let (lanes, per_dispatch) = hemisphere_sizes(rays, (fewest, most));
+                assert!(lanes.is_power_of_two() && lanes <= WORKGROUP, "{rays} rays, {fewest}..{most} subsets: {lanes} lanes");
+                let worst = per_dispatch * rays.div_ceil(fewest) as usize;
+                assert!(worst <= RAYS_PER_DISPATCH, "{rays} rays, {fewest}..{most} subsets: up to {worst} rays per dispatch");
+            }
+            assert_eq!(hemisphere_sizes(rays, (1, 1)), (rays.clamp(1, WORKGROUP).next_power_of_two(), RAYS_PER_DISPATCH / rays as usize));
+        }
+    }
+
     /// The GPU baker, or None (test skipped) without a hardware adapter.
     fn gpu() -> Option<GpuBaker> {
         let g = GpuBaker::new();
-- 
2.55.0.windows.5

🤖 Generated with Claude Code

When every ray share of an antialiased texel fell below the surface, the
texel got the map's display neutral (raw thickness 1.0) where a 1x1 bake
gives the maximum ray distance, an outlier under min/max normalization.
Such a texel now reports what one query with no accepted ray does:
unoccluded, and as thick as the maximum ray distance.
Lanes are sized for a full texel's share of the rays, and so were the
queries per dispatch; but an edge texel with few covered subsamples casts
more rays per query, so in an unusual UV layout a dispatch could cast
several times RAYS_PER_DISPATCH rays. Dispatches are now sized from the
fewest subsets in the batch, so none exceeds the budget. Lanes, and so the
results, are unchanged.
The ray-counting test works from the query fields, and the bake-level
comparison averages shares, so neither pins down which rays each share of
a texel casts. Compare every query's GPU result with the CPU tracer's, for
shares of several sizes mixed with whole texels in one batch, including
shares that lose every ray.
# Conflicts:
#	crates/bake/src/lib.rs
#	crates/render/src/gpu_bake.rs
wgpu's error scopes are per thread, so the batch's scope on the calling
thread never saw a failed write_buffer made by a rayon worker: the error
went to the baker's no-op uncaptured-error handler and the batch traced
stale rows instead of falling back to the CPU. Each worker's write now
runs in a scope of its own.
A 96-texel row at 8x8 is one full 64-texel span and a partial one. The
position and world-normal maps of a quad must match the 1x1 bake texel for
texel; a span shifted by one texel fails.
The GPU tracer sized the threads that share a query's rays from the most
subsets of any query in the batch, so a batch holding only edge texels
(a run of thin UV slivers) reduced their rays in a different order, and
regrouping texels into batches changed a few values by float rounding.
Hemisphere now carries the bake's subsamples per texel and the threads are
sized from that, the same in every batch. 1x1 bakes are unchanged.
Each upload thread assembled its rows in a Vec and then write_buffer
copied them into wgpu's staging memory. The threads now write their rows
into a write_buffer_with view, so each row is written once. Maps are
bit-identical; on an M3 Pro an 8x8 bake without mesh curvature is about
10% faster and a 1x1 bake with it about 3% faster.
Rename the batch-size test to what it checks: an antialiased batch holds
2^18 texels' subsamples up to 2^20 of them, so only 2x2 batches hold as
many texels as unantialiased ones.
@simonhull

Copy link
Copy Markdown
Contributor Author

Thanks @SteamSmith. I merged #274's follow-ups into this branch (a merge, not a rebase) and pushed five commits for your notes. The description is updated.

  1. Upload errors on workers: a real bug. wgpu 30's core keeps error scopes per thread (HashMap<ThreadId, Vec<ErrorScope>>), so with the baker's no-op uncaptured handler a failed write on a rayon worker was lost. Fixed with your patch, so each worker's write has its own scope. a_failed_upload_is_an_error fails without it.

  2. Results depending on batching: fixed as you suggested. Hemisphere has a new subsamples field set from the bake context, and the GPU sizes threads per query from it, not from the batch's largest share. gpu_hemisphere_results_do_not_depend_on_batching checks that a batch of only small shares gives the same bytes as those shares inside a mixed batch, and the old sizing fails it. So "output is unchanged" no longer needs a qualifier.

  3. Speed claims: you're right that the table predates mesh curvature becoming the default. The description now leads with numbers on current main (M3 Pro, material ball):

    I couldn't reproduce the 1×1 slowdown on this Mac. You were right about the intermediate Vec in upload. Rather than cast_slice for the ray rows only, each thread now builds its rows, query rows included, straight into wgpu's staging memory with write_buffer_with. Maps hash identically before and after.

  4. Batch size: the test is now antialiased_batches_hold_more_subsamples_up_to_a_cap, with the texel counts for each antialiasing level in a comment. The description gives the per-level counts too. Each buffer stays under the 128 MiB binding limit (64 MiB of query rows and up to 96 MiB of results), about 256 MiB in all with staging, worked out from the code.

  5. Dispatch size: comes with the Bake: split each texel's rays between its antialiasing subsamples #274 merge. Dispatches are sized from the largest share.

  6. Constants: each of AA_BATCH, SPAN_SAMPLES and FILL_CHUNK now has a line saying why it has that value.

Your span test is in as antialiased_spans_write_each_texel_in_place. Shifting the second span by one texel fails it.

I ran the bake and render tests (135 passed), the engine bake tests (31), clippy, fmt and cargo xtask wasm. On the overlap with #360's batch constants: whichever lands second takes the merge.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants