Skip to content

Keep MikkTSpace's tangent for each triangle corner - #277

Draft
simonhull wants to merge 4 commits into
storytold:mainfrom
simonhull:fix/per-corner-tangent-sign
Draft

simonhull wants to merge 4 commits into
storytold:mainfrom
simonhull:fix/per-corner-tangent-sign

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.

Cause

The bake and the viewport build a triangle's tangent frame from the same per-vertex tangents, but they take the bitangent sign w differently. geom::surface_at, and so the bake and both path tracers, takes it from the triangle's first corner. shade_mesh interpolates tan.w, which shortens the bitangent and flips it past the midpoint. They agree only when a triangle's three corners carry the same sign, and Mesh::compute_tangents did not guarantee that, in two ways:

  • One tangent per vertex. MikkTSpace gives every triangle corner its own frame, but set_tangent_encoded wrote it into the vertex, so the last face written won. Where faces with opposite UV orientation share a vertex (the line where mirrored UVs meet, the common case for symmetric models), the shared vertex kept one face's sign, and the other face's triangles came out with mixed corners. On a 64 × 32 sphere with its UVs mirrored about the middle, 127 of 4096 triangles were mixed.
  • Zero-area triangles. MikkTSpace skips them and gives their corners a neighbour's frame. A vertex that only zero-area triangles use gets its fallback frame (1, 0, 0, −1) instead. The UV sphere's pole vertex on the u seam is one: the pole triangle holding it has corners (+1, +1, −1). This triangle covers 64 texels of a 256² map. It has zero area on the mesh, but it has UV area, so the bake fills those texels. The material ball has the same case.
  • Triangles with collapsed UVs. A triangle with real area whose UVs collapse to a line or a point never starts a MikkTSpace group of its own. Any corner no neighbouring group reaches keeps the initial frame (1, 0, 0, −1).

On a minimal mixed triangle the viewport decoded the bake up to 40.7° off; on the sphere's seam texels, 0.67°.

Fix

compute_tangents keeps MikkTSpace's frame per corner, then splits vertices so that every corner keeps it:

  • MikkTSpace writes to a per-corner buffer. The first corner of a vertex sets its tangent. Each further distinct tangent gets a copy of the vertex, with the same position, normal, UV and color, and that corner's index moves to the copy. This is the per-face-vertex result MikkTSpace defines, and what MikkTSpace-based tools expect.
  • A triangle MikkTSpace cannot orient (two corners at one position, or UVs collapsed to a line or point) can still have corners that disagree on the sign. Each of its corners takes the sign most of its reached corners carry, or the first reached corner's on a tie. set_tangent records which corners MikkTSpace reached. Taking the first corner's sign, or the majority over all corners, would spread the placeholder sign of an unreached corner and split vertices that the triangle shares with real triangles. On a small repro (one real triangle and two collapsed-UV triangles), first-corner gives 8 vertices, majority 7 and reached corners 5.
  • Corners are buffered as Vec<Vec4> plus a reached flag (17 bytes per corner). MikkTSpace writes every corner when it succeeds.
  • A mesh without such vertices comes out bit-identical: same vertices, same order, same tangents.

I fixed the data rather than the shader. A flat per-triangle sign in the viewport (@interpolate(flat) on w) would make the viewport agree with the bake on any data. But the exported mesh and normal map would still disagree with tools that recompute MikkTSpace per corner, and flat interpolation's provoking vertex is not portable to the WebGL backend the web build uses. With consistent data, the bake, the viewport, the path tracers and the subdivided displacement mesh all build the same frame, and the existing interpolation is exact.

