Skip to content

Bake: split each texel's rays between its antialiasing subsamples - #274

Draft
simonhull wants to merge 5 commits into
storytold:mainfrom
simonhull:fix/bake-aa-ray-budget
Draft

simonhull wants to merge 5 commits into
storytold:mainfrom
simonhull:fix/bake-aa-ray-budget

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.

Fixes the antialiasing cost in #196. Antialiasing defaults to off, and with it off this PR changes nothing.

Cause

With antialiasing on, every subsample of a texel became a full bake sample, and every ray map (ambient occlusion, bent normal, thickness) cast its whole ray count per subsample. At 8×8 a texel cast 64 × its configured rays: 4096 AO rays at the default 64. A default 8K bake that takes about 68 s with AA off takes about 70 min with 8×8 on an M3 Pro GPU (extrapolated from the measured 47–58× at 2K), and hours on the CPU fallback. The configured ray count was really "rays per subsample".

Fix

A texel's rays are now split between its covered subsamples instead of repeated for each.

  • The ray count stays per texel. Each texel draws from one stratified pattern of max(rays, subsamples) directions (the same Hemisphere::direction pattern as before), rotated by the texel's seed. Its covered subsamples take interleaved shares of it: of k covered subsamples, number s casts rays s, s + k, s + 2k, …. A fully covered texel casts exactly the configured number of rays. Its directions are the same well-stratified set a 1×1 bake would use, only spread over the subsample positions. Edge texels split the same budget over fewer subsamples, so they don't get noisier.
  • A share holds only part of the pattern's elevations: its rays share their low index bits, and a ray's elevation comes from its bit-reversed index. That is harmless for AO and thickness, which average back to the whole pattern, but a bent normal normalized per share and then averaged leaned up to 11.6° off on the reference wall scene. So a subsample of a split texel returns the unnormalized sum of its open directions, and the texel adds its subsamples' sums and normalizes once. Its bent normal is the one its whole pattern gives, as at 1×1.
  • Query gains subset and subsets. The CPU tracer and the GPU shader both walk the share with a stride. The GPU packs the two values into the query's unused fourth row, so the buffer layout and Params don't change. Lanes per query are sized for one share, not for the whole pattern. Dispatches are sized so that even a batch of the largest shares stays under the per-dispatch ray budget.
  • If every ray of a subsample's share falls below the surface (shading normals far off the faces), it has no estimate. It reports NaN, and the texel average (or bent-normal sum) skips it, the same way a 1×1 texel skips its rejected rays. The texel average now skips non-finite values per map instead of turning the whole texel neutral. Without this, AO on leaning normals came out 0.28 instead of 0.10 at 8×8. If every share of a texel rejects all its rays, the texel takes the value a 1×1 texel with no accepted ray gets: AO 1.0 and thickness the maximum ray distance, not the display neutral.
  • One ray per subsample, the transfers from the high poly (normal, height, ID, opacity, position…), is unchanged: that is what AA is for.
  • With AA off, each texel is one query that casts every ray with the same seed. The output is bit-identical to before.

Measured

Apple M3 Pro. The scene is hilo from the #196 profile: a 4,096-triangle low poly baked from a 4.2M-triangle high poly at 2048². Default maps: AO and thickness at 64 rays each, plus normal, ID and the other transfers. Times are medians of 3 runs, in seconds. CPU 8×8 before is a single run (28 min).

tracer AA before after hemisphere rays per texel
GPU 1×1 4.40 4.50 128 → 128
GPU 8×8 248.5 26.9 (9.2×) 8192 → 128
CPU 1×1 32.7 33.3 (noise) 128 → 128
CPU 8×8 1656.6 54.8 (30×) 8192 → 128
  • Hemisphere tracing at 8×8 drops from 234 s to 10.5 s on the GPU, and from 1636 s to 32.4 s on the CPU. On the CPU that is the same as at 1×1.
  • What 8×8 still costs on top of 1×1 is the work that is meant to scale with subsamples: building and evaluating 64× the samples (about 13.7 s "other") and the per-subsample transfer rays.
  • The GPU also spends 2.7× longer than at 1×1 on the same number of hemisphere rays. Each query now casts 2 rays, so per-query setup dominates. Packing a texel's subsamples into one workgroup could close that gap; it is not part of this PR.
  • Summing the bent normals per texel doesn't change the speed: GPU 8×8 on hilo, run alternately with the build without it, took 33.98 s against 34.24 s (medians of 3, on a busier machine than the table above).
  • GPU 1×1 was 1.5–2% slower in repeated back-to-back runs (4.41/4.46 → 4.51/4.53), probably the per-query stride in the shader loop. Output is bit-identical.

