From aef225f3a6d59c7f63e2c7b12711d18c5ed2cd69 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:14:41 -0500 Subject: [PATCH 01/10] feat(bake): Auto-rebake keeps one mesh map up to date A map chosen with `bake.autoRebake {map}` (or the new Auto-rebake checkbox in the bake mode's per-map panel) bakes itself again, alone, whenever what it was baked from changes: the texture set's bake settings (except which maps are ticked), the low poly, the high polys or the cage. The apps poll `Session::auto_rebake_due` each frame and bake the due sets in the background; `bake.autoRebake.run` does the same once, blocking, for agents and scripts. A set only takes part once it has the map baked at its current output size, so Auto-rebake keeps a bake current without starting one or leaving a set's maps at two sizes. A manual bake of the map also marks the set up to date, and a change made while a bake runs triggers another. The choice isn't saved in the project. The other maps of the set are left as they were. Strings translated in all nine languages (native-speaker review welcome, as for the rest). Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- crates/engine/src/auto_rebake.rs | 168 +++++++++++++++++++++++++++++ crates/engine/src/bake_cmds.rs | 6 +- crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/session.rs | 3 + crates/engine/tests/auto_rebake.rs | 92 ++++++++++++++++ crates/ui-egui/src/i18n/de.rs | 5 + crates/ui-egui/src/i18n/es.rs | 5 + crates/ui-egui/src/i18n/fr.rs | 5 + crates/ui-egui/src/i18n/it.rs | 5 + crates/ui-egui/src/i18n/ja.rs | 5 + crates/ui-egui/src/i18n/ko.rs | 5 + crates/ui-egui/src/i18n/pt_br.rs | 5 + crates/ui-egui/src/i18n/zh_hans.rs | 2 + crates/ui-egui/src/lib.rs | 23 +++- crates/ui-egui/src/windows.rs | 12 ++- 17 files changed, 339 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/auto_rebake.rs create mode 100644 crates/engine/tests/auto_rebake.rs diff --git a/ROADMAP.md b/ROADMAP.md index 007c96bd..9b9e1a17 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,7 +16,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer) | | Materials and assets | 8 | 86% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | -| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | +| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly or the high polys change); high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | | Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | diff --git a/crates/engine/src/auto_rebake.rs b/crates/engine/src/auto_rebake.rs new file mode 100644 index 00000000..039a3878 --- /dev/null +++ b/crates/engine/src/auto_rebake.rs @@ -0,0 +1,168 @@ +//! Auto-rebake: one mesh map that bakes itself again when what it was baked from changes. +//! +//! The map is chosen with `bake.autoRebake`. From then on, [`Session::auto_rebake_due`] names the +//! texture sets whose bake inputs (the set's bake settings except the list of maps, the low poly, +//! the high polys and the cage) differ from those of their last bake of that map. +//! The apps poll it each frame and bake the due sets in the background; `bake.autoRebake.run` +//! does the same thing once, blocking, for agents and scripts. +//! +//! A set only takes part once it has the map baked at its current output size: Auto-rebake +//! keeps a bake up to date, it doesn't start one, and it never leaves a set's maps at two sizes. +//! The choice isn't part of the project. + +use std::collections::BTreeMap; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_bake::Progress; +use texturecraft_core::BakedMap; + +use crate::bake_cmds::BakeTask; +use crate::commands::{CommandSpec, always, bad, boolp, strp}; +use crate::{Result, Session, cmd}; + +/// Which map rebakes itself, and what each texture set was last baked from. +#[derive(Clone, Debug, Default)] +pub struct AutoRebake { + pub map: Option, + /// Fingerprint of each set's bake inputs when it last baked [`AutoRebake::map`]. + seen: BTreeMap, + /// Fingerprint taken when a set's bake started, kept when that bake finishes. + pending: BTreeMap, +} + +pub fn specs() -> Vec { + vec![ + cmd!( + "bake.autoRebake", + "Auto-rebake", + [], + None, + "{map?: map id (e.g. \"normal_base\", \"height\") to keep up to date, or null / off: true to turn it off; no params: just report} → {map, due: [texture sets that need a rebake]}", + always, + auto_rebake + ), + cmd!( + "bake.autoRebake.run", + "Run Auto-rebake", + [], + None, + "{cpu?: true (skip the GPU)} → {rebaked: [texture sets]}: bakes the Auto-rebake map of every set whose bake inputs changed since it was last baked, now", + always, + auto_rebake_run + ), + ] +} + +impl Session { + /// A fingerprint of everything a bake of texture set `ts` is made from, except which maps it + /// makes. + pub fn bake_inputs_key(&self, ts: usize) -> Option { + let set = self.doc.project.texture_sets.get(ts)?; + let mut settings = set.bake.clone(); + settings.maps.clear(); + settings.enabled = true; + let mut h = DefaultHasher::new(); + serde_json::to_string(&settings).ok()?.hash(&mut h); + (Arc::as_ptr(&self.mesh) as usize).hash(&mut h); + for m in &self.bake_meshes.high { + (Arc::as_ptr(&m.mesh) as usize).hash(&mut h); + } + self.bake_meshes.cage.as_ref().map(|c| Arc::as_ptr(&c.mesh) as usize).hash(&mut h); + Some(h.finish()) + } + + /// Texture sets whose Auto-rebake map is out of date. A set seen for the first time (a project + /// just opened, a bake from before Auto-rebake was on) is taken as up to date. + pub fn auto_rebake_due(&mut self) -> Vec { + let Some(map) = self.auto_rebake.map else { return Vec::new() }; + let mut due = Vec::new(); + for ts in 0..self.doc.project.texture_sets.len() { + let Some(set) = self.doc.project.texture_sets.get(ts).filter(|t| t.bake.enabled) else { continue }; + let columns = set.tile_grid().map_or(1, |g| g.cols); + let baked = self.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map) && b.resolution == set.bake.resolution.saturating_mul(columns)); + let Some(key) = self.bake_inputs_key(ts).filter(|_| baked) else { continue }; + match self.auto_rebake.seen.get(&ts) { + None => { + self.auto_rebake.seen.insert(ts, key); + } + Some(seen) if *seen != key => due.push(ts), + Some(_) => {} + } + } + due + } + + /// Call right before building the bake task of `ts`: remembers what it is baked from, so a + /// finished bake of the Auto-rebake map marks the set up to date (and a change made while it + /// ran still triggers another). + pub fn begin_bake(&mut self, ts: usize) { + if let Some(key) = self.bake_inputs_key(ts) { + self.auto_rebake.pending.insert(ts, key); + } + } + + /// The bake task of `ts` restricted to one map (Auto-rebake's: the other maps stay as they are). + pub fn bake_task_for(&self, ts: usize, only: Option) -> Result { + let mut task = self.bake_task(ts)?; + if let Some(m) = only { + task.settings.maps = std::iter::once(m).collect(); + } + Ok(task) + } + + /// Records a finished bake: when it made the Auto-rebake map, the set is up to date. + pub(crate) fn note_baked(&mut self, ts: usize, made: impl Iterator) { + let key = self.auto_rebake.pending.remove(&ts); + if let (Some(key), Some(map)) = (key, self.auto_rebake.map) + && made.into_iter().any(|m| m == map) + { + self.auto_rebake.seen.insert(ts, key); + } + } + + /// Bakes every due set's Auto-rebake map now (blocking); returns the sets. + pub fn auto_rebake_now(&mut self, cpu: bool) -> Result> { + let due = self.auto_rebake_due(); + let map = self.auto_rebake.map; + for &ts in &due { + self.begin_bake(ts); + let mut task = self.bake_task_for(ts, map)?; + if cpu { + task.tracer = None; + } + let out = task.run(&Progress::new())?; + self.apply_bake(ts, out)?; + } + Ok(due) + } +} + +fn state(s: &mut Session) -> Value { + json!({ "map": s.auto_rebake.map.map(BakedMap::id), "due": s.auto_rebake_due() }) +} + +fn auto_rebake(s: &mut Session, p: &Value) -> Result { + if boolp(p, "off") == Some(true) || p.get("map").is_some_and(Value::is_null) { + s.auto_rebake = AutoRebake::default(); + } else if let Some(id) = p.get("map") { + let map = id.as_str().and_then(BakedMap::parse).ok_or_else(|| bad("bake.autoRebake", format!("unknown mesh map {id}")))?; + if s.auto_rebake.map != Some(map) { + s.auto_rebake = AutoRebake { map: Some(map), ..AutoRebake::default() }; + } + } else if strp(p, "map").is_some() { + return Err(bad("bake.autoRebake", "`map` must be a map id or null")); + } + Ok(state(s)) +} + +fn auto_rebake_run(s: &mut Session, p: &Value) -> Result { + if s.auto_rebake.map.is_none() { + return Err(bad("bake.autoRebake.run", "no Auto-rebake map is set; run bake.autoRebake {map} first")); + } + let rebaked = s.auto_rebake_now(boolp(p, "cpu") == Some(true))?; + s.update(); + Ok(json!({ "rebaked": rebaked })) +} diff --git a/crates/engine/src/bake_cmds.rs b/crates/engine/src/bake_cmds.rs index d6387636..57cdbc25 100644 --- a/crates/engine/src/bake_cmds.rs +++ b/crates/engine/src/bake_cmds.rs @@ -177,6 +177,7 @@ impl Session { /// Store a finished bake (one undo step). pub fn apply_bake(&mut self, ts: usize, out: BakeOutput) -> Result<()> { self.log.push(format!("Baked texture set {ts} ({})", out.tracer)); + let made: Vec = out.maps.keys().copied().collect(); self.edit("Bake mesh maps", |s| { let maps: BTreeSet = out.maps.keys().copied().collect(); let entry = s.doc.baked.entry(ts).or_default(); @@ -186,11 +187,14 @@ impl Session { } s.doc.project.texture_set_mut(ts)?.baked.extend(maps); Ok(()) - }) + })?; + self.note_baked(ts, made.into_iter()); + Ok(()) } /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { + self.begin_bake(ts); let mut task = self.bake_task(ts)?; if cpu { task.tracer = None; diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 1d6b0cb8..cc946813 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -66,6 +66,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); v.extend(crate::bake_cmds::specs()); + v.extend(crate::auto_rebake::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2afa239..26e18949 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,6 +8,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod auto_rebake; pub mod bake_cmds; pub mod camera_cmds; pub mod commands; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index fa239848..2ef66011 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -320,6 +320,8 @@ pub struct Session { pub mesh_source: Option<(String, Vec)>, /// High-definition meshes and cage for baking (saved inside the project). pub bake_meshes: crate::BakeMeshes, + /// The map that bakes itself again when its inputs change (not saved). + pub auto_rebake: crate::auto_rebake::AutoRebake, pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, @@ -375,6 +377,7 @@ impl Session { bvh: Arc::new(bvh), mesh_source, bake_meshes: Default::default(), + auto_rebake: Default::default(), caches, undo: Vec::new(), redo: Vec::new(), diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs new file mode 100644 index 00000000..c4fe8644 --- /dev/null +++ b/crates/engine/tests/auto_rebake.rs @@ -0,0 +1,92 @@ +//! Auto-rebake: one mesh map bakes itself again when its bake inputs change. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with a high poly just above it, baked once with height and opacity. +fn baked_session() -> (Session, std::path::PathBuf) { + let mesh = primitives::builtin("plane").unwrap(); + let mut obj = String::from("o Part_high\n"); + for p in &mesh.positions { + obj += &format!("v {} {} {}\n", p.x, p.y + 0.002, p.z); + } + for t in mesh.indices.chunks_exact(3) { + obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); + } + let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("hp.obj"); + std::fs::write(&path, obj).unwrap(); + let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + execute(&mut s, "bake.highPoly.add", &json!({ "path": path.display().to_string() })).unwrap(); + execute(&mut s, "bake.settings", &json!({ "resolution": 128, "dilation": 0, "maps": ["height", "opacity"] })).unwrap(); + execute(&mut s, "bake.run", &json!({ "cpu": true })).unwrap(); + (s, dir) +} + +fn due(s: &mut Session) -> Vec { + execute(s, "bake.autoRebake", &Value::Null).unwrap()["due"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() +} + +fn image(s: &Session, map: BakedMap) -> Arc> { + s.doc.baked[&0].maps[&map].clone() +} + +#[test] +fn a_changed_bake_input_rebakes_only_the_chosen_map() { + let (mut s, dir) = baked_session(); + // Off by default; nothing is due and the run command says what to do first. + assert_eq!(execute(&mut s, "bake.autoRebake", &Value::Null).unwrap()["map"], Value::Null); + assert!(execute(&mut s, "bake.autoRebake.run", &Value::Null).is_err()); + let r = execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); + assert_eq!(r["map"], "height"); + assert!(due(&mut s).is_empty(), "turning it on takes the current bake as up to date"); + + // Which maps are ticked is not a bake input; a setting is. + execute(&mut s, "bake.settings", &json!({ "maps": ["height", "opacity", "ambient_occlusion"] })).unwrap(); + assert!(due(&mut s).is_empty()); + execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2, "maps": ["height", "opacity"] })).unwrap(); + assert_eq!(due(&mut s), [0]); + + let (height, opacity) = (image(&s, BakedMap::Height), image(&s, BakedMap::Opacity)); + let r = execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); + assert_eq!(r["rebaked"], json!([0])); + assert!(!Arc::ptr_eq(&height, &image(&s, BakedMap::Height)), "the Auto-rebake map was baked again"); + assert!(Arc::ptr_eq(&opacity, &image(&s, BakedMap::Opacity)), "the other maps were left alone"); + assert!(due(&mut s).is_empty(), "and the set is up to date"); + assert_eq!(execute(&mut s, "bake.autoRebake.run", &Value::Null).unwrap()["rebaked"], json!([])); + + // A manual bake of the map also counts; a changed high poly list is a change again. + execute(&mut s, "bake.settings", &json!({ "antialiasing": 2 })).unwrap(); + assert_eq!(due(&mut s), [0]); + s.begin_bake(0); + let out = s.bake_task_for(0, None).unwrap().run(&texturecraft_engine::bake::Progress::new()).unwrap(); + s.apply_bake(0, out).unwrap(); + assert!(due(&mut s).is_empty(), "a manual bake of the map marks it up to date"); + execute(&mut s, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + assert_eq!(due(&mut s), [0]); + + // A different output size is left to a manual bake: the maps would end up at two sizes. + execute(&mut s, "bake.settings", &json!({ "resolution": 256 })).unwrap(); + assert!(due(&mut s).is_empty()); + + // Hostile input, and turning it off. + for bad in [json!({ "map": "nonsense" }), json!({ "map": 3 })] { + assert!(execute(&mut s, "bake.autoRebake", &bad).is_err(), "{bad}"); + } + assert_eq!(execute(&mut s, "bake.autoRebake", &json!({ "map": null })).unwrap()["map"], Value::Null); + assert!(due(&mut s).is_empty()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_set_without_the_map_baked_is_left_alone() { + let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); + execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap(); + assert!(due(&mut s).is_empty(), "Auto-rebake keeps a bake up to date, it doesn't start one"); +} diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ce534a6f..728fab62 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -689,6 +689,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Größe wird geändert"), ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), ("Return to painting mode", "Zurück zum Malmodus"), + ("Auto-rebake", "Automatisch neu backen"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Diese Map automatisch neu backen, wenn sich ihre Bake-Einstellungen, das Low-Poly- oder die High-Poly-Meshes ändern", + ), ("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"), ("Rotation", "Drehung"), ("Rotation (degrees)", "Drehung (Grad)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 2b57afd8..22d221f4 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -680,6 +680,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), ("Return to painting mode", "Volver al modo de pintura"), + ("Auto-rebake", "Rehornear automáticamente"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Vuelve a hornear este mapa automáticamente cuando cambian sus ajustes de horneado, la malla low poly o las high poly", + ), ("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"), ("Rotation", "Rotación"), ("Rotation (degrees)", "Rotación (grados)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0e72b031..f1ef103a 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -689,6 +689,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionnement"), ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), ("Return to painting mode", "Revenir au mode peinture"), + ("Auto-rebake", "Précalcul automatique"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Précalcule à nouveau cette carte automatiquement quand ses réglages de précalcul, le maillage low poly ou les maillages high poly changent", + ), ("Right-click a layer > Create smart material", "Clic droit sur un calque > Créer un matériau intelligent"), ("Rotation", "Rotation"), ("Rotation (degrees)", "Rotation (degrés)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9260b188..dd5f04b4 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -689,6 +689,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), ("Return to painting mode", "Torna alla modalità pittura"), + ("Auto-rebake", "Bake automatico"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Esegue di nuovo il bake di questa mappa quando cambiano le sue impostazioni di bake, la mesh low poly o le mesh high poly", + ), ("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"), ("Rotation", "Rotazione"), ("Rotation (degrees)", "Rotazione (gradi)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2e333ab9..f670e670 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -668,6 +668,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), ("Return to painting mode", "ペイントモードに戻る"), + ("Auto-rebake", "自動再ベイク"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "ベイク設定、ローポリ、またはハイポリが変わると、このマップを自動的にベイクし直します", + ), ("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"), ("Rotation", "回転"), ("Rotation (degrees)", "回転 (度)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 3945c9a9..e18daf69 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -659,6 +659,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), ("Return to painting mode", "페인팅 모드로 돌아가기"), + ("Auto-rebake", "자동 다시 베이크"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "베이크 설정, 로우 폴리 또는 하이 폴리가 바뀌면 이 맵을 자동으로 다시 베이크합니다", + ), ("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"), ("Rotation", "회전"), ("Rotation (degrees)", "회전 (도)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 788df7f9..ffa080e8 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -677,6 +677,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), ("Return to painting mode", "Voltar ao modo de pintura"), + ("Auto-rebake", "Refazer bake automaticamente"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Refaz o bake deste mapa automaticamente quando as configurações de bake, a malha low poly ou as high poly mudam", + ), ("Right-click a layer > Create smart material", "Clique com o botão direito em uma camada > Criar material inteligente"), ("Rotation", "Rotação"), ("Rotation (degrees)", "Rotação (graus)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3de5246c..e6c1b6b4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -608,6 +608,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), ("Return to painting mode", "返回绘画模式"), + ("Auto-rebake", "自动重新烘焙"), + ("Bake this map again by itself when its bake settings, the low poly or the high polys change", "当烘焙设置、低模或高模发生变化时,自动重新烘焙此贴图"), ("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"), ("Rotation", "旋转"), ("Rotation (degrees)", "旋转(度)"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bd53bd98..e7261b22 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -51,6 +51,8 @@ pub struct BakeJob { pub queue: Vec, pub current: Option<(usize, Arc, std::sync::mpsc::Receiver>)>, pub total: usize, + /// Bake only this map (an Auto-rebake); None bakes every ticked map. + pub only: Option, } /// The browser build's notice when WebGPU is unavailable and wgpu fell back to WebGL2. @@ -176,7 +178,7 @@ impl TextureCraftApp { return; } let total = sets.len(); - self.bake = Some(BakeJob { queue: sets, current: None, total }); + self.bake = Some(BakeJob { queue: sets, current: None, total, only: None }); } fn poll_bake(&mut self, ctx: &egui::Context) { @@ -213,8 +215,9 @@ impl TextureCraftApp { self.toast(i18n::tr("Mesh maps baked"), false); return; } - let ts = job.queue.remove(0); - match self.session.bake_task(ts) { + let (ts, only) = (job.queue.remove(0), job.only); + self.session.begin_bake(ts); + match self.session.bake_task_for(ts, only) { Ok(task) => { let progress = Arc::new(Progress::new()); let p = progress.clone(); @@ -228,6 +231,19 @@ impl TextureCraftApp { } } + /// Auto-rebake: when the chosen map's bake inputs changed, bake it again in the background + /// (one set after another, only that map), unless a bake or a stroke is running. + fn drive_auto_rebake(&mut self) { + if self.bake.is_some() || self.session.stroke_active() || self.session.auto_rebake.map.is_none() { + return; + } + let due = self.session.auto_rebake_due(); + if !due.is_empty() { + let total = due.len(); + self.bake = Some(BakeJob { queue: due, current: None, total, only: self.session.auto_rebake.map }); + } + } + pub fn cancel_bake(&mut self) { if let Some(job) = self.bake.take() && let Some((_, p, _)) = job.current @@ -369,6 +385,7 @@ impl eframe::App for TextureCraftApp { web_files::dropped(self, ctx, f); } self.poll_bake(ctx); + self.drive_auto_rebake(); self.poll_resize(ctx); let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0); if (ctx.zoom_factor() - scale).abs() > 1e-3 { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 2ecafdd6..13bc3dc4 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -578,7 +578,17 @@ fn bake_panel(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); match selected { None => common_params(app, ui, &mut b), - Some(m) => map_params(ui, m, &mut b), + Some(m) => { + let mut auto = app.session.auto_rebake.map == Some(m); + if ui + .checkbox(&mut auto, tr("Auto-rebake")) + .on_hover_text(tr("Bake this map again by itself when its bake settings, the low poly or the high polys change")) + .changed() + { + app.run("bake.autoRebake", if auto { json!({ "map": m.id() }) } else { json!({ "off": true }) }); + } + map_params(ui, m, &mut b) + } } if b.direction == [0.0; 3] { b.direction = before.direction; From 5e21cb47c52f2b8605df4c5649598968930bd752 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:19:17 -0500 Subject: [PATCH 02/10] i18n: Arabic strings for Auto-rebake Arabic landed after this branch was cut, and the translation test requires every string in every language. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/i18n/ar.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0320cbf7..79b889b4 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -650,6 +650,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), ("Return to painting mode", "العودة إلى نمط الرسم"), + ("Auto-rebake", "إعادة الخبز تلقائيًا"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "يعيد خبز هذه الخريطة تلقائيًا عند تغيّر إعدادات الخبز أو المجسّم منخفض الدقة أو المجسّمات عالية الدقة", + ), ("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"), ("Rotation", "التدوير"), ("Rotation (degrees)", "التدوير (بالدرجات)"), From ffd311f5167dd5df48e54c03a825f3d143b7ad05 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:50:09 -0500 Subject: [PATCH 03/10] feat(import): MaterialX (.mtlx) material import as a fill layer file.importMaterialX {path, material?, name?} reads an open_pbr_surface, standard_surface or gltf_pbr material and adds one fill layer: image inputs (directly, through a nodegraph output or normalmap/convert/constant nodes, with fileprefix and the first UDIM tile) become image resources and sources, literal values become uniform sources (sRGB-tagged colours converted to linear, colours on scalar channels averaged), the displacement shader becomes height, and the first image's uvtiling becomes the UV projection scale. Emission follows the specifications' defaults (off unless emission_luminance / emission is above 0). Images are read only from the document's folder and below: a document is untrusted. Channels the texture set lacks, unreadable images and unsupported nodes are reported in `warnings`; nothing to import is an error. The whole import is one undo step. Written from the ASWF MaterialX 1.39 and OpenPBR Surface specifications; the reader caps size, depth and element count and has mutation tests. The inverse of the MaterialX export in #50. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/materialx_cmds.rs | 148 +++++++ crates/engine/src/resource_cmds.rs | 2 +- crates/engine/tests/materialx_import.rs | 124 ++++++ crates/formats/src/lib.rs | 1 + crates/formats/src/materialx_read.rs | 542 ++++++++++++++++++++++++ 8 files changed, 819 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/materialx_cmds.rs create mode 100644 crates/engine/tests/materialx_import.rs create mode 100644 crates/formats/src/materialx_read.rs diff --git a/ROADMAP.md b/ROADMAP.md index 8563db44..9e5116a5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,7 +11,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| -| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | +| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | | Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index b8938a19..dbd5c868 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -66,6 +66,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); v.extend(crate::bake_cmds::specs()); + v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f2e6920..352d8002 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -21,6 +21,7 @@ pub mod layer_ops; pub mod mask_cmds; pub mod material_lib; pub mod materials; +pub mod materialx_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs new file mode 100644 index 00000000..8a212dd7 --- /dev/null +++ b/crates/engine/src/materialx_cmds.rs @@ -0,0 +1,148 @@ +//! `file.importMaterialX`: a MaterialX (`.mtlx`) material becomes one fill layer. +//! +//! The document is read by [`texturecraft_formats::materialx_read`]; here its image files are +//! loaded (only from the document's own folder and below: a document is untrusted, and its +//! `file` values must not reach other files), added to the project as resources and set as the +//! fill's sources, with constants as uniform sources. The whole import is one undo step. Channels +//! the texture set doesn't have, images that can't be read and anything the reader skipped are +//! reported in `warnings`; the import goes ahead with the rest. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_core::{Channel, Fill, Layer, LayerKind, Projection, Source}; +use texturecraft_formats::materialx_read::{Material, Value as Mtlx}; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::{EngineError, Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "file.importMaterialX", + "Import MaterialX material...", + ["File"], + None, + "{path: a .mtlx file, material?: the surfacematerial to read (default: the first), name?: layer name} → {layer, material, channels, resources, warnings}: one fill layer with the material's textures (read from the file's folder) and values; open_pbr_surface, standard_surface and gltf_pbr are read", + always, + import + )] +} + +/// Loads an image file named in the document (relative to it): its bytes, or why not. +pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; + +impl Session { + /// Add `material` as a fill layer on the active texture set, loading its images with `load`. + /// Returns the reply of `file.importMaterialX`. + pub fn import_material(&mut self, material: Material, name: Option<&str>, load: Loader) -> Result { + let mut warnings = material.warnings.clone(); + let ts = self.ts(); + let available = self.doc.project.texture_set(ts).map(|t| t.channel_list()).unwrap_or_default(); + let mut fill = Fill { projection: Projection::Uv { scale: material.uv_tiling, rotation: 0.0, offset: [0.0, 0.0] }, ..Fill::default() }; + // Resources to add (name and encoded bytes), and their decoded images for the session. + let mut added: Vec<(String, Arc>)> = Vec::new(); + let mut decoded = Vec::new(); + let mut names: BTreeMap = BTreeMap::new(); + let mut channels: Vec = Vec::new(); + for (channel, value) in &material.channels { + if !available.contains(channel) { + warnings.push(format!("{} was skipped: this texture set has no such channel", channel.id())); + continue; + } + let source = match value { + Mtlx::Constant(c) => Source::Uniform(*c), + Mtlx::Image(file) => { + let resource = match names.get(file) { + Some(n) => n.clone(), + None => { + let loaded = + load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string())); + let (bytes, image) = match loaded { + Ok(v) => v, + Err(e) => { + warnings.push(format!("{} was skipped: {file}: {e}", channel.id())); + continue; + } + }; + let leaf = file.rsplit(['/', '\\']).next().unwrap_or(file); + let base = texturecraft_formats::sanitize_resource_name(leaf); + let (mut unique, mut n) = (base.clone(), 2); + while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) { + unique = format!("{n}_{base}"); + n += 1; + } + added.push((unique.clone(), Arc::new(bytes))); + decoded.push((unique.clone(), crate::resource_cmds::decoded(image))); + names.insert(file.clone(), unique.clone()); + unique + } + }; + Source::Image { name: resource } + } + }; + fill.sources.insert(*channel, source); + channels.push(*channel); + } + if channels.is_empty() { + let why = if warnings.is_empty() { String::new() } else { format!(" ({})", warnings.join("; ")) }; + return Err(EngineError::Other(format!("file.importMaterialX: nothing to import from {:?}{why}", material.name))); + } + let layer_name = name.map(str::to_string).unwrap_or_else(|| self.doc.project.next_layer_name(ts, &material.name)); + let resource_names: Vec = added.iter().map(|(n, _)| n.clone()).collect(); + let id = self.edit("Import MaterialX material", |s| { + for (n, bytes) in &added { + s.doc.resources.insert(n.clone(), bytes.clone()); + } + let id = s.doc.project.alloc_id(); + crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels)) + })?; + self.images.extend(decoded); + Ok(json!({ + "layer": id.0, + "material": material.name, + "channels": channels.iter().map(|c| c.id()).collect::>(), + "resources": resource_names, + "warnings": warnings, + })) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn import(s: &mut Session, p: &Value) -> Result { + use std::path::{Component, Path}; + let cmd = "file.importMaterialX"; + let path = strp(p, "path").filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, "`path` is required"))?; + let meta = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + if !meta.is_file() || meta.len() > texturecraft_formats::materialx_read::MAX_BYTES as u64 { + return Err(bad(cmd, format!("{path} is not a MaterialX file of a readable size"))); + } + let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?; + let load = |file: &str| -> std::result::Result, String> { + // `` stands for a tile number; the first tile is read. + let file = file.replace("", "1001"); + let rel = Path::new(&file); + let outside = "the file is outside the material's folder"; + if rel.is_absolute() || rel.components().any(|c| matches!(c, Component::ParentDir | Component::Prefix(_) | Component::RootDir)) { + return Err(outside.into()); + } + let full = dir.join(rel).canonicalize().map_err(|e| e.to_string())?; + if !full.starts_with(&dir) { + return Err(outside.into()); + } + let len = std::fs::metadata(&full).map_err(|e| e.to_string())?.len(); + if len > 512 << 20 { + return Err("the file is over 512 MiB".into()); + } + std::fs::read(&full).map_err(|e| e.to_string()) + }; + s.import_material(material, strp(p, "name"), &load) +} + +#[cfg(target_arch = "wasm32")] +fn import(_: &mut Session, _: &Value) -> Result { + Err(EngineError::Other("file paths are not available in the browser".into())) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 95736cbd..9bdf3949 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { /// Largest accepted resource file. const MAX_BYTES: usize = 512 << 20; -fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { +pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb }) } diff --git a/crates/engine/tests/materialx_import.rs b/crates/engine/tests/materialx_import.rs new file mode 100644 index 00000000..aa51746f --- /dev/null +++ b/crates/engine/tests/materialx_import.rs @@ -0,0 +1,124 @@ +//! `file.importMaterialX`: a .mtlx material becomes one fill layer with its textures. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerKind, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap() +} + +fn png(path: &Path, rgb: [u8; 3]) { + image::RgbImage::from_pixel(4, 4, image::Rgb(rgb)).save(path).unwrap(); +} + +fn folder(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("tc_mtlx_import_{tag}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("tex")).unwrap(); + dir +} + +const MATERIAL: &str = r#" + + + + + + + + + + + + + + + + + + + + + +"#; + +fn fill_of(s: &Session, layer: u64) -> texturecraft_engine::core::Fill { + let l = s.doc.project.layer(texturecraft_engine::core::LayerId(layer)).unwrap(); + match &l.kind { + LayerKind::Fill(f) => f.clone(), + other => panic!("not a fill: {other:?}"), + } +} + +#[test] +fn a_material_becomes_one_fill_layer_in_one_undo_step() { + let dir = folder("ok"); + png(&dir.join("tex/base.png"), [200, 40, 40]); + // A file next to the folder that a hostile document tries to reach. + png(&dir.parent().unwrap().join("escape.png"), [1, 2, 3]); + let mtlx = dir.join("brick.mtlx"); + std::fs::write(&mtlx, MATERIAL).unwrap(); + + let mut s = session(); + let before = s.doc.resources.len(); + let r = execute(&mut s, "file.importMaterialX", &json!({ "path": mtlx.display().to_string() })).unwrap(); + assert_eq!(r["material"], "Brick"); + let fill = fill_of(&s, r["layer"].as_u64().unwrap()); + // The one image used twice is one resource; the constant is uniform. + assert_eq!(r["resources"].as_array().unwrap().len(), 1, "{r}"); + let name = r["resources"][0].as_str().unwrap().to_string(); + assert!(matches!(fill.sources.get(&Channel::BaseColor), Some(Source::Image { name: n }) if *n == name)); + assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { name: n }) if *n == name)); + assert_eq!(fill.sources.get(&Channel::Metallic), Some(&Source::Uniform([1.0; 3]))); + assert!(matches!(fill.projection, texturecraft_engine::core::Projection::Uv { scale, .. } if scale == [3.0, 3.0]), "{:?}", fill.projection); + assert_eq!(s.doc.resources.len(), before + 1); + assert!(s.images.contains_key(&name), "the image is decoded for the viewport"); + + // The traversal and the missing file were skipped with a warning, not read. + let warnings = r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect::>(); + assert!(fill.sources.get(&Channel::Normal).is_none() && fill.sources.get(&Channel::Height).is_none(), "{fill:?}"); + assert!(warnings.iter().any(|w| w.contains("outside")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("missing.png")), "{warnings:?}"); + // A channel the texture set doesn't have is reported, not invented. + let has_coat = s.doc.project.texture_set(s.ts()).unwrap().channel_list().contains(&Channel::CoatWeight); + assert_eq!(fill.sources.contains_key(&Channel::CoatWeight), has_coat); + assert_eq!(warnings.iter().any(|w| w.contains("no such channel")), !has_coat, "{warnings:?}"); + assert!(!s.doc.resources.keys().any(|k| k.contains("escape")), "nothing outside the folder was imported"); + + // One undo removes the layer and its images together. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.resources.len(), before); + assert!(s.doc.project.layer(texturecraft_engine::core::LayerId(r["layer"].as_u64().unwrap())).is_err()); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_file(dir.parent().unwrap().join("escape.png")); +} + +#[test] +fn bad_documents_and_paths_are_errors_that_change_nothing() { + let dir = folder("bad"); + let mut s = session(); + let layers = |s: &Session| s.doc.project.texture_sets[0].stack.len(); + let (n, res) = (layers(&s), s.doc.resources.len()); + let run = |s: &mut Session, p: Value| execute(s, "file.importMaterialX", &p); + assert!(run(&mut s, json!({})).is_err()); + assert!(run(&mut s, json!({ "path": dir.join("nope.mtlx").display().to_string() })).is_err()); + for (i, text) in ["", "garbage", "", ""].iter().enumerate() { + let f = dir.join(format!("bad{i}.mtlx")); + std::fs::write(&f, text).unwrap(); + assert!(run(&mut s, json!({ "path": f.display().to_string() })).is_err(), "{text:?}"); + } + // Only images that can't be read: nothing to import is an error, not an empty layer. + let only_missing = MATERIAL.replace("base.png", "none.png"); + let f = dir.join("missing.mtlx"); + std::fs::write(&f, only_missing.replace("", "")).unwrap(); + assert!(run(&mut s, json!({ "path": f.display().to_string() })).is_err()); + // A material that isn't in the document. + std::fs::write(dir.join("m.mtlx"), MATERIAL).unwrap(); + assert!(run(&mut s, json!({ "path": dir.join("m.mtlx").display().to_string(), "material": "Nope" })).is_err()); + assert_eq!((layers(&s), s.doc.resources.len()), (n, res), "refused imports leave the project alone"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 3af93ab2..5bd6059e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -26,6 +26,7 @@ pub mod export; #[cfg(not(target_arch = "wasm32"))] pub mod fonts; pub mod image_res; +pub mod materialx_read; pub mod mesh_export; pub mod mesh_import; pub mod presets; diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs new file mode 100644 index 00000000..eecd2d71 --- /dev/null +++ b/crates/formats/src/materialx_read.rs @@ -0,0 +1,542 @@ +//! Reading a MaterialX (`.mtlx`) material into TextureCraft's channels, written from the ASWF +//! MaterialX specification (1.39) and the OpenPBR Surface and glTF PBR node definitions. Pure +//! Rust: no MaterialX library is linked. +//! +//! [`read_materialx`] finds a `surfacematerial`, follows its `surfaceshader` to an +//! `open_pbr_surface`, `standard_surface` or `gltf_pbr` node, and turns each input TextureCraft +//! has a channel for into a literal value or an image file: +//! +//! - a literal `value` becomes a constant (`color3` values tagged `srgb_texture` are converted +//! to linear; a colour given for a scalar channel is averaged); +//! - an input wired to a `tiledimage` or `image` node (directly or through a `nodegraph` +//! output) becomes that node's `file` (with `fileprefix` applied); `normalmap`, `convert` and +//! `constant` nodes in between are passed through; +//! - the material's `displacementshader` becomes the height channel; +//! - `uvtiling` of the first tiled image is returned as the UV tiling. +//! +//! Anything else (maths nodes, procedural patterns, other shaders) is skipped with a warning +//! rather than guessed at. Emission follows the specifications' defaults: OpenPBR emits nothing +//! unless `emission_luminance` is above 0, and `standard_surface` unless `emission` is. +//! +//! The reader takes untrusted bytes: the document size, nesting and element count are capped, a +//! wiring loop stops at a depth limit, and every failure is an error, never a panic. + +use std::collections::HashMap; + +use quick_xml::events::{BytesStart, Event}; +use texturecraft_core::Channel; +use texturecraft_texel::srgb_to_linear; + +use crate::{FormatError, Result, malformed}; + +const KIND: &str = "MaterialX document"; +/// Largest document read, in bytes. +pub const MAX_BYTES: usize = 16 << 20; +const MAX_DEPTH: usize = 64; +const MAX_ELEMENTS: usize = 200_000; +/// Longest chain of nodes followed from one shader input. +const MAX_HOPS: usize = 16; + +/// What one channel is set from. +#[derive(Clone, Debug, PartialEq)] +pub enum Value { + /// A constant: linear RGB for colours, `[v, v, v]` for scalars. + Constant([f32; 3]), + /// An image file, as written in the document (`fileprefix` applied), relative to it. + Image(String), +} + +/// A material read from a document. +#[derive(Clone, Debug, PartialEq)] +pub struct Material { + pub name: String, + /// The channels the material sets, in a fixed order. + pub channels: Vec<(Channel, Value)>, + /// The first image's `uvtiling` (1, 1 when none). + pub uv_tiling: [f32; 2], + /// What was skipped and why. + pub warnings: Vec, +} + +// --------------------------------------------------------------------------------------------- +// XML. + +#[derive(Default)] +struct El { + name: String, + attrs: Vec<(String, String)>, + children: Vec, +} + +impl El { + fn attr(&self, k: &str) -> Option<&str> { + self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) + } + + /// The child element named `name` (the `name` attribute: inputs and nodes are looked up by it). + fn input(&self, name: &str) -> Option<&El> { + self.children.iter().find(|c| c.attr("name") == Some(name)) + } +} + +fn element(e: &BytesStart) -> El { + let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); + let attrs = e + .attributes() + .with_checks(false) + .flatten() + .map(|a| { + (text(a.key.local_name().as_ref()), a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned())) + }) + .collect(); + El { name: text(e.local_name().as_ref()), attrs, children: Vec::new() } +} + +fn parse_xml(bytes: &[u8]) -> Result { + let mut reader = quick_xml::Reader::from_reader(bytes); + let mut stack = vec![El::default()]; + let mut count = 0usize; + loop { + let event = reader.read_event().map_err(|e| malformed(KIND, e))?; + if matches!(event, Event::Start(_) | Event::Empty(_)) { + count += 1; + if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH { + return Err(FormatError::TooLarge(format!( + "the MaterialX document has more than {MAX_ELEMENTS} elements or is nested deeper than {MAX_DEPTH}" + ))); + } + } + match event { + Event::Start(e) => stack.push(element(&e)), + Event::Empty(e) => { + if let Some(parent) = stack.last_mut() { + parent.children.push(element(&e)); + } + } + Event::End(_) => { + let el = stack.pop().filter(|_| !stack.is_empty()).ok_or_else(|| malformed(KIND, "unbalanced end tag"))?; + if let Some(parent) = stack.last_mut() { + parent.children.push(el); + } + } + Event::Eof => break, + _ => {} + } + } + match (stack.pop(), stack.is_empty()) { + (Some(root), true) => Ok(root), + _ => Err(malformed(KIND, "unclosed elements at the end of the document")), + } +} + +// --------------------------------------------------------------------------------------------- +// Shader input tables: (shader input, channel). `kind` says how to read the value. + +#[derive(Clone, Copy, PartialEq)] +enum Shader { + OpenPbr, + Standard, + Gltf, +} + +const OPEN_PBR: &[(&str, Channel)] = &[ + ("base_color", Channel::BaseColor), + ("base_metalness", Channel::Metallic), + ("specular_roughness", Channel::Roughness), + ("geometry_normal", Channel::Normal), + ("geometry_opacity", Channel::Opacity), + ("emission_color", Channel::Emissive), + ("coat_weight", Channel::CoatWeight), + ("coat_roughness", Channel::CoatRoughness), + ("geometry_coat_normal", Channel::CoatNormal), + ("fuzz_weight", Channel::SheenWeight), + ("fuzz_color", Channel::SheenColor), + ("fuzz_roughness", Channel::SheenRoughness), + ("specular_roughness_anisotropy", Channel::AnisotropyLevel), + ("transmission_weight", Channel::Transmission), + ("subsurface_weight", Channel::ScatterWeight), +]; + +const STANDARD: &[(&str, Channel)] = &[ + ("base_color", Channel::BaseColor), + ("metalness", Channel::Metallic), + ("specular_roughness", Channel::Roughness), + ("normal", Channel::Normal), + ("opacity", Channel::Opacity), + ("emission_color", Channel::Emissive), + ("coat", Channel::CoatWeight), + ("coat_roughness", Channel::CoatRoughness), + ("coat_normal", Channel::CoatNormal), + ("sheen", Channel::SheenWeight), + ("sheen_color", Channel::SheenColor), + ("sheen_roughness", Channel::SheenRoughness), + ("specular_anisotropy", Channel::AnisotropyLevel), + ("transmission", Channel::Transmission), + ("subsurface", Channel::ScatterWeight), +]; + +const GLTF: &[(&str, Channel)] = &[ + ("base_color", Channel::BaseColor), + ("metallic", Channel::Metallic), + ("roughness", Channel::Roughness), + ("normal", Channel::Normal), + ("alpha", Channel::Opacity), + ("emission", Channel::Emissive), + ("occlusion", Channel::AmbientOcclusion), + ("clearcoat", Channel::CoatWeight), + ("clearcoat_roughness", Channel::CoatRoughness), + ("clearcoat_normal", Channel::CoatNormal), + ("sheen_color", Channel::SheenColor), + ("sheen_roughness", Channel::SheenRoughness), + ("transmission", Channel::Transmission), +]; + +// --------------------------------------------------------------------------------------------- +// Resolving what feeds an input. + +struct Doc<'a> { + root: &'a El, + /// Every node by name: the document's own, and each nodegraph's (qualified `graph/node`). + nodes: HashMap, + /// Each nodegraph's outputs: `graph/output` to the node name inside (qualified). + outputs: HashMap, + tiling: Option<[f32; 2]>, + warnings: Vec, +} + +enum Found { + Constant(Vec), + Image(String), + None, +} + +fn numbers(text: &str) -> Option> { + let v: Option> = text.split(',').map(|p| p.trim().parse::().ok().filter(|f| f.is_finite())).collect(); + v.filter(|v| !v.is_empty() && v.len() <= 4) +} + +impl<'a> Doc<'a> { + fn new(root: &'a El) -> Doc<'a> { + let mut nodes = HashMap::new(); + let mut outputs = HashMap::new(); + for c in &root.children { + match (c.name.as_str(), c.attr("name")) { + ("nodegraph", Some(g)) => { + for n in &c.children { + let Some(name) = n.attr("name") else { continue }; + if n.name == "output" { + if let Some(from) = n.attr("nodename") { + outputs.insert(format!("{g}/{name}"), format!("{g}/{from}")); + } + } else { + nodes.insert(format!("{g}/{name}"), n); + } + } + } + (_, Some(name)) => { + nodes.insert(name.to_owned(), c); + } + _ => {} + } + } + Doc { root, nodes, outputs, tiling: None, warnings: Vec::new() } + } + + /// What `input` (an `` element of a node) resolves to; `scope` is the nodegraph the + /// node lives in, if any. + fn resolve(&mut self, input: &El, scope: Option<&str>, hops: usize) -> Found { + if hops > MAX_HOPS { + self.warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); + return Found::None; + } + if let Some(v) = input.attr("value") { + return numbers(v).map_or(Found::None, |n| Found::Constant(self.tag(input, n))); + } + let target = match (input.attr("nodegraph"), input.attr("output"), input.attr("nodename")) { + (Some(g), out, _) => { + let out = out.map(str::to_owned).or_else(|| self.outputs.keys().find_map(|k| k.strip_prefix(&format!("{g}/")).map(str::to_owned))); + out.and_then(|o| self.outputs.get(&format!("{g}/{o}")).cloned()) + } + (None, _, Some(n)) => { + Some(scope.map_or_else(|| n.to_owned(), |g| format!("{g}/{n}"))).filter(|q| self.nodes.contains_key(q)).or_else(|| Some(n.to_owned())) + } + _ => None, + }; + let Some(node) = target.as_deref().and_then(|t| self.nodes.get(t).copied()) else { return Found::None }; + let scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g.to_owned()); + let scope = scope.as_deref(); + match node.name.as_str() { + "tiledimage" | "image" => { + let Some(file) = node.input("file").and_then(|f| f.attr("value")) else { + self.warnings.push(format!("image node {:?} has no file", node.attr("name").unwrap_or(""))); + return Found::None; + }; + let prefix = + [node.input("file").and_then(|f| f.attr("fileprefix")), node.attr("fileprefix"), self.root.attr("fileprefix")].into_iter().flatten().next(); + if self.tiling.is_none() + && let Some(t) = + node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0)) + { + self.tiling = Some([t[0], t[1]]); + } + Found::Image(format!("{}{file}", prefix.unwrap_or(""))) + } + "normalmap" | "convert" => match node.input("in") { + Some(i) => self.resolve(i, scope, hops + 1), + None => Found::None, + }, + "constant" => match node.input("value") { + Some(v) => self.resolve(v, scope, hops + 1), + None => Found::None, + }, + other => { + self.warnings.push(format!("a {other} node ({:?}) is not supported; its input was skipped", node.attr("name").unwrap_or(""))); + Found::None + } + } + } + + /// Literal values tagged with an sRGB colour space are converted to linear. + fn tag(&self, input: &El, mut n: Vec) -> Vec { + let space = input.attr("colorspace").or_else(|| self.root.attr("colorspace")).unwrap_or(""); + if input.attr("colorspace").is_some() && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) && n.len() >= 3 { + n.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); + } + n + } +} + +fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { + match (channel.kind(), n) { + (_, [a]) => [*a; 3], + (texturecraft_core::ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], + (_, [r, g, b, ..]) => { + let mean = (r + g + b) / 3.0; + [mean; 3] + } + _ => Channel::default_value(channel), + } +} + +/// The literal number of `input`, if it is one. +fn literal(shader: &El, name: &str) -> Option { + shader.input(name).and_then(|i| i.attr("value")).and_then(numbers).and_then(|n| n.first().copied()) +} + +/// Read the material called `material` (default: the first) from a `.mtlx` document. +pub fn read_materialx(bytes: &[u8], material: Option<&str>) -> Result { + crate::guard(KIND, || read_inner(bytes, material)) +} + +fn read_inner(bytes: &[u8], material: Option<&str>) -> Result { + if bytes.len() > MAX_BYTES { + return Err(FormatError::TooLarge(format!("the MaterialX document is over {} MiB", MAX_BYTES >> 20))); + } + let top = parse_xml(bytes)?; + let root = top.children.iter().find(|c| c.name == "materialx").ok_or_else(|| malformed(KIND, "no element"))?; + let mut doc = Doc::new(root); + let materials: Vec<&El> = root.children.iter().filter(|c| c.name == "surfacematerial").collect(); + let mat = match material { + Some(name) => materials + .iter() + .copied() + .find(|m| m.attr("name") == Some(name)) + .ok_or_else(|| FormatError::Invalid(format!("no material named {name:?} (found: {})", names(&materials))))?, + None => materials.first().copied().ok_or_else(|| FormatError::Unsupported("the document has no surfacematerial".into()))?, + }; + let mut out = Material { name: mat.attr("name").unwrap_or("Material").to_owned(), channels: Vec::new(), uv_tiling: [1.0, 1.0], warnings: Vec::new() }; + let shader = mat + .input("surfaceshader") + .and_then(|i| i.attr("nodename")) + .and_then(|n| doc.nodes.get(n).copied()) + .ok_or_else(|| malformed(KIND, "the material has no surface shader"))?; + let (kind, table) = match shader.name.as_str() { + "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR), + "standard_surface" => (Shader::Standard, STANDARD), + "gltf_pbr" => (Shader::Gltf, GLTF), + other => return Err(FormatError::Unsupported(format!("the surface shader is a {other}; open_pbr_surface, standard_surface and gltf_pbr are read"))), + }; + // Emission is off by default in OpenPBR and standard_surface. + let emits = match kind { + Shader::OpenPbr => { + shader.input("emission_luminance").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission_luminance").is_some_and(|v| v > 0.0)) + } + Shader::Standard => shader.input("emission").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission").is_some_and(|v| v > 0.0)), + Shader::Gltf => true, + }; + let weight = match kind { + Shader::OpenPbr => literal(shader, "base_weight"), + Shader::Standard => literal(shader, "base"), + Shader::Gltf => None, + }; + if weight.is_some_and(|w| (w - 1.0).abs() > 1e-6) { + doc.warnings.push("the base weight isn't 1; it was ignored".into()); + } + for &(input, channel) in table { + let Some(el) = shader.input(input) else { continue }; + if channel == Channel::Emissive && !emits && kind != Shader::Gltf { + doc.warnings.push(format!("{input} was skipped: the shader's emission is 0")); + continue; + } + match doc.resolve(el, None, 0) { + Found::Constant(n) => out.channels.push((channel, Value::Constant(to_constant(channel, &n)))), + Found::Image(f) => out.channels.push((channel, Value::Image(f))), + Found::None => {} + } + } + // The displacement shader's `displacement` input is the height. + if let Some(d) = mat.input("displacementshader").and_then(|i| i.attr("nodename")).and_then(|n| doc.nodes.get(n).copied()) + && let Some(i) = d.input("displacement") + { + match doc.resolve(i, None, 0) { + Found::Constant(n) => out.channels.push((Channel::Height, Value::Constant(to_constant(Channel::Height, &n)))), + Found::Image(f) => out.channels.push((Channel::Height, Value::Image(f))), + Found::None => {} + } + } + out.uv_tiling = doc.tiling.unwrap_or([1.0, 1.0]); + out.warnings = doc.warnings; + Ok(out) +} + +fn names(materials: &[&El]) -> String { + let n: Vec<&str> = materials.iter().filter_map(|m| m.attr("name")).collect(); + if n.is_empty() { "none".into() } else { n.join(", ") } +} + +#[cfg(test)] +mod tests { + use super::*; + + const OPENPBR: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + +"#; + + fn get(m: &Material, c: Channel) -> Option<&Value> { + m.channels.iter().find(|(ch, _)| *ch == c).map(|(_, v)| v) + } + + #[test] + fn open_pbr_inputs_become_channels() { + let m = read_materialx(OPENPBR.as_bytes(), None).unwrap(); + assert_eq!(m.name, "Stone"); + assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("stone_base.png".into()))); + assert_eq!(get(&m, Channel::Roughness), Some(&Value::Image("stone_r.png".into()))); + assert_eq!(get(&m, Channel::Normal), Some(&Value::Image("stone_n.png".into())), "through the normalmap node"); + assert_eq!(get(&m, Channel::Height), Some(&Value::Image("stone_h.png".into())), "from the displacement shader"); + assert_eq!(get(&m, Channel::Metallic), Some(&Value::Constant([1.0; 3]))); + assert_eq!(get(&m, Channel::CoatWeight), Some(&Value::Constant([0.25; 3]))); + assert_eq!(get(&m, Channel::Emissive), Some(&Value::Constant([1.0, 0.5, 0.0]))); + assert_eq!(m.uv_tiling, [4.0, 2.0]); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + } + + #[test] + fn emission_is_off_unless_the_shader_emits() { + let x = OPENPBR.replace(r#""#, ""); + let m = read_materialx(x.as_bytes(), None).unwrap(); + assert!(get(&m, Channel::Emissive).is_none()); + assert!(m.warnings.iter().any(|w| w.contains("emission")), "{:?}", m.warnings); + let zero = OPENPBR.replace(r#"value="2" />"#, r#"value="0" />"#); + assert!(get(&read_materialx(zero.as_bytes(), None).unwrap(), Channel::Emissive).is_none()); + } + + #[test] + fn standard_surface_nodegraphs_prefixes_and_colour_spaces() { + let x = r#" + + + + + + + + + + + + + +"#; + let m = read_materialx(x.as_bytes(), Some("M2")).unwrap(); + assert_eq!(m.name, "M2"); + assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("tex/a.png".into())), "through the nodegraph, with the prefix"); + assert_eq!(get(&m, Channel::Roughness), Some(&Value::Constant([0.4; 3]))); + assert_eq!(get(&m, Channel::Opacity), Some(&Value::Constant([0.5; 3])), "a colour on a scalar channel is averaged"); + let Some(Value::Constant(c)) = get(&m, Channel::SheenColor) else { panic!("sheen colour") }; + assert!((c[0] - 0.214).abs() < 1e-3, "sRGB 0.5 is linear 0.214: {c:?}"); + assert!(m.warnings.iter().any(|w| w.contains("base weight")), "{:?}", m.warnings); + assert!(read_materialx(x.as_bytes(), Some("nope")).is_err()); + } + + #[test] + fn unsupported_nodes_and_shaders_are_reported() { + let x = OPENPBR.replace(r#""#; + assert!(matches!(read_materialx(other.as_bytes(), None), Err(FormatError::Unsupported(_)))); + } + + #[test] + fn hostile_documents_are_errors() { + for bad in ["", "not xml", "", "", "", ""] { + assert!(read_materialx(bad.as_bytes(), None).is_err(), "{bad:?}"); + } + // A wiring loop and a deep tree stop instead of running forever or overflowing. + let loop_doc = r#" + + "#; + let m = read_materialx(loop_doc.as_bytes(), None).unwrap(); + assert!(m.channels.is_empty() && m.warnings.iter().any(|w| w.contains("loops")), "{:?}", m.warnings); + let deep = format!("{}{}", "".repeat(200), "".repeat(200)); + assert!(matches!(read_materialx(deep.as_bytes(), None), Err(FormatError::TooLarge(_)))); + // Numbers: NaN, inf and over-long lists are not values. + let nan = OPENPBR.replace(r#"value="0.25""#, r#"value="NaN""#); + assert!(get(&read_materialx(nan.as_bytes(), None).unwrap(), Channel::CoatWeight).is_none()); + } + + #[test] + fn xml_entities_in_file_names_are_decoded() { + let x = OPENPBR.replace("stone_base.png", "a&b <1>.png"); + let m = read_materialx(x.as_bytes(), None).unwrap(); + assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("a&b <1>.png".into()))); + } + + #[test] + fn mutated_documents_never_panic() { + // Truncations and byte flips of a real document: errors or materials, never a panic. + let bytes = OPENPBR.as_bytes(); + for cut in (0..bytes.len()).step_by(7) { + let _ = read_materialx(&bytes[..cut], None); + } + for i in (0..bytes.len()).step_by(5) { + let mut b = bytes.to_vec(); + b[i] ^= 0x5a; + let _ = read_materialx(&b, None); + } + } +} From 2385524b005c45aa67b9c054d739839f9ffb0654 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:53:56 -0500 Subject: [PATCH 04/10] test: use contains_key in the MaterialX import test Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/tests/materialx_import.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/materialx_import.rs b/crates/engine/tests/materialx_import.rs index aa51746f..cdd77fbf 100644 --- a/crates/engine/tests/materialx_import.rs +++ b/crates/engine/tests/materialx_import.rs @@ -80,7 +80,7 @@ fn a_material_becomes_one_fill_layer_in_one_undo_step() { // The traversal and the missing file were skipped with a warning, not read. let warnings = r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect::>(); - assert!(fill.sources.get(&Channel::Normal).is_none() && fill.sources.get(&Channel::Height).is_none(), "{fill:?}"); + assert!(!fill.sources.contains_key(&Channel::Normal) && !fill.sources.contains_key(&Channel::Height), "{fill:?}"); assert!(warnings.iter().any(|w| w.contains("outside")), "{warnings:?}"); assert!(warnings.iter().any(|w| w.contains("missing.png")), "{warnings:?}"); // A channel the texture set doesn't have is reported, not invented. From f0242058f2280fd89b31d60d8259cd64e67e5843 Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Sun, 1 Nov 2026 23:06:43 +0100 Subject: [PATCH 05/10] cli: support builtin: in info command (#63) --- apps/texturecraft-cli/src/main.rs | 12 ++++++++++-- apps/texturecraft-cli/tests/cli.rs | 10 ++++++++++ crates/formats/src/lib.rs | 2 +- crates/formats/src/mesh_import/mod.rs | 5 +++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index ec1e4f2d..d53f2827 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -10,14 +10,14 @@ use serde_json::{Value, json}; use texturecraft_automation::security::{client_token, server_token}; use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc}; use texturecraft_engine::core::PROJECT_EXT; -use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes}; +use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report}; const USAGE: &str = "\ texturecraft-cli: headless TextureCraft USAGE: texturecraft-cli --version - texturecraft-cli info + texturecraft-cli info > Texture sets, layers, triangles, materials and the UV report, as JSON. texturecraft-cli commands [--filter ] List the engine commands (id, label, params). @@ -217,6 +217,14 @@ fn report_json(r: &MeshReport) -> Value { fn info(a: &Args) -> R { let file = a.pos(0, "")?; + if let Some(id) = file.strip_prefix("builtin:") { + let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| format!("unknown built-in mesh `{id}`"))?; + let report = mesh_report(&m); + return print_json(&json!({ + "file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(), + "materials": m.materials, "textureSets": m.materials, "uv": report_json(&report), + })); + } if !is_project(file) { let m = import_mesh(Path::new(file)).map_err(|e| format!("cannot read {file}: {e}"))?; return print_json(&json!({ diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 254eabb4..0c1b0ae2 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -97,6 +97,16 @@ fn info_on_a_mesh_reports_uvs() { let _ = std::fs::remove_dir_all(&d); } +#[test] +fn info_on_a_builtin_mesh() { + let info = json(&["info", "builtin:cube"]); + assert_eq!(info["kind"], "mesh"); + assert_eq!(info["file"], "builtin:cube"); + assert_eq!(info["triangles"], 1728); + assert_eq!(info["uv"]["uvsGenerated"], false); + assert_eq!(cli(&["info", "builtin:bogus"]).status.code(), Some(1)); +} + #[test] fn render_writes_a_png() { let d = tmp("render"); diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 249ff0f7..3b589832 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -33,7 +33,7 @@ pub use export::{ }; pub use image_res::{DecodedImage, decode_image}; pub use mesh_export::{GlbTextures, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, usd_bytes, usd_export_options}; -pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, self_contained_mesh}; +pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh}; #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 361d7837..3daff3c2 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -496,6 +496,11 @@ fn smooth_normals(mesh: &Mesh) -> Vec { weld.iter().map(|w| acc.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()) +} + fn report(mesh: &Mesh, uvs_generated: bool, mut warnings: Vec) -> MeshReport { let (mut out_of_range, mut zero_area) = (0, 0); for t in 0..mesh.triangle_count() { From 4917eda4a818b71483cfb9677beec203ee631eb4 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:56:46 -0500 Subject: [PATCH 06/10] feat(ui): File > Import MaterialX material... with a file picker The menu item opens a .mtlx picker and runs file.importMaterialX; the new layer's name is toasted, the reader's warnings go to the Log, and the Layers panel is focused. The menu label and the picker's filter name are translated in all ten languages; menu parity is 54 of 54. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/i18n/ar.rs | 2 ++ crates/ui-egui/src/i18n/de.rs | 2 ++ crates/ui-egui/src/i18n/es.rs | 2 ++ crates/ui-egui/src/i18n/fr.rs | 2 ++ crates/ui-egui/src/i18n/it.rs | 2 ++ crates/ui-egui/src/i18n/ja.rs | 2 ++ crates/ui-egui/src/i18n/ko.rs | 2 ++ crates/ui-egui/src/i18n/pt_br.rs | 2 ++ crates/ui-egui/src/i18n/zh_hans.rs | 2 ++ crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/windows.rs | 13 +++++++++++++ docs/parity.md | 3 ++- 12 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 495f1d59..76759b6e 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -399,6 +399,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "استورد صورة (ملف > استيراد الموارد) لإسقاطها على المجسم."), ("Import images to use them in fills and masks", "استورد الصور لاستخدامها في التعبئة والأقنعة"), ("Import resources...", "استيراد الموارد..."), + ("Import MaterialX material...", "استيراد مادة MaterialX..."), + ("MaterialX materials", "مواد MaterialX"), ("Import...", "استيراد..."), ("Imported template \"{name}\"", "تم استيراد القالب \"{name}\""), ("Imported {name}", "تم استيراد {name}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b20b228f..3da95541 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -423,6 +423,8 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Import images to use them in fills and masks", "Bilder importieren, um sie in Füllungen und Masken zu verwenden"), ("Import resources...", "Ressourcen importieren..."), + ("Import MaterialX material...", "MaterialX-Material importieren..."), + ("MaterialX materials", "MaterialX-Materialien"), ("Import...", "Importieren..."), ("Imported template \"{name}\"", "Vorlage „{name}“ importiert"), ("Imported {name}", "{name} importiert"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 829a54aa..8775e290 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -417,6 +417,8 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Import images to use them in fills and masks", "Importar imágenes para usarlas en rellenos y máscaras"), ("Import resources...", "Importar recursos..."), + ("Import MaterialX material...", "Importar material MaterialX..."), + ("MaterialX materials", "Materiales MaterialX"), ("Import...", "Importar..."), ("Imported template \"{name}\"", "Plantilla \"{name}\" importada"), ("Imported {name}", "{name} importado"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index eb9744c7..dd2c1521 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -423,6 +423,8 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Import images to use them in fills and masks", "Importez des images pour les utiliser dans les remplissages et les masques"), ("Import resources...", "Importer des ressources..."), + ("Import MaterialX material...", "Importer un matériau MaterialX..."), + ("MaterialX materials", "Matériaux MaterialX"), ("Import...", "Importer..."), ("Imported template \"{name}\"", "Modèle « {name} » importé"), ("Imported {name}", "{name} importé"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 664a3732..975a7554 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -420,6 +420,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "Importa un'immagine (File > Importa risorse) per proiettarla sulla mesh."), ("Import images to use them in fills and masks", "Importa immagini per usarle in riempimenti e maschere"), ("Import resources...", "Importa risorse..."), + ("Import MaterialX material...", "Importa materiale MaterialX..."), + ("MaterialX materials", "Materiali MaterialX"), ("Import...", "Importa..."), ("Imported template \"{name}\"", "Modello \"{name}\" importato"), ("Imported {name}", "{name} importato"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 3e79b658..ba49e580 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -408,6 +408,8 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Import images to use them in fills and masks", "画像をインポートして塗りつぶしやマスクで使用"), ("Import resources...", "リソースをインポート..."), + ("Import MaterialX material...", "MaterialX マテリアルをインポート..."), + ("MaterialX materials", "MaterialX マテリアル"), ("Import...", "インポート..."), ("Imported template \"{name}\"", "テンプレート「{name}」をインポートしました"), ("Imported {name}", "{name} をインポートしました"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 47d765cf..9f42b255 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -402,6 +402,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "메시에 투영할 이미지를 가져오세요 (파일 > 리소스 가져오기)."), ("Import images to use them in fills and masks", "채우기와 마스크에 사용할 이미지를 가져옵니다"), ("Import resources...", "리소스 가져오기..."), + ("Import MaterialX material...", "MaterialX 머티리얼 가져오기..."), + ("MaterialX materials", "MaterialX 머티리얼"), ("Import...", "가져오기..."), ("Imported template \"{name}\"", "템플릿 \"{name}\" 가져옴"), ("Imported {name}", "가져옴: {name}"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index ee434a60..9135d140 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -414,6 +414,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "Importe uma imagem (Arquivo > Importar recursos) para projetá-la na malha."), ("Import images to use them in fills and masks", "Importe imagens para usá-las em preenchimentos e máscaras"), ("Import resources...", "Importar recursos..."), + ("Import MaterialX material...", "Importar material MaterialX..."), + ("MaterialX materials", "Materiais MaterialX"), ("Import...", "Importar..."), ("Imported template \"{name}\"", "Modelo \"{name}\" importado"), ("Imported {name}", "{name} importado"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 41bd7998..82917b0a 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -360,6 +360,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "导入图像(文件 > 导入资源)以将其投影到网格上。"), ("Import images to use them in fills and masks", "导入图像以在填充和遮罩中使用"), ("Import resources...", "导入资源..."), + ("Import MaterialX material...", "导入 MaterialX 材质..."), + ("MaterialX materials", "MaterialX 材质"), ("Import...", "导入..."), ("Imported template \"{name}\"", "已导入模板“{name}”"), ("Imported {name}", "已导入 {name}"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index bad5be7a..8a5b0069 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -45,6 +45,7 @@ pub const CATALOG: &[Item] = &[ it("File", "Remove unused resources...", "file.removeUnused", None), sep("File"), it("File", "Import resources...", "resource.import", None), + it("File", "Import MaterialX material...", "file.importMaterialX", None), it("File", "Export Textures...", "ui.export", Some("Ctrl+Shift+E")), it("File", "Export Mesh...", "file.exportMesh", None), sep("File"), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index eab0046e..e9ac6353 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -963,6 +963,19 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> app.ui.dock.focus(crate::docking::Panel::Assets); true } + "file.importMaterialX" => { + if let Some(p) = rfd::FileDialog::new().add_filter(tr("MaterialX materials"), &["mtlx"]).pick_file() + && let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()})) + { + let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { + app.session.log.push(format!("MaterialX {name}: {w}")); + } + app.toast(trf("Imported {name}", &[("name", &name)]), false); + app.ui.dock.focus(crate::docking::Panel::Layers); + } + true + } "file.exportMesh" => { let name = format!("{}.obj", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name)); if let Some(p) = rfd::FileDialog::new() diff --git a/docs/parity.md b/docs/parity.md index 86866434..2fc63bf5 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**53 of 53 menu items live (100%).** +**54 of 54 menu items live (100%).** ## File @@ -17,6 +17,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Save a copy... | `file.saveCopy` | | live | | Remove unused resources... | `file.removeUnused` | | live | | Import resources... | `resource.import` | | live | +| Import MaterialX material... | `file.importMaterialX` | | live | | Export Textures... | `ui.export` | Ctrl+Shift+E | live | | Export Mesh... | `file.exportMesh` | | live | | Quit | `ui.quit` | Ctrl+Q | live | From 9d1a989efabe9b3ca88b3f10b28f36b7115b5ca3 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:26:02 +0700 Subject: [PATCH 07/10] MaterialX import: clamp uvtiling like a fill's UV scale, reuse the resource size limit uvtiling is clamped to 0.001..=1000, the range layer.fill.projection accepts. Image files are capped by resource_cmds::MAX_BYTES instead of a second copy of the number. --- crates/engine/src/materialx_cmds.rs | 4 ++-- crates/engine/src/resource_cmds.rs | 2 +- crates/formats/src/materialx_read.rs | 5 ++++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 8a212dd7..4dc1168f 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -134,8 +134,8 @@ fn import(s: &mut Session, p: &Value) -> Result { return Err(outside.into()); } let len = std::fs::metadata(&full).map_err(|e| e.to_string())?.len(); - if len > 512 << 20 { - return Err("the file is over 512 MiB".into()); + if len > crate::resource_cmds::MAX_BYTES as u64 { + return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20)); } std::fs::read(&full).map_err(|e| e.to_string()) }; diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 9bdf3949..3f1d098a 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec { } /// Largest accepted resource file. -const MAX_BYTES: usize = 512 << 20; +pub(crate) const MAX_BYTES: usize = 512 << 20; pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb }) diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs index eecd2d71..c8cd8b39 100644 --- a/crates/formats/src/materialx_read.rs +++ b/crates/formats/src/materialx_read.rs @@ -277,7 +277,8 @@ impl<'a> Doc<'a> { && let Some(t) = node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0)) { - self.tiling = Some([t[0], t[1]]); + // The range a fill's UV scale accepts (`layer.fill.projection`). + self.tiling = Some([t[0].clamp(0.001, 1000.0), t[1].clamp(0.001, 1000.0)]); } Found::Image(format!("{}{file}", prefix.unwrap_or(""))) } @@ -451,6 +452,8 @@ mod tests { assert_eq!(get(&m, Channel::Emissive), Some(&Value::Constant([1.0, 0.5, 0.0]))); assert_eq!(m.uv_tiling, [4.0, 2.0]); assert!(m.warnings.is_empty(), "{:?}", m.warnings); + let extreme = OPENPBR.replace(r#"value="4, 2""#, r#"value="1e9, 1e-9""#); + assert_eq!(read_materialx(extreme.as_bytes(), None).unwrap().uv_tiling, [1000.0, 0.001], "clamped like a fill's UV scale"); } #[test] From b7543a49bc7a76bbc5b92b21ebdc95dfb67f15a8 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:34:16 +0700 Subject: [PATCH 08/10] Auto-rebake: a cancelled or failed bake waits for the next input change After Cancel or a bake error the app re-queued the same Auto-rebake on the next frame, forever, because a set only counted as up to date after a successful bake. Session::bake_abandoned records the set being baked and the queued ones as seen; cancel_bake and the bake error paths call it. Also drops a useless into_iter() and an unreachable branch in bake.autoRebake. --- crates/engine/src/auto_rebake.rs | 18 +++++++++++----- crates/engine/tests/auto_rebake.rs | 33 +++++++++++++++++++++++++++--- crates/ui-egui/src/lib.rs | 19 ++++++++++------- 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/auto_rebake.rs b/crates/engine/src/auto_rebake.rs index 039a3878..800eb514 100644 --- a/crates/engine/src/auto_rebake.rs +++ b/crates/engine/src/auto_rebake.rs @@ -20,7 +20,7 @@ use texturecraft_bake::Progress; use texturecraft_core::BakedMap; use crate::bake_cmds::BakeTask; -use crate::commands::{CommandSpec, always, bad, boolp, strp}; +use crate::commands::{CommandSpec, always, bad, boolp}; use crate::{Result, Session, cmd}; /// Which map rebakes itself, and what each texture set was last baked from. @@ -114,15 +114,25 @@ impl Session { } /// Records a finished bake: when it made the Auto-rebake map, the set is up to date. - pub(crate) fn note_baked(&mut self, ts: usize, made: impl Iterator) { + pub(crate) fn note_baked(&mut self, ts: usize, mut made: impl Iterator) { let key = self.auto_rebake.pending.remove(&ts); if let (Some(key), Some(map)) = (key, self.auto_rebake.map) - && made.into_iter().any(|m| m == map) + && made.any(|m| m == map) { self.auto_rebake.seen.insert(ts, key); } } + /// Records bakes of `sets` that were cancelled, failed or never started: Auto-rebake leaves + /// those sets alone until their bake inputs change again, instead of retrying every frame. + pub fn bake_abandoned(&mut self, sets: impl IntoIterator) { + for ts in sets { + if let Some(key) = self.auto_rebake.pending.remove(&ts).or_else(|| self.bake_inputs_key(ts)) { + self.auto_rebake.seen.insert(ts, key); + } + } + } + /// Bakes every due set's Auto-rebake map now (blocking); returns the sets. pub fn auto_rebake_now(&mut self, cpu: bool) -> Result> { let due = self.auto_rebake_due(); @@ -152,8 +162,6 @@ fn auto_rebake(s: &mut Session, p: &Value) -> Result { if s.auto_rebake.map != Some(map) { s.auto_rebake = AutoRebake { map: Some(map), ..AutoRebake::default() }; } - } else if strp(p, "map").is_some() { - return Err(bad("bake.autoRebake", "`map` must be a map id or null")); } Ok(state(s)) } diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs index c4fe8644..9775c19c 100644 --- a/crates/engine/tests/auto_rebake.rs +++ b/crates/engine/tests/auto_rebake.rs @@ -8,7 +8,7 @@ use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; /// A plane with a high poly just above it, baked once with height and opacity. -fn baked_session() -> (Session, std::path::PathBuf) { +fn baked_session(tag: &str) -> (Session, std::path::PathBuf) { let mesh = primitives::builtin("plane").unwrap(); let mut obj = String::from("o Part_high\n"); for p in &mesh.positions { @@ -17,7 +17,7 @@ fn baked_session() -> (Session, std::path::PathBuf) { for t in mesh.indices.chunks_exact(3) { obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); } - let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{}", std::process::id())); + let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{tag}_{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("hp.obj"); std::fs::write(&path, obj).unwrap(); @@ -38,7 +38,7 @@ fn image(s: &Session, map: BakedMap) -> Arc> { #[test] fn a_changed_bake_input_rebakes_only_the_chosen_map() { - let (mut s, dir) = baked_session(); + let (mut s, dir) = baked_session("rebake"); // Off by default; nothing is due and the run command says what to do first. assert_eq!(execute(&mut s, "bake.autoRebake", &Value::Null).unwrap()["map"], Value::Null); assert!(execute(&mut s, "bake.autoRebake.run", &Value::Null).is_err()); @@ -83,6 +83,33 @@ fn a_changed_bake_input_rebakes_only_the_chosen_map() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn a_cancelled_or_failed_bake_is_not_queued_again_until_the_inputs_change() { + let (mut s, dir) = baked_session("cancel"); + execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); + assert!(due(&mut s).is_empty()); + execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2 })).unwrap(); + assert_eq!(due(&mut s), [0]); + + // What the app does: start the bake, cancel it, record the abandoned bake. + s.begin_bake(0); + let mut task = s.bake_task_for(0, Some(BakedMap::Height)).unwrap(); + task.tracer = None; + let progress = texturecraft_engine::bake::Progress::new(); + progress.cancel(); + assert!(task.run(&progress).is_err(), "a cancelled bake fails"); + s.bake_abandoned([0]); + assert!(due(&mut s).is_empty(), "not queued again on the next frame"); + + // The next change makes it due again; a bake that never started (queued behind a failed + // one) is recorded the same way. + execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap(); + assert_eq!(due(&mut s), [0]); + s.bake_abandoned([0]); + assert!(due(&mut s).is_empty()); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_set_without_the_map_baked_is_left_alone() { let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e7261b22..588986d3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -190,19 +190,19 @@ impl TextureCraftApp { let ts = *ts; job.current = None; if let Err(e) = self.session.apply_bake(ts, out) { + self.session.bake_abandoned([ts]); self.toast(e.to_string(), true); } } Ok(Err(e)) => { - job.current = None; let msg = e.to_string(); - self.bake = None; + self.cancel_bake(); self.toast(msg, true); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.bake = None; + self.cancel_bake(); self.toast(i18n::tr("The bake worker stopped"), true); return; } @@ -226,7 +226,10 @@ impl TextureCraftApp { job.current = Some((ts, progress, rx)); } } - Err(e) => self.toast(e.to_string(), true), + Err(e) => { + self.session.bake_abandoned([ts]); + self.toast(e.to_string(), true); + } } } } @@ -244,12 +247,14 @@ impl TextureCraftApp { } } + /// Stops the bake job (also after an error). The set being baked and the queued ones wait for + /// their next bake input change before Auto-rebake tries them again. pub fn cancel_bake(&mut self) { - if let Some(job) = self.bake.take() - && let Some((_, p, _)) = job.current - { + let Some(job) = self.bake.take() else { return }; + if let Some((_, p, _)) = &job.current { p.cancel.store(true, Ordering::Relaxed); } + self.session.bake_abandoned(job.current.map(|(ts, ..)| ts).into_iter().chain(job.queue)); } /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when From 60428ef1c014100021100b548b85332b5cd3511f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:39:07 +0700 Subject: [PATCH 09/10] Auto-rebake: register its commands before the bake commands Keeps the line clear of the one MaterialX import adds after the bake commands, so the two pull requests merge without a conflict. --- crates/engine/src/commands.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 3692cf6d..bca289cb 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -66,8 +66,8 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); - v.extend(crate::bake_cmds::specs()); v.extend(crate::auto_rebake::specs()); + v.extend(crate::bake_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); From 5a64fa20f9ddcd45432781f3e81de46fce78b295 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 12:36:18 +0700 Subject: [PATCH 10/10] Effect paste: keep the active target, offer it on any row A paste into a layer of another texture set set the session's target to the new effect, so a later stroke in the active set could commit to it. The target now changes only for a paste into the active set. The layer and effect row menus offered Paste effect only while a layer was already selected, though a click selects the row first; they now check the clipboard alone. --- crates/engine/src/effect_clipboard.rs | 7 +++++-- crates/engine/tests/content_effects.rs | 15 +++++++++++++++ crates/ui-egui/src/dock.rs | 6 ++++-- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index 8132c9ca..36aa5f3a 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { } /// The copied effect, if the clipboard holds one. -fn clipboard_effect(s: &Session) -> Option { +pub fn clipboard_effect(s: &Session) -> Option { s.clipboard.as_ref().and_then(|(doc, id)| doc.project.effect(*id).map(|_| *id)) } @@ -114,10 +114,13 @@ fn paste(s: &mut Session, p: &Value) -> Result { s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c))); } } + // The target belongs to the active set's selection: a paste into another set leaves it. if let Some((lts, _, _)) = s.doc.project.locate(layer) { s.selected.insert(lts, layer); + if lts == s.ts() { + s.target = StackTarget::Effect(new); + } } - s.target = StackTarget::Effect(new); Ok(new) })?; Ok(json!({ "effect": new.0 })) diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index e6c75e1e..70eb81cf 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -200,6 +200,21 @@ fn effects_copy_and_paste_between_layers_and_stacks() { assert!(execute(&mut s, "effect.paste", &Value::Null).is_err(), "the anchor is on the layer itself"); } +#[test] +fn pasting_an_effect_into_another_texture_set_keeps_the_active_target() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut s, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + execute(&mut s, "effect.copy", &Value::Null).unwrap(); + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + let other = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap(); + let before = s.target; + let pasted = id(execute(&mut s, "effect.paste", &json!({"layer": other})).unwrap(), "effect"); + assert_eq!(s.target, before, "the active set's selection keeps its target"); + assert_eq!(s.doc.project.effect(LayerId(pasted)).map(|(owner, _)| owner), Some(LayerId(other))); +} + #[test] fn histogram_counts_what_an_effect_reads() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 5d0f6186..659e5895 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -582,7 +582,8 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef } resp.context_menu(|ui| { let keymap = app.ui.keymap.clone(); - let paste = crate::menus::enabled(app, "effect.paste"); + // The row is selected before the paste runs, so a copied effect is all it needs. + let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. for (label, id, keys, enabled) in [ (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), @@ -693,7 +694,8 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ui.separator(); run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true); run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true); - let (paste_layer, paste_effect) = (crate::menus::enabled(app, "layer.paste"), crate::menus::enabled(app, "effect.paste")); + let paste_layer = crate::menus::enabled(app, "layer.paste"); + let paste_effect = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), paste_layer); run(app, ui, tr("Paste effect"), "effect.paste", json!({}), paste_effect); let paste_instance = crate::menus::enabled(app, "layer.pasteInstance");