Repository navigation
Conversation
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. CodeRabbit Verify
|
|
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.
34aa22e to
4036655
Compare
|
Review notes (prepared with Claude Code) PR #275Verdict: 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
Changes requested
Patch 2 below is a test that checks a row with a full span and a partial one. Notes
Patch 1: catch upload errors on the threads that writeThe changes described above, as a patch you can apply ( Show the patchFrom 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.5Patch 2: test that antialiased spans write each texel in placeThe changes described above, as a patch you can apply ( Show the patchFrom 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.5Patch 3: thickness fallback (the first fix on #274, adapted to this branch)The changes described above, as a patch you can apply ( Show the patchFrom 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.5Patch 4: dispatch sizing (the optional fix on #274, adapted to this branch)The changes described above, as a patch you can apply ( Show the patchFrom 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.
|
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.
Your span test is in as I ran the bake and render tests (135 passed), the engine bake tests (31), clippy, fmt and |
# Conflicts: # crates/bake/src/lib.rs
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
hiloscene 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 inhemispheresfor 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:bake_rowsbuilds 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.hemispherescollected aVecof rows per query, concatenated them into a second buffer, andwrite_buffercopied 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_rowsworks 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.queue.write_buffer_with, with no intermediateVec. 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.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.GpuScenesplits into the scene (roots) andBatches(buffers andrun), 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.
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).
hilois the 4,096-triangle low poly baked from a 4.2M-triangle high poly.ballis 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.Verified
antialiased_batches_hold_more_subsamples_up_to_a_cap(crates/bake/src/tests.rs) counts batches through the publicTracertrait. 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_placechecks a row with a full span and a partial one. Shifting the second span by one texel fails it.a_failed_upload_is_an_errorfails 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.hiloandball, GPU 1×1, GPU 8×8 and CPU 8×8.hiloandball, CPU and GPU), and at 1×1 tomain(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 onhilo, 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_cpuandgpu_respects_secondary_ray_filters_and_ground_planepass, and so do all 58 bake tests, including the ray-budget PR's tests.cargo +1.96.0 xtask cipassed before the review changes. Since then I've run the bake, render and engine bake tests, clippy, fmt andcargo xtask wasm.Not changed
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.bake.wgsl,Query,Paramsand the 64-byte query row are untouched.RaySceneis 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 asyncRayScene: a larger change for another PR.