Verified

  • New tests in crates/bake/src/tests.rs:

    • antialiasing_splits_each_texels_rays_between_its_subsamples counts rays through the public Tracer trait. At 2×2/4×4/8×8 a texel casts exactly max(rays, subsamples). Before the fix: 4× to 64× that.
    • antialiasing_keeps_the_mean_and_cost_of_traced_maps_and_still_smooths_them uses a floor through a turned cube, so occlusion and thickness both have hard slanted edges. At 4×4, AO and thickness keep the 1×1 mean against a 4× resolution box-filtered reference (bias ≤ 2e-4), cast the same rays as 1×1 (before the fix: 16×), and cut the edge-texel error about 10–15× (AO 0.109 → 0.007, thickness 0.075 → 0.007).
    • antialiasing_skips_ray_subsets_that_fall_entirely_below_the_surface fails if empty shares count as unoccluded.
    • without_antialiasing_a_texel_is_one_query_casting_every_ray checks that 1×1 is one query per texel, with no split.
    • antialiasing_keeps_bent_normals_unbiased bakes a quad beside a wall at 2×2, 4×4 and 8×8 and compares the mean bent normal of four bands with the 1×1 bake's. They are within 0.1° (limit 0.5°). With each share normalized on its own they were 0.7–10.8° off.
  • The analytic reference scenes (Bake: analytic reference scenes for the mesh-map baker #279, run here on top of this branch) all pass on the CPU and the GPU tracer. In occlusion_beside_a_wall (256 rays, eight bands of floor from the far edge to the wall's base, tolerance 1.4–2.5°), the bent normal's largest error per band, uniform / cosine rays:

    AA main share normalized on its own this PR
    1×1 0.04° / 0.04° 0.04° / 0.04° 0.04° / 0.04°
    2×2 0.03° / 0.00° 8.3° / 4.7° 0.05° / 0.03°
    4×4 0.02° / 0.03° 11.5° / 7.0° 0.04° / 0.03°
    8×8 0.00° / 0.03° 11.6° / 7.5° 0.04° / 0.04°

    The table is the CPU tracer. The suite checks 1×1 and 2×2; I ran 4×4 and 8×8 by hand. The GPU tracer gives the same errors to within 0.02°. AO was within tolerance in every case.

  • 1×1 output is bit-identical to main. I hashed the full data of all ten maps on two scenes (hilo with a high poly, ball without) at 2048², on both the CPU and GPU tracers, and all 40 hashes match.

  • gpu_bake_matches_the_cpu (2×2 AA, 16–24 rays) passes, so the GPU and CPU agree on the split.

  • Review follow-ups:

    • antialiasing_gives_a_texel_with_no_accepted_ray_the_unantialiased_value fails without the fallback (thickness 1.0 instead of 0.2).
    • hemisphere_dispatches_stay_under_the_ray_budget fails with the old dispatch sizing.
    • gpu_hemisphere_queries_match_the_cpu_share_by_share compares every GPU query with the CPU one for shares of 1, 3, 4, 16 and 64. A shader that ignores the stride or the share offset fails it.
    • GPU bake times with the new dispatch sizing (M3 Pro, material ball, 1024² 8×8 and 256² 8×8 at 4096 rays) are within run-to-run noise of before.
  • 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.

What antialiasing does now

Antialiasing still smooths edges and keeps the mean, but it no longer reduces ray noise. A texel casts the configured rays however finely it is sampled, so texel-to-texel AO noise stays at the 1×1 level instead of falling with the subsample count. This changes what the setting does ("2×2 on a 2K map renders at 4K" is no longer true for ray maps), so it needs a maintainer's decision. A user who wants less noise can raise the ray count, which now costs what it says.

Where a leaning shading normal makes shares accept different numbers of rays, the equal-weight mean of share means is slightly biased: about −0.005 AO and thickness at 4×4, against −0.0002 before. The leaning-normal test runs at 8×8 with 64 rays, one ray per share, so it doesn't cover this.

Not changed

  • The interleaving stays a plain stride. I also tried rotating the deal (in block j of k rays, share s takes ray j·k + (s + j) mod k), so that every share spans every elevation band. On its own it cut the wall-scene bent-normal error from up to 11.6° to 1.9°, still far above main's 0.04°, because each share's bent normal was still normalized on its own. Combined with the single normalization it made no measurable difference to the reference scenes or the leaning-normal test, and it made the edge error in the AA test worse (AO 0.0072 → 0.0114, thickness 0.0069 → 0.0156). It would also add a modulo per ray to the shader loop.
  • Mesh curvature still casts its ring probes per subsample. The probes are a fixed geometric stencil, not Monte Carlo samples, so splitting them would change what each sample measures.
  • The rays setting and its 4096 cap stay per texel.
  • Thickness min/max normalization still stretches to the single most extreme texel. An 8×8 bake now has 1×1-level noise, not 64× the rays, so that one extreme texel can shift the normalized mean a little (hilo at 256²: 0.903 at 1×1, 0.936 at 8×8; the raw means are equal). This is the existing sensitivity of min/max normalization to outliers.

@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.
@simonhull
simonhull force-pushed the fix/bake-aa-ray-budget branch from a5f3e18 to cbac42a Compare November 10, 2026 16:06
@SteamSmith

Copy link
Copy Markdown
Collaborator

Review notes (prepared with Claude Code)

PR #274

Verdict: merge after rework. The ray split is sound. One bug needs a fix, and the maintainers need to decide one behaviour question.

What I checked

  • The shares are interleaved so a fully covered texel casts exactly max(rays, subsamples) rays, and seeds are the global texel index. With antialiasing off, all ten maps are bit-identical to main on two scenes, on both the CPU and GPU tracers (40 of 40 hashes). The GPU shader matches the CPU query by query (largest difference 9.5e-7).
  • Both the bent-normal sum and the NaN skip are needed: normalising each share on its own gives a 2.05 degree error at 2x2, and counting empty shares as unoccluded gives AO 0.276 instead of 0.096. The PR's own assertions catch both.
  • An 8x8 CPU bake of a material ball at 256 squared (AO and thickness at 64 rays) went from 17.5 s to 0.8 s (single runs). I reviewed this on main before you rebased; the change is the same and both patches below apply to the rebased branch.

Changes requested

  1. A texel whose subsamples all reject every ray gets the display neutral. Raw thickness comes out 1.0 with antialiasing against 0.25 (the maximum ray distance) without it, and main gives 0.25 either way, so this is a regression. It only happens for degenerate shading normals or very low ray counts, but 1.0 is an outlier under min/max thickness normalisation. Fix: when no ray was accepted, use 1.0 for AO and the maximum distance for thickness, as the unantialiased path does. Patch 1 below, with a test that fails without it.
  2. Dispatch sizing (optional hardening). Lanes and queries per dispatch are both sized from the largest subset count in a batch. A dispatch cannot hold more texels than its batch, and a texel casts at most max(rays, subsamples) rays however it is split, so the realistic worst case at 4096 rays is about 4x the ray budget, and it needs a pathological UV layout. Sizing dispatches from the smallest subset count removes it (patch 2); it means more, smaller dispatches, which I did not time. I could not test the driver-watchdog case on a slow GPU.
  3. Add a per-query GPU-against-CPU test. The ray-counting test works from the query fields, so it cannot notice a tracer that ignores the stride. A probe that compares each GPU query with the CPU one passes today and would catch it.
  4. Narrow "Fixes Baking mesh maps is extremely slow #196". Antialiasing defaults to off and the report did not say it was on; with it off this PR changes nothing. "Fixes the antialiasing cost in Baking mesh maps is extremely slow #196" is accurate.

Question for the maintainers

The documented behaviour is "2x2 on a 2K map renders at 4K". With this PR antialiasing still smooths edges and keeps the mean, but it no longer reduces ray noise: texel-to-texel AO spread stays 0.0044 at every level, where main falls to 0.00056 at 8x8. That is a reasonable trade for speed, but it changes what the setting does, so it should be an explicit decision.

Minor

  • When shares accept different numbers of rays (leaning shading normals), the equal-weight mean of share means is slightly biased: at 4x4 the mean AO moves by -0.0050 against -0.0002 on main (thickness -0.0048 against -0.0017). That is small, but the PR's leaning-normal test only runs 8x8 at 64 rays, where each share is a single ray and the bias cannot show, so nothing tests it. It is worth stating in the text.
  • Not run: GPU timing at 8K, a driver-watchdog test, cargo xtask ci, the Bake: analytic reference scenes for the mesh-map baker #279 reference scenes on this branch.

Patch 1: a split texel with no accepted ray keeps the unantialiased value

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 f242e621daae879415e22390ea118919546f1368 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 1/2] 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 b8afbbe..1c5bc6b 100644
--- a/crates/bake/src/lib.rs
+++ b/crates/bake/src/lib.rs
@@ -370,22 +370,27 @@ 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);
 
     rows.par_iter_mut().zip(&samples_by_row).zip(&row_offsets).for_each(|((row, samples), &first)| {
         let mut sample_values = [[0.0f32; 3]; BakedMap::ALL.len()];
         let mut row_sample_index = 0;
         for x in 0..width {
             let texel_samples = samples.get(row_sample_index..).unwrap_or_default().iter().take_while(|sample| sample.x == x).count();
-            let bent = texel_bent_normal(bent_results, first + row_sample_index..first + row_sample_index + texel_samples);
+            let texel = first + row_sample_index..first + row_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(row_sample_index).filter(|sample| sample.x == x) {
                 let sample_index = first + row_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);
@@ -411,6 +416,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 2: size hemisphere dispatches from the fewest covered subsamples (optional)

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 714da5506ef95bc973b521d082415fc6c1708aec 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 2/2] 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 several times RAYS_PER_DISPATCH rays in an
uncommon layout. Size dispatches from the fewest covered subsamples.

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 db292c0..357d821 100644
--- a/crates/render/src/gpu_bake.rs
+++ b/crates/render/src/gpu_bake.rs
@@ -301,6 +301,16 @@ impl GpuScene<'_> {
     }
 }
 
+/// 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]
@@ -329,14 +339,15 @@ impl RayScene for GpuScene<'_> {
             })
             .collect::<Result<Vec<_>, BakeError>>()?
             .concat();
-        // 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 {
@@ -362,7 +373,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;
@@ -386,6 +397,22 @@ mod tests {
 
     use super::*;
 
+    /// 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.
@simonhull

Copy link
Copy Markdown
Contributor Author

Thanks @SteamSmith. I checked each point and agree with all of them. Pushed 74e1ddb, 0d41478 and dced3e4, and updated the description.

  1. No accepted ray falls back to the display neutral: a real regression, fixed with your lib.rs change. A texel whose shares all reject every ray now gets AO 1.0 and the maximum distance for thickness, as at 1×1. I moved the test into src/tests.rs as antialiasing_gives_a_texel_with_no_accepted_ray_the_unantialiased_value, reusing the existing helpers. Without the fix it fails with thickness 1.0 against 0.2.
  2. Dispatch sizing: applied unchanged. Lanes are still sized from the largest share, so results don't change, and reverting it fails hemisphere_dispatches_stay_under_the_ray_budget. You hadn't timed it, so I did: GPU bakes on an M3 Pro (material ball, AO, thickness and bent normal, 1024² 8×8 at 64 and 256 rays, 2×2 at 256, and 256² 8×8 at 4096 rays) are within run-to-run noise of before. All dispatches go in one submission.
  3. Per-query GPU test: added gpu_hemisphere_queries_match_the_cpu_share_by_share. It runs shares of 1, 3, 4, 16 and 64 in one batch on the material ball, including shares that lose every ray. A shader that ignores the stride fails it, and so does one that keeps the stride but ignores the share offset. gpu_bake_matches_the_cpu also catches both, so the new test mainly pins down where the mismatch is.
  4. "Fixes Baking mesh maps is extremely slow #196": narrowed to "the antialiasing cost in Baking mesh maps is extremely slow #196".

The maintainer question: the description now has a "What antialiasing does now" section. It says plainly that antialiasing no longer reduces ray noise and that this changes what the setting does. It also states the share-mean bias you measured (about −0.005 at 4×4) and that the leaning-normal test can't see it.

I ran the bake and render tests (131 passed), the engine bake tests (31), clippy, fmt and cargo xtask wasm.

@autocraft-bot autocraft-bot Bot added performance needs decision Needs a product or scope decision by a maintainer labels Nov 26, 2026

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

Labels

needs decision Needs a product or scope decision by a maintainer performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants