craft-mesh-ops: tangents read glTF UVs with v up again

compute_tangents and compute_tangents_split pass the UVs to MikkTSpace
and to the f64 fallback with v negated, as main did with 1 - v. glTF
UVs run v down the image, so without the flip the bitangent followed
increasing v and every unmirrored mesh got w = -1, which inverts the
green channel of glTF normal maps.

The tests expect w = +1 for unmirrored UVs again, preview_orb sets +1
again, and the primitive check counts mirrored tangents as before and
also checks that each bitangent points up the image. A new test checks
that a plain quad keeps w = +1 with both functions.
This commit is contained in:
dotCooCoo committed 2026-11-29 19:14:57 -08:00
1 parent 49db2160e8
commit 607aeb0b55
3 files changed
+58 -20

No files matched your search

+2 -1
View File
@@ -16,7 +16,8 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form
available. MikkTSpace omits those faces. A mesh with more than 2,048 noncollapsed triangles around one vertex, or with non-finite
positions or UVs, or whose largest absolute position or UV component is nonzero and outside 1e-6 to 1e6, gets per-corner tangents from f64 UV gradients instead of MikkTSpace.
An edge-connected region containing a face whose f32 UV gradients overflow or underflow uses that fallback.
Both paths use the stored UVs. The generated corner frames of a triangle with usable UV gradients
Both paths read the stored glTF UVs (v down) with v negated, so an unmirrored mapping gets
`w = +1`. The generated corner frames of a triangle with usable UV gradients
share one handedness sign. With `compute_tangents`, a vertex shared by mirrored triangles keeps
the first triangle's frame, so the stored signs of the other triangle can differ; use
`compute_tangents_split` when both sides of a mirrored seam need their own frames. It splits only
+47 -14
View File
@@ -244,7 +244,8 @@ impl Mesh {
/// Faces with coincident corners stay in the mesh but are omitted from MikkTSpace. Their
/// corners reuse a generated frame for the same vertex when one is available.
/// Edge-connected regions containing a face whose f32 UV gradients overflow, underflow or reverse the UV orientation use the fallback.
/// Both paths use the stored UVs. The generated corner frames of a triangle with usable UV
/// Both paths read the stored UVs with v up, so an unmirrored glTF mapping (v down) gets
/// `w = +1`. The generated corner frames of a triangle with usable UV
/// gradients share one handedness sign. The stored per-vertex frames need not: a vertex shared
/// by mirrored triangles keeps the first one's frame. [`Mesh::compute_tangents_split`] keeps
/// both sides of a mirrored seam when the mesh passes its input checks (indices in range, an
@@ -380,16 +381,17 @@ impl Mesh {
self.uvs = vec![Vec2::ZERO; n];
}
let normals: Vec<Vec3> = self.normals.iter().copied().map(tangent_normal).collect();
let uvs = tangent_uvs(&self.uvs);
let mut corners = vec![Vec4::ZERO; self.indices.len()];
// MikkTSpace receives noncollapsed faces with valid indices and bounded attributes.
let usable = in_safe_range(self.positions.iter().flat_map(|p| p.to_array()))
&& in_safe_range(self.uvs.iter().flat_map(|uv| uv.to_array()))
&& in_safe_range(uvs.iter().flat_map(|uv| uv.to_array()))
&& self.indices.iter().all(|&i| (i as usize) < n);
let mut g = Mikk {
positions: &self.positions,
normals: &normals,
uvs: &self.uvs,
uvs: &uvs,
indices: &self.indices,
corners: &mut corners,
faces: if usable { Mikk::noncollapsed_faces(&self.positions, &self.indices) } else { None },
@@ -399,13 +401,13 @@ impl Mesh {
let mut fallback_faces: Vec<usize> = if affordable {
(0..g.face_count())
.map(|face| g.original_face(face))
.filter(|&face| !mikk_uvs_safe(&self.positions, &self.uvs, &self.indices[face * 3..face * 3 + 3]))
.filter(|&face| !mikk_uvs_safe(&self.positions, &uvs, &self.indices[face * 3..face * 3 + 3]))
.collect()
} else {
Vec::new()
};
if !fallback_faces.is_empty() {
let welded = tangent_vertex_ids(&self.positions, &normals, &self.uvs, self.indices.iter().copied());
let welded = tangent_vertex_ids(&self.positions, &normals, &uvs, self.indices.iter().copied());
let eligible = g.faces.clone().unwrap_or_else(|| (0..self.indices.len() / 3).collect());
fallback_faces = connected_fallback_faces(&welded, &eligible, &fallback_faces);
let mut faces = g.faces.take().unwrap_or_else(|| (0..self.indices.len() / 3).collect());
@@ -413,11 +415,11 @@ impl Mesh {
g.faces = Some(faces);
}
if !(affordable && g.face_count() != 0 && (g.face_count() == face_count || g.affordable()) && mikktspace::generate_tangents(&mut g)) {
fill_simple_tangents(&self.positions, &normals, &self.uvs, &self.indices, g.corners);
fill_simple_tangents(&self.positions, &normals, &uvs, &self.indices, g.corners);
g.fill_collapsed_corners();
} else {
let fallback_indices: Vec<u32> = fallback_faces.iter().flat_map(|&face| self.indices[face * 3..face * 3 + 3].iter().copied()).collect();
let fallback = simple_tangents(&self.positions, &normals, &self.uvs, &fallback_indices);
let fallback = simple_tangents(&self.positions, &normals, &uvs, &fallback_indices);
for (slot, face) in fallback_faces.into_iter().enumerate() {
let start = face * 3;
g.corners[start..start + 3].copy_from_slice(&fallback[slot * 3..slot * 3 + 3]);
@@ -711,6 +713,13 @@ fn connected_fallback_faces(indices: &[u32], eligible: &[usize], seeds: &[usize]
}
/// Per-corner tangents from f64 triangle UV gradients.
/// The UVs that MikkTSpace and the fallback receive. They expect OpenGL texture coordinates
/// (v up); our UVs are glTF (v down). With v negated, the bitangent `cross(N, T) * w` points up
/// the image, as glTF requires. Negating keeps differences in v that `1 - v` would round away.
fn tangent_uvs(uvs: &[Vec2]) -> Vec<Vec2> {
uvs.iter().map(|uv| Vec2::new(uv.x, -uv.y)).collect()
}
fn simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: &[u32]) -> Vec<Vec4> {
let mut corners = vec![Vec4::ZERO; indices.len()];
fill_simple_tangents(positions, normals, uvs, indices, &mut corners);
@@ -1365,7 +1374,7 @@ mod tests {
let determinant = (mesh.uvs[1].as_dvec2() - mesh.uvs[0].as_dvec2()).perp_dot(mesh.uvs[2].as_dvec2() - mesh.uvs[0].as_dvec2());
assert!(determinant < 0.0);
mesh.compute_tangents();
assert!(mesh.tangents.iter().all(|tangent| tangent.w < 0.0));
assert!(mesh.tangents.iter().all(|tangent| tangent.w > 0.0));
}
#[test]
@@ -1383,7 +1392,7 @@ mod tests {
assert!(!mikk_uvs_safe(&mesh.positions, &mesh.uvs, &mesh.indices));
mesh.compute_tangents();
for tangent in &mesh.tangents {
assert_eq!(tangent.w.is_sign_negative(), wide_determinant.is_sign_negative());
assert_ne!(tangent.w.is_sign_negative(), wide_determinant.is_sign_negative());
}
}
@@ -1475,7 +1484,7 @@ mod tests {
let corners = mesh.corner_tangents();
assert_eq!(corners[0].w, corners[3].w);
for &tangent in &corners[0..3] {
assert!((Vec3::Z.cross(tangent.truncate()) * tangent.w).dot(Vec3::Y) > 0.0);
assert!((Vec3::Z.cross(tangent.truncate()) * tangent.w).dot(Vec3::Y) < 0.0);
}
}
@@ -1679,7 +1688,7 @@ mod tests {
let corners = mesh.corner_tangents();
for &tangent in &corners[copies * 3..copies * 3 + 3] {
assert_eq!(tangent, corners[0]);
assert_eq!(tangent.w, -1.0);
assert_eq!(tangent.w, 1.0);
}
assert!(corners[copies * 3 + 3..].iter().all(|tangent| tangent.is_finite() && tangent.w == 1.0));
}
@@ -1720,7 +1729,7 @@ mod tests {
for tangent in mesh.tangents {
assert!(tangent.truncate().dot(Vec3::X) > 0.99, "{offset} {scale} {orientation}: {tangent:?}");
let bitangent = Vec3::Z.cross(tangent.truncate()) * tangent.w;
assert!(bitangent.dot(Vec3::Y * orientation) > 0.99, "{offset} {scale} {orientation}: {tangent:?}");
assert!(bitangent.dot(-Vec3::Y * orientation) > 0.99, "{offset} {scale} {orientation}: {tangent:?}");
}
}
}
@@ -2139,6 +2148,30 @@ mod tests {
assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents);
}
#[test]
fn unmirrored_quad_keeps_a_positive_bitangent_sign() {
// glTF UVs (v down) on a quad facing +Z: u follows +X and v decreases along +Y, so the
// bitangent `cross(N, T) * w` must point up the image (+Y), which needs w = +1.
let quad = || {
Mesh::from_parts(
vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y],
Some(vec![Vec3::Z; 4]),
vec![Vec2::Y, Vec2::ONE, Vec2::X, Vec2::ZERO],
vec![0, 1, 2, 0, 2, 3],
"Default",
)
.unwrap()
};
let mut split = quad();
assert!(split.compute_tangents_split().is_empty());
for m in [quad(), split] {
assert_eq!(m.tangents.len(), 4);
for t in &m.tangents {
assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == 1.0, "{t:?}");
}
}
}
#[test]
fn far_and_tiny_triangles_keep_their_tangent() {
for edge in [1e-20_f32, 1e20] {
@@ -2151,7 +2184,7 @@ mod tests {
)
.unwrap();
for t in &m.tangents {
assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == -1.0, "edge {edge}: {t:?}");
assert!((t.truncate() - Vec3::X).length() < 1e-4 && t.w == 1.0, "edge {edge}: {t:?}");
}
}
}
@@ -2166,7 +2199,7 @@ mod tests {
*uv = Vec2::new(uv.x * flip.x, uv.y * flip.y);
}
m.compute_tangents();
let fallback = simple_tangents(&m.positions, &m.normals, &m.uvs, &m.indices);
let fallback = simple_tangents(&m.positions, &m.normals, &tangent_uvs(&m.uvs), &m.indices);
assert_eq!(m.tangents.len(), 4);
for (&index, simple) in m.indices.iter().zip(&fallback) {
let mikk = m.tangents[index as usize];
+9 -5
View File
@@ -256,7 +256,7 @@ pub fn preview_orb() -> Mesh {
.zip(&m.normals)
.map(|(p, n)| {
let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X);
(around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(-1.0)
(around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0)
})
.collect();
m
@@ -545,7 +545,8 @@ mod tests {
}
/// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u),
/// and each reconstructed bitangent follows increasing v where the UV gradient is defined.
/// tangent frames are unit length and perpendicular to their normals, and the UV mapping is
/// not mirrored (tangent handedness +1).
fn check(m: &Mesh, max_u: f32) {
m.validate().unwrap();
let mut bad = 0;
@@ -571,6 +572,9 @@ mod tests {
assert!(tangent.truncate().dot(normal).abs() < 1e-3, "{tangent:?}, {normal:?}");
assert!(tangent.w == 1.0 || tangent.w == -1.0, "{tangent:?}");
}
let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count();
assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents");
// glTF UVs run v down the image, and the bitangent `cross(N, T) * w` points up it.
let (mut opposed, mut tested) = (0, 0);
for &[a, b, c] in m.indices.as_chunks::<3>().0 {
let (a, b, c) = (a as usize, b as usize, c as usize);
@@ -580,18 +584,18 @@ mod tests {
continue;
}
let (e1, e2) = (m.positions[b].as_dvec3() - m.positions[a].as_dvec3(), m.positions[c].as_dvec3() - m.positions[a].as_dvec3());
let Some(bitangent) = ((e2 * d1.x - e1 * d2.x) / determinant).try_normalize() else { continue };
let Some(increasing_v) = ((e2 * d1.x - e1 * d2.x) / determinant).try_normalize() else { continue };
for vertex in [a, b, c] {
let tangent = m.tangents[vertex];
let reconstructed = m.normals[vertex].as_dvec3().cross(tangent.truncate().as_dvec3()) * tangent.w as f64;
tested += 1;
let alignment = reconstructed.dot(bitangent);
let alignment = reconstructed.dot(-increasing_v);
assert!(alignment.is_finite(), "vertex {vertex}: {alignment}");
opposed += usize::from(alignment < 0.0);
}
}
assert!(tested > 0);
assert!(opposed * 50 < tested, "{opposed} tangent frames oppose increasing v");
assert!(opposed * 50 < tested, "{opposed} bitangents point down the image");
}
#[test]