Verified

  • New test in crates/geom/src/mesh.rs: every_triangle_corner_keeps_its_mikktspace_frame. It runs on a "bowtie" (two coplanar triangles sharing only their apex, the second with mirrored UVs) and on the 32 × 16 UV sphere, each welded back to its unsplit layout. Every triangle's corners must agree on the sign, every corner must keep its position, normal and UV, and every corner of a triangle with area must have exactly MikkTSpace's tangent and sign. Running compute_tangents again must not split anything more.

    • Before the fix it fails on both meshes: bowtie triangle 0 has signs (−1, +1, +1), sphere triangle 63 has (+1, +1, −1).
  • New test in crates/bake/src/tests.rs: mirrored_triangles_sharing_a_vertex_decode_in_the_viewport_as_baked. It bakes the bowtie from a tilted plane and decodes every covered texel in the viewport's frame (interpolated normal, tangent and w). Every texel must be within 0.1° of the plane's normal. Before the fix: 40.72° off.

  • The reference suite from Bake: analytic reference scenes for the mesh-map baker #279, run here on top of this branch but not committed:

    • mixed_tangent_signs_decode_like_the_viewport builds the bowtie and takes its tangents from compute_tangents. It fails on main (40.72° on the CPU and the GPU tracer) and passes here on both at 0.00°.
    • The normal round trip on the UV sphere now has 0 texels on mixed-sign triangles, down from 64. Its float decode error over all 65,536 texels is p99 0.020°, max 0.034° (GPU 0.040°), down from 0.668° on the seam texels. That is single-precision rounding. The 8-bit numbers don't change, because the display encoding is a separate fix.
    • Every other reference scene passes on the CPU and the GPU tracer.
  • Vertex counts:

    mesh triangles vertices before → after mixed-sign triangles before → after
    UV sphere 32 × 16 1,024 561 → 561 1 → 0
    material ball 22,016 11,481 → 11,481 1 → 0
    rounded box, torus, crate unchanged 0 → 0
    sphere 64 × 32, UVs mirrored about the middle 4,096 2,145 → 2,241 (+4.5%) 127 → 0

    The zero-area pole triangles only change sign, so they add no vertices.

  • New tests: collapsed_uv_triangles_take_their_reached_corners_sign and triangle_sign_follows_the_reached_corners. Both fail under the first-corner rule and under the majority rule.

  • compute_tangents on a 1M-triangle sphere (release, 5 rounds of 7 runs on a shared machine): 656 ms on main, 652 ms with this PR. That is within noise, so I can't claim a difference either way.

  • Ran: geom and bake tests, the engine package with panic_hunt, fmt, cargo xtask wasm and cargo xtask layers. I haven't re-run cargo +1.96.0 xtask ci since the review changes.

Not changed

  • The mesh layout and file formats. Mesh keeps one tangent per vertex; only the vertex count can grow, and only where frames differ. .tcraft stores the source mesh file and imports it again on load, so existing projects get the split layout when they open. Painted data is per texel, and most of the code that relates meshes works from positions, UVs or triangle corners, not vertex numbers: UV-island fill, preserve strokes on reimport, the custom cage (matched by triangle), and the bake's welded ray normals. None of it changes. The exception is polygon fill's Polygon mode on main, which keys diagonals by vertex index. Where a split crosses a polygon diagonal (a quad whose two triangles have opposite UV orientation), that polygon fills as two groups. Keying polygon_edges by position, as position_edges already does, would fix it in a few lines once this lands.
  • Exports. OBJ, GLB and USD don't write tangents, so importers recompute MikkTSpace per corner. Its result now matches the frames the maps were baked in, on mirrored seams too. The split vertices are written as duplicate vertices (same position, normal and UV), which MikkTSpace welds back by itself.
  • Wireframe. An edge on the boundary of a split now belongs to two different vertex pairs, so wire_edges draws it even if it is a polygon diagonal, the same as for an edge on a UV seam (and polygon fill groups across it, see above). On mirrored models that boundary is the mirror line, which is usually made of real edges.
  • The shader still interpolates tan.w. On consistent data that is exact.
  • Hand-built meshes that set mixed signs directly still disagree between the bake and the viewport.

