Skip to content

Bake: analytic reference scenes for the mesh-map baker - #279

Draft
simonhull wants to merge 7 commits into
storytold:mainfrom
simonhull:test/bake-reference-scenes
Draft

simonhull wants to merge 7 commits into
storytold:mainfrom
simonhull:test/bake-reference-scenes

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.

What

A correctness suite for the mesh-map baker. The roadmap says baking accuracy is unverified, and that Height, Bent Normal and Opacity in particular need reference validation. These tests build small scenes in code where the correct map values follow in closed form, so they fail when the baker is wrong, not just when its output changes. They are meant to back the baker speedups (#195, #196) and any later ones.

  • crates/bake/tests/reference_scenes/mod.rs holds the scenes, derivations and checks. Each check takes the tracer as a parameter.
  • crates/bake/tests/reference.rs runs them on the CPU tracer, one test per scene.
  • crates/render/src/gpu_reference.rs includes the same file (#[path]) and runs every check on the GPU tracer. Without an adapter it skips, the same way gpu_bake_matches_the_cpu does.
  • crates/engine/tests/bake.rs gains an end-to-end check of the exported normal in both formats.

Monte Carlo tolerances are 4σ of the mean, from a bound on the per-ray variance times the rays averaged. Each tolerance's reasoning is in a comment next to it. The tolerances assume only the configured rays per texel, so they hold whether antialiasing repeats rays per subsample (main) or splits them (#196). All tests are fast: the CPU file runs in about 0.3 s in release, and the GPU run in about 0.7 s.

Scenes and expected values

Scene Expected (closed form) Tolerance Measured worst
AO beside a wall of height h, distance d, 8 bands × 2 AA modes × 2 distributions uniform 1 − β/π, cosine (1 + cos β)/2, β = atan(h/d) (lune solid angle and view factor) 4σ Bernoulli, 0.004–0.007 (+1e-3 for the finite wall) 0.0005
Bent normal, same scene uniform: leans β/2 away from the wall; cosine: (−sin²β, π − β + ½ sin 2β) normalized 4σ of the mean direction, 1.4–2.5° 0.04°
AO in an open 2×2×1 box, 4 rings sum of the opening's corner-rectangle solid angles (uniform) or view factors (cosine, Howell B-2) 4σ, 0.005–0.012 0.0002
Bent normal in the box (uniform) mean direction of the opening (Arvo's vector irradiance) as above 0.05°
Height of two steps (+0.05, −0.03) Manual 0.5 + h; ray distances 0.5 + h/(f + r); min/max 1 and 0 1e-5 0
Height of a spherical cap (R 1, 0.2 high) √(1 − r²) − 0.8 2e-4 (linear interpolation of the 0.01 grid), rim excluded 4.2e-5
Tangent-space normal of a tilted plane, plain / mirrored / 90°-rotated UVs (n·T, n·B, n·N), T along +u, B up the image 1e-5 6e-8
World normal (with and without high poly) and bounding-box position the interpolated normal / (p − min)/(max − min), averaged over 2×2 subsamples 1e-5 0
Thickness of a 0.2 slab: 120° cone and full hemisphere (capped at D = 1), uniform and cosine T ln(1/C)/(1 − C), 2T/(1 + C), T(1 + ln(D/T)), 2T − T²/D 4σ, 0.0023 0.0002
Opacity of a hole whose edges sit on quarter texels, AA 1×1 and 4×4 the share of subsamples outside the hole 1e-6 0 (46 partial texels)
Padding between two islands, dilation 3 and 16 each gutter texel takes the nearer island's value (Chebyshev), neutral past the width exact 0 wrong of 936 / 2016
UV seam: cylinder halves with plain and rotated UVs, ringed high poly decoded tangent normals agree across the seam; world normals too 2.5° / 5° (1.5 texels of gradient each side, derived in the comment) 0.58° / 2.45°
Export: tilted high poly over the plane primitive OpenGL (n·x, −n·z, n·y), DirectX (n·x, n·z, n·y) 1 step of 8 bits pass

Normal-map round trip

A 32 × 16 UV sphere baked at 256² from a bumpy sphere (bump tilt p50 6.0°, max 14.7°). Every texel is decoded the way the viewport does: the shade_mesh frame (interpolated normal, tangent made orthogonal, cross(n, t) · w with interpolated w), the display's 8-bit packing (core::blend::rnm onto a flat detail, (v · 255 + 0.5) as u8) and the shader's snorm8. The result is compared with the high-poly normal the transfer ray hit, found by casting the same ray independently.

p50 p99 max assert
float decode 0.0000° 0.020° 0.040° p99 < 0.05°, max < 0.1°
8-bit, as the viewport shows it 0.359° 0.597° 0.672° p50 < 0.45°, p99 < 0.75°, max < 0.8° (bound √3 · 0.0079 rad = 0.78°)

The mirrored-UV sphere (bitangent sign −1 everywhere) gives the same numbers (8-bit max 0.681°). The bake and the viewport agree on the frame, the bitangent sign and the OpenGL green, except for the case below.

Results

Findings

Each of these is fixed in its own PR. This suite stays as the check.

  1. Splitting a texel's rays between AA subsamples biased the bent normal. I found this in my own first version of Bake: split each texel's rays between its antialiasing subsamples #274. Each subsample cast rays s, s + k, s + 2k, … of the texel's pattern. A ray's elevation is the radical inverse of its index, so each subsample was confined to one elevation band. AO is linear in the rays, so it stayed right. The bent normal, though, was normalized per subsample before being averaged, and came out up to 8.3° off beside a wall at 2×2 (main: 0.04°). Bake: split each texel's rays between its antialiasing subsamples #274 now sums the unnormalized directions over the texel and normalizes once. occlusion_beside_a_wall passes at 2×2, 4×4 and 8×8.
  2. The bake and the viewport disagree on triangles with mixed bitangent signs.
    • geom::surface_at, and so the bake and the CPU path tracer, takes the sign w of the triangle's first vertex.
    • shade_mesh interpolates tan.w, which flips the bitangent partway across the triangle.
    • Mesh::compute_tangents keeps one tangent per vertex, so mirrored UVs meeting at a vertex produce such triangles. So do the zero-area pole triangles of a UV sphere.
    • Minimal case: two triangles that share only their apex, the second with mirrored UVs, with tangents from compute_tangents. The viewport decodes the bake up to 40.7° off.
    • mixed_tangent_signs_decode_like_the_viewport (CPU and GPU) is #[ignore]d here until Keep MikkTSpace's tangent for each triangle corner #277 lands. On that branch it passes at 0.00°.
  3. The viewport's 8-bit main-normal packing didn't match its decode. The display packed round(255 (½ + ½x)), but snorm8 reads (byte − 128)/127. As a result, every decoded normal was off by a median 0.36° (p99 0.60°). Pack the viewport's main normal the way the shaders read it #278 packs 128 + 127x, as the coat normal already did. This halves the error to rounding alone.

Not covered

  • Mesh curvature and normal-map curvature (no closed form I trust).
  • ID maps, skew and painted cages, custom cage files, match by mesh name (existing tests cover them behaviourally).
  • AO attenuation curves beyond None (the existing occlusion_falls_off_linearly_to_the_max_distance covers Linear), the ground plane, and backface or self-occlusion filters.
  • Height "Relative to ray distances" with frontal ≠ rear. The bake maps it as 0.5 + h/(f + r), centred on zero height. map/normalization.rs has a branch that would map [−rear, frontal] onto 0..1 instead, but it is skipped for this mode, so it never runs. The two differ when f ≠ r. The test uses f = r, where they agree. Which one is intended needs a decision.
  • The viewport's Shade::normal_y (DirectX green flip) is never set to −1. Baked and imported normals reach the shader as OpenGL, so the export path is the only DirectX conversion. The engine test covers it.
  • UDIM atlases and rectangular maps.

@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.

@chasse20

chasse20 commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Nice

@chasse20 chasse20 self-assigned this Nov 6, 2026
@chasse20

Copy link
Copy Markdown
Contributor

Claimed

@SteamSmith

Copy link
Copy Markdown
Collaborator

I'm taking this one for review.

Small scenes built in code whose correct map values follow in closed
form: AO and bent normals beside a wall and inside an open box (lune
solid angle, view factors, vector irradiance), height of a step and a
spherical cap, tangent-space normals of a tilted plane in three UV
layouts, world normal and position, slab thickness, opacity of a hole
with 4x4 antialiasing, padding between two islands, and a UV seam.

A normal-map round trip bakes a bumpy sphere and decodes every texel the
way the viewport does (shade_mesh frame, 8-bit display packing, snorm8),
comparing with the high-poly normal the transfer ray hit.

The scenes take the tracer as a parameter: crates/bake/tests/reference.rs
runs them on the CPU, and the render crate includes the same file to run
them on the GPU tracer. An engine test checks the exported normal of a
tilted high poly in both OpenGL and DirectX.

mixed_tangent_signs_decode_like_the_viewport is ignored: the bake takes
a triangle's first-vertex bitangent sign, the viewport interpolates it,
and compute_tangents keeps one tangent per vertex, so two triangles
meeting at a vertex with mirrored UVs decode up to 40.7 degrees off. It
passes with the per-corner tangent sign fix.
@simonhull
simonhull force-pushed the test/bake-reference-scenes branch from abbbcec to b101fa1 Compare November 10, 2026 16:07
@SteamSmith

Copy link
Copy Markdown
Collaborator

Review notes (prepared with Claude Code)

PR #279

Verdict: merge after a small rework. Analytic expectations are what the baker has been missing. I re-derived each one independently and they are correct, the suite is deterministic and fast, and it catches baker bugs the 65 existing unit tests miss.

What I checked

  • Derivations: wall AO and bent normal (uniform and cosine), open-box corner solid angles and view factors, the four slab-thickness integrals, the spherical-cap bound, the three tilted-plane tangent frames, the seam bounds and the engine's OpenGL/DirectX expectations. All correct.
  • Runs: three repeat runs give byte-identical output on CPU and GPU. CPU suite about 0.35 s (0.46 s in the dev profile CI uses), GPU about 2-3 s. clippy -D warnings and cargo fmt --check are clean. No behaviour changes; where the spec is silent the tests pin what the code does today.
  • Mutation testing (one deliberate break of the baker at a time): dropping tangent.w and a constant ray seed for every texel are caught by this suite but not by the unit tests; flipping the bitangent sign, a UV v-flip and an unnormalised interpolated normal are caught by both; a cosine exponent of 0.45, uniform elevation x^1.05, a missed thickness ray counted as 0.95 D, no ray rotation and a bent normal that keeps 10% of occluded rays are all caught (these were mutants of the GPU shader; the 0.95 D one is caught only by the uniform 180-degree case, and after the tolerance fix below only narrowly, 0.010 off against 0.0091).
  • With Keep MikkTSpace's tangent for each triangle corner #277: the ignored mixed-sign scenes pass (0.00 degrees, no mixed texels) both on Keep MikkTSpace's tangent for each triangle corner #277 as submitted and with the reached-corner sign rule suggested there. Once a triangle has one sign the bake and viewport agree under any rule, so this suite does not need to tell the rules apart.

Changes requested

  1. Thickness tolerance for the two 180-degree cases. thickness_of_a_slab derives every tolerance from the 120-degree cone's cosine, so these two cases bound a ray's distance by [T, 2T] instead of [T, D], giving 0.0023 instead of 0.0091. (Against the true variance of independent rays the stated "4 sigma" is 1.4 sigma for uniform and 2.0 sigma for cosine, so it is still too tight and the fix stands.) Use each case's own half angle; patch 1.
  2. Doc comments. About 61% of the new functions have one (43 of 71); CodeRabbit's docstring check wants 80%. Patch 1 brings it to 100%. Patch 2 is applied on top of patch 1.
  3. After Keep MikkTSpace's tangent for each triangle corner #277 lands, remove both #[ignore]s and assert that the round trip finds no texels on mixed-sign triangles instead of leaving them out.

Suggestions

  • Texels an island edge only partly covers are not tested. A bake that divides each texel by all 16 subsamples instead of the covered ones passes all 65 unit tests and all 12 scenes. Patch 2 adds a quad inset by a quarter texel at 4x4 antialiasing (124 partly covered texels); it fails with that mutant (0.4375 off) and passes on main on CPU and GPU.
  • GPU tests skip too eagerly. The probe turns any GPU bake error into a skip, so a WGSL compile error in bake.wgsl makes this test and gpu_bake_matches_the_cpu print "skipping" and pass. Skip only when there is no hardware adapter.
  • Some expected values come from the code under test. texels() uses UvGBuffer and surface_at, so a v-flip in the UV rasteriser moves the bake and the expectation together (only the seam scene catches it). world_normal_and_position checks the pipeline, not geometry.
  • Tolerances are honest 4-sigma bounds for independent rays, but the baker's rotated Hammersley rays give errors 10-60 times smaller, so small biases pass: a cosine exponent of 0.49 survives, and so does a missed thickness ray counted as 0.95 D in the cosine hemisphere case. Tightening with a measured error envelope or more rays is the maintainers' call.
  • viewport_tangent_normal copies today's 8-bit packing instead of calling it, so after Pack the viewport's main normal the way the shaders read it #278 it no longer models the viewport. Its note that each component is off by at most 0.0079 holds only for x >= 0 (0.0089 at x = -0.26), so max < 0.8 degrees is not guaranteed by the derivation (measured 0.67 and 0.68).
  • Never exercised: min_distance is always 0, and AO and bent normal always share one ray pass. The opacity scene prints its 46 partly covered texels but asserts none. The open_box doc comment sits on BOX_HEIGHT rather than the function. The seam's 5-degree budget is valid only because the y and theta errors are perpendicular (4.5 degrees, not 6.1); the comment should say so.
  • Height: with frontal = rear the test cannot tell h / (f + r) from h / (2f), and the RelativeToRayDistances branch at normalization.rs:52-56 is unreachable because line 17 skips that mode. The PR already asks for a maintainer decision on the intended mapping.
  • Magic numbers are test-only; the round-trip limits are fitted to measurements rather than derived (stating that would help).

Notes

Patch 1: per-case thickness tolerance and doc comments

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 60dff5dac7f15b3a8cb657439979af0ae7518045 Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 07:06:41 -0500
Subject: [PATCH] test(#279): per-case thickness tolerance, doc comments on
 helpers

The slab thickness tolerance used the 120-degree cone's cosine for every
case, so the two hemisphere cases bounded a ray's distance by [T, 2T]
instead of [T, D] and their "4 sigma" was about 1 sigma of the bound
(0.0023 instead of 0.0091). Use each case's own half angle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 crates/bake/tests/reference.rs            | 14 ++++++++++++++
 crates/bake/tests/reference_scenes/mod.rs | 18 ++++++++++++++++--
 crates/render/src/gpu_reference.rs        |  2 ++
 3 files changed, 32 insertions(+), 2 deletions(-)

diff --git a/crates/bake/tests/reference.rs b/crates/bake/tests/reference.rs
index d0bb814..2b7e6ee 100644
--- a/crates/bake/tests/reference.rs
+++ b/crates/bake/tests/reference.rs
@@ -4,71 +4,85 @@ mod reference_scenes;
 
 use texturecraft_bake::tracing::CpuTracer;
 
+/// Run the reference check `name` on the CPU tracer
 fn run(name: &str) {
     let (_, check) = reference_scenes::CHECKS.iter().find(|(check, _)| *check == name).unwrap();
     check(&CpuTracer);
 }
 
+/// The `occlusion_beside_a_wall` reference scene on the CPU tracer
 #[test]
 fn occlusion_beside_a_wall() {
     run("occlusion_beside_a_wall");
 }
 
+/// The `occlusion_inside_an_open_box` reference scene on the CPU tracer
 #[test]
 fn occlusion_inside_an_open_box() {
     run("occlusion_inside_an_open_box");
 }
 
+/// The `height_of_a_step` reference scene on the CPU tracer
 #[test]
 fn height_of_a_step() {
     run("height_of_a_step");
 }
 
+/// The `height_of_a_spherical_cap` reference scene on the CPU tracer
 #[test]
 fn height_of_a_spherical_cap() {
     run("height_of_a_spherical_cap");
 }
 
+/// The `tangent_normal_of_a_tilted_plane` reference scene on the CPU tracer
 #[test]
 fn tangent_normal_of_a_tilted_plane() {
     run("tangent_normal_of_a_tilted_plane");
 }
 
+/// The `world_normal_and_position` reference scene on the CPU tracer
 #[test]
 fn world_normal_and_position() {
     run("world_normal_and_position");
 }
 
+/// The `thickness_of_a_slab` reference scene on the CPU tracer
 #[test]
 fn thickness_of_a_slab() {
     run("thickness_of_a_slab");
 }
 
+/// The `opacity_of_a_hole` reference scene on the CPU tracer
 #[test]
 fn opacity_of_a_hole() {
     run("opacity_of_a_hole");
 }
 
+/// The `normal_map_round_trip` reference scene on the CPU tracer
 #[test]
 fn normal_map_round_trip() {
     run("normal_map_round_trip");
 }
 
+/// The `normal_map_round_trip_with_mirrored_uvs` reference scene on the CPU tracer
 #[test]
 fn normal_map_round_trip_with_mirrored_uvs() {
     run("normal_map_round_trip_with_mirrored_uvs");
 }
 
+/// The `padding_fills_each_gutter_from_the_nearest_island` reference scene on the CPU tracer
 #[test]
 fn padding_fills_each_gutter_from_the_nearest_island() {
     run("padding_fills_each_gutter_from_the_nearest_island");
 }
 
+/// The `tangent_normals_agree_across_a_uv_seam` reference scene on the CPU tracer
 #[test]
 fn tangent_normals_agree_across_a_uv_seam() {
     run("tangent_normals_agree_across_a_uv_seam");
 }
 
+/// The mixed-sign reference scene on the CPU tracer
 #[test]
 #[ignore = "fails until the per-corner tangent sign fix: compute_tangents keeps one tangent per vertex, so mirrored UVs meeting at a vertex mix bitangent signs in a triangle"]
 fn mixed_tangent_signs_decode_like_the_viewport() {
diff --git a/crates/bake/tests/reference_scenes/mod.rs b/crates/bake/tests/reference_scenes/mod.rs
index 9a8f096..3202742 100644
--- a/crates/bake/tests/reference_scenes/mod.rs
+++ b/crates/bake/tests/reference_scenes/mod.rs
@@ -44,6 +44,7 @@ pub const CHECKS: [(&str, Check); 12] = [
 // ---------------------------------------------------------------------------------------------
 // Baking and sampling helpers
 
+/// Bake settings at `resolution`² for `maps`, with no dilation or diffusion so every texel is a raw bake value
 fn settings(resolution: u32, antialiasing: BakeAntialiasing, maps: &[BakedMap]) -> BakeSettings {
     let mut settings = BakeSettings::default();
     settings.common.resolution = BakeResolution::from_pixels(resolution).unwrap();
@@ -66,6 +67,7 @@ fn cage(settings: &mut BakeSettings, frontal: f32, rear: f32) {
     settings.cage.relative_to_bounding_box = false;
 }
 
+/// Bake `low` (and `high`, if any) on `tracer`, failing if the tracer fell back to the CPU
 fn bake_with(tracer: &dyn Tracer, low: &Mesh, high: Option<&Mesh>, settings: &BakeSettings) -> BakeOutput {
     let low_bvh = Bvh::new(low);
     let high_bvh = high.map(Bvh::new);
@@ -87,15 +89,18 @@ struct Texel {
 }
 
 impl Texel {
+    /// Mean of `value` over the texel's covered subsamples
     fn mean(&self, value: impl Fn(&Surface) -> f32) -> f32 {
         self.surfaces.iter().map(value).sum::<f32>() / self.surfaces.len() as f32
     }
 
+    /// Mean of the vector `value` over the texel's covered subsamples
     fn mean_vector(&self, value: impl Fn(&Surface) -> Vec3) -> Vec3 {
         self.surfaces.iter().map(value).sum::<Vec3>() / self.surfaces.len() as f32
     }
 }
 
+/// Every texel of material 0 that has at least one covered subsample, with those subsamples' surfaces
 fn texels(mesh: &Mesh, resolution: u32, antialiasing: BakeAntialiasing) -> Vec<Texel> {
     let (size, per_axis) = (resolution as usize, antialiasing.samples_per_axis() as usize);
     let fine = UvGBuffer::new(mesh, 0, (size * per_axis) as u32, (size * per_axis) as u32);
@@ -110,22 +115,27 @@ fn texels(mesh: &Mesh, resolution: u32, antialiasing: BakeAntialiasing) -> Vec<T
         .collect()
 }
 
+/// The first component of `map` at texel `index`
 fn scalar(output: &BakeOutput, map: BakedMap, index: usize) -> f32 {
     output.maps[&map][index * map.components()]
 }
 
+/// The three components of `map` at texel `index`
 fn vector(output: &BakeOutput, map: BakedMap, index: usize) -> Vec3 {
     Vec3::from_slice(&output.maps[&map][index * 3..index * 3 + 3])
 }
 
+/// A packed 0..1 vector back in −1..1
 fn unpack(packed: Vec3) -> Vec3 {
     packed * 2.0 - Vec3::ONE
 }
 
+/// A −1..1 vector packed into 0..1, as the baker stores normals
 fn pack(normal: Vec3) -> Vec3 {
     normal * 0.5 + Vec3::splat(0.5)
 }
 
+/// The angle between two directions, in degrees
 fn degrees_between(a: Vec3, b: Vec3) -> f32 {
     a.normalize().dot(b.normalize()).clamp(-1.0, 1.0).acos().to_degrees()
 }
@@ -281,6 +291,7 @@ pub fn occlusion_beside_a_wall(tracer: &dyn Tracer) {
 /// Floor `-1..1` square (baked) inside four walls of height `BOX_HEIGHT` facing inwards, no lid
 const BOX_HEIGHT: f32 = 1.0;
 
+/// The open box scene: the floor (material 0) and its four walls (material 1)
 fn open_box() -> Mesh {
     let mut mesh = floor([-1.0, 1.0], [-1.0, 1.0], 0.0, |x, z| Vec2::new((x + 1.0) * 0.5, (z + 1.0) * 0.5));
     let h = BOX_HEIGHT;
@@ -368,6 +379,7 @@ pub fn occlusion_inside_an_open_box(tracer: &dyn Tracer) {
 // ---------------------------------------------------------------------------------------------
 // Height
 
+/// Height-map settings with `normalization` and a scaling divisor of 1
 fn height_settings(resolution: u32, normalization: HeightNormalization) -> BakeSettings {
     let mut settings = settings(resolution, BakeAntialiasing::None, &[BakedMap::Height]);
     settings.maps.height.parameters.normalization = normalization;
@@ -515,8 +527,10 @@ pub fn thickness_of_a_slab(tracer: &dyn Tracer) {
         settings.maps.thickness.parameters.self_occlusion = SelfOcclusion::Always;
         let output = bake_with(tracer, &slab, None, &settings);
         let measured = top.iter().map(|t| scalar(&output, BakedMap::Thickness, t.index)).sum::<f32>() / top.len() as f32;
-        // A ray's distance lies in [T, min(T / C, D)]: variance ≤ (range / 2)²
-        let range = (T / cone.max(T / max_distance)).min(max_distance) - T;
+        // A ray's distance lies in [T, min(T / C, D)], C the cosine of this case's half angle
+        // (0 for the hemisphere, where the cap D bounds it): variance ≤ (range / 2)²
+        let case_cone = (spread * 0.5f32).to_radians().cos();
+        let range = (T / case_cone.max(T / max_distance)).min(max_distance) - T;
         let tolerance = four_sigma((range * 0.5).powi(2), RAYS as usize * top.len());
         eprintln!("slab thickness, {spread}° {distribution:?}: {measured:.4} vs {expected:.4} (±{tolerance:.4}) over {} texels", top.len());
         assert!((measured - expected).abs() < tolerance, "slab thickness {spread}° {distribution:?}: {measured} vs {expected}");
diff --git a/crates/render/src/gpu_reference.rs b/crates/render/src/gpu_reference.rs
index 60e167b..833d1b9 100644
--- a/crates/render/src/gpu_reference.rs
+++ b/crates/render/src/gpu_reference.rs
@@ -39,6 +39,7 @@ fn gpu() -> Option<GpuBaker> {
     }
 }
 
+/// Every reference scene on the GPU tracer (skipped without an adapter)
 #[test]
 fn gpu_bakes_the_reference_scenes() {
     let Some(gpu) = gpu() else { return };
@@ -48,6 +49,7 @@ fn gpu_bakes_the_reference_scenes() {
     }
 }
 
+/// The mixed-sign reference scene on the GPU tracer
 #[test]
 #[ignore = "fails until the per-corner tangent sign fix: compute_tangents keeps one tangent per vertex, so mirrored UVs meeting at a vertex mix bitangent signs in a triangle"]
 fn gpu_mixed_tangent_signs_decode_like_the_viewport() {
-- 
2.55.0.windows.5

Patch 2: partly covered texels scene (apply after patch 1)

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 bbbfaa8086665d2c8d9295077048ab7f846135f9 Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 10:42:16 -0500
Subject: [PATCH] test(#279): partly covered texels average only their covered
 subsamples

No reference scene had an island edge inside a texel under antialiasing,
so a bake that divided each texel by all of its subsamples instead of
the covered ones passed every scene and every bake unit test. An island
inset by a quarter texel at 4x4 antialiasing gives 124 partly covered
border texels whose world normal must still read exactly +y.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 crates/bake/tests/reference.rs            |  6 ++++++
 crates/bake/tests/reference_scenes/mod.rs | 25 ++++++++++++++++++++++-
 2 files changed, 30 insertions(+), 1 deletion(-)

diff --git a/crates/bake/tests/reference.rs b/crates/bake/tests/reference.rs
index 2b7e6ee..f6a5afd 100644
--- a/crates/bake/tests/reference.rs
+++ b/crates/bake/tests/reference.rs
@@ -82,6 +82,12 @@ fn tangent_normals_agree_across_a_uv_seam() {
     run("tangent_normals_agree_across_a_uv_seam");
 }
 
+/// Texels on an island's border average only the subsamples the island covers
+#[test]
+fn partly_covered_texels_average_only_their_covered_subsamples() {
+    run("partly_covered_texels_average_only_their_covered_subsamples");
+}
+
 /// The mixed-sign reference scene on the CPU tracer
 #[test]
 #[ignore = "fails until the per-corner tangent sign fix: compute_tangents keeps one tangent per vertex, so mirrored UVs meeting at a vertex mix bitangent signs in a triangle"]
diff --git a/crates/bake/tests/reference_scenes/mod.rs b/crates/bake/tests/reference_scenes/mod.rs
index 3202742..448392c 100644
--- a/crates/bake/tests/reference_scenes/mod.rs
+++ b/crates/bake/tests/reference_scenes/mod.rs
@@ -26,7 +26,7 @@ use texturecraft_geom::{Bvh, Mesh, Surface, UvGBuffer, primitives, surface_at};
 pub type Check = fn(&dyn Tracer);
 
 /// Every check, by name, for the tracer-parameterized runners.
-pub const CHECKS: [(&str, Check); 12] = [
+pub const CHECKS: [(&str, Check); 13] = [
     ("occlusion_beside_a_wall", occlusion_beside_a_wall),
     ("occlusion_inside_an_open_box", occlusion_inside_an_open_box),
     ("height_of_a_step", height_of_a_step),
@@ -39,6 +39,7 @@ pub const CHECKS: [(&str, Check); 12] = [
     ("normal_map_round_trip_with_mirrored_uvs", normal_map_round_trip_with_mirrored_uvs),
     ("padding_fills_each_gutter_from_the_nearest_island", padding_fills_each_gutter_from_the_nearest_island),
     ("tangent_normals_agree_across_a_uv_seam", tangent_normals_agree_across_a_uv_seam),
+    ("partly_covered_texels_average_only_their_covered_subsamples", partly_covered_texels_average_only_their_covered_subsamples),
 ];
 
 // ---------------------------------------------------------------------------------------------
@@ -566,6 +567,28 @@ pub fn opacity_of_a_hole(tracer: &dyn Tracer) {
     }
 }
 
+/// An island whose edges sit a quarter texel inside the texel grid, so its border texels are
+/// covered by 3 of 4 subsample columns (or rows) at 4 × 4 antialiasing and its corners by 9 of
+/// 16. The world normal is +y everywhere on it, so every covered texel, partial ones included,
+/// must read exactly `pack(+y)`: a texel averages its covered subsamples, not all 16.
+pub fn partly_covered_texels_average_only_their_covered_subsamples(tracer: &dyn Tracer) {
+    const SIZE: u32 = 32;
+    // A quarter texel: between the subsample centres at 1/8 and 3/8 of a texel
+    let inset = 0.25 / SIZE as f32;
+    let low =
+        floor([-1.0, 1.0], [-1.0, 1.0], 0.0, |x, z| Vec2::new(inset + (x + 1.0) * 0.5 * (1.0 - 2.0 * inset), inset + (z + 1.0) * 0.5 * (1.0 - 2.0 * inset)));
+    let antialiasing = BakeAntialiasing::Subsampling4x4;
+    let output = bake_with(tracer, &low, None, &settings(SIZE, antialiasing, &[BakedMap::WorldNormal]));
+    let texels = texels(&low, SIZE, antialiasing);
+    let partial = texels.iter().filter(|t| t.surfaces.len() < 16).count();
+    let worst = texels.iter().map(|t| (vector(&output, BakedMap::WorldNormal, t.index) - pack(Vec3::Y)).abs().max_element()).fold(0.0, f32::max);
+    eprintln!("partly covered texels: {partial} of {}, worst error {worst:.2e}", texels.len());
+    // Every border texel of the 32 × 32 grid is partly covered
+    assert_eq!(partial, 4 * (SIZE as usize - 1), "partly covered texels");
+    // Averaging identical packed normals: exact up to single-precision rounding
+    assert!(worst < 1e-6, "partly covered texels read {worst} off the island's normal");
+}
+
 // ---------------------------------------------------------------------------------------------
 // Normal-map round trip: bake, then decode as the viewport does
 
-- 
2.55.0.windows.5

🤖 Generated with Claude Code

The slab thickness tolerance used the 120-degree cone's cosine for every
case, so the two hemisphere cases bounded a ray's distance by [T, 2T]
instead of [T, D]: 0.0023 instead of 0.0091 over the 240 top texels.
Use each case's own half angle.

Document every helper and test runner, and move the open box's
description from BOX_HEIGHT onto open_box.
…ed subsamples

No reference scene had an island edge inside a texel under antialiasing,
so a bake that divided each texel by all of its subsamples instead of
the covered ones passed every scene. An island inset by a quarter texel
at 4x4 antialiasing gives 124 partly covered border texels whose world
normal must still read exactly +y; with that mutant they read 0.4375 off,
on the CPU and the GPU.
The probe turned any GPU bake error into a skip, so a WGSL compile
error in bake.wgsl made the GPU reference test print "skipping" and
pass. Ask for the adapter the way the GPU baker does and skip only when
there is none or it is a software renderer; otherwise a bake that falls
back to the CPU fails the test.
… components

The note said the 8-bit display path puts each component at most 0.0079
off, which holds only for components >= 0: the error is (1 - c/2) / 127,
up to 0.0118 as c falls towards -1, so the asserted 0.8-degree maximum
was not backed by the derivation. Bound the transverse components by the
sine of the measured bump tilt and z by its cosine, derive the maximum
angle from that (0.80 degrees here, measured 0.67 and 0.68), and say
that the p50, p99 and float limits are fitted to measurements.

Note that viewport_tangent_normal models the display packing from
before storytold#278, by copying it.
…in the seam budget

The opacity scene printed its partly covered texels but asserted none:
require the 46 border texels of the hole at 4x4 antialiasing and none
without it. The seam's 5-degree world-normal budget holds because the
theta and y errors turn the normal about perpendicular axes (4.5
degrees, not their 6.1-degree sum); say so.
@simonhull

Copy link
Copy Markdown
Contributor Author

Thanks @SteamSmith, the re-derivations and the mutation runs are a great help. I've pushed five commits (4385f9c..ead2b70):

  1. Per-case thickness tolerance and doc comments: your patch 1. I confirmed the numbers: the 120° cases use ±0.0023 and the 180° cases ±0.0091, and against the per-ray variance the old tolerance was 1.35σ (uniform) and 2.0σ (cosine). Every function in the three files now has a doc comment. One correction to the patch: open_box's doc says "materials 1 to 4", because Mesh::append gives each wall its own material. That doc now sits on the function, and BOX_HEIGHT has its own line.
  2. Partly covered texels: your patch 2, unchanged. The quad is inset by a quarter texel at 4×4 (124 partly covered texels). Dividing by all 16 subsamples fails it by 0.4375 on the CPU and on the GPU (Metal), and no other scene catches that.
  3. GPU skip: gpu_reference.rs now asks for the adapter the way GpuBaker does (high performance, software renderers refused) and skips only when there is none. With an invalid line in bake.wgsl, the test now fails with "the bake fell back to the CPU" instead of passing as a skip. Two limits on this:
    • The probe doesn't copy Gpu::new's compute-limits check, so a hardware adapter without usable compute would fail the test instead of skipping.
    • gpu_bake_matches_the_cpu lives in gpu_bake.rs, outside this PR, so its gpu() helper still skips on a shader error. That's worth its own small PR.
  4. The 8-bit bound: the per-component error is exactly (1 − c/2)/127. That's 0.0079 for c ≥ 0 and up to 0.0118 near −1, matching your 0.0089 at −0.26. The bound is now derived from the measured bump tilt and computed in the test: 0.800° at 14.7°, against measured maxima of 0.672° and 0.681° on CPU and GPU. The p50, p99 and float limits are labelled as fitted to measurements. viewport_tangent_normal notes that it models the packing from before Pack the viewport's main normal the way the shaders read it #278.
  5. Smaller notes:
    • The opacity scene now asserts its 46 partly covered texels at 4×4 (2·13 + 2·12 − 4 from the hole's span) and 0 without antialiasing.
    • The seam comment explains the 4.5° budget: the errors turn the normal about perpendicular axes, so they combine as √(3.9² + 2.2²) rather than summing to 6.1°.
  6. The #[ignore]s: agreed. Once Keep MikkTSpace's tangent for each triangle corner #277 lands I'll drop both and make the round trip assert that no texels fall on mixed-sign triangles.

Left for now: tighter tolerances from a measured error envelope, expectations computed without UvGBuffer/surface_at, and coverage for min_distance and separate AO and bent-normal passes. These would make the suite stronger but go beyond pinning today's behaviour. The height mapping (h/(f+r) against h/(2f), and the unreachable RelativeToRayDistances branch) still needs a maintainer decision, as the description says.

I ran cargo nextest run --release -p texturecraft-bake (78 passed) and -p texturecraft-render (59 passed, with the GPU reference test run on Metal), plus clippy with -D warnings and fmt.

@autocraft-bot autocraft-bot Bot added infra Tests, CI, docs, build, packaging, tooling needs decision Needs a product or scope decision by a maintainer labels Nov 26, 2026
Main bakes bent normal maps in tangent space, like the normal map (storytold#542).
The occlusion scenes now read the baked bent normal through their floors'
tangent frame before comparing it with the analytic world direction; the
largest error is 0.04 degrees against tolerances of about 2.5.

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

infra Tests, CI, docs, build, packaging, tooling needs decision Needs a product or scope decision by a maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants