From 8700efc30c2d1e6b50b16d5e007ad55ba26b46b0 Mon Sep 17 00:00:00 2001 From: ATOM Date: Wed, 25 Nov 2026 22:45:46 -0600 Subject: [PATCH 1/4] feat(mesh): make normal recomputation a real export option --- crates/automation/src/headless.rs | 4 +- crates/automation/src/rpc.rs | 4 +- crates/automation/src/server.rs | 3 + crates/engine/src/file_cmds.rs | 87 ++++++++++++++++++++--- crates/ui-egui/src/mesh_export_options.rs | 19 +++-- crates/ui-egui/src/state.rs | 13 ++++ crates/ui-egui/src/web_files.rs | 6 +- crates/ui-egui/src/windows.rs | 3 +- crates/ui-egui/tests/it/side_panels.rs | 25 +++++++ docs/control-protocol.md | 4 +- 10 files changed, 144 insertions(+), 24 deletions(-) diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 6f86119e..94e4924f 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -225,9 +225,9 @@ impl Headless { /// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the /// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it. - pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result { + pub fn export_mesh(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result { self.require_project()?; - let out = self.session.mesh_export(path, format)?; + let out = self.session.mesh_export_with_normals(path, format, recompute_normals)?; let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or("."); self.create_dir_all(dir)?; let mut textures = Vec::new(); diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index d159bc80..b0a21e77 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -5,7 +5,7 @@ //! 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?}`, `bake.mesh.add {path, cage?}`, +//! `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 @@ -94,7 +94,7 @@ impl Headless { "project.save" => self.save(str_of(p, "path")), "mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")), "mesh.reimport" => self.reimport_mesh(str_of(p, "path"), bool_of(p, "preserveStrokes")?), - "mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format")), + "mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format"), bool_of(p, "recomputeNormals")?), "bake.mesh.add" => self.add_bake_mesh(required(p, "path")?, bool_of(p, "cage")?), "resource.import" => self.import_resource(required(p, "path")?), "material.save" => self.material_save(p), diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 0ce54f55..f870ad9a 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -141,6 +141,9 @@ pub struct MeshExportParams { /// written next to it) or usdz (textures packaged); default: from the extension, else obj. #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, + /// Replace stored normals with smooth area-weighted normals on the exported copy (default false). + #[serde(default, rename = "recomputeNormals", skip_serializing_if = "Option::is_none")] + pub recompute_normals: Option, } #[derive(Debug, Deserialize, Serialize, JsonSchema)] diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 28595a1f..e827ef0e 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -69,7 +69,7 @@ pub fn specs() -> Vec { "Export Mesh...", ["File"], None, - "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", + "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj), recomputeNormals?: bool (default false: smooth area-weighted normals replace the stored normals on the exported copy only); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", always, export_mesh ), @@ -115,15 +115,32 @@ fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Op impl Session { /// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included). pub fn mesh_obj_bytes(&self) -> Result> { - texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name).map_err(fe) + self.mesh_obj_bytes_with_normals(false) + } + + /// [`Session::mesh_obj_bytes`], optionally replacing normals on the exported copy only. + pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result> { + let mut mesh = self.source_mesh(); + if recompute_normals { + mesh.compute_normals(); + } + texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe) } /// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like /// [`Session::mesh_usd`]'s), to write next to it, named after `stem` (the OBJ file's). pub fn mesh_obj_with_mtl(&mut self, stem: &str) -> Result<(Vec, texturecraft_formats::NamedFiles)> { + self.mesh_obj_with_mtl_and_normals(stem, false) + } + + /// [`Session::mesh_obj_with_mtl`], optionally replacing normals on the exported copy only. + pub fn mesh_obj_with_mtl_and_normals(&mut self, stem: &str, recompute_normals: bool) -> Result<(Vec, texturecraft_formats::NamedFiles)> { // shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is // one image); their tiles export through Export textures with `$udim` names. let mut mesh = self.source_mesh(); + if recompute_normals { + mesh.compute_normals(); + } // A mesh without materials has one implicit material (and texture set). if mesh.materials.is_empty() { mesh.materials.push("default".into()); @@ -136,16 +153,34 @@ impl Session { /// composite, through the texture export pipeline) embedded. glTF has no UV tiles: a /// UV-tiled set embeds its tile atlas, with the mesh's UVs in atlas space. pub fn mesh_glb_bytes(&mut self) -> Result> { + self.mesh_glb_bytes_with_normals(false) + } + + /// [`Session::mesh_glb_bytes`], optionally replacing normals on the exported copy only. + pub fn mesh_glb_bytes_with_normals(&mut self, recompute_normals: bool) -> Result> { let files = self.material_files(texturecraft_formats::glb_export_options(), true, self.mesh.materials.len())?; let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect(); - texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe) + let mut mesh = self.mesh.as_ref().clone(); + if recompute_normals { + mesh.compute_normals(); + } + texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe) } /// The working mesh as USD with a UsdPreviewSurface per material (textures like /// [`Session::mesh_glb_bytes`]): usdz packages them, usda / usdc list them to write alongside. pub fn mesh_usd(&mut self, format: texturecraft_formats::UsdFormat) -> Result { + self.mesh_usd_with_normals(format, false) + } + + /// [`Session::mesh_usd`], optionally replacing normals on the exported copy only. + pub fn mesh_usd_with_normals(&mut self, format: texturecraft_formats::UsdFormat, recompute_normals: bool) -> Result { let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?; - texturecraft_formats::usd_bytes(&self.mesh, &self.doc.project.name, &files, format).map_err(fe) + let mut mesh = self.mesh.as_ref().clone(); + if recompute_normals { + mesh.compute_normals(); + } + texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe) } /// The texture sets of the first `materials` materials rendered with `opts` (as a tile atlas @@ -1159,7 +1194,7 @@ fn write_materialx( #[cfg(not(target_arch = "wasm32"))] fn export_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.exportMesh")?; - let out = s.mesh_export(path, strp(p, "format"))?; + let out = s.mesh_export_with_normals(path, strp(p, "format"), crate::commands::boolp(p, "recomputeNormals").unwrap_or(false))?; let dir = std::path::Path::new(&out.path).parent().unwrap_or(std::path::Path::new("")); let texture_paths: Vec = out.textures.iter().map(|(name, _)| dir.join(name)).collect(); let main_path = std::path::PathBuf::from(&out.path); @@ -1196,6 +1231,12 @@ impl Session { /// The working mesh as a file for `path`, in `format` (obj, glb, usda, usdc, usdz; default: /// from the extension, else OBJ). The extension is appended when it doesn't match. pub fn mesh_export(&mut self, path: &str, format: Option<&str>) -> Result { + self.mesh_export_with_normals(path, format, false) + } + + /// [`Session::mesh_export`], optionally computing smooth area-weighted normals on the + /// exported copy. The project's source and render meshes are never changed. + pub fn mesh_export_with_normals(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result { let ext = match format { Some(f) if MESH_EXPORT_FORMATS.contains(&f) => f.to_string(), Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", MESH_EXPORT_FORMATS.join(", ")))), @@ -1204,12 +1245,12 @@ impl Session { }; let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") }; let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) { - ("glb", _) => (self.mesh_glb_bytes()?, Vec::new()), + ("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()), (_, Some(format)) => { - let usd = self.mesh_usd(format)?; + let usd = self.mesh_usd_with_normals(format, recompute_normals)?; (usd.bytes, usd.textures) } - _ => self.mesh_obj_with_mtl(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"))?, + _ => self.mesh_obj_with_mtl_and_normals(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"), recompute_normals)?, }; Ok(MeshExport { path, bytes, textures }) } @@ -1402,6 +1443,36 @@ f 1/1 2/2 3/3 let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn mesh_export_can_recompute_normals_without_changing_the_project() { + let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + 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(); + 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(); + for (format, suffix) in [("obj", "obj"), ("glb", "glb"), ("usda", "usda")] { + let path = dir.join(format!("cube-{format}.{suffix}")); + let reply = crate::execute(&mut s, "file.exportMesh", &json!({"path": path, "recomputeNormals": true})).unwrap(); + 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"); + } + } + assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged"); + assert!(s.mesh.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the render project is unchanged"); + let stored_path = dir.join("stored.obj"); + let stored = crate::execute(&mut s, "file.exportMesh", &json!({"path": stored_path})).unwrap(); + let stored = std::fs::read(stored["path"].as_str().unwrap()).unwrap(); + let stored = texturecraft_formats::import_mesh_bytes("stored.obj", &stored).unwrap().mesh; + assert!(stored.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the default keeps stored normals for compatibility"); + let _ = std::fs::remove_dir_all(&dir); + } + #[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(); diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 8458db61..822962b3 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -31,6 +31,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut export, mut cancel) = (false, false); + let mut triangulated = true; crate::windows::dialog(ctx, "mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { ui.set_width(DIALOG_WIDTH); @@ -38,7 +39,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); option( ui, - true, + &mut triangulated, + false, tr("Apply triangulation"), &[ tr("Splits every face with more than three corners into triangles; triangles stay as they are."), @@ -49,11 +51,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); option( ui, + &mut app.ui.mesh_recompute_normals, true, tr("Recompute vertex normals"), &[ tr("Replaces the mesh's vertex normals with newly computed ones in the exported file."), - tr("TextureCraft cannot do this yet: it writes the vertex normals the mesh has in the project."), + 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(8.0); @@ -76,12 +79,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -/// A greyed option under a choice, ticked as the reference shows it, with an info icon at the -/// row's right end whose tooltip has the paragraphs `info` -fn option(ui: &mut Ui, checked: bool, label: &str, info: &[&str]) { +/// An option under a choice, greyed when `enabled` is false, with an info icon at the row's right +/// end whose tooltip has the paragraphs `info`. +fn option(ui: &mut Ui, checked: &mut bool, enabled: bool, label: &str, info: &[&str]) { ui.horizontal(|ui| { ui.add_space(OPTION_INDENT); - unavailable::checkbox(ui, checked, label); + if enabled { + ui.checkbox(checked, label); + } else { + unavailable::checkbox(ui, *checked, label); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let icon = ui.label(egui::RichText::new(egui_phosphor::regular::INFO).color(Tokens::get(ui.ctx()).text_dim)); icon.on_hover_ui(|ui| { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index dd814ef7..fe313410 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -566,6 +566,9 @@ pub struct UiState { /// Window ▸ Hide UI (Tab): only the viewport. pub hide_ui: bool, pub windows: Windows, + /// Mesh Export Options: compute smooth normals on the exported copy, not the project. + #[serde(default = "default_true")] + pub mesh_recompute_normals: bool, pub uv_zoom: f32, pub uv_pan: [f32; 2], /// The 2D view's turn, counter-clockwise on screen in radians (Alt+left drag) @@ -770,6 +773,7 @@ impl Default for UiState { selected_baked_map: None, hide_ui: false, windows: Windows::default(), + mesh_recompute_normals: true, uv_zoom: 1.0, uv_pan: [0.0, 0.0], uv_rotation: 0.0, @@ -851,6 +855,15 @@ mod tests { assert_eq!(crate::start_ui(None, &mut session).prefs.language, crate::i18n::SYSTEM_LANGUAGE); } + #[test] + fn mesh_export_normal_choice_defaults_on_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"); + } + #[test] fn adopting_a_layout_keeps_recent_files_export_settings_and_shortcuts() { let mut ui = UiState { recent: vec!["a.tcraft".into()], ..UiState::default() }; diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 5687f5db..89c86600 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -337,9 +337,9 @@ mod web { pub fn export_mesh(app: &mut TextureCraftApp, ext: &str) { let name = format!("{}.{ext}", sanitize_file_stem(&app.session.doc.project.name)); let bytes = match ext { - "glb" => app.session.mesh_glb_bytes(), - "usdz" => app.session.mesh_usd(texturecraft_engine::formats::UsdFormat::Usdz).map(|u| u.bytes), - _ => app.session.mesh_obj_bytes(), + "glb" => app.session.mesh_glb_bytes_with_normals(app.ui.mesh_recompute_normals), + "usdz" => app.session.mesh_usd_with_normals(texturecraft_engine::formats::UsdFormat::Usdz, app.ui.mesh_recompute_normals).map(|u| u.bytes), + _ => app.session.mesh_obj_bytes_with_normals(app.ui.mesh_recompute_normals), }; match bytes.map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) { Ok(()) => app.toast(trf("Downloaded {name}", &[("name", &name)]), false), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index a172926a..1ea09b80 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -609,7 +609,8 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> .file_name(name); app.ask_file(dialog, Bound::Project, |app, paths| { if let Some(path) = paths.first() - && let Some(result) = app.run("file.exportMesh", json!({"path": path.display().to_string()})) + && let Some(result) = + app.run("file.exportMesh", json!({"path": path.display().to_string(), "recomputeNormals": app.ui.mesh_recompute_normals})) { let saved_path = result["path"].as_str().unwrap_or_default(); app.toast(trf("Exported mesh to {path}", &[("path", &saved_path)]), false); diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index aab7c36d..f3a31394 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -174,6 +174,31 @@ fn export_mesh_asks_the_options_then_the_file() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn recompute_normals_is_an_enabled_keyboard_operable_checkbox() { + let mut harness = app(); + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "file.exportMesh"); + 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); + + 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"); + 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_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"))); +} + /// Whether the Log lists `line` (the status bar under it repeats the last message) fn log_lists(harness: &Harness<'_, TextureCraftApp>, line: &str) -> bool { harness.query_all_by_label(line).any(|node| node.rect().bottom() < STATUS_BAR_TOP) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 71c95e6f..e3179022 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -382,7 +382,7 @@ With `rebuildUvs: true`, the project file saves the generated layout. Reopening | `project_save` | `{path?}` | `.tcraft` (appended if missing), relative to the write root | | `mesh_import` | `{path, resolution?}` | New project from .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl; a .gltf's buffers and images and a loose USD layer's textures are read from its folder | | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | -| `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | +| `mesh_export` | `{path, format?, recomputeNormals?}` | The mesh as obj, glb, usda, usdc or usdz below the write root; `recomputeNormals: true` writes smooth area-weighted normals on the exported copy (default false) (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | | `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | @@ -457,7 +457,7 @@ File access follows `--read-root` / `--write-root` as for MCP. | `project.save` | `{path?}` | | `mesh.import` | `{path, resolution?, name?}` | | `mesh.reimport` | `{path?, preserveStrokes?}` | -| `mesh.export` | `{path, format?}` | +| `mesh.export` | `{path, format?, recomputeNormals?}` | | `bake.mesh.add` | `{path, cage?}` | | `resource.import` | `{path}` | | `material.save` | `{path, layer?, name?}` | From 14deaa61de145f560de5a36642b9e13676ed5f5b Mon Sep 17 00:00:00 2001 From: ATOM Date: Wed, 25 Nov 2026 23:34:31 -0600 Subject: [PATCH 2/4] fix(ui): preserve normal export choice across layouts --- crates/ui-egui/src/state.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index fe313410..24c5f7a4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -735,6 +735,7 @@ impl UiState { } self.export = keep.export; + self.mesh_recompute_normals = keep.mesh_recompute_normals; self.recent = keep.recent; self.last_template = keep.last_template; self.prefs = keep.prefs; @@ -869,7 +870,9 @@ mod tests { let mut ui = UiState { recent: vec!["a.tcraft".into()], ..UiState::default() }; ui.export.preset = "Mine".into(); ui.keymap.insert("file.save".into(), "F5".into()); + ui.mesh_recompute_normals = false; let mut layout = UiState::default(); + assert!(layout.mesh_recompute_normals); layout.dock.close(crate::docking::Panel::Assets); ui.adopt_layout(layout); @@ -878,6 +881,7 @@ mod tests { assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); assert_eq!(ui.export.preset, "Mine"); assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); + assert!(!ui.mesh_recompute_normals, "a layout does not change the user's export setting"); } #[test] From 0fbfec1c3d732dc9ba18c9f55f8bc7cd5dc6a7a9 Mon Sep 17 00:00:00 2001 From: ATOM Date: Thu, 26 Nov 2026 10:36:05 -0600 Subject: [PATCH 3/4] fix(mesh): weld recomputed normals and make export opt-in --- crates/automation/src/rpc.rs | 5 +-- crates/engine/src/file_cmds.rs | 44 +++++++++++++++++++---- crates/formats/src/mesh_import/mod.rs | 21 ++--------- crates/geom/src/mesh.rs | 21 +++++++++++ crates/ui-egui/src/mesh_export_options.rs | 4 +-- crates/ui-egui/src/state.rs | 13 +++---- crates/ui-egui/tests/it/side_panels.rs | 12 +++---- 7 files changed, 78 insertions(+), 42 deletions(-) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index b0a21e77..aefb4919 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -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 diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index e827ef0e..553f6ffa 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -122,7 +122,7 @@ impl Session { pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result> { 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(); diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 6450878b..5e0d2468 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -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, Option>)> { 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 Vec { - 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()) diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 03d47845..3bae99f4 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -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 { + 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 diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 822962b3..7d5cb5c2 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -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 diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c1fe25e5..1f447556 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -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); diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 62362f74..399a5161 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -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) From 448d22aa26904396d22d007d9f6209e2be117f82 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:31:02 +0000 Subject: [PATCH 4/4] Apply review fixes - docs/ui-parity.md --- docs/ui-parity.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1e45c49d..26198df6 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -71,8 +71,10 @@ that closes it back onto the bar; the float is saved with the UI state. with materials that refer to the exported textures; greyed in the browser), *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected for export"). *Export MaterialX* beside them is a TextureCraft addition: it adds `materialX: true` to the - export. The prompt's *With displacement/tessellation* choice and both option checkboxes are - greyed; TextureCraft exports the mesh as it is. + export. The prompt's *With displacement/tessellation* choice and *Apply triangulation* are greyed + (TextureCraft exports the mesh as it is, triangulated). *Recompute vertex normals* works and sits under + *Without displacement/tessellation*, off by default: it writes smooth area-weighted normals to the + exported copy only. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the samples so far and a note; it floats when first opened and is not opened by itself in Rendering mode), *Properties - Paint* while a project is open (other tools read "Properties - ",