The bake takes a triangle's bitangent sign from its first corner, the
viewport interpolates tan.w; they agree only when the corners agree.
compute_tangents wrote MikkTSpace's per-corner tangents into the vertex,
so the last face won: where mirrored UVs meet at a shared vertex, the
other face's triangles mixed signs (127 of 4096 triangles on a sphere
with mirrored UVs). MikkTSpace also gives a vertex used only by
zero-area triangles its fallback frame with w = -1, which mixed the UV
sphere's pole triangle on the seam.

compute_tangents now collects the tangents per corner and gives each
distinct tangent of a vertex its own copy of the vertex (same position,
normal, UV, color), as MikkTSpace expects. Corners of a triangle that
still disagree, only possible in zero-area triangles, take the first
corner's sign. Meshes without such vertices come out unchanged.

Tests: every corner keeps MikkTSpace's frame and every triangle one sign
(bowtie with a mirrored half, UV sphere); a bowtie baked from a tilted
plane decodes in the viewport's frame within 0.1 degrees, 40.7 before.
@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.

@SteamSmith

Copy link
Copy Markdown
Collaborator

Review notes (prepared with Claude Code)

PR #277

Verdict: merge after a small rework. The fix is correct and follows the published MikkTSpace algorithm: each triangle corner gets its own frame, and a vertex is split where its corners disagree. Three things to change.

What I checked

