fix(mesh): weld recomputed normals and make export opt-in

This commit is contained in:
ATOM committed 2026-11-26 10:36:05 -06:00
1 parent 6a3b3c1ba0
commit 0fbfec1c3d
7 files changed
+78 -42

No files matched your search

+3 -2
View File
@@ -4,8 +4,9 @@
//!
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
//! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`,
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?,
//! `preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`, `bake.mesh.add {path, cage?}`,
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`,
//! `mesh.reimport {path?, preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`,
//! `bake.mesh.add {path, cage?}`,
//! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}`
//! (workspace-scoped versions of the engine commands),
//! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the
+37 -7
View File
@@ -122,7 +122,7 @@ impl Session {
pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result<Vec<u8>> {
let mut mesh = self.source_mesh();
if recompute_normals {
mesh.compute_normals();
mesh.compute_smooth_normals();
}
texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe)
}
@@ -139,7 +139,7 @@ impl Session {
// one image); their tiles export through Export textures with `$udim` names.
let mut mesh = self.source_mesh();
if recompute_normals {
mesh.compute_normals();
mesh.compute_smooth_normals();
}
// A mesh without materials has one implicit material (and texture set).
if mesh.materials.is_empty() {
@@ -162,7 +162,7 @@ impl Session {
let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect();
let mut mesh = self.mesh.as_ref().clone();
if recompute_normals {
mesh.compute_normals();
mesh.compute_smooth_normals();
}
texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe)
}
@@ -178,7 +178,7 @@ impl Session {
let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?;
let mut mesh = self.mesh.as_ref().clone();
if recompute_normals {
mesh.compute_normals();
mesh.compute_smooth_normals();
}
texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe)
}
@@ -1449,7 +1449,7 @@ f 1/1 2/2 3/3
std::sync::Arc::make_mut(&mut s.source).normals.fill(texturecraft_geom::glam::Vec3::Y);
std::sync::Arc::make_mut(&mut s.mesh).normals.fill(texturecraft_geom::glam::Vec3::Y);
let mut expected = s.source_mesh();
expected.compute_normals();
expected.compute_smooth_normals();
let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
@@ -1459,8 +1459,14 @@ f 1/1 2/2 3/3
let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap();
let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh;
assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex");
for (actual, wanted) in back.normals.iter().zip(&expected.normals) {
assert!((*actual - *wanted).length() < 1e-4, "{format}: stored normals were exported instead of recomputed ones");
for (position, actual) in back.positions.iter().zip(&back.normals) {
let wanted = expected
.positions
.iter()
.zip(&expected.normals)
.find_map(|(expected_position, normal)| ((*expected_position - *position).length() < 1e-4).then_some(*normal))
.unwrap_or_else(|| panic!("{format}: exported position {position:?} is missing from the source"));
assert!((*actual - wanted).length() < 1e-4, "{format}: actual {actual:?}, wanted {wanted:?}");
}
}
assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged");
@@ -1473,6 +1479,30 @@ f 1/1 2/2 3/3
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn recomputed_normals_weld_uv_seams_in_exported_mesh() {
use texturecraft_geom::glam::Vec3;
// Two triangles meet along 0--2, but their UV island split duplicates that edge as 3--4.
let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 0.0, 1.0)];
let mesh = Mesh::from_parts(
positions,
Some(vec![Vec3::Y; 6]),
vec![Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.5), Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.5, 1.0)],
vec![0, 1, 2, 3, 4, 5],
"Default",
)
.unwrap();
let mut s = Session::new_project("seam", mesh, "builtin:seam", None, 128).unwrap();
let bytes = s.mesh_glb_bytes_with_normals(true).unwrap();
let back = texturecraft_formats::import_mesh_bytes("seam.glb", &bytes).unwrap().mesh;
for point in [Vec3::ZERO, Vec3::Y] {
let normals: Vec<_> = back.positions.iter().zip(&back.normals).filter_map(|(position, normal)| (*position == point).then_some(*normal)).collect();
assert!(normals.len() >= 2, "{point:?}: the UV seam must still have two exported vertices");
assert!(normals.windows(2).all(|pair| (pair[0] - pair[1]).length() < 1e-5), "{point:?}: UV split normals disagree: {normals:?}");
}
}
#[test]
fn rejected_glb_export_preserves_existing_files_and_publishes_nothing() {
let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
+2 -19
View File
@@ -25,7 +25,7 @@ use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4};
use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap, weld_ids};
use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap};
use texturecraft_geom::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh, UvGBuffer};
use crate::{FormatError, Result};
@@ -508,7 +508,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
mesh.normals = match normals {
Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(),
_ => smooth_normals(&mesh),
_ => mesh.smooth_normals(),
};
if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) {
mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect();
@@ -641,23 +641,6 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec<texturecraft_core::Camer
.collect()
}
/// Area-weighted smooth normals over welded positions (UV seams do not split shading).
fn smooth_normals(mesh: &Mesh) -> Vec<Vec3> {
let welded_vertices = weld_ids(&mesh.positions);
let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
for triangle in mesh.indices.as_chunks::<3>().0 {
let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default();
let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0]));
for v in triangle {
if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) {
*a += face;
}
}
}
welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect()
}
/// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings).
pub fn mesh_report(mesh: &Mesh) -> MeshReport {
report(mesh, false, Vec::new())
+21
View File
@@ -245,6 +245,27 @@ impl Mesh {
self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect();
}
/// Area-weighted smooth normals over welded positions, so UV and material seams do not split shading.
pub fn smooth_normals(&self) -> Vec<Vec3> {
let welded_vertices = crate::unwrap::weld_ids(&self.positions);
let mut normals = vec![Vec3::ZERO; self.positions.len()];
for triangle in self.indices.as_chunks::<3>().0 {
let p = |i: u32| self.positions.get(i as usize).copied().unwrap_or_default();
let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0]));
for v in triangle {
if let Some(accumulated) = welded_vertices.get(*v as usize).and_then(|welded| normals.get_mut(*welded as usize)) {
*accumulated += face;
}
}
}
welded_vertices.iter().map(|welded| normals.get(*welded as usize).and_then(|normal| normal.try_normalize()).unwrap_or(Vec3::Y)).collect()
}
/// Replace normals with [`Mesh::smooth_normals`] on this mesh.
pub fn compute_smooth_normals(&mut self) {
self.normals = self.smooth_normals();
}
/// The faces MikkTSpace sees: each importer quad (a fan pair marked in [`Mesh::diagonals`])
/// as one four-corner face, like Blender hands it over, and every other triangle as a
/// triangle. Polygons with more than four corners stay fan triangles. The vertex and index
+2 -2
View File
@@ -47,8 +47,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
tr("TextureCraft keeps meshes as triangles, so the exported mesh is always triangulated."),
],
);
ui.add_space(GROUP_GAP);
unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation"))));
option(
ui,
&mut app.ui.mesh_recompute_normals,
@@ -59,6 +57,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
tr("On: smooth area-weighted normals from the exported geometry. Off: the project's stored normals. The project itself is not changed."),
],
);
ui.add_space(GROUP_GAP);
unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation"))));
ui.add_space(8.0);
// One row keeps the window to its contents; a bare right-to-left layout fills the screen height
+7 -6
View File
@@ -567,7 +567,8 @@ pub struct UiState {
pub hide_ui: bool,
pub windows: Windows,
/// Mesh Export Options: compute smooth normals on the exported copy, not the project.
#[serde(default = "default_true")]
/// Off by default so an export keeps the project's authored normals unless the user opts in.
#[serde(default)]
pub mesh_recompute_normals: bool,
pub uv_zoom: f32,
pub uv_pan: [f32; 2],
@@ -778,7 +779,7 @@ impl Default for UiState {
selected_baked_map: None,
hide_ui: false,
windows: Windows::default(),
mesh_recompute_normals: true,
mesh_recompute_normals: false,
uv_zoom: 1.0,
uv_pan: [0.0, 0.0],
uv_rotation: 0.0,
@@ -862,12 +863,12 @@ mod tests {
}
#[test]
fn mesh_export_normal_choice_defaults_on_for_older_saved_states() {
assert!(UiState::default().mesh_recompute_normals);
fn mesh_export_normal_choice_defaults_off_for_older_saved_states() {
assert!(!UiState::default().mesh_recompute_normals);
let mut saved = serde_json::to_value(UiState::default()).unwrap();
saved.as_object_mut().unwrap().remove("mesh_recompute_normals");
let loaded: UiState = serde_json::from_value(saved).unwrap();
assert!(loaded.mesh_recompute_normals, "older states keep the dialog's checked default");
assert!(!loaded.mesh_recompute_normals, "older states keep the project's stored normals unless the user opts in");
}
#[test]
@@ -881,7 +882,7 @@ mod tests {
ui.keymap.insert("file.save".into(), "F5".into());
ui.mesh_recompute_normals = false;
let mut layout = UiState::default();
assert!(layout.mesh_recompute_normals);
layout.mesh_recompute_normals = true;
layout.dock.close(crate::docking::Panel::Assets);
ui.adopt_layout(layout);
+6 -6
View File
@@ -185,21 +185,21 @@ fn recompute_normals_is_an_enabled_keyboard_operable_checkbox() {
harness.run_steps(SETTLE_FRAMES);
let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals");
assert!(!checkbox.accesskit_node().is_disabled(), "the option is really available");
assert!(is_on(&checkbox), "it starts checked, as the dialog always showed it");
assert!(harness.state().ui.mesh_recompute_normals);
assert!(!is_on(&checkbox), "stored normals are kept until the user opts in");
assert!(!harness.state().ui.mesh_recompute_normals);
checkbox.focus();
harness.key_press(egui::Key::Space);
harness.run_steps(SETTLE_FRAMES);
assert!(!harness.state().ui.mesh_recompute_normals, "Space changes the setting used by export");
assert!(harness.state().ui.mesh_recompute_normals, "Space changes the setting used by export");
let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals");
assert!(!is_on(&checkbox), "the accessibility tree reports the unchecked state");
assert!(is_on(&checkbox), "the accessibility tree reports the checked state");
assert_eq!(checkbox.accesskit_node().label().as_deref(), Some("Recompute vertex normals"));
checkbox.click();
harness.run_steps(SETTLE_FRAMES);
assert!(harness.state().ui.mesh_recompute_normals, "a pointer click turns it back on");
assert!(is_on(&harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals")));
assert!(!harness.state().ui.mesh_recompute_normals, "a pointer click turns it back off");
assert!(!is_on(&harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals")));
}
/// Whether the Log lists `line` (the status bar under it repeats the last message)