Changes requested

  1. The sign rule for triangles MikkTSpace cannot orient. The doc comment says only zero-area triangles can mix signs. A triangle with real 3D area but collapsed UVs does too: the mikktspace crate leaves any corner no neighbouring group reaches on its initial frame, tangent (1, 0, 0) with w = -1. "First corner wins" then spreads that placeholder sign when the unreached corner comes first, which splits the vertices the triangle shares with real triangles and makes a hidden polygon diagonal show in the wireframe. Taking the majority sign fails the other way when two corners are unreached. On a small repro (a real triangle plus two collapsed-UV triangles) main gives 5 vertices, first-corner 8, majority 7. Implementing set_tangent instead of set_tangent_encoded shows which corners were reached; taking the sign of the reached corners (first reached corner on a tie) gives 5. Bake and viewport agreement holds under any of these rules after unification; the rule only decides which vertices get split.
  2. Clippy. chunks_exact(3) fails clippy on current stable (main uses as_chunks since Fix the Rust 1.99 clippy findings #234). CI's pinned toolchain accepted it, so this is only about staying current.
  3. The per-corner buffer is twice the size it needs to be. Option<Vec4> is 32 bytes per corner (about 1.9 GB extra at the 20M-triangle cap). mikktspace writes every corner when it succeeds, so a plain Vec<Vec4> plus a reached flag (17 bytes) is enough.

The patch below does all three (its own cost is about +5-8% over main, estimated from noisy runs, against +3-5% for the PR as submitted) and adds two tests (collapsed_uv_triangles_take_their_reached_corners_sign fails under both first-corner and majority).

Notes

  • Polygon fill groups triangles by vertex-index diagonals (polygon_fill.rs, triangle_partition.rs), so a split across a diagonal splits the polygon into two fill groups. This is from reading the code; I did not run it. The PR text says the code that relates meshes works from positions, UVs or triangle corners, not vertex numbers, which this one place does not follow.
  • Separate from this PR: Mesh::from_parts runs MikkTSpace before it checks indices. An out-of-range index reads the missing vertex as the origin, and mikktspace underflows (generated.rs:1100) if that leaves every triangle degenerate; the out-of-bounds read in release is from reading the source, not from a run. Importers check indices first, so files cannot reach it, but it deserves its own fix.
  • Not run: the engine suite, xtask ci, layers and wasm beyond the geometry crate, a live app run.

Patch: reached-corner sign rule, as_chunks and a 17-byte corner buffer

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 491eb427e2cb34ca01031b20c978bb41ea5bfa9a Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 09:47:13 -0500
Subject: [PATCH] fix(#277): sign of reached corners, as_chunks, 16-byte corner
 buffer

A triangle MikkTSpace cannot orient is not only a zero-area one: a
triangle with area but collapsed UVs keeps mikktspace's untouched frame
(w = -1) on every corner no neighbour group reaches. Neither the first
corner's sign nor the majority sign picks the neighbours' sign in every
case (first corner fails when the untouched corner comes first; majority
fails when two corners are untouched), and each wrong pick splits the
shared vertices and shows hidden polygon diagonals. Record which corners
mikktspace reached (set_tangent sees the untouched frame) and take their
sign.

Store corners as Vec<Vec4> (16 bytes) plus a reached flag instead of
Option<Vec4> (32 bytes): mikktspace writes every corner when it succeeds.
Use as_chunks, which clippy on current stable requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 crates/geom/src/mesh.rs | 128 +++++++++++++++++++++++++++++++++-------
 1 file changed, 106 insertions(+), 22 deletions(-)

diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs
index 1c121ec..0e19cf9 100644
--- a/crates/geom/src/mesh.rs
+++ b/crates/geom/src/mesh.rs
@@ -223,9 +223,10 @@ impl Mesh {
     /// then build the same frame. Copies keep the vertex's position, normal, UV and color, so
     /// nothing but the vertex count changes.
     ///
-    /// A zero-area triangle can still get corners of both signs: a vertex no other triangle
-    /// uses gets MikkTSpace's fallback frame (w = −1), e.g. at a UV sphere's pole on the seam.
-    /// Such corners take the sign of the triangle's first corner.
+    /// A triangle MikkTSpace cannot orient can still get corners of both signs: a zero-area
+    /// triangle, or one with area but collapsed UVs. A corner MikkTSpace never reaches keeps
+    /// its untouched frame (w = −1), e.g. at a UV sphere's pole on the seam. Such a triangle's
+    /// corners all take the sign of its reached corners ([`triangle_sign`]).
     pub fn compute_tangents(&mut self) {
         self.tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); self.positions.len()];
         if self.normals.len() != self.positions.len() {
@@ -236,13 +237,12 @@ impl Mesh {
         }
         // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then.
         let usable = !crate::unwrap::all_triangles_degenerate(self);
-        let mut g = Mikk { mesh: self, corners: vec![None; self.indices.len()] };
+        let mut g = Mikk { mesh: self, corners: vec![UNTOUCHED_CORNER; self.indices.len()], reached: vec![false; self.indices.len()] };
         if usable && mikktspace::generate_tangents(&mut g) {
-            let mut corners = g.corners;
-            for triangle in corners.chunks_exact_mut(3) {
-                if let Some(Some(first)) = triangle.first().copied() {
-                    triangle.iter_mut().flatten().for_each(|t| t.w = first.w);
-                }
+            let (mut corners, reached) = (g.corners, g.reached);
+            for (triangle, reached) in corners.as_chunks_mut::<3>().0.iter_mut().zip(reached.as_chunks::<3>().0) {
+                let w = triangle_sign(triangle, reached);
+                triangle.iter_mut().for_each(|t| t.w = w);
             }
             self.split_by_corner_tangents(&corners);
         } else {
@@ -257,13 +257,12 @@ impl Mesh {
     }
 
     /// Give every index its corner's tangent: the first corner of a vertex sets its tangent,
-    /// and each further distinct tangent gets a copy of the vertex. Corners without a tangent
-    /// keep their vertex.
-    fn split_by_corner_tangents(&mut self, corners: &[Option<Vec4>]) {
+    /// and each further distinct tangent gets a copy of the vertex.
+    fn split_by_corner_tangents(&mut self, corners: &[Vec4]) {
         let mut first: Vec<Option<Vec4>> = vec![None; self.positions.len()];
         let mut copies: std::collections::HashMap<(u32, [u32; 4]), u32> = std::collections::HashMap::new();
         for (k, tangent) in corners.iter().enumerate() {
-            let (Some(tangent), Some(&v)) = (tangent, self.indices.get(k)) else { continue };
+            let Some(&v) = self.indices.get(k) else { continue };
             let Some(seen) = first.get_mut(v as usize) else { continue };
             let vertex = match seen {
                 None => {
@@ -447,10 +446,39 @@ impl Mesh {
     }
 }
 
+/// The tangent frame mikktspace 0.3 gives a corner it never reaches (`genTangSpace` fills its
+/// frames with this before grouping): tangent +X, bitangent +Y, both magnitudes 1, not
+/// orientation preserving, so w = −1.
+const UNTOUCHED_TANGENT: [f32; 3] = [1.0, 0.0, 0.0];
+/// The untouched frame's bitangent; see [`UNTOUCHED_TANGENT`].
+const UNTOUCHED_BITANGENT: [f32; 3] = [0.0, 1.0, 0.0];
+/// The untouched frame's tangent and bitangent magnitudes; see [`UNTOUCHED_TANGENT`].
+const UNTOUCHED_MAGNITUDE: f32 = 1.0;
+/// The untouched frame as `set_tangent_encoded` would see it.
+const UNTOUCHED_CORNER: Vec4 = Vec4::new(1.0, 0.0, 0.0, -1.0);
+
+/// The bitangent sign all corners of a triangle take: the sign most of the corners MikkTSpace
+/// reached carry (the first reached corner's on a tie), or the first corner's when it reached
+/// none. Only a triangle MikkTSpace cannot orient (zero area, or collapsed UVs) mixes signs;
+/// its unreached corners carry the untouched w = −1, which says nothing about its neighbours.
+fn triangle_sign(corners: &[Vec4; 3], reached: &[bool; 3]) -> f32 {
+    let signs: Vec<f32> = corners.iter().zip(reached).filter(|(_, r)| **r).map(|(t, _)| t.w).collect();
+    let Some(&first) = signs.first() else { return corners[0].w };
+    let positive = signs.iter().filter(|w| **w >= 0.0).count();
+    match positive.cmp(&(signs.len() - positive)) {
+        std::cmp::Ordering::Greater => 1.0,
+        std::cmp::Ordering::Less => -1.0,
+        std::cmp::Ordering::Equal => first,
+    }
+}
+
 /// MikkTSpace's view of a mesh; it writes each triangle corner's tangent to `corners`.
 struct Mikk<'a> {
     mesh: &'a Mesh,
-    corners: Vec<Option<Vec4>>,
+    /// Each triangle corner's tangent, w the bitangent sign (16 bytes per corner)
+    corners: Vec<Vec4>,
+    /// Whether MikkTSpace gave the corner a frame (false: it kept the untouched one)
+    reached: Vec<bool>,
 }
 
 impl Mikk<'_> {
@@ -478,9 +506,19 @@ impl mikktspace::Geometry for Mikk<'_> {
         let uv = self.mesh.uvs.get(self.vi(face, vert)).copied().unwrap_or_default();
         [uv.x, 1.0 - uv.y]
     }
-    fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) {
-        if let Some(t) = face.checked_mul(3).and_then(|k| k.checked_add(vert)).and_then(|k| self.corners.get_mut(k)) {
-            *t = Some(Vec4::from_array(tangent));
+    /// Record the corner's tangent with its sign, and whether MikkTSpace reached it.
+    fn set_tangent(&mut self, tangent: [f32; 3], bi_tangent: [f32; 3], f_mag_s: f32, f_mag_t: f32, preserves_orientation: bool, face: usize, vert: usize) {
+        let Some(k) = face.checked_mul(3).and_then(|k| k.checked_add(vert)) else { return };
+        if let Some(t) = self.corners.get_mut(k) {
+            *t = Vec3::from_array(tangent).extend(if preserves_orientation { 1.0 } else { -1.0 });
+        }
+        let untouched = tangent == UNTOUCHED_TANGENT
+            && bi_tangent == UNTOUCHED_BITANGENT
+            && f_mag_s == UNTOUCHED_MAGNITUDE
+            && f_mag_t == UNTOUCHED_MAGNITUDE
+            && !preserves_orientation;
+        if let Some(r) = self.reached.get_mut(k) {
+            *r = !untouched;
         }
     }
 }
@@ -531,13 +569,59 @@ mod tests {
         Mesh { indices, ..mesh.clone() }
     }
 
+    /// MikkTSpace's tangent for every triangle corner of `mesh`, and whether it reached the corner
+    fn mikktspace_frames(mesh: &Mesh) -> (Vec<Vec4>, Vec<bool>) {
+        let mut g = Mikk { mesh, corners: vec![UNTOUCHED_CORNER; mesh.indices.len()], reached: vec![false; mesh.indices.len()] };
+        assert!(mikktspace::generate_tangents(&mut g));
+        (g.corners, g.reached)
+    }
+
     /// MikkTSpace's tangent for every triangle corner of `mesh`
     fn mikktspace_corners(mesh: &Mesh) -> Vec<Vec4> {
-        let mut g = Mikk { mesh, corners: vec![None; mesh.indices.len()] };
-        assert!(mikktspace::generate_tangents(&mut g));
-        g.corners.into_iter().map(Option::unwrap).collect()
+        mikktspace_frames(mesh).0
+    }
+
+    /// A triangle A = (0, 1, 2) with real UVs, and two triangles with area whose UVs collapse
+    /// onto the line v = 0.5: C1 = (3, 1, 0) shares A's edge 0-1, C2 = (0, 4, 3) shares C1's
+    /// edge 0-3. MikkTSpace reaches C1 at 0 and 1 (from A) and C2 at 0 only; vertices 3 and 4
+    /// belong to no triangle it can orient. A's UVs are mirrored, so A has w = +1 and the
+    /// untouched corners w = −1: C1's first corner is untouched, C2's only reached one is first.
+    fn collapsed_uv_fan() -> Mesh {
+        let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z, Vec3::new(0.5, 0.0, -1.0), Vec3::new(-1.0, 0.0, -0.5)];
+        let uvs = vec![Vec2::new(0.0, 0.5), Vec2::new(0.5, 0.5), Vec2::new(0.0, 0.0), Vec2::new(0.25, 0.5), Vec2::new(0.75, 0.5)];
+        Mesh::from_parts(positions, Some(vec![Vec3::Y; 5]), uvs, vec![0, 1, 2, 3, 1, 0, 0, 4, 3], "Fan").unwrap()
+    }
+
+    /// Triangles with area but collapsed UVs take the sign MikkTSpace gave their reached
+    /// corners, whichever corner comes first and however many corners it left untouched, so
+    /// no vertex they share with a real triangle is split and no polygon diagonal shows.
+    #[test]
+    fn collapsed_uv_triangles_take_their_reached_corners_sign() {
+        let m = collapsed_uv_fan();
+        let (raw, reached) = mikktspace_frames(&m);
+        assert_eq!(raw.iter().map(|t| t.w).collect::<Vec<_>>(), [1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0], "MikkTSpace mixes C1 and C2");
+        assert_eq!(reached, [true, true, true, false, true, true, true, false, false]);
+        assert!(m.indices.iter().all(|v| m.tangents[*v as usize].w == 1.0), "every corner takes A's sign: {:?}", m.tangents);
+        assert_eq!(m.vertex_count(), 5, "no vertex is split");
+        let mut shown = m.clone();
+        shown.diagonals = vec![0b001, 0b010, 0];
+        assert!(!shown.wire_edges()[0].contains(&(0, 1)), "the diagonal A and C1 share stays hidden");
+    }
+
+    /// The sign of most reached corners wins, the first reached one on a tie; untouched
+    /// corners count only when no corner was reached.
+    #[test]
+    fn triangle_sign_follows_the_reached_corners() {
+        let t = |w: f32| Vec4::new(1.0, 0.0, 0.0, w);
+        assert_eq!(triangle_sign(&[t(-1.0), t(1.0), t(1.0)], &[false, true, true]), 1.0);
+        assert_eq!(triangle_sign(&[t(1.0), t(-1.0), t(-1.0)], &[true, false, false]), 1.0);
+        assert_eq!(triangle_sign(&[t(-1.0), t(1.0), t(-1.0)], &[true, true, true]), -1.0);
+        assert_eq!(triangle_sign(&[t(-1.0), t(1.0), t(-1.0)], &[false, true, true]), 1.0);
+        assert_eq!(triangle_sign(&[t(1.0), t(-1.0), t(-1.0)], &[false, false, false]), 1.0);
     }
 
+    /// After `compute_tangents`, every triangle corner of a bowtie with a mirrored half and of a
+    /// UV sphere carries MikkTSpace's own frame for that corner, and no triangle mixes signs.
     #[test]
     fn every_triangle_corner_keeps_its_mikktspace_frame() {
         for (name, split) in [("bowtie", bowtie()), ("UV sphere", crate::primitives::sphere(1.0, 32, 16))] {
@@ -545,12 +629,12 @@ mod tests {
             let corners = mikktspace_corners(&unsplit);
             let shared = || unsplit.indices.iter().zip(&corners);
             let vertex_needs_two_signs = shared().any(|(v, t)| shared().any(|(u, s)| u == v && s.w != t.w));
-            let triangle_mixes_signs = corners.chunks_exact(3).any(|c| c.iter().any(|t| t.w != c[0].w));
+            let triangle_mixes_signs = corners.as_chunks::<3>().0.iter().any(|c| c.iter().any(|t| t.w != c[0].w));
             assert!(vertex_needs_two_signs || triangle_mixes_signs, "{name}: one tangent per vertex would mix signs in a triangle");
             let mut m = unsplit.clone();
             m.compute_tangents();
             m.validate().unwrap();
-            for (t, (tri, wanted)) in m.indices.chunks_exact(3).zip(corners.chunks_exact(3)).enumerate() {
+            for (t, (tri, wanted)) in m.indices.as_chunks::<3>().0.iter().zip(corners.as_chunks::<3>().0).enumerate() {
                 let w = tri.iter().map(|v| m.tangents[*v as usize].w).collect::<Vec<_>>();
                 assert!(w.iter().all(|sign| Some(sign) == w.first()), "{name}: triangle {t} mixes bitangent signs {w:?}");
                 let [a, b, c] = unsplit.tri(t).unwrap().map(|v| unsplit.positions[v]);
-- 
2.55.0.windows.5

🤖 Generated with Claude Code

Clippy on current stable rejects chunks_exact with a constant chunk
size; main moved to as_chunks in storytold#234. The three chunks_exact calls
this change added now use as_chunks. The older ones elsewhere in the
file are left for main's version to replace.
Zero-area triangles are not the only ones whose corners can mix
bitangent signs. A triangle with area but collapsed UVs can too: MikkTSpace
cannot orient it, so it gets a frame only at the corners a neighbouring
group reaches. Every other corner keeps the initial frame (tangent +X,
w = -1). Taking the first corner's sign spreads that placeholder when the
unreached corner comes first. Taking the majority fails when two corners
are unreached. Either way the triangle's vertices split away from the
real neighbours and a hidden polygon diagonal shows in the wireframe.
For a real triangle with two collapsed-UV neighbours, the first-corner
rule gives 8 vertices and the majority rule 7, where 5 is right.

Implement set_tangent instead of set_tangent_encoded, so the initial
frame is visible, and record whether each corner was reached. A triangle
then takes the sign most of its reached corners carry, the first reached
corner's sign on a tie, and its first corner's sign when none was
reached. The vote does not allocate.

MikkTSpace writes every corner when it succeeds, so corners are stored
as Vec<Vec4> plus a reached flag (17 bytes per corner) instead of
Option<Vec4> (32 bytes).

Tests: collapsed-UV triangles keep their neighbour's sign, split no
vertex and keep the shared diagonal hidden (fails under the first-corner
and majority rules), and a unit test of the sign vote.
@simonhull

Copy link
Copy Markdown
Contributor Author

Thanks @SteamSmith. I checked each point against mikktspace 0.3.0 and they all held. I've pushed 7a7feba and 47bc3ce, and updated the description.

  1. Sign rule: done as you proposed. set_tangent records which corners were reached, and a triangle takes the sign most of its reached corners carry, the first reached corner's on a tie. Your repro gives 8 vertices with first-corner, 7 with majority and 5 with reached corners. Two changes from your patch:

    • triangle_sign no longer collects a Vec per triangle; it's an allocation-free vote, since that's a million allocations on a 1M-triangle mesh.
    • A doc note on the constant covers the one blind spot: a corner that really was reached but carries exactly the initial frame counts as unreached. That only matters in a triangle whose other reached corners disagree.

    collapsed_uv_triangles_take_their_reached_corners_sign and triangle_sign_follows_the_reached_corners both fail under the first-corner and majority rules.

  2. as_chunks: done for the PR's own lines. The three remaining chunks_exact calls in mesh.rs are code this PR doesn't touch, which main already changed in Fix the Rust 1.99 clippy findings #234.

  3. Corner buffer: Vec<Vec4> plus a reached flag, 17 bytes per corner. I confirmed genTangSpace calls set_tangent for every corner when it succeeds.

Timing: on a 1M-triangle sphere (5 rounds of 7 runs, shared machine), main took 656 ms, the PR as submitted 666 ms and the PR now 652 ms. That's within noise, so the description no longer claims +5%.

Your notes:

  • Polygon fill: confirmed. polygon_edges keys diagonals by vertex-index pairs, so a quad with opposite UV orientation on its two triangles fills as two groups once it's split. With the new rule, collapsed-UV triangles no longer cause splits, so only that case remains. The fix is small: key by quantized position, as position_edges does. polygon_fill.rs is only on main, so I'd do it as a follow-up once this lands. The description now says so instead of claiming no vertex-number dependence.
  • Mesh::from_parts: confirmed. It runs MikkTSpace before validate(). all_triangles_degenerate counts a missing vertex as different from the origin, but Mikk::position reads it as the origin. So indices [0,1,2] over two positions get past the guard and hit the usize underflow at generated.rs:1100: a debug panic, and in release a walk off the end of pTriInfos. Importers validate first, so files can't reach it, but it should be fixed. I'll open a separate PR that validates indices before computing tangents.

I ran the geom and bake tests (81 passed), the engine package with panic_hunt, fmt, cargo xtask wasm and cargo xtask layers. Vertex counts are unchanged from the PR as submitted (UV sphere 561, material ball 11,481).

@simonhull

Copy link
Copy Markdown
Contributor Author

The Mesh::from_parts crash from your notes is now #386. compute_tangents skips MikkTSpace when an index is out of range, and from_parts refuses such indices before building anything. Both new tests panic at generated.rs:1100 without the fix.

Main hands MikkTSpace the importer's quads as four-corner faces. Each face
now knows its first triangle, and a quad corner's frame goes to every
triangle corner it stands for (both triangles' copies of the shared
corners), so the corner signs and vertex splits work for quads too.

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

bugfix Fixes something that is broken: wrong result, crash, data loss

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants