From cda95901388f75aac14b1b4c4696be90b604d9b1 Mon Sep 17 00:00:00 2001 From: JonRC Date: Mon, 2 Nov 2026 23:55:08 -0300 Subject: [PATCH 001/190] Headless render on adapters without compute shaders, and the wgpu env vars The headless device asked for Limits::default(), which needs compute shaders, so the viewport render failed on WSL2's GL driver and other WebGL2-class adapters. It now asks for the adapter's own limits: the viewport draws with fragment passes only, and the GPU path tracer checks the device's limits itself. headless::adapter() builds the instance from wgpu's environment and honours WGPU_ADAPTER_NAME and WGPU_POWER_PREF (default high) like the desktop app. GPU baking uses it too. With no adapter at all, the render error says that path tracing needs no GPU. Fixes #190 --- apps/texturecraft-cli/src/main.rs | 2 +- apps/texturecraft-cli/tests/cli.rs | 18 +++++++++++ crates/automation/src/headless.rs | 2 +- crates/render/src/gpu_bake.rs | 4 +-- crates/render/src/headless.rs | 49 +++++++++++++++++++++++++++--- docs/control-protocol.md | 4 ++- 6 files changed, 69 insertions(+), 10 deletions(-) diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index faa29afa..d877bc41 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -33,7 +33,7 @@ USAGE: [--pitch ] [--samples ] [--bounces ] [--cpu] Render the viewport to PNG (needs a GPU or software adapter); --camera looks through a camera saved in the project (camera.add); --samples path traces it instead (Rendering - mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU. + mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU (no GPU needed). texturecraft-cli new > [--resolution ] [--sample] New project; --sample bakes and applies a smart material to every texture set. The sample's mesh maps are baked at the resolution up to 1024 px (most of the file's size), diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 686bee97..beb508f0 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -141,6 +141,24 @@ fn render_writes_a_png() { let _ = std::fs::remove_dir_all(&d); } +/// Without a GPU, the viewport render's error says what still works. A backend this platform +/// lacks stands in for a machine without a GPU: the CLI's wgpu instance reads `WGPU_BACKEND`. +#[test] +fn render_without_a_gpu_points_to_path_tracing() { + let d = tmp("no-gpu"); + let out = d.join("ball.png"); + let absent = if cfg!(target_os = "macos") { "dx12" } else { "metal" }; + let o = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) + .env("WGPU_BACKEND", absent) + .args(["render", "builtin:cube", p(&out), "--size", "64x64"]) + .output() + .unwrap(); + let err = String::from_utf8_lossy(&o.stderr); + assert_eq!(o.status.code(), Some(1), "{err}"); + assert!(err.contains("cannot render") && err.contains("path tracing (`samples`) needs no GPU"), "{err}"); + let _ = std::fs::remove_dir_all(&d); +} + #[test] fn path_traced_render_needs_no_gpu() { let d = tmp("trace"); diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 87d58648..03be6fc5 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -342,7 +342,7 @@ impl Headless { } let gpu = match self.gpu.get_or_insert_with(Gpu::new) { Ok(g) => g, - Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))), + Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}; path tracing (`samples`) needs no GPU"))), }; // Last-resort guard: wgpu panics on device errors; drop the device and report instead. let session = &mut self.session; diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index 08fc76eb..653beac8 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -61,9 +61,7 @@ fn err(e: impl std::fmt::Display) -> BakeError { impl Gpu { fn new() -> Result { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); - let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; - let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?; + let adapter = crate::headless::adapter()?; let info = adapter.get_info(); if info.device_type == wgpu::DeviceType::Cpu { return Err(format!("{} is a software renderer", info.name)); diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index f22dd1d4..90dff9c1 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -9,13 +9,39 @@ pub struct Headless { pub adapter_name: String, } +/// The adapter for work without a window (renders, path tracing, GPU baking). Like the desktop app, +/// it honours `WGPU_ADAPTER_NAME` (part of the adapter's name, any case) and `WGPU_POWER_PREF` +/// (`high`, the default, `low` or `none`); the instance reads wgpu's other variables +/// (`WGPU_BACKEND`, `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER`, ...). +pub fn adapter() -> Result { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + if let Ok(name) = std::env::var("WGPU_ADAPTER_NAME") { + let wanted = name.to_lowercase(); + let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); + if let Some(a) = adapters.into_iter().find(|a| a.get_info().name.to_lowercase().contains(&wanted)) { + return Ok(a); + } + log::warn!("no GPU adapter matches WGPU_ADAPTER_NAME `{name}`; choosing by power preference"); + } + let power_preference = wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::HighPerformance); + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference, ..Default::default() })) + .map_err(|e| format!("no GPU adapter: {e}")) +} + +/// The limits a headless device asks for: all the adapter has. The viewport draws with fragment +/// passes only, so an adapter without compute shaders (WebGL2-class, or the GL driver WSL2 offers +/// on an integrated GPU) still renders it; the GPU path tracer checks the device's limits itself. +fn required_limits(adapter: &wgpu::Limits) -> wgpu::Limits { + adapter.clone() +} + impl Headless { - /// Create a device on the default adapter. Errors when no GPU (or software) adapter exists. + /// Create a device on [`adapter`]. Errors when no GPU (or software) adapter exists. pub fn new() -> Result { - let instance = wgpu::Instance::default(); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).map_err(|e| format!("no GPU adapter: {e}"))?; + let adapter = adapter()?; let adapter_name = adapter.get_info().name; - let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).map_err(|e| format!("no GPU device: {e}"))?; + let desc = wgpu::DeviceDescriptor { label: Some("tc_headless"), required_limits: required_limits(&adapter.limits()), ..Default::default() }; + let (device, queue) = pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device on {adapter_name}: {e}"))?; let renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); Ok(Headless { device, queue, renderer, adapter_name }) } @@ -28,3 +54,18 @@ impl Headless { self.renderer.read_view(&self.device, &self.queue, frame.view_id) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// An adapter without compute shaders still gets a device for the viewport: asking for + /// `Limits::default()` failed there with "Limit 'max_compute_workgroups_per_dimension' value + /// 65535 is better than allowed 0" (WSL2's GL driver on an Intel GPU). + #[test] + fn an_adapter_without_compute_shaders_fits_the_device() { + for adapter in [wgpu::Limits::downlevel_webgl2_defaults(), wgpu::Limits::downlevel_defaults(), wgpu::Limits::default()] { + assert!(required_limits(&adapter).check_limits(&adapter), "{adapter:?}"); + } + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3d7c2206..b8dc0670 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -281,4 +281,6 @@ steps or an object with an optional input and output (paths relative to the curr ``` Errors print `texturecraft-cli : error: …` and exit 1; usage errors exit 2. The CLI is a -console program and never opens a window; `render` needs a GPU or software adapter. +console program and never opens a window; `render` needs a GPU or software adapter, unless it path +traces (`--samples`). Like the desktop app, it takes the high-performance GPU; `WGPU_ADAPTER_NAME` +(part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low` or `none`) picks another. From c7bcf4cf22cb6a9e5f0701abd3263641a13d96b8 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:21:09 -0600 Subject: [PATCH 002/190] Restore the document when a command panics mid-edit --- crates/automation/src/rpc.rs | 4 +-- crates/automation/src/server.rs | 4 +-- crates/engine/src/session.rs | 16 ++++++++++-- crates/engine/tests/session.rs | 44 +++++++++++++++++++++++++++++++++ 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index d159bc80..021bc527 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -122,8 +122,8 @@ impl Headless { } } -/// Answer one request line. A panic inside a command becomes an error reply (edits run on a -/// snapshot, so the session stays consistent). +/// Answer one request line. A panic inside a command becomes an error reply; `Session::edit` +/// restores the document on unwind, so the session stays consistent. pub fn respond(h: &Mutex, line: &str) -> Value { let req: Value = match serde_json::from_str(line) { Ok(v) => v, diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 0bd6f4df..8fb3cbe9 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -316,8 +316,8 @@ impl TexturecraftMcp { match &*self.backend { Backend::Headless(h) => { let (h, m) = (h.clone(), method.to_string()); - // A panicking command poisons the lock, but edits run on a document snapshot - // (`Session::edit`), so the session stays consistent: keep serving. + // A panicking command poisons the lock; `Session::edit` restores the document on + // unwind, so the session stays consistent: keep serving. tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p)) .await .unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`")))) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 10a90287..13f4d2e9 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -482,7 +482,8 @@ impl Session { // ----------------------------------------------------------------------------------------- // History - /// Run an undoable edit. On error the document is left untouched. + /// Run an undoable edit. On error, or if `f` panics, the document is left untouched (other + /// session state, such as the selection, is not restored). pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { self.edit_merging(label, self.merge_edits, f) } @@ -491,7 +492,18 @@ impl Session { /// same label (a drag in the viewport is one step however many updates it makes). pub fn edit_merging(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result) -> Result { let before = self.doc.clone(); - let result = f(self).and_then(|v| match self.doc.project.instance_cycle() { + // A panic inside `f` must not leave a half-edited document behind: the automation + // servers catch panics and keep serving this session. (On wasm a panic aborts, so + // there is nothing to restore.) + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))); + let result = match ran { + Ok(r) => r, + Err(panic) => { + self.doc = before; + std::panic::resume_unwind(panic); + } + }; + let result = result.and_then(|v| match self.doc.project.instance_cycle() { Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))), None => Ok(v), }); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..9c3a1fec 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -128,6 +128,50 @@ fn panic_hunt() { } } +/// A command that panics halfway through an edit leaves the document and history as they were. +#[test] +fn a_panic_inside_an_edit_restores_the_document() { + let mut s = session(); + let project = s.doc.project.clone(); + let history = s.history_labels(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = s.edit("Half done", |s| -> texturecraft_engine::Result<()> { + s.doc.project.name = "changed".into(); + panic!("boom"); + }); + })); + assert!(r.is_err(), "the panic still reaches the caller"); + assert_eq!(s.doc.project, project, "the half-made change was rolled back"); + assert_eq!(s.history_labels(), history, "no undo step was recorded"); +} + +/// A command that fails leaves the project as it was (AGENTS rule 5: commands are atomic). +#[test] +fn failed_commands_leave_the_project_unchanged() { + let hostile = [ + Value::Null, + json!({}), + json!({"layer": u64::MAX, "ts": 99, "channel": "nope", "mode": "???", "opacity": f64::MAX}), + json!({"layer": 1, "index": -5, "delta": i64::MIN, "above": "x", "points": [[f64::MAX, -1e300]], "size": -1e30}), + json!({"resolution": 0, "maps": ["x"], "rays": u64::MAX, "antialiasing": 3, "color": [1], "value": "nan"}), + json!({"effect": 0, "x": 1e30, "y": -1e30, "viewport": [0, 0], "mesh": "../../etc", "material": ""}), + ]; + let mut offenders = Vec::new(); + for spec in command_specs() { + if spec.id == "project.sample" { + continue; // slow (bakes); covered elsewhere + } + for p in &hostile { + let mut s = session(); + let before = s.doc.project.clone(); + if execute(&mut s, spec.id, p).is_err() && s.doc.project != before { + offenders.push(format!("{} {p}", spec.id)); + } + } + } + assert!(offenders.is_empty(), "failed commands changed the project:\n{}", offenders.join("\n")); +} + #[test] fn copy_paste_flatten_and_resize_keep_the_look() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); From afe8fcea29c52254c9c9cbccd73c7d54143cdd43 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:08:29 -0600 Subject: [PATCH 003/190] Restore history and tool state when painting paths panics render_paths swaps the undo/redo stacks and tool state out while it paints. It now puts them back on unwind as well as on return, so a panicking path render no longer loses the session's history. --- crates/engine/src/path_tool.rs | 75 ++++++++++++++++++++++++++-------- 1 file changed, 57 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 150a103e..69d4918f 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -390,33 +390,49 @@ impl Session { }; // Each path goes through the regular stroke and fill code with its own settings; their // own history entries are dropped (the caller records one step). + let mut out = vec![Value::Null; start]; + let result = self.while_painting_paths(eid, |s| { + let mut result = Ok(()); + for i in start..=shapes.len() { + if i == from.min(shapes.len()) && i > start { + let pixels = &s.doc.pixels; + let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect(); + s.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers }); + } + let Some(sh) = shapes.get(i) else { break }; + match s.paint_shape(sh) { + Ok(v) => out.push(v), + Err(e) => { + result = Err(e); + break; + } + } + } + result + }); + result.map(|_| out) + } + + /// Run `f` with the session switched into path-painting state (path tool on sublayer `eid`, + /// empty history), then put the tool, camera, target, quick-mask flag and the undo/redo + /// stacks back. A panic in `f` restores them too before it continues unwinding: the + /// automation servers catch panics and keep serving this session, and must not find its + /// history gone. + fn while_painting_paths(&mut self, eid: LayerId, f: impl FnOnce(&mut Session) -> T) -> T { let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo)); self.target = StackTarget::Effect(eid); self.quick_mask.editing = false; self.tool.tool = Tool::Path; self.painting_paths = true; - let mut out = vec![Value::Null; start]; - let mut result = Ok(()); - for i in start..=shapes.len() { - if i == from.min(shapes.len()) && i > start { - let pixels = &self.doc.pixels; - let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect(); - self.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers }); - } - let Some(sh) = shapes.get(i) else { break }; - match self.paint_shape(sh) { - Ok(v) => out.push(v), - Err(e) => { - result = Err(e); - break; - } - } - } + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))); self.painting_paths = false; (self.tool, self.camera, self.target, self.quick_mask.editing) = saved; (self.undo, self.redo) = history; - result.map(|_| out) + match ran { + Ok(v) => v, + Err(panic) => std::panic::resume_unwind(panic), + } } fn paint_shape(&mut self, shape: &PathShape) -> Result { @@ -556,4 +572,27 @@ mod tests { assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); } + + #[test] + fn a_panic_while_painting_paths_restores_history_and_tool_state() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + s.update(); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.2], [0.9, 0.25]], "commit": true})).unwrap(); + let eid = texturecraft_core::LayerId(r["committed"]["effect"].as_u64().unwrap()); + assert!(!s.history_labels().is_empty()); + let labels = s.history_labels(); + let (target, tool) = (s.target, s.tool.tool); + + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + s.while_painting_paths(eid, |s| { + s.edit("nested", |_| Ok(())).unwrap(); + panic!("paint failed"); + }) + })); + assert!(panicked.is_err()); + assert_eq!(s.history_labels(), labels); + assert_eq!((s.target, s.tool.tool), (target, tool)); + assert!(!s.painting_paths); + } } From 1e0a17a09bec324c5d3f66518eb0f91e199968b2 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:48:03 -0500 Subject: [PATCH 004/190] fix(formats): files a mesh references must stay inside its folder after links are followed below() only checks the text of a referenced path, so a symbolic link or junction inside the mesh's folder could lead a glTF/FBX/USD reference to any file the user can read, which was then embedded in the project. read_mesh_file now canonicalizes the folder and the file and refuses anything outside. Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/mesh_import/external.rs | 46 +++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs index 25fa8bbd..bbe79671 100644 --- a/crates/formats/src/mesh_import/external.rs +++ b/crates/formats/src/mesh_import/external.rs @@ -57,7 +57,20 @@ pub fn self_contained_mesh(name: &str, bytes: Vec, read: &mut dyn FnMut(&str pub fn read_mesh_file(path: &std::path::Path) -> Result { let bytes = crate::read_capped(path, MAX_MESH_FILE_BYTES)?; let dir = path.parent().unwrap_or_else(|| std::path::Path::new("")); - self_contained_mesh(&path.to_string_lossy(), bytes, &mut |rel| crate::read_capped(&dir.join(rel), MAX_MESH_FILE_BYTES).ok()) + self_contained_mesh(&path.to_string_lossy(), bytes, &mut |rel| read_inside(dir, rel)) +} + +/// `rel` (already checked by [`below`]) read from below `dir`, or None when it is missing, too big, +/// or, once symbolic links and junctions are followed, is not inside `dir`: `below` only looks at +/// the text of the path, so a link in the folder could otherwise lead to any file. +#[cfg(not(target_arch = "wasm32"))] +fn read_inside(dir: &std::path::Path, rel: &str) -> Option> { + let root = std::fs::canonicalize(if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir }).ok()?; + let file = std::fs::canonicalize(dir.join(rel)).ok()?; + if !file.starts_with(&root) { + return None; + } + crate::read_capped(&file, MAX_MESH_FILE_BYTES).ok() } /// `asset` as a path below the mesh's folder (`/`-separated, `.` and `..` resolved), or None when @@ -126,6 +139,37 @@ fn image_mime(path: &str) -> &'static str { mod tests { use super::*; + /// A link `link` inside `dir` leading to `target` (a folder): a symbolic link on Unix, a junction + /// on Windows. False when the system refuses to make one. + #[cfg(not(target_arch = "wasm32"))] + fn link_dir(link: &std::path::Path, target: &std::path::Path) -> bool { + #[cfg(unix)] + return std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + return std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success()); + #[cfg(not(any(unix, windows)))] + return false; + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_link_in_the_mesh_folder_cannot_lead_outside_it() { + let base = std::env::temp_dir().join(format!("tc-mesh-link-{}", std::process::id())); + let (dir, outside) = (base.join("model"), base.join("secret")); + std::fs::create_dir_all(dir.join("tex")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("key.txt"), b"private").unwrap(); + std::fs::write(dir.join("tex/a.png"), b"inside").unwrap(); + assert_eq!(read_inside(&dir, "tex/a.png").as_deref(), Some(&b"inside"[..]), "ordinary files below the folder are read"); + assert_eq!(read_inside(&dir, "tex/missing.png"), None); + if link_dir(&dir.join("out"), &outside) { + assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder"); + } else { + eprintln!("skipped the link case: this system would not make a link"); + } + let _ = std::fs::remove_dir_all(&base); + } + #[test] fn below_keeps_paths_inside_the_folder() { assert_eq!(below("tex/a.png").as_deref(), Some("tex/a.png")); From 45c3d5decd63ebde976b714d7f11c706afae1d44 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:59:04 -0500 Subject: [PATCH 005/190] test(#255): links that stay inside the folder, file links and a linked mesh folder Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/mesh_import/external.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs index bbe79671..6629a8f0 100644 --- a/crates/formats/src/mesh_import/external.rs +++ b/crates/formats/src/mesh_import/external.rs @@ -167,6 +167,20 @@ mod tests { } else { eprintln!("skipped the link case: this system would not make a link"); } + // A link that stays inside the folder is an ordinary shortcut and still works. + if link_dir(&dir.join("shortcut"), &dir.join("tex")) { + assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside"); + } + // A link to a single outside file (Unix symbolic links; Windows file links need privileges). + #[cfg(unix)] + { + std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap(); + assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file"); + } + // The mesh's own folder reached through a link is fine: both sides are resolved. + if link_dir(&base.join("alias"), &dir) { + assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link"); + } let _ = std::fs::remove_dir_all(&base); } From 24210c4678a2e658ab6861d59ba44fa58d5b8b79 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:31:33 -0500 Subject: [PATCH 006/190] docs(#255): doc comments for the touched functions and the new tests Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/mesh_import/external.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs index 6629a8f0..0897d666 100644 --- a/crates/formats/src/mesh_import/external.rs +++ b/crates/formats/src/mesh_import/external.rs @@ -151,6 +151,8 @@ mod tests { return false; } + /// Files are read through ordinary paths and links that stay inside the folder, but not through a link + /// (folder or file) that leads outside it. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_link_in_the_mesh_folder_cannot_lead_outside_it() { From c1540bcce4fa5dbab9ad21ca26d10ac6ce87363b Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:19:07 -0600 Subject: [PATCH 007/190] Compare the whole document in the atomicity tests Both tests compared only the project, so a command that changed pixels or resources before failing or panicking would still pass. They now compare every document field, and the failed-command test also checks that no undo step was recorded. --- crates/engine/tests/session.rs | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 9c3a1fec..7fa4402d 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1,7 +1,8 @@ use serde_json::{Value, json}; +use texturecraft_engine::compose::PixelStore; use texturecraft_engine::core::Channel; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, command_specs, execute}; +use texturecraft_engine::{Document, Session, command_specs, execute}; fn session() -> Session { let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); @@ -12,6 +13,13 @@ fn session() -> Session { s } +/// Whether two documents hold the same content (`Document` has no `PartialEq`). Destructured so +/// a new field must be compared here too. +fn same_document(a: &Document, b: &Document) -> bool { + let Document { project, pixels: PixelStore { layers, masks }, baked, resources } = a; + *project == b.project && *layers == b.pixels.layers && *masks == b.pixels.masks && *baked == b.baked && *resources == b.resources +} + #[test] fn scripted_stroke_paints_and_undo_restores() { let mut s = session(); @@ -132,22 +140,25 @@ fn panic_hunt() { #[test] fn a_panic_inside_an_edit_restores_the_document() { let mut s = session(); - let project = s.doc.project.clone(); + let before = s.doc.clone(); let history = s.history_labels(); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let _ = s.edit("Half done", |s| -> texturecraft_engine::Result<()> { s.doc.project.name = "changed".into(); + s.doc.pixels.mask_mut(texturecraft_engine::core::LayerId(u64::MAX), (64, 64)); + s.doc.resources.insert("half.png".into(), std::sync::Arc::new(vec![1, 2, 3])); panic!("boom"); }); })); assert!(r.is_err(), "the panic still reaches the caller"); - assert_eq!(s.doc.project, project, "the half-made change was rolled back"); + assert!(same_document(&s.doc, &before), "the half-made change was rolled back"); assert_eq!(s.history_labels(), history, "no undo step was recorded"); } -/// A command that fails leaves the project as it was (AGENTS rule 5: commands are atomic). +/// A command that fails leaves the document and history as they were (AGENTS rule 5: commands +/// are atomic). #[test] -fn failed_commands_leave_the_project_unchanged() { +fn failed_commands_leave_the_document_unchanged() { let hostile = [ Value::Null, json!({}), @@ -163,13 +174,13 @@ fn failed_commands_leave_the_project_unchanged() { } for p in &hostile { let mut s = session(); - let before = s.doc.project.clone(); - if execute(&mut s, spec.id, p).is_err() && s.doc.project != before { + let (before, history) = (s.doc.clone(), s.history_labels()); + if execute(&mut s, spec.id, p).is_err() && (!same_document(&s.doc, &before) || s.history_labels() != history) { offenders.push(format!("{} {p}", spec.id)); } } } - assert!(offenders.is_empty(), "failed commands changed the project:\n{}", offenders.join("\n")); + assert!(offenders.is_empty(), "failed commands changed the document:\n{}", offenders.join("\n")); } #[test] From 04c3a23c60df84932466a5dc5f25f2c4059b3289 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:19:07 -0600 Subject: [PATCH 008/190] Say what a panicking command leaves behind Session::edit rolls the document back, but scripted strokes commit outside it, and the selection, tool and other session state are not restored. The server comments claimed the session stays consistent. --- crates/automation/src/rpc.rs | 5 +++-- crates/automation/src/server.rs | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 021bc527..a5afe38f 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -122,8 +122,9 @@ impl Headless { } } -/// Answer one request line. A panic inside a command becomes an error reply; `Session::edit` -/// restores the document on unwind, so the session stays consistent. +/// Answer one request line. A panic inside a command becomes an error reply. `Session::edit` +/// rolls the document back on unwind, but work outside it (scripted strokes) and other session +/// state, such as the selection or tool, is not rolled back. pub fn respond(h: &Mutex, line: &str) -> Value { let req: Value = match serde_json::from_str(line) { Ok(v) => v, diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 8fb3cbe9..d037114a 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -316,8 +316,9 @@ impl TexturecraftMcp { match &*self.backend { Backend::Headless(h) => { let (h, m) = (h.clone(), method.to_string()); - // A panicking command poisons the lock; `Session::edit` restores the document on - // unwind, so the session stays consistent: keep serving. + // A panicking command poisons the lock: keep serving. `Session::edit` rolls the + // document back on unwind, but work outside it (scripted strokes) and other + // session state, such as the selection or tool, is not rolled back. tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p)) .await .unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`")))) From 3a18128ec4178111ee4a72d2a95150e0668b94f1 Mon Sep 17 00:00:00 2001 From: JonRC Date: Mon, 9 Nov 2026 09:57:00 -0300 Subject: [PATCH 009/190] Headless: rank the adapters a name matches, keep the environment map out of render targets From review on #192: - WGPU_ADAPTER_NAME took the first adapter whose name matched. Several can match (one GPU on two backends, two GPUs of a vendor, an empty name), so rank them as the desktop selector does: hardware first, then WGPU_POWER_PREF, then native backends before OpenGL. - The limits test only checked a clone. It now asks wgpu's noop backend, reporting WebGL2 limits, for the device Headless::new requests. - The environment map was created as a render target, which needs float color buffers that GLES and WebGL2 may lack. It is only uploaded and sampled. - The no-GPU CLI test clears inherited WGPU_ADAPTER_NAME/WGPU_POWER_PREF and checks that --samples renders under the same backend. --- apps/texturecraft-cli/tests/cli.rs | 26 +++++--- crates/render/Cargo.toml | 4 ++ crates/render/src/headless.rs | 103 +++++++++++++++++++++++------ crates/render/src/renderer.rs | 41 ++++++++++-- docs/control-protocol.md | 1 + 5 files changed, 140 insertions(+), 35 deletions(-) diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index beb508f0..52ab15a6 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -141,21 +141,31 @@ fn render_writes_a_png() { let _ = std::fs::remove_dir_all(&d); } -/// Without a GPU, the viewport render's error says what still works. A backend this platform -/// lacks stands in for a machine without a GPU: the CLI's wgpu instance reads `WGPU_BACKEND`. +/// Without a GPU, the viewport render's error says what still works, and that does work. A backend +/// this platform lacks stands in for a machine without a GPU: the CLI's wgpu instance reads +/// `WGPU_BACKEND`. #[test] fn render_without_a_gpu_points_to_path_tracing() { let d = tmp("no-gpu"); - let out = d.join("ball.png"); + let out = d.join("cube.png"); let absent = if cfg!(target_os = "macos") { "dx12" } else { "metal" }; - let o = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) - .env("WGPU_BACKEND", absent) - .args(["render", "builtin:cube", p(&out), "--size", "64x64"]) - .output() - .unwrap(); + let render = |extra: &[&str]| { + Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) + .env("WGPU_BACKEND", absent) + .env_remove("WGPU_ADAPTER_NAME") + .env_remove("WGPU_POWER_PREF") + .args(["render", "builtin:cube", p(&out), "--size", "64x64"]) + .args(extra) + .output() + .unwrap() + }; + let o = render(&[]); let err = String::from_utf8_lossy(&o.stderr); assert_eq!(o.status.code(), Some(1), "{err}"); assert!(err.contains("cannot render") && err.contains("path tracing (`samples`) needs no GPU"), "{err}"); + let o = render(&["--samples", "2"]); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + assert_eq!(image::open(&out).unwrap().width(), 64); let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 080f12ba..e385d882 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -29,3 +29,7 @@ wasm-bindgen-futures = "0.4" [dev-dependencies] image = { workspace = true } + +# The noop backend stands in for an adapter without compute shaders in the headless tests. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +wgpu = { workspace = true, features = ["noop"] } diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index 90dff9c1..225b6f9b 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -15,35 +15,66 @@ pub struct Headless { /// (`WGPU_BACKEND`, `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER`, ...). pub fn adapter() -> Result { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let power = wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::HighPerformance); if let Ok(name) = std::env::var("WGPU_ADAPTER_NAME") { - let wanted = name.to_lowercase(); let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); - if let Some(a) = adapters.into_iter().find(|a| a.get_info().name.to_lowercase().contains(&wanted)) { + let infos: Vec = adapters.iter().map(wgpu::Adapter::get_info).collect(); + if let Some(a) = pick_adapter(&infos, &name, power).and_then(|i| adapters.into_iter().nth(i)) { return Ok(a); } log::warn!("no GPU adapter matches WGPU_ADAPTER_NAME `{name}`; choosing by power preference"); } - let power_preference = wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::HighPerformance); - pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference, ..Default::default() })) + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() })) .map_err(|e| format!("no GPU adapter: {e}")) } -/// The limits a headless device asks for: all the adapter has. The viewport draws with fragment -/// passes only, so an adapter without compute shaders (WebGL2-class, or the GL driver WSL2 offers -/// on an integrated GPU) still renders it; the GPU path tracer checks the device's limits itself. -fn required_limits(adapter: &wgpu::Limits) -> wgpu::Limits { - adapter.clone() +/// Which of `infos` `WGPU_ADAPTER_NAME=name` picks. Several adapters may match (the same GPU on two +/// backends, two GPUs of one vendor): rank them as the desktop app's selector does, hardware before +/// software, then `power`, then native backends before OpenGL, then the listing order. +fn pick_adapter(infos: &[wgpu::AdapterInfo], name: &str, power: wgpu::PowerPreference) -> Option { + use wgpu::{Backend, DeviceType, PowerPreference}; + let wanted = name.to_lowercase(); + infos + .iter() + .enumerate() + .filter(|(_, info)| info.name.to_lowercase().contains(&wanted)) + .min_by_key(|(index, info)| { + let lower = info.name.to_lowercase(); + let software = info.device_type == DeviceType::Cpu || ["llvmpipe", "lavapipe", "warp"].iter().any(|s| lower.contains(s)); + let power_rank = match (power, info.device_type) { + (PowerPreference::None, DeviceType::Cpu) => 1, + (PowerPreference::None, _) => 0, + (PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 0, + (PowerPreference::LowPower, DeviceType::DiscreteGpu) | (PowerPreference::HighPerformance, DeviceType::IntegratedGpu) => 1, + (_, DeviceType::Other) => 2, + (_, DeviceType::VirtualGpu) => 3, + (_, DeviceType::Cpu) => 4, + }; + let backend_rank = match (power, info.backend) { + (PowerPreference::None, _) | (_, Backend::Vulkan | Backend::Metal | Backend::Dx12) => 0, + (_, Backend::Gl) => 1, + _ => 2, + }; + (software, power_rank, backend_rank, *index) + }) + .map(|(index, _)| index) +} + +/// A device on `adapter` with all its limits. The viewport draws with fragment passes only, so an +/// adapter without compute shaders (WebGL2-class, or the GL driver WSL2 offers on an integrated GPU) +/// still renders it; the GPU path tracer checks the device's limits itself. +fn device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue), String> { + let desc = wgpu::DeviceDescriptor { label: Some("tc_headless"), required_limits: adapter.limits(), ..Default::default() }; + pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device on {}: {e}", adapter.get_info().name)) } impl Headless { /// Create a device on [`adapter`]. Errors when no GPU (or software) adapter exists. pub fn new() -> Result { let adapter = adapter()?; - let adapter_name = adapter.get_info().name; - let desc = wgpu::DeviceDescriptor { label: Some("tc_headless"), required_limits: required_limits(&adapter.limits()), ..Default::default() }; - let (device, queue) = pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device on {adapter_name}: {e}"))?; + let (device, queue) = device(&adapter)?; let renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); - Ok(Headless { device, queue, renderer, adapter_name }) + Ok(Headless { device, queue, renderer, adapter_name: adapter.get_info().name }) } /// Render a frame and read it back as RGBA8 (sRGB-encoded). @@ -59,13 +90,45 @@ impl Headless { mod tests { use super::*; - /// An adapter without compute shaders still gets a device for the viewport: asking for - /// `Limits::default()` failed there with "Limit 'max_compute_workgroups_per_dimension' value - /// 65535 is better than allowed 0" (WSL2's GL driver on an Intel GPU). + /// An adapter without compute shaders still gets a device for the viewport. wgpu's noop backend + /// stands in for one (WSL2's GL driver on an Intel GPU, a WebGL2-class GPU): asking it for + /// `Limits::default()` failed with "Limit 'max_compute_workgroups_per_dimension' value 65535 is + /// better than allowed 0". #[test] - fn an_adapter_without_compute_shaders_fits_the_device() { - for adapter in [wgpu::Limits::downlevel_webgl2_defaults(), wgpu::Limits::downlevel_defaults(), wgpu::Limits::default()] { - assert!(required_limits(&adapter).check_limits(&adapter), "{adapter:?}"); - } + fn an_adapter_without_compute_shaders_gets_a_device() { + let noop = wgpu::NoopBackendOptions { enable: true, limits: Some(wgpu::Limits::downlevel_webgl2_defaults()), ..Default::default() }; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::NOOP, + backend_options: wgpu::BackendOptions { noop, ..Default::default() }, + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + assert_eq!(adapter.limits().max_compute_workgroups_per_dimension, 0); + device(&adapter).unwrap(); + } + + fn info(name: &str, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> wgpu::AdapterInfo { + wgpu::AdapterInfo { name: name.into(), ..wgpu::AdapterInfo::new(device_type, backend) } + } + + /// A `WGPU_ADAPTER_NAME` that several adapters match still follows `WGPU_POWER_PREF`, and an + /// empty one matches them all. + #[test] + fn a_name_several_adapters_match_follows_the_power_preference() { + use wgpu::{Backend::*, DeviceType::*, PowerPreference as P}; + let gpus = [ + info("Intel(R) Iris(R) Xe Graphics", IntegratedGpu, Vulkan), + info("Intel(R) Arc(TM) A770", DiscreteGpu, Vulkan), + info("llvmpipe (LLVM 15)", Cpu, Gl), + ]; + assert_eq!(pick_adapter(&gpus, "intel", P::HighPerformance), Some(1)); + assert_eq!(pick_adapter(&gpus, "intel", P::LowPower), Some(0)); + assert_eq!(pick_adapter(&gpus, "INTEL", P::None), Some(0)); + assert_eq!(pick_adapter(&gpus, "", P::HighPerformance), Some(1)); + assert_eq!(pick_adapter(&gpus, "llvm", P::HighPerformance), Some(2)); + assert_eq!(pick_adapter(&gpus, "nvidia", P::HighPerformance), None); + // One GPU on two backends: the native one before OpenGL. + let twice = [info("D3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Gl), info("Microsoft Direct3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Vulkan)]; + assert_eq!(pick_adapter(&twice, "rtx 4050", P::HighPerformance), Some(1)); } } diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index ad2bc2bf..dad046ab 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -325,6 +325,20 @@ pub fn aux_size(size: (u32, u32)) -> u32 { impl Tex { fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, mips: u32) -> Tex { + // COPY_SRC: the GPU path tracer copies the display textures into its arrays. + let usage = + wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC; + Self::with_usage(device, label, w, h, format, mips, usage) + } + + /// The environment map, uploaded from the CPU and sampled, never drawn into. As a render target + /// it would need float color buffers, which GLES and WebGL2 may lack (see [`hdr_renderable`]). + fn environment(device: &wgpu::Device, w: u32, h: u32) -> Tex { + let usage = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST; + Self::with_usage(device, "tc_env", w, h, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS, usage) + } + + fn with_usage(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, mips: u32, usage: wgpu::TextureUsages) -> Tex { let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some(label), size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, @@ -332,11 +346,7 @@ impl Tex { sample_count: 1, dimension: wgpu::TextureDimension::D2, format, - // COPY_SRC: the GPU path tracer copies the display textures into its arrays. - usage: wgpu::TextureUsages::TEXTURE_BINDING - | wgpu::TextureUsages::COPY_DST - | wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::COPY_SRC, + usage, view_formats: &[], }); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); @@ -1104,7 +1114,7 @@ impl Renderer { layout: &refraction_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }], }); - let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + let env = Tex::environment(device, PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1]); let mut renderer = Renderer { target_format, @@ -1188,7 +1198,7 @@ impl Renderer { }; let levels = ibl::prefilter(&img, ENV_LEVELS); if self.env.texture.width() != img.width || self.env.texture.height() != img.height { - self.env = Tex::new(device, "tc_env", img.width, img.height, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + self.env = Tex::environment(device, img.width, img.height); } for (l, lv) in levels.iter().enumerate() { let bytes: Vec = lv.data.iter().flat_map(|c| [c[0], c[1], c[2], 1.0]).flat_map(|v| half::f16::from_f32(v).to_le_bytes()).collect(); @@ -2302,6 +2312,23 @@ mod tests { h.renderer.display_textures()[0][0].width() } + /// The environment map is only uploaded and sampled. A render target usage would ask for float + /// color buffers, which GLES and WebGL2 adapters may not have. + #[test] + fn the_environment_map_is_not_a_render_target() { + let Ok(mut h) = Headless::new() else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let usage = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST; + assert_eq!(h.renderer.env.texture.usage(), usage, "the built-in environment"); + // An imported image of another size makes a new texture. + let image = ImageRes { width: 256, height: 128, rgba: vec![[0.5, 0.5, 0.5, 1.0]; 256 * 128], srgb: false }; + h.renderer.set_environment(&h.device, &h.queue, "resource:grey", Some(&image)); + assert_eq!(h.renderer.env.texture.width(), 256); + assert_eq!(h.renderer.env.texture.usage(), usage, "an imported environment"); + } + fn prepare(h: &mut Headless) { let mut enc = h.device.create_command_encoder(&Default::default()); h.renderer.resolve_pending(&h.device); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b1382aea..77555785 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -335,3 +335,4 @@ Errors print `texturecraft-cli : error: …` and exit 1; usage errors e console program and never opens a window; `render` needs a GPU or software adapter, unless it path traces (`--samples`). Like the desktop app, it takes the high-performance GPU; `WGPU_ADAPTER_NAME` (part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low` or `none`) picks another. +`WGPU_BACKEND` narrows the list first, so a name on a backend it leaves out matches nothing. From cd1f8c5daa61a08981cddb367a740a975114a9c4 Mon Sep 17 00:00:00 2001 From: SteamSmith Date: Sat, 14 Nov 2026 11:31:03 -0500 Subject: [PATCH 010/190] fix(#255): test the link guard through read_mesh_file, fail instead of skipping, document hard-link limit Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/mesh_import/external.rs | 81 ++++++++++++++-------- 1 file changed, 53 insertions(+), 28 deletions(-) diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs index 0897d666..3bf375cf 100644 --- a/crates/formats/src/mesh_import/external.rs +++ b/crates/formats/src/mesh_import/external.rs @@ -52,7 +52,10 @@ pub fn self_contained_mesh(name: &str, bytes: Vec, read: &mut dyn FnMut(&str } /// Read mesh file `path` with the files it references from its folder (see -/// [`self_contained_mesh`]), each at most [`MAX_MESH_FILE_BYTES`]. +/// [`self_contained_mesh`]), each at most [`MAX_MESH_FILE_BYTES`]. A referenced file is used only +/// when, after symbolic links and junctions are followed, it is still inside the mesh's folder; +/// one that leads outside counts as not found (a warning, like a missing file), while links that +/// stay inside the folder work. Hard links cannot be told apart by path: see [`read_inside`]. #[cfg(not(target_arch = "wasm32"))] pub fn read_mesh_file(path: &std::path::Path) -> Result { let bytes = crate::read_capped(path, MAX_MESH_FILE_BYTES)?; @@ -63,6 +66,12 @@ pub fn read_mesh_file(path: &std::path::Path) -> Result { /// `rel` (already checked by [`below`]) read from below `dir`, or None when it is missing, too big, /// or, once symbolic links and junctions are followed, is not inside `dir`: `below` only looks at /// the text of the path, so a link in the folder could otherwise lead to any file. +/// +/// Limit: a HARD link is an ordinary directory entry, so a hard link in the folder to a file +/// outside it looks like a file inside it and is read. Telling them apart needs the link count, +/// which std offers only on Unix (and a count above one is also what legitimate files can have); +/// we don't use `unsafe`, so it is not checked. Making a hard link needs write access to the +/// folder and read access to the target. #[cfg(not(target_arch = "wasm32"))] fn read_inside(dir: &std::path::Path, rel: &str) -> Option> { let root = std::fs::canonicalize(if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir }).ok()?; @@ -152,38 +161,54 @@ mod tests { } /// Files are read through ordinary paths and links that stay inside the folder, but not through a link - /// (folder or file) that leads outside it. + /// (folder or file) that leads outside it. Fails when the system refuses to make the links (Unix + /// symbolic links and Windows junctions need no privilege), so it cannot pass without testing them. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_link_in_the_mesh_folder_cannot_lead_outside_it() { let base = std::env::temp_dir().join(format!("tc-mesh-link-{}", std::process::id())); - let (dir, outside) = (base.join("model"), base.join("secret")); - std::fs::create_dir_all(dir.join("tex")).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - std::fs::write(outside.join("key.txt"), b"private").unwrap(); - std::fs::write(dir.join("tex/a.png"), b"inside").unwrap(); - assert_eq!(read_inside(&dir, "tex/a.png").as_deref(), Some(&b"inside"[..]), "ordinary files below the folder are read"); - assert_eq!(read_inside(&dir, "tex/missing.png"), None); - if link_dir(&dir.join("out"), &outside) { - assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder"); - } else { - eprintln!("skipped the link case: this system would not make a link"); - } - // A link that stays inside the folder is an ordinary shortcut and still works. - if link_dir(&dir.join("shortcut"), &dir.join("tex")) { - assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside"); - } - // A link to a single outside file (Unix symbolic links; Windows file links need privileges). - #[cfg(unix)] - { - std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap(); - assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file"); - } - // The mesh's own folder reached through a link is fine: both sides are resolved. - if link_dir(&base.join("alias"), &dir) { - assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link"); - } let _ = std::fs::remove_dir_all(&base); + let (dir, outside) = (base.join("model"), base.join("secret")); + let result = std::panic::catch_unwind(|| { + std::fs::create_dir_all(dir.join("tex")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("key.txt"), b"private").unwrap(); + std::fs::write(dir.join("tex/a.png"), b"inside").unwrap(); + assert_eq!(read_inside(&dir, "tex/a.png").as_deref(), Some(&b"inside"[..]), "ordinary files below the folder are read"); + assert_eq!(read_inside(&dir, "tex/missing.png"), None); + assert!(link_dir(&dir.join("out"), &outside), "this system would not make a link"); + assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder"); + // A link that stays inside the folder is an ordinary shortcut and still works. + assert!(link_dir(&dir.join("shortcut"), &dir.join("tex")), "this system would not make a link"); + assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside"); + // A link to a single outside file (Unix symbolic links; Windows file links need privileges). + #[cfg(unix)] + { + std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap(); + assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file"); + } + // The mesh's own folder reached through a link is fine: both sides are resolved. + assert!(link_dir(&base.join("alias"), &dir), "this system would not make a link"); + assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link"); + + // The same through read_mesh_file: the outside bytes must not end up in the glTF. + std::fs::write( + dir.join("m.gltf"), + br#"{"asset": {"version": "2.0"}, "buffers": [{"uri": "out/key.txt", "byteLength": 7}, {"uri": "tex/a.png", "byteLength": 6}]}"#, + ) + .unwrap(); + let mesh = read_mesh_file(&dir.join("m.gltf")).unwrap(); + let text = String::from_utf8(mesh.bytes).unwrap(); + let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b); + assert!(!text.contains(&b64(b"private")), "outside bytes were inlined"); + assert!(text.contains(&b64(b"inside")), "the inside file is inlined"); + assert_eq!(mesh.warnings.len(), 1, "{:?}", mesh.warnings); + assert!(mesh.warnings[0].contains("out/key.txt"), "{:?}", mesh.warnings); + }); + let _ = std::fs::remove_dir_all(&base); + if let Err(e) = result { + std::panic::resume_unwind(e); + } } #[test] From 924bd44ca9065f6f9a2121824d7223f31e0e9f79 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:25:53 +0000 Subject: [PATCH 011/190] Find MaterialCraft in the sibling launcher install folder Fixes #201 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/link_cmds.rs | 8 ++++++-- crates/engine/tests/materialcraft_sibling.rs | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 crates/engine/tests/materialcraft_sibling.rs diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 1fcf5b34..db52a8b6 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -217,7 +217,8 @@ fn save_source(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser".into())) } -/// A MaterialCraft executable: `$`, else next to this program, else `name` on `PATH`. +/// A MaterialCraft executable: `$`, else next to this program, else in the sibling +/// `MaterialCraft` folder (the launcher's layout), else `name` on `PATH`. #[cfg(not(target_arch = "wasm32"))] pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf { if let Some(p) = std::env::var_os(env).filter(|p| !p.is_empty()) { @@ -225,7 +226,10 @@ pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf { } let exe = format!("{name}{}", std::env::consts::EXE_SUFFIX); - std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join(&exe))).filter(|p| p.is_file()).unwrap_or_else(|| exe.into()) + let dir = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf)); + let beside = dir.as_ref().map(|d| d.join(&exe)); + let sibling = dir.as_ref().and_then(|d| Some(d.parent()?.join("MaterialCraft").join(&exe))); + beside.into_iter().chain(sibling).find(|p| p.is_file()).unwrap_or_else(|| exe.into()) } /// A command for a MaterialCraft executable that opens no console window. diff --git a/crates/engine/tests/materialcraft_sibling.rs b/crates/engine/tests/materialcraft_sibling.rs new file mode 100644 index 00000000..7a69f713 --- /dev/null +++ b/crates/engine/tests/materialcraft_sibling.rs @@ -0,0 +1,17 @@ +//! A launcher install puts each app in its own folder: `/TextureCraft` and `/MaterialCraft`. + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn finds_materialcraft_in_sibling_app_folder() { + let exe = std::env::current_exe().unwrap(); + let root = exe.parent().unwrap().parent().unwrap(); + let dir = root.join("MaterialCraft"); + let name = "mc-sibling-probe"; + let file = format!("{name}{}", std::env::consts::EXE_SUFFIX); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(&file), b"").unwrap(); + let found = texturecraft_engine::link_cmds::materialcraft_tool(name, "TEXTURECRAFT_TEST_UNSET_ENV"); + std::fs::remove_file(dir.join(&file)).unwrap(); + let _ = std::fs::remove_dir(&dir); + assert_eq!(found, dir.join(&file)); +} From c25c984395ad379a51bef33871bbd77b6e97f197 Mon Sep 17 00:00:00 2001 From: Kirill M <176898419+JaffarSk24@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:13:17 +0100 Subject: [PATCH 012/190] i18n: offer Russian MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LANGUAGES gains ru (Русский); ru-RU, ru-SK and ru_RU.UTF-8 resolve to it. Its texturecraft.tsv catalog comes from craft-i18n; Cyrillic is drawn by egui's built-in fonts. Docs list eleven languages. --- ROADMAP.md | 5 +++-- crates/ui-egui/src/fonts.rs | 6 ++++-- crates/ui-egui/src/i18n.rs | 5 +++-- docs/features.md | 4 ++-- docs/localization-parity.md | 1 + 5 files changed, 13 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 759dfde7..4ff0ad33 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,7 +95,7 @@ incomplete validation; they are not measured success rates or speed comparisons. | UI/UX fidelity | ~65% | 20 | TBD | Current editing/bake/export UI checked; [gaps](docs/ui-parity.md), ArtCraft UI adoption and revalidation after refactoring remain | | File formats / interchange | ~60% | 10 | TBD | Current native save and basic exports exercised; possible `.tcraft`/output-package reworks, unfinished upstream `.mcmat`, `.spp` and consumer validation remain | | Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete | -| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement | +| Localization | ~35% | 4 | TBD | Eleven picker languages in source; optional shared catalogs/fonts and native-language review need current measurement | | Performance | ~40% | 10 | TBD | Dirty-tile/budgeted architecture and benchmark code exist; no matched performance budgets or large-project results from this review | | Stability | ~55% | 10 | TBD | Small save/reopen and undo/redo passed; recovery, large projects and long sessions need coverage, including after format/library migrations | | Platforms | ~65% | 3 | TBD | Desktop/web build and packaging paths exist; this review ran Windows only | @@ -158,7 +158,7 @@ exist; older reports must not turn them into fresh missing-feature claims. ## Languages -The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at +The [picker](crates/ui-egui/src/i18n.rs) contains eleven languages. Shared catalogs are optional at build time; missing entries fall back to English, and builds without catalogs offer English only. The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%” rows are not a current measurement. This audit ran an English build without external catalogs. @@ -170,6 +170,7 @@ rows are not a current measurement. This audit ran an English build without exte | Spanish | `es` | Not remeasured | Catalog dependent; native review pending | | Hindi | `hi` | No picker entry | Not offered | | Arabic | `ar` | Not remeasured | Catalog/font dependent; shaping/layout needs current review | +| Russian | `ru` | Catalog dependent | Added with the craft-i18n `ru/texturecraft.tsv` catalog; reviewed by a native speaker | | French | `fr` | Not remeasured | Catalog dependent; native review pending | | Portuguese (Brazil) | `pt-BR` | Not remeasured | Catalog dependent; native review pending | | Indonesian | `id` | No picker entry | Not offered | diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index b31b423a..6f11efec 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -278,9 +278,11 @@ mod tests { assert_eq!(Script::of_language("ko"), Some(Script::Korean)); assert_eq!(Script::of_language("ar"), Some(Script::Arabic)); assert_eq!(Script::of_language("de"), None); + assert_eq!(Script::of_language("ru"), None); for l in &crate::i18n::LANGUAGES { - // Past the Latin blocks and their diacritics. - let other_script = l.name.chars().any(|c| c > '\u{036F}'); + // Past the Latin blocks and their diacritics. Cyrillic needs no fallback: the UI fonts + // themselves carry it (egui's Ubuntu and craft-fonts' Inter). + let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c)); assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code); } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index bbbea0ec..fe1cca17 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -37,7 +37,7 @@ pub struct Language { pub english: &'static str, } -const COUNT: usize = 10; +const COUNT: usize = 11; pub static LANGUAGES: [Language; COUNT] = [ Language { code: "en", name: "English", english: "English" }, @@ -46,6 +46,7 @@ pub static LANGUAGES: [Language; COUNT] = [ Language { code: "es", name: "Español", english: "Spanish" }, Language { code: "pt-BR", name: "Português (Brasil)", english: "Portuguese (Brazil)" }, Language { code: "it", name: "Italiano", english: "Italian" }, + Language { code: "ru", name: "Русский", english: "Russian" }, Language { code: "ja", name: "日本語", english: "Japanese" }, Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" }, Language { code: "ko", name: "한국어", english: "Korean" }, @@ -386,7 +387,7 @@ mod tests", assert_eq!(trf("{a} of {b} {c}", &[("a", &1), ("b", &2)]), "1 of 2 {c}"); assert_eq!(trf("{unclosed", &[]), "{unclosed"); for (locale, code) in - [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("nl-NL", "en"), ("", "en")] + [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("ru-SK", "ru"), ("ru_RU.UTF-8", "ru"), ("nl-NL", "en"), ("", "en")] { assert_eq!(language_for_locale(locale), code, "{locale}"); } diff --git a/docs/features.md b/docs/features.md index 79bae167..1a66c200 100644 --- a/docs/features.md +++ b/docs/features.md @@ -260,8 +260,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel to a text file with each entry's recorded UTC time, severity and source. The desktop app asks for a destination, and the browser downloads the file. - A **History** panel: click any step to go back to it, or forward again to an undone one. -- **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, - Korean and Arabic, switchable live. +- **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese, + Chinese, Korean and Arabic, switchable live. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch navigation and project open, save and download. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index fb6a8a49..3625d0cd 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -29,6 +29,7 @@ generator, filter and brush alpha names (**KEYS** strings, counted by the | Arabic | `ar` | KEYS (100%) | yes | Arabic glyphs: craft-fonts (Noto Sans Arabic) or system fonts on desktop; egui shapes the text and orders it right to left (panels keep the left-to-right layout) | yes | full | 0 h | | French | `fr` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | | Portuguese (Brazil) | `pt-BR` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | +| Russian | `ru` | KEYS (~99%) | yes | Cyrillic: egui's built-in fonts | yes | full with the craft-i18n `ru/texturecraft.tsv` catalog | 0 h | | Indonesian | `id` | 0 | no | Latin | no | none | 3 h | | Japanese | `ja` | KEYS (100%) | yes | CJK glyphs: craft-fonts (BIZ UDPGothic) or system fonts on desktop | no | full | 2 h (review) | | German | `de` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | From ab13dc9870bdd5251497031c37a98a72937b8926 Mon Sep 17 00:00:00 2001 From: Kirill M <176898419+JaffarSk24@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:09:28 +0100 Subject: [PATCH 013/190] i18n: format the locale test; features.md says a build without catalogs offers English only --- crates/ui-egui/src/i18n.rs | 15 ++++++++++++--- docs/features.md | 3 ++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index fe1cca17..a0697be5 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -386,9 +386,18 @@ mod tests", assert_eq!(trf("Saved {path}", &[("path", &"a.tcraft")]), "Saved a.tcraft"); assert_eq!(trf("{a} of {b} {c}", &[("a", &1), ("b", &2)]), "1 of 2 {c}"); assert_eq!(trf("{unclosed", &[]), "{unclosed"); - for (locale, code) in - [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("ru-SK", "ru"), ("ru_RU.UTF-8", "ru"), ("nl-NL", "en"), ("", "en")] - { + for (locale, code) in [ + ("de-AT", "de"), + ("pt_PT.UTF-8", "pt-BR"), + ("zh-Hant-TW", "zh-Hans"), + ("ja", "ja"), + ("ko_KR", "ko"), + ("ar-EG", "ar"), + ("ru-SK", "ru"), + ("ru_RU.UTF-8", "ru"), + ("nl-NL", "en"), + ("", "en"), + ] { assert_eq!(language_for_locale(locale), code, "{locale}"); } set_language("de"); diff --git a/docs/features.md b/docs/features.md index 1a66c200..220eadf2 100644 --- a/docs/features.md +++ b/docs/features.md @@ -261,7 +261,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA for a destination, and the browser downloads the file. - A **History** panel: click any step to go back to it, or forward again to an undone one. - **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese, - Chinese, Korean and Arabic, switchable live. + Chinese, Korean and Arabic, switchable live. A build without the shared craft-i18n catalogs + offers English only. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch navigation and project open, save and download. From 025aff43182c6b0c3fc3795a9d91739c0856c50e Mon Sep 17 00:00:00 2001 From: Kirill M <176898419+JaffarSk24@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:09:29 +0100 Subject: [PATCH 014/190] tests: pin the UI harnesses to English The app starts in the system language and these tests find controls by their English labels, so on a machine whose language TextureCraft offers they failed. Each harness built around TextureCraftApp now sets prefs.language to en right after it is built, as rail.rs and settings_window.rs already did; the toolbar-only harnesses, which never run a full frame, set the language directly. ui_state_persistence keeps the saved state it tests. --- crates/ui-egui/tests/bake_preview.rs | 2 ++ crates/ui-egui/tests/brush_cursor_2d.rs | 2 ++ crates/ui-egui/tests/it/bake_job_mesh.rs | 2 ++ crates/ui-egui/tests/it/bake_mode.rs | 4 ++++ crates/ui-egui/tests/it/bake_presets.rs | 3 +++ crates/ui-egui/tests/it/brush_drag.rs | 3 +++ crates/ui-egui/tests/it/camera_views.rs | 3 +++ crates/ui-egui/tests/it/clone_source_view.rs | 2 ++ crates/ui-egui/tests/it/close_unsaved.rs | 2 ++ crates/ui-egui/tests/it/color_selection_editor.rs | 3 +++ crates/ui-egui/tests/it/curvature_generator.rs | 2 ++ crates/ui-egui/tests/it/effect_rows.rs | 4 ++++ crates/ui-egui/tests/it/effect_sliders.rs | 3 +++ crates/ui-egui/tests/it/export_template_guards.rs | 2 ++ crates/ui-egui/tests/it/file_dialogs.rs | 2 ++ crates/ui-egui/tests/it/filter_picker.rs | 3 +++ crates/ui-egui/tests/it/frame_selection.rs | 2 ++ crates/ui-egui/tests/it/generator_panel.rs | 2 ++ crates/ui-egui/tests/it/history_panel.rs | 3 +++ crates/ui-egui/tests/it/import_resources.rs | 1 + crates/ui-egui/tests/it/inactive_set_hint.rs | 2 ++ crates/ui-egui/tests/it/layer_blending_options.rs | 2 ++ crates/ui-egui/tests/it/layer_clipboard.rs | 3 +++ crates/ui-egui/tests/it/layer_multi_select.rs | 2 ++ crates/ui-egui/tests/it/layer_rename.rs | 2 ++ crates/ui-egui/tests/it/layers_panel.rs | 3 +++ crates/ui-egui/tests/it/levels_editor.rs | 2 ++ crates/ui-egui/tests/it/mask_export.rs | 2 ++ crates/ui-egui/tests/it/mask_value_swap.rs | 2 ++ crates/ui-egui/tests/it/named_layouts.rs | 2 ++ crates/ui-egui/tests/it/nav_buttons.rs | 2 ++ crates/ui-egui/tests/it/new_project_baked_maps.rs | 3 +++ crates/ui-egui/tests/it/path_in_view.rs | 4 ++++ crates/ui-egui/tests/it/path_list.rs | 2 ++ crates/ui-egui/tests/it/pen_pressure.rs | 2 ++ crates/ui-egui/tests/it/polygon_fill.rs | 3 +++ crates/ui-egui/tests/it/project_config.rs | 1 + crates/ui-egui/tests/it/properties_popup.rs | 2 ++ crates/ui-egui/tests/it/shelf_click.rs | 2 ++ crates/ui-egui/tests/it/shelf_drop.rs | 2 ++ crates/ui-egui/tests/it/shelf_hover_preview.rs | 2 ++ crates/ui-egui/tests/it/shelf_panel.rs | 2 ++ crates/ui-egui/tests/it/shift_lines_2d.rs | 3 +++ crates/ui-egui/tests/it/shift_lines_3d.rs | 2 ++ crates/ui-egui/tests/it/shortcut_keys.rs | 2 ++ crates/ui-egui/tests/it/skew_paint.rs | 2 ++ crates/ui-egui/tests/it/smudge_channels.rs | 2 ++ crates/ui-egui/tests/it/snapped_lines.rs | 2 ++ crates/ui-egui/tests/it/split_divider.rs | 2 ++ crates/ui-egui/tests/it/symmetry.rs | 2 ++ crates/ui-egui/tests/it/symmetry_2d.rs | 2 ++ crates/ui-egui/tests/it/tool_availability.rs | 4 ++++ crates/ui-egui/tests/it/tool_settings_saved.rs | 2 ++ crates/ui-egui/tests/it/toolbar.rs | 7 +++++++ crates/ui-egui/tests/it/user_smart_mask.rs | 2 ++ crates/ui-egui/tests/list_panels.rs | 3 +++ 56 files changed, 136 insertions(+) diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 1703abde..9e00f082 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -20,6 +20,8 @@ fn harness() -> Harness<'static, TextureCraftApp> { session.view = ViewMode::UvChecker; let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(3); harness diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 6c54d052..323b7924 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::state::{Mode, ViewLayout}; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 60f6f03e..6d166d46 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let progress = Arc::new(Progress::new()); let (tx, receiver) = std::sync::mpsc::channel(); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 787f8645..4144b903 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -13,6 +13,8 @@ fn harness(map: Option) -> Harness<'static, TextureCraftApp> { session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R64; session.doc.project.texture_sets[0].bake.maps.select(map); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); @@ -222,6 +224,7 @@ fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() { ) .unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); let before = harness.state().session.doc.project.clone(); @@ -273,6 +276,7 @@ fn bake_texture_sets_list_uv_tiles_and_their_resolutions() { texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); let before = session.doc.project.clone(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/bake_presets.rs b/crates/ui-egui/tests/it/bake_presets.rs index 5adef4ea..081ea242 100644 --- a/crates/ui-egui/tests/it/bake_presets.rs +++ b/crates/ui-egui/tests/it/bake_presets.rs @@ -18,6 +18,8 @@ fn harness() -> Harness<'static, TextureCraftApp> { } let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::MeshMapBakers); @@ -175,6 +177,7 @@ fn a_partial_bake_does_not_count_preserved_unchecked_maps() { set.bake.maps.select([BakedMap::Id]); set.bake_excluded_tiles.insert(1002); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.state_mut().start_bake(vec![0]); diff --git a/crates/ui-egui/tests/it/brush_drag.rs b/crates/ui-egui/tests/it/brush_drag.rs index ecc5393f..fe565535 100644 --- a/crates/ui-egui/tests/it/brush_drag.rs +++ b/crates/ui-egui/tests/it/brush_drag.rs @@ -23,6 +23,8 @@ fn drag(h: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let c = h.state().viewport_rect.center(); let (brush, yaw, history) = { @@ -51,6 +53,7 @@ fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { fn app(layout: texturecraft_ui_egui::state::ViewLayout) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.state_mut().ui.layout = layout; h.run_steps(4); h diff --git a/crates/ui-egui/tests/it/camera_views.rs b/crates/ui-egui/tests/it/camera_views.rs index 83e05d2c..f2c04225 100644 --- a/crates/ui-egui/tests/it/camera_views.rs +++ b/crates/ui-egui/tests/it/camera_views.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } @@ -105,6 +107,7 @@ fn alt_shift_drag_orbits_in_quarter_turns() { fn slow_glide_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/clone_source_view.rs b/crates/ui-egui/tests/it/clone_source_view.rs index 16297442..376391ef 100644 --- a/crates/ui-egui/tests/it/clone_source_view.rs +++ b/crates/ui-egui/tests/it/clone_source_view.rs @@ -16,6 +16,8 @@ const MARKER_STROKE: f32 = 1.2; fn clone_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; execute(&mut harness.state_mut().session, "tool.clone", &serde_json::Value::Null).unwrap(); harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/close_unsaved.rs b/crates/ui-egui/tests/it/close_unsaved.rs index e1b74688..978e91f5 100644 --- a/crates/ui-egui/tests/it/close_unsaved.rs +++ b/crates/ui-egui/tests/it/close_unsaved.rs @@ -11,6 +11,8 @@ fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 4278b0b3..8e596a4c 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -44,6 +44,8 @@ fn color_selection_session(with_id_map: bool) -> (texturecraft_engine::Session, fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { let (session, effect) = color_selection_session(with_id_map); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); (harness, effect) } @@ -274,6 +276,7 @@ fn color_selection_snapshots_and_quick_mask_pick() { app.ui.layout = texturecraft_ui_egui::state::ViewLayout::Only3D; app }); + harness.state_mut().ui.prefs.language = "en".into(); let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); eprintln!("Offscreen adapter: {adapter:?}"); diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs index a5b321bc..cb85de57 100644 --- a/crates/ui-egui/tests/it/curvature_generator.rs +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -19,6 +19,8 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { let builder = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)); let builder = if render { builder.wgpu() } else { builder }; let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); harness.state_mut().ui.dock.focus(Panel::Properties); diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index fdd04351..1b2447fb 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -33,6 +33,8 @@ fn dragging_an_effect_row_reorders_its_stack() { let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); let order = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); @@ -59,6 +61,7 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); assert_eq!(effect, effect_of(&harness).id.0); @@ -96,6 +99,7 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { execute(&mut session, "effect.set", &json!({"effect": effect, "blend": "Multiply"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index 3a4a2e63..858f5816 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -22,6 +22,8 @@ fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); (harness, effect) } @@ -93,6 +95,7 @@ fn content_levels_pick_the_histogram_channel() { texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); channel_picker(&harness).click(); diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 9cfc0071..67eb2c93 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -15,6 +15,8 @@ use library::Library; fn harness(library: &Library) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().session.load_export_presets(library.0.clone()); let base = texturecraft_engine::formats::builtin_presets().remove(0); diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index a8876e9e..b92d7a1d 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -14,6 +14,8 @@ fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 36abe572..536664f7 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -18,6 +18,8 @@ fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) { session.target = StackTarget::Effect(effect); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); (harness, effect) } @@ -174,6 +176,7 @@ fn filter_picker_snapshots_and_frame_timings() { eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info()); TextureCraftApp::new(cc, session) }); + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(20); let start = std::time::Instant::now(); open_picker(&mut harness); diff --git a/crates/ui-egui/tests/it/frame_selection.rs b/crates/ui-egui/tests/it/frame_selection.rs index f93c8b51..d17976b9 100644 --- a/crates/ui-egui/tests/it/frame_selection.rs +++ b/crates/ui-egui/tests/it/frame_selection.rs @@ -11,6 +11,8 @@ o Floor\nusemtl Floor\nv -100 -1 -100\nv 100 -1 -100\nv 0 -1 100\nvt 0 0\nvt 1 0 fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::from_mesh_bytes("scene.obj", SCENE_OBJ.as_bytes(), 256, "scene").unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 796051e8..6a3846bf 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -23,6 +23,8 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); let builder = if render { builder.wgpu() } else { builder }; let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); harness.state_mut().ui.dock.focus(Panel::Properties); diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index 7103161b..e1f823e0 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -11,6 +11,8 @@ use texturecraft_ui_egui::docking::Panel; /// Show document history so row clicks exercise the same command dispatch as the application fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.focus(Panel::History); harness.run_steps(4); harness @@ -168,6 +170,7 @@ fn clicking_a_history_step_returns_to_it() { } let done = session.history_labels().len(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.state_mut().ui.dock.focus(Panel::History); h.run_steps(4); let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone(); diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs index 173a3dc9..32df131d 100644 --- a/crates/ui-egui/tests/it/import_resources.rs +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -259,6 +259,7 @@ fn import_resources_snapshot() { let dir = TempDir::new("import-resources-snapshot"); let session = Session::new_project("Resources", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); invoke(&mut h); diff --git a/crates/ui-egui/tests/it/inactive_set_hint.rs b/crates/ui-egui/tests/it/inactive_set_hint.rs index c6f1f8f1..fd884628 100644 --- a/crates/ui-egui/tests/it/inactive_set_hint.rs +++ b/crates/ui-egui/tests/it/inactive_set_hint.rs @@ -13,6 +13,8 @@ const SEARCH_STEP: f32 = 8.0; fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); assert_eq!(harness.state().session.ts(), 0); assert_eq!(harness.state().session.tool.tool, Tool::Paint); diff --git a/crates/ui-egui/tests/it/layer_blending_options.rs b/crates/ui-egui/tests/it/layer_blending_options.rs index d20dc7b4..534495a1 100644 --- a/crates/ui-egui/tests/it/layer_blending_options.rs +++ b/crates/ui-egui/tests/it/layer_blending_options.rs @@ -9,6 +9,8 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/layer_clipboard.rs b/crates/ui-egui/tests/it/layer_clipboard.rs index efcf40c0..c6b0d32b 100644 --- a/crates/ui-egui/tests/it/layer_clipboard.rs +++ b/crates/ui-egui/tests/it/layer_clipboard.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let layer = h.state().session.selected_layer().unwrap(); let name = h.state().session.doc.project.layers[&layer].name.clone(); @@ -80,6 +82,7 @@ fn layer_shortcuts_act_on_a_selected_effect() { let p = serde_json::json!({"target": "content", "filter": "invert"}); let effect = id(texturecraft_engine::execute(&mut session, "effect.add.filter", &p).unwrap(), "effect"); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let effects = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.get(&layer).map(|l| l.content_effects.len()); h.event(egui::Event::Copy); diff --git a/crates/ui-egui/tests/it/layer_multi_select.rs b/crates/ui-egui/tests/it/layer_multi_select.rs index 92201b7c..08e09b12 100644 --- a/crates/ui-egui/tests/it/layer_multi_select.rs +++ b/crates/ui-egui/tests/it/layer_multi_select.rs @@ -16,6 +16,8 @@ fn harness() -> (Harness<'static, TextureCraftApp>, [LayerId; 4]) { let rows = ["Row A", "Row B", "Row C", "Row D"] .map(|name| LayerId(execute(&mut session, "layer.add.paint", &json!({ "name": name })).unwrap()["layer"].as_u64().unwrap())); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); (h, rows) } diff --git a/crates/ui-egui/tests/it/layer_rename.rs b/crates/ui-egui/tests/it/layer_rename.rs index 55b47bd9..5a5d40d2 100644 --- a/crates/ui-egui/tests/it/layer_rename.rs +++ b/crates/ui-egui/tests/it/layer_rename.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> (Harness<'static, TextureCraftApp>, u64) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let layer = h.state().session.selected_layer().unwrap().0; (h, layer) diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index ccbd9074..b57a1d65 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -23,6 +23,8 @@ fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { execute(&mut session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Effect M"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); (h, layer) } @@ -140,6 +142,7 @@ fn hidpi_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Active one"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_pixels_per_point(2.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); (h, layer) } diff --git a/crates/ui-egui/tests/it/levels_editor.rs b/crates/ui-egui/tests/it/levels_editor.rs index 3fef7357..9a08e0ad 100644 --- a/crates/ui-egui/tests/it/levels_editor.rs +++ b/crates/ui-egui/tests/it/levels_editor.rs @@ -39,6 +39,8 @@ fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraft // Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); (harness, effect) } diff --git a/crates/ui-egui/tests/it/mask_export.rs b/crates/ui-egui/tests/it/mask_export.rs index 808c4055..fce6ba7f 100644 --- a/crates/ui-egui/tests/it/mask_export.rs +++ b/crates/ui-egui/tests/it/mask_export.rs @@ -23,6 +23,8 @@ fn harness(mask: bool) -> Harness<'static, TextureCraftApp> { execute(&mut session, "effect.add.fill", &json!({"value": 0.5})).unwrap(); } let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/mask_value_swap.rs b/crates/ui-egui/tests/it/mask_value_swap.rs index d5f22ebc..54c7c088 100644 --- a/crates/ui-egui/tests/it/mask_value_swap.rs +++ b/crates/ui-egui/tests/it/mask_value_swap.rs @@ -10,6 +10,8 @@ fn harness() -> Harness<'static, TextureCraftApp> { texturecraft_engine::execute(&mut session, "mask.add.white", &serde_json::Value::Null).unwrap(); session.target = StackTarget::Mask; let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/named_layouts.rs b/crates/ui-egui/tests/it/named_layouts.rs index 18264949..d63c4017 100644 --- a/crates/ui-egui/tests/it/named_layouts.rs +++ b/crates/ui-egui/tests/it/named_layouts.rs @@ -11,6 +11,8 @@ fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_accessibility_check(false).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness } diff --git a/crates/ui-egui/tests/it/nav_buttons.rs b/crates/ui-egui/tests/it/nav_buttons.rs index 9138d0e9..edaae448 100644 --- a/crates/ui-egui/tests/it/nav_buttons.rs +++ b/crates/ui-egui/tests/it/nav_buttons.rs @@ -18,6 +18,8 @@ const WINDOW: egui::Vec2 = vec2(1280.0, 800.0); fn app(layout: ViewLayout) -> (Harness<'static, TextureCraftApp>, Rect) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(WINDOW).with_pixels_per_point(1.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint; harness.state_mut().ui.layout = ViewLayout::Only3D; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/new_project_baked_maps.rs b/crates/ui-egui/tests/it/new_project_baked_maps.rs index d171b8ef..e964a609 100644 --- a/crates/ui-egui/tests/it/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/it/new_project_baked_maps.rs @@ -20,6 +20,8 @@ fn harness_for(dir: &Path) -> Harness<'static, TextureCraftApp> { std::fs::write(&mesh, TWO_MATERIALS).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.state_mut().ui.windows.new_project = true; h.state_mut().ui.new_project.resolution = 256; h.state_mut().ui.new_project.file = Some(mesh.display().to_string()); @@ -134,6 +136,7 @@ fn new_project_baked_maps_snapshots() { eprintln!("snapshot adapter: {adapter:?}"); TextureCraftApp::new(cc, session) }); + h.state_mut().ui.prefs.language = "en".into(); let dir = TempDir::new("new-project-baked-maps-snapshots"); let mesh = dir.join("Ball.obj"); std::fs::write(&mesh, TWO_MATERIALS).unwrap(); diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs index f24e6b46..59d6eb1f 100644 --- a/crates/ui-egui/tests/it/path_in_view.rs +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -23,6 +23,8 @@ fn harness() -> AppHarness<'static> { execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); // Tall enough that the 2D view's texture square takes A, B and C let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); h @@ -157,6 +159,7 @@ fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() { let path = session.tool.path.clone(); let history = session.history_labels(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Split; harness.run_steps(4); let view_3d = harness.state().viewport_rect; @@ -214,6 +217,7 @@ fn split_harness() -> (AppHarness<'static>, Pos2, Pos2) { execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Split; harness.run_steps(4); let view_3d = harness.state().viewport_rect; diff --git a/crates/ui-egui/tests/it/path_list.rs b/crates/ui-egui/tests/it/path_list.rs index 799ba000..eadf8fd9 100644 --- a/crates/ui-egui/tests/it/path_list.rs +++ b/crates/ui-egui/tests/it/path_list.rs @@ -15,6 +15,8 @@ fn path_rows_edit_and_remove_paths() { let eid = LayerId(r["committed"]["effect"].as_u64().unwrap()); execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let editing = |h: &Harness<'_, TextureCraftApp>| h.state().session.tool.path.editing; let count = |h: &Harness<'_, TextureCraftApp>| h.state().session.paths(eid).map_or(0, <[_]>::len); diff --git a/crates/ui-egui/tests/it/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs index 36b67d2b..68ce339d 100644 --- a/crates/ui-egui/tests/it/pen_pressure.rs +++ b/crates/ui-egui/tests/it/pen_pressure.rs @@ -25,6 +25,8 @@ fn frame(harness: &mut Harness<'_, TextureCraftApp>, pen: Option<(TouchPhase, Op fn paint_2d(input: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) -> f64 { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.state_mut().session.tool.brush.min_size = 0.0; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs index ab50cb53..d24e3c0b 100644 --- a/crates/ui-egui/tests/it/polygon_fill.rs +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::TextureCraftApp; fn polygon_fill_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.tool = Tool::PolygonFill; harness.run_steps(4); harness @@ -132,6 +134,7 @@ fn polygon_fill_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); eprintln!("Offscreen adapter: {} ({:?}), driver {} {}", adapter.name, adapter.backend, adapter.driver, adapter.driver_info); harness.state_mut().session.tool.tool = Tool::PolygonFill; diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 1371e05b..b8511f20 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -815,6 +815,7 @@ fn project_config_snapshots() { let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap(); session.doc.project.mesh_path = file.display().to_string(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(6); open_window(&mut h); h.run_steps(6); diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 8d3b413f..8addb99a 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::state::{Mode, ViewLayout}; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness } diff --git a/crates/ui-egui/tests/it/shelf_click.rs b/crates/ui-egui/tests/it/shelf_click.rs index bc11cfdb..bc3708dc 100644 --- a/crates/ui-egui/tests/it/shelf_click.rs +++ b/crates/ui-egui/tests/it/shelf_click.rs @@ -13,6 +13,8 @@ const SMART_TYPE: usize = 1; fn shelf(tab: usize, label: &str) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1920.0, 1032.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.shelf_tab = tab; harness.state_mut().ui.shelf_filter = label.to_lowercase(); harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index 56e57f62..747e7883 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -20,6 +20,8 @@ const MENU_REACH: f32 = 60.0; fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); assert_eq!(harness.state().session.ts(), 0); harness diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index 237de107..215d5dd2 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -28,6 +28,8 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static .with_step_dt(step_seconds) .with_pixels_per_point(pixels_per_point) .build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.shelf_tab = MATERIALS_TAB; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index d8b7a30c..926b80d3 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -30,6 +30,8 @@ const REFERENCE_COLUMNS: usize = 4; fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/shift_lines_2d.rs b/crates/ui-egui/tests/it/shift_lines_2d.rs index 08537f4f..11192e0a 100644 --- a/crates/ui-egui/tests/it/shift_lines_2d.rs +++ b/crates/ui-egui/tests/it/shift_lines_2d.rs @@ -31,6 +31,8 @@ const BESIDE_LINE_IN_RADII: f32 = 3.0; fn uv_view_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness @@ -254,6 +256,7 @@ fn shift_line_snapshots() { eprintln!("Shift-line snapshot adapter: {:?}", adapter.get_info()); TextureCraftApp::new(context, session) }); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); click(&mut harness, FIRST_CLICK, false); diff --git a/crates/ui-egui/tests/it/shift_lines_3d.rs b/crates/ui-egui/tests/it/shift_lines_3d.rs index 2c009a9b..0f181c1a 100644 --- a/crates/ui-egui/tests/it/shift_lines_3d.rs +++ b/crates/ui-egui/tests/it/shift_lines_3d.rs @@ -23,6 +23,8 @@ const SEARCH_REACH: f32 = 300.0; fn view_3d_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only3D; harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs index 3d10749b..b3776540 100644 --- a/crates/ui-egui/tests/it/shortcut_keys.rs +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::state::ViewLayout; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index dd3b5d02..def255aa 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -15,6 +15,8 @@ fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.state_mut().ui.mode = Mode::Baking; h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); diff --git a/crates/ui-egui/tests/it/smudge_channels.rs b/crates/ui-egui/tests/it/smudge_channels.rs index 63826cd1..badd1c8c 100644 --- a/crates/ui-egui/tests/it/smudge_channels.rs +++ b/crates/ui-egui/tests/it/smudge_channels.rs @@ -13,6 +13,8 @@ use texturecraft_ui_egui::state::PropsTab; fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); run(&mut harness, "tool.smudge", Value::Null); harness diff --git a/crates/ui-egui/tests/it/snapped_lines.rs b/crates/ui-egui/tests/it/snapped_lines.rs index 44a37b86..992eb26c 100644 --- a/crates/ui-egui/tests/it/snapped_lines.rs +++ b/crates/ui-egui/tests/it/snapped_lines.rs @@ -28,6 +28,8 @@ const MAX_DIFFERENCE: f32 = 0.01; fn app(layout: ViewLayout) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = layout; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 98a6c39c..e869d1c6 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -37,6 +37,8 @@ impl eframe::Storage for MemoryStorage { fn split_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness } diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index 030e709a..7a64389d 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -26,6 +26,8 @@ fn app_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(1024, 256).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1760.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/symmetry_2d.rs b/crates/ui-egui/tests/it/symmetry_2d.rs index 29025dcd..6336eaaa 100644 --- a/crates/ui-egui/tests/it/symmetry_2d.rs +++ b/crates/ui-egui/tests/it/symmetry_2d.rs @@ -14,6 +14,8 @@ const CLICK: Pos2 = pos2(700.0, 420.0); fn uv_view_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index cc6d97ff..63fa59b6 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -25,6 +25,8 @@ fn select_nothing(session: &mut Session) { fn app_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness } @@ -139,6 +141,7 @@ fn bake_painting_turns_on_the_shelf_paint_tool() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); assert!(shelf_button_disabled(&harness, "Paint (1)"), "nothing is being painted yet"); @@ -189,6 +192,7 @@ fn tool_availability_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { for (brightness, suffix) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; diff --git a/crates/ui-egui/tests/it/tool_settings_saved.rs b/crates/ui-egui/tests/it/tool_settings_saved.rs index b5c5fd73..597f98e1 100644 --- a/crates/ui-egui/tests/it/tool_settings_saved.rs +++ b/crates/ui-egui/tests/it/tool_settings_saved.rs @@ -11,6 +11,8 @@ use memory_storage::MemoryStorage; fn saving_the_app_stores_the_current_brush_and_tool_settings() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(2); let tool = &mut harness.state_mut().session.tool; tool.brush.size = 0.37; diff --git a/crates/ui-egui/tests/it/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs index 23fa3e40..02eab838 100644 --- a/crates/ui-egui/tests/it/toolbar.rs +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -19,6 +19,10 @@ fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> theme::apply(context, theme::Brightness::default(), theme::Accent::default()); }) .build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + // Only the toolbar is painted, so no frame applies the preference: set the language itself + texturecraft_ui_egui::i18n::set_language("en"); harness.run_steps(4); harness } @@ -200,6 +204,9 @@ fn toolbar_window_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + // Only the toolbar is painted, so no frame applies the preference: set the language itself + texturecraft_ui_egui::i18n::set_language("en"); harness.state_mut().session.tool.tool = Tool::Path; harness.state_mut().session.tool.brush.lazy = 20.0; for (width, scale) in [(1600.0, 1.0), (960.0, 1.0), (960.0, 1.5)] { diff --git a/crates/ui-egui/tests/it/user_smart_mask.rs b/crates/ui-egui/tests/it/user_smart_mask.rs index da94ccda..4b7d186d 100644 --- a/crates/ui-egui/tests/it/user_smart_mask.rs +++ b/crates/ui-egui/tests/it/user_smart_mask.rs @@ -16,6 +16,8 @@ fn harness(prepare: impl FnOnce(&mut texturecraft_engine::Session)) -> Harness<' let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); prepare(&mut session); let mut harness = Harness::builder().with_size(WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness } diff --git a/crates/ui-egui/tests/list_panels.rs b/crates/ui-egui/tests/list_panels.rs index afec1051..e0c7a4a9 100644 --- a/crates/ui-egui/tests/list_panels.rs +++ b/crates/ui-egui/tests/list_panels.rs @@ -51,6 +51,8 @@ fn the_history_list_fills_a_tall_panel() { } let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); dock_in_left_column(&mut harness, "History"); harness.run_steps(STARTUP_FRAMES); @@ -63,6 +65,7 @@ fn the_history_list_fills_a_tall_panel() { fn the_log_list_fills_a_tall_panel() { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); for line in 0..ROWS { harness.state_mut().session.log.push(format!("Log line {line}")); } From ead50b5e8756b602de2a340ae95d1d6c9a4dbb8c Mon Sep 17 00:00:00 2001 From: supersfera Date: Sat, 21 Nov 2026 19:42:25 -0800 Subject: [PATCH 015/190] Add Russian translation (ru). Register Russian in LANGUAGES and add Russian strings to the Linux desktop, AppStream, and MIME metadata. Copyright (c) 2026 SuperSfera LLC, MIT OR Apache-2.0. --- crates/ui-egui/src/i18n.rs | 3 ++- .../linux/ai.storyteller.texturecraft.desktop | 5 +++++ .../ai.storyteller.texturecraft.metainfo.xml.in | 15 +++++++++++++++ .../linux/ai.storyteller.texturecraft.mime.xml | 13 +++++++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index bbbea0ec..a08fe1a2 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -37,7 +37,7 @@ pub struct Language { pub english: &'static str, } -const COUNT: usize = 10; +const COUNT: usize = 11; pub static LANGUAGES: [Language; COUNT] = [ Language { code: "en", name: "English", english: "English" }, @@ -50,6 +50,7 @@ pub static LANGUAGES: [Language; COUNT] = [ Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" }, Language { code: "ko", name: "한국어", english: "Korean" }, Language { code: "ar", name: "العربية", english: "Arabic" }, + Language { code: "ru", name: "Русский", english: "Russian" }, ]; static CURRENT: AtomicUsize = AtomicUsize::new(0); diff --git a/packaging/linux/ai.storyteller.texturecraft.desktop b/packaging/linux/ai.storyteller.texturecraft.desktop index ded29c5d..e1cb409a 100644 --- a/packaging/linux/ai.storyteller.texturecraft.desktop +++ b/packaging/linux/ai.storyteller.texturecraft.desktop @@ -1,8 +1,12 @@ +# Russian translation © 2026 SuperSfera LLC, MIT OR Apache-2.0 [Desktop Entry] Type=Application Name=TextureCraft +Name[ru]=TextureCraft GenericName=3D Texture Painter +GenericName[ru]=Рисование 3D-текстур Comment=Paint PBR textures directly on 3D meshes +Comment[ru]=Рисование PBR-текстур прямо на 3D-моделях Exec=texturecraft %F TryExec=texturecraft Icon=ai.storyteller.texturecraft @@ -11,4 +15,5 @@ StartupNotify=true StartupWMClass=texturecraft Categories=Graphics;3DGraphics; Keywords=texture;paint;pbr;material;3d;mesh;bake;gltf;fbx;usd; +Keywords[ru]=текстура;рисование;pbr;материал;3d;сетка;меш;запекание;gltf;fbx;usd; MimeType=application/x-texturecraft;model/gltf-binary;model/gltf+json;model/x-fbx;model/vnd.collada+xml;model/x-usd;model/vnd.usda;model/vnd.usdz+zip;model/x-alembic;model/obj;model/x-ply;model/stl; diff --git a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in index e04f156c..9b14d960 100644 --- a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in +++ b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in @@ -7,6 +7,7 @@ MIT OR Apache-2.0 TextureCraft Paint PBR textures directly on 3D meshes + Рисование PBR-текстур прямо на 3D-моделях Learning Machines LLC @@ -16,11 +17,21 @@ expect: familiar menus, shortcuts, panels and tools, with texture sets, layers, masks, fills and effects painted straight onto the model.

+

+ TextureCraft — открытая нативная программа для рисования 3D-текстур, устроенная так, + как привыкли художники по текстурам: знакомые меню, сочетания клавиш, панели и + инструменты, а наборы текстур, слои, маски, заливки и эффекты наносятся прямо на + модель. +

  • Open glTF/GLB, FBX, COLLADA, USD (USDA/USDC/USDZ), Alembic, OBJ, PLY and STL meshes and save projects as .tcraft
  • +
  • Открытие сеток glTF/GLB, FBX, COLLADA, USD (USDA/USDC/USDZ), Alembic, OBJ, PLY и STL и сохранение проектов в .tcraft
  • Paint base colour, roughness, metallic, normal and height together with PBR brushes
  • +
  • Рисование базового цвета, шероховатости, металличности, нормалей и высоты одновременно с помощью PBR-кистей
  • Bake mesh maps and export texture sets as PNG, EXR, TGA, JPEG or TIFF
  • +
  • Запекание карт сетки и экспорт наборов текстур в PNG, EXR, TGA, JPEG или TIFF
  • Every action is a command, scriptable from a CLI and a JSON control channel
  • +
  • Каждое действие — это команда, которую можно вызывать из CLI и через управляющий канал JSON
ai.storyteller.texturecraft.desktop @@ -36,9 +47,13 @@ texture painting + рисование текстур pbr + pbr 3d + 3d mesh + сетка #f0c39c diff --git a/packaging/linux/ai.storyteller.texturecraft.mime.xml b/packaging/linux/ai.storyteller.texturecraft.mime.xml index cf5204b3..2b1b811e 100644 --- a/packaging/linux/ai.storyteller.texturecraft.mime.xml +++ b/packaging/linux/ai.storyteller.texturecraft.mime.xml @@ -1,16 +1,19 @@ + TextureCraft project + Проект TextureCraft glTF binary model + Двоичная модель glTF @@ -18,11 +21,13 @@ glTF model + Модель glTF FBX model + Модель FBX @@ -30,11 +35,13 @@ COLLADA model + Модель COLLADA Universal Scene Description + Universal Scene Description @@ -44,17 +51,20 @@ Universal Scene Description (text) + Universal Scene Description (текст) Universal Scene Description package + Пакет Universal Scene Description Alembic model + Модель Alembic @@ -62,11 +72,13 @@ Wavefront OBJ model + Модель Wavefront OBJ PLY model + Модель PLY @@ -75,6 +87,7 @@ STL model + Модель STL From e4585fb2b34234e7a5f4b58ee0db1f744e500048 Mon Sep 17 00:00:00 2001 From: supersfera Date: Sat, 21 Nov 2026 20:23:02 -0800 Subject: [PATCH 016/190] ru: update language-script test for Cyrillic --- crates/ui-egui/src/fonts.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index b31b423a..5a5eb801 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -279,8 +279,9 @@ mod tests { assert_eq!(Script::of_language("ar"), Some(Script::Arabic)); assert_eq!(Script::of_language("de"), None); for l in &crate::i18n::LANGUAGES { - // Past the Latin blocks and their diacritics. - let other_script = l.name.chars().any(|c| c > '\u{036F}'); + // Past the Latin blocks and their diacritics. Cyrillic is already in the + // interface font (Inter / Ubuntu-Light), so Russian needs no fallback script. + let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c)); assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code); } } From 7f6375bf98716f0c93d1d422dcf7edc41c9962ca Mon Sep 17 00:00:00 2001 From: supersfera Date: Tue, 24 Nov 2026 07:10:16 -0800 Subject: [PATCH 017/190] ru: state CC0-1.0 for Russian metainfo strings --- packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in | 1 + 1 file changed, 1 insertion(+) diff --git a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in index 9b14d960..65088b0f 100644 --- a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in +++ b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in @@ -1,4 +1,5 @@ + From 6120bdd79de129bfb712262feba6353cf64b3369 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:48:58 +0100 Subject: [PATCH 018/190] Resources Updater: find changed resource files on disk and update or relink them Image resources imported from a file remember its path and modification time. resource.status lists each resource as outdated, missing, up to date or without a file; resource.update reads changed files again and resource.relink points a resource at another file, each as one undo step that recomposites every layer using the resource. Undo and redo drop pixels decoded from bytes they replace under the same name. The shelf's Resources Updater button opens a window with the project's resources (outdated first), status and name filters, Update, Select new resource, Show in folder, Refresh and Update All. When the app gets the focus back after files changed, a notice offers to update them. Automation refuses the three commands, since they read host paths the project names. --- crates/automation/src/workspace.rs | 6 + crates/core/src/lib.rs | 2 + crates/core/src/project.rs | 5 + crates/core/src/resource_source.rs | 17 + crates/engine/src/commands.rs | 4 +- crates/engine/src/lib.rs | 8 + crates/engine/src/link_cmds.rs | 1 + crates/engine/src/reloaded_file.rs | 28 ++ crates/engine/src/resource_cmds.rs | 24 +- crates/engine/src/resource_state.rs | 15 + crates/engine/src/resource_status.rs | 39 ++ crates/engine/src/resource_update_cmds.rs | 241 +++++++++++ crates/engine/src/session.rs | 2 + crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/resource_updater.rs | 227 +++++++++++ crates/ui-egui/src/lib.rs | 29 +- crates/ui-egui/src/menus.rs | 3 + crates/ui-egui/src/resources_updater.rs | 383 ++++++++++++++++++ .../src/resources_updater/row_request.rs | 9 + crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/state/resources_updater.rs | 19 + crates/ui-egui/src/toast_action.rs | 34 ++ crates/ui-egui/src/toolbar.rs | 28 +- crates/ui-egui/src/windows.rs | 1 + crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/resources_updater.rs | 137 +++++++ docs/control-protocol.md | 22 +- docs/features.md | 7 + 28 files changed, 1287 insertions(+), 11 deletions(-) create mode 100644 crates/core/src/resource_source.rs create mode 100644 crates/engine/src/reloaded_file.rs create mode 100644 crates/engine/src/resource_state.rs create mode 100644 crates/engine/src/resource_status.rs create mode 100644 crates/engine/src/resource_update_cmds.rs create mode 100644 crates/engine/tests/it/resource_updater.rs create mode 100644 crates/ui-egui/src/resources_updater.rs create mode 100644 crates/ui-egui/src/resources_updater/row_request.rs create mode 100644 crates/ui-egui/src/state/resources_updater.rs create mode 100644 crates/ui-egui/src/toast_action.rs create mode 100644 crates/ui-egui/tests/it/resources_updater.rs diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index a1f18ab9..2e590e15 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -138,6 +138,9 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, + + // The Resources Updater reads the files a project names, which may lie outside the read root + "resource.status" | "resource.update" | "resource.relink" => false, _ => !id.starts_with("file.") && !has_path, }; if allowed { @@ -245,6 +248,9 @@ mod tests { assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err()); assert!(authorize_command("file.reimportMesh", &json!({})).is_ok()); assert!(authorize_command("file.close", &json!({})).is_ok()); + for id in ["resource.status", "resource.update", "resource.relink"] { + assert!(authorize_command(id, &json!({})).is_err(), "{id} reads the host paths a project names"); + } assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 88ee96d1..2c5db23b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -51,6 +51,7 @@ pub mod project; pub mod projector; pub mod ramp_curve; pub mod randomized_seed; +pub mod resource_source; mod saved_decal; mod saved_projection; pub mod selection_background; @@ -133,6 +134,7 @@ pub use project::{ pub use projector::Projector; pub use ramp_curve::RampCurve; pub use randomized_seed::RandomizedSeed; +pub use resource_source::ResourceSource; pub use selection_background::SelectionBackground; pub use shape_crop::ShapeCrop; pub use slope_blending::SlopeBlending; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 649f4f6d..a4e004ec 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -445,6 +445,10 @@ pub struct Project { /// The project's colour swatches (linear RGB), in the order they were added; projects without any save none #[serde(default, skip_serializing_if = "Vec::is_empty")] pub swatches: Vec<[f32; 3]>, + /// The files image resources were imported from, by resource name (the Resources Updater + /// reads them again). Resources made in the app or imported without a file path have none. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub resource_sources: BTreeMap, } impl Project { @@ -462,6 +466,7 @@ impl Project { display: DisplaySettings::default(), cameras: Vec::new(), swatches: Vec::new(), + resource_sources: BTreeMap::new(), } } diff --git a/crates/core/src/resource_source.rs b/crates/core/src/resource_source.rs new file mode 100644 index 00000000..793122cf --- /dev/null +++ b/crates/core/src/resource_source.rs @@ -0,0 +1,17 @@ +//! Where an image resource was imported from, so the Resources Updater can read it again + +use serde::{Deserialize, Serialize}; + +/// The file an image resource was read from and its modification time then. +/// +/// The resource's stored bytes are the file's bytes at that time, so a file whose size or +/// contents differ from them has changed on disk. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResourceSource { + /// Path of the file on the machine that imported it. + pub path: String, + /// The file's modification time when it was read, in milliseconds since the Unix epoch + /// (0 when unknown). An unchanged time and size skip reading the file again. + #[serde(default)] + pub modified_ms: u64, +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index e34e9327..bb177191 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -31,7 +31,7 @@ impl CommandSpec { /// that only return data or do nothing without parameters, and the ones that replace the /// open project (the menu asks to save first). pub fn bindable(&self) -> bool { - const NOT_FROM_A_KEY: [&str; 13] = [ + const NOT_FROM_A_KEY: [&str; 14] = [ "project.inspect", "project.templates", "project.new", @@ -45,6 +45,7 @@ impl CommandSpec { "bake.preview", "camera.set", "textureSet.settings", + "resource.status", ]; const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"]; !(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params) @@ -143,6 +144,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); + v.extend(crate::resource_update_cmds::specs()); v.extend(crate::material_lib::specs()); v.extend(crate::link_cmds::specs()); v.extend(crate::smart_masks::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..0d2f8d3c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -68,7 +68,13 @@ pub mod preview; mod procedural_params; pub mod project_cmds; pub mod quick_mask; +// Reloading resource files reads paths on native targets only +#[cfg(not(target_arch = "wasm32"))] +mod reloaded_file; pub mod resource_cmds; +pub mod resource_state; +pub mod resource_status; +pub mod resource_update_cmds; pub mod session; mod session_log; pub mod set_cmds; @@ -97,6 +103,8 @@ pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use log::{LogEntry, LogLevel, SessionLog}; pub use path_tool::PathState; +pub use resource_state::ResourceState; +pub use resource_status::ResourceStatus; pub use project_cmds::sample_session; pub use session::{ CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index a20182f6..1312aedd 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -623,6 +623,7 @@ impl Session { for name in old_names.iter().filter(|name| !used_names.contains(name)) { session.doc.resources.remove(name); + session.doc.project.resource_sources.remove(name); } Ok(names) diff --git a/crates/engine/src/reloaded_file.rs b/crates/engine/src/reloaded_file.rs new file mode 100644 index 00000000..b65582d2 --- /dev/null +++ b/crates/engine/src/reloaded_file.rs @@ -0,0 +1,28 @@ +//! An image file read again for a resource, checked before the project changes + +use texturecraft_core::ResourceSource; +use texturecraft_formats::DecodedImage; + +use crate::Result; + +/// A resource's new bytes, their decoded pixels and the file they came from +pub(crate) struct ReloadedFile { + pub name: String, + pub bytes: Vec, + pub image: DecodedImage, + pub source: ResourceSource, +} + +impl ReloadedFile { + /// Read and decode `path` for resource `name` within the resource limits (`cmd` names errors) + pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result { + let file_path = std::path::Path::new(path); + + // Taken before reading, so a write during the read still shows as a change later + let modified_ms = crate::resource_update_cmds::modified_ms_of(file_path); + let bytes = crate::resource_cmds::read_resource_file(cmd, file_path, crate::resource_cmds::MAX_BYTES as u64)?; + let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{path}: {error}")))?; + + Ok(ReloadedFile { name, bytes, image, source: ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms } }) + } +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 39d9fb6c..d20cb60e 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -146,6 +146,16 @@ impl Session { self.drop_missing_image_view(); } + /// Undo and redo restore resource bytes under the same name (the Resources Updater replaces + /// them in place): the pixels decoded from the bytes `other` held are stale + pub(crate) fn forget_replaced_images(&mut self, other: &crate::Document) { + for (name, bytes) in &self.doc.resources { + if other.resources.get(name).is_some_and(|previous| !Arc::ptr_eq(previous, bytes)) { + self.images.remove(name); + } + } + } + /// The "Other..." view cannot show an image that is gone (removed or renamed): the material comes back pub(crate) fn drop_missing_image_view(&mut self) { if self.view == crate::ViewMode::Image && !self.view_image.as_ref().is_some_and(|name| self.images.contains_key(name)) { @@ -172,8 +182,18 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; + let prefix = strp(p, "prefix").unwrap_or(""); + + // Taken before reading, so a write during the read still shows as a change in the Resources Updater + let modified_ms = crate::resource_update_cmds::modified_ms_of(std::path::Path::new(path)); let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; + let source = texturecraft_core::ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms }; + + let name = s.edit("Import resource", |session| { + let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?; + session.doc.project.resource_sources.insert(name.clone(), source); + Ok(name) + })?; Ok(json!({ "name": name })) } @@ -255,6 +275,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { s.edit("Remove resource", |s| { s.doc.resources.remove(&name); + s.doc.project.resource_sources.remove(&name); Ok(()) })?; s.sync_images(); @@ -277,6 +298,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { if !unused.is_empty() { s.edit("Remove unused resources", |s| { s.doc.resources.retain(|k, _| !unused.contains(k)); + s.doc.project.resource_sources.retain(|k, _| !unused.contains(k)); Ok(()) })?; s.sync_images(); diff --git a/crates/engine/src/resource_state.rs b/crates/engine/src/resource_state.rs new file mode 100644 index 00000000..1a3e427c --- /dev/null +++ b/crates/engine/src/resource_state.rs @@ -0,0 +1,15 @@ +//! One row of the Resources Updater: an image resource, its file and how they compare + +use crate::resource_status::ResourceStatus; + +/// An image resource, the file it came from and whether that file changed on disk +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResourceState { + /// The resource's name in the project. + pub name: String, + pub status: ResourceStatus, + /// The file it was imported from or relinked to (None: made in the app or imported without a path). + pub path: Option, + /// Why the file could not be checked (with [`ResourceStatus::Missing`]). + pub error: Option, +} diff --git a/crates/engine/src/resource_status.rs b/crates/engine/src/resource_status.rs new file mode 100644 index 00000000..8e8efc70 --- /dev/null +++ b/crates/engine/src/resource_status.rs @@ -0,0 +1,39 @@ +//! Whether an image resource still matches the file it was imported from + +/// How an image resource compares with its file on disk. The order is the Resources Updater's +/// list order: what needs attention first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ResourceStatus { + /// The file changed since it was read: Update reads it again. + Outdated, + /// The file is gone, or cannot be read. + Missing, + /// The file still holds the resource's bytes. + UpToDate, + /// Made in the app or imported without a file path: there is nothing to compare with. + NoSource, +} + +impl ResourceStatus { + pub const ALL: [ResourceStatus; 4] = [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource]; + + /// The id used by the control protocol + pub fn id(self) -> &'static str { + match self { + ResourceStatus::Outdated => "outdated", + ResourceStatus::Missing => "missing", + ResourceStatus::UpToDate => "upToDate", + ResourceStatus::NoSource => "noSource", + } + } + + /// The name shown in the Resources Updater (English; the shell translates it) + pub fn label(self) -> &'static str { + match self { + ResourceStatus::Outdated => "Outdated", + ResourceStatus::Missing => "Missing", + ResourceStatus::UpToDate => "Up to date", + ResourceStatus::NoSource => "No source file", + } + } +} diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs new file mode 100644 index 00000000..ea69042d --- /dev/null +++ b/crates/engine/src/resource_update_cmds.rs @@ -0,0 +1,241 @@ +//! The Resources Updater: compare image resources with the files they came from, read changed +//! files again and point a resource at another file. Each change is one undo step, and every +//! layer, mask and view using a changed resource recomposites. + +use serde_json::{Value, json}; +use texturecraft_core::ResourceSource; + +use crate::commands::{CommandSpec, always, bad}; +use crate::resource_state::ResourceState; +use crate::resource_status::ResourceStatus; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "resource.status", + "Check resources on disk", + [], + None, + "{} → {resources: [{name, status: outdated|missing|upToDate|noSource, path?, error?}] (outdated first), total, outdated}", + always, + |s, _| Ok(status(s)) + ), + cmd!( + "resource.update", + "Update resources", + [], + None, + "{names?: [resource name] (default: every outdated resource)} → {updated, failed: [{name, error}]} — reads their files again, one undo step", + always, + update + ), + cmd!( + "resource.relink", + "Relink resource", + [], + None, + "{name, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", + always, + relink + ), + ] +} + +impl Session { + /// The image resources with their files and how they compare, outdated first, then by name. + /// Reads a file only when its size matches the stored bytes but its modification time does not. + pub fn resource_states(&self) -> Vec { + let sources = &self.doc.project.resource_sources; + let mut states: Vec = self + .doc + .resources + .iter() + .filter(|(name, _)| self.images.contains_key(*name) || sources.contains_key(*name)) + .map(|(name, bytes)| { + let source = sources.get(name); + let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(source, bytes)); + ResourceState { name: name.clone(), status, path: source.map(|source| source.path.clone()), error } + }) + .collect(); + + states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); + states + } + + /// Put reloaded files in place of their resources' bytes and pixels as one undo step + #[cfg(not(target_arch = "wasm32"))] + fn install_reloaded(&mut self, label: &str, files: Vec) -> Result> { + if files.is_empty() { + return Ok(Vec::new()); + } + + let decoded = self.edit(label, |session| { + let mut decoded = Vec::with_capacity(files.len()); + for file in files { + session.doc.resources.insert(file.name.clone(), std::sync::Arc::new(file.bytes)); + session.doc.project.resource_sources.insert(file.name.clone(), file.source); + decoded.push((file.name, file.image)); + } + + Ok(decoded) + })?; + + // The edit marked every set using a replaced resource for recompositing; the new pixels are read then + let mut names = Vec::with_capacity(decoded.len()); + for (name, image) in decoded { + if crate::fill_alpha::matches_saved_picture(&name, &image) { + self.library_alphas.insert(name.clone()); + } else { + self.library_alphas.remove(&name); + } + + self.images.insert(name.clone(), crate::resource_cmds::decoded(image)); + names.push(name); + } + + Ok(names) + } +} + +/// How `stored` (a resource's bytes) compares with the file `source` names now +#[cfg(not(target_arch = "wasm32"))] +fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Option) { + let path = std::path::Path::new(&source.path); + let metadata = match std::fs::metadata(path) { + Ok(metadata) if metadata.is_file() => metadata, + Ok(_) => return (ResourceStatus::Missing, Some(format!("{} is not a regular file", source.path))), + Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))), + }; + + if metadata.len() != stored.len() as u64 { + return (ResourceStatus::Outdated, None); + } + + let modified_ms = modified_ms(&metadata); + if modified_ms != 0 && modified_ms == source.modified_ms { + return (ResourceStatus::UpToDate, None); + } + + // A newer time alone is not a change: the file may have been saved again unchanged + match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { + Ok(bytes) if bytes == stored => (ResourceStatus::UpToDate, None), + Ok(_) => (ResourceStatus::Outdated, None), + Err(error) => (ResourceStatus::Missing, Some(error.to_string())), + } +} + +#[cfg(target_arch = "wasm32")] +fn compare_with_file(_: &ResourceSource, _: &[u8]) -> (ResourceStatus, Option) { + (ResourceStatus::Missing, Some("file paths are not available in the browser".to_string())) +} + +/// A file's modification time in milliseconds since the Unix epoch (0 when the system has none) +#[cfg(not(target_arch = "wasm32"))] +fn modified_ms(metadata: &std::fs::Metadata) -> u64 { + let since_epoch = metadata.modified().ok().and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok()); + since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)) +} + +/// [`modified_ms`] of the file at `path` (0 when it cannot be read) +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn modified_ms_of(path: &std::path::Path) -> u64 { + std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)) +} + +/// `path` made absolute against the working folder, so the record does not depend on where the app started +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn absolute_path(path: &str) -> String { + std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()) +} + +fn status(s: &Session) -> Value { + let states = s.resource_states(); + let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count(); + let resources: Vec = states + .iter() + .map(|state| { + let mut row = json!({"name": state.name, "status": state.status.id()}); + if let Some(path) = &state.path { + row["path"] = json!(path); + } + if let Some(error) = &state.error { + row["error"] = json!(error); + } + + row + }) + .collect(); + + json!({"resources": resources, "total": states.len(), "outdated": outdated}) +} + +#[cfg(not(target_arch = "wasm32"))] +fn update(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "resource.update"; + + let names: Vec = match p.get("names") { + None | Some(Value::Null) => s.resource_states().into_iter().filter(|state| state.status == ResourceStatus::Outdated).map(|state| state.name).collect(), + Some(Value::Array(names)) => { + names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad(CMD, "`names` must be resource names"))).collect::>()? + } + Some(_) => return Err(bad(CMD, "`names` must be an array of resource names")), + }; + + // Every name is checked before any file is read + for name in &names { + if !s.doc.resources.contains_key(name) { + return Err(bad(CMD, format!("no resource `{name}`"))); + } + if !s.doc.project.resource_sources.contains_key(name) { + return Err(bad(CMD, format!("`{name}` has no source file: relink it to a file first"))); + } + } + + // A file that cannot be read fails alone; the others still update + let (mut files, mut failed) = (Vec::new(), Vec::new()); + for name in names { + let Some(path) = s.doc.project.resource_sources.get(&name).map(|source| source.path.clone()) else { continue }; + match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &path) { + // Unchanged contents need no undo step + Ok(file) if s.doc.resources.get(&name).is_some_and(|stored| **stored == file.bytes) => {} + Ok(file) => files.push(file), + Err(error) => failed.push(json!({"name": name, "error": error.to_string()})), + } + } + + if files.is_empty() && !failed.is_empty() { + let reasons: Vec<&str> = failed.iter().filter_map(|failure| failure["error"].as_str()).collect(); + return Err(bad(CMD, format!("nothing was updated: {}", reasons.join("; ")))); + } + + let updated = s.install_reloaded("Update resources", files)?; + Ok(json!({"updated": updated, "failed": failed})) +} + +#[cfg(not(target_arch = "wasm32"))] +fn relink(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "resource.relink"; + + let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string(); + let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; + if !s.doc.resources.contains_key(&name) { + return Err(bad(CMD, format!("no resource `{name}`"))); + } + + let file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + let path = file.source.path.clone(); + s.install_reloaded("Relink resource", vec![file])?; + + Ok(json!({"name": name, "path": path})) +} + +#[cfg(target_arch = "wasm32")] +fn update(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.update", "file paths are not available in the browser")) +} + +#[cfg(target_arch = "wasm32")] +fn relink(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.relink", "file paths are not available in the browser")) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..beb20ab0 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -957,6 +957,7 @@ impl Session { let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; let current = std::mem::replace(&mut self.doc, restored); self.after_history(¤t); + self.forget_replaced_images(¤t); self.redo.push((label.clone(), current)); self.sync_images(); Ok(label) @@ -977,6 +978,7 @@ impl Session { let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; let current = std::mem::replace(&mut self.doc, restored); self.after_history(¤t); + self.forget_replaced_images(¤t); self.undo.push((label.clone(), current)); self.sync_images(); Ok(label) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ce9f1614..5010e30f 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -55,6 +55,7 @@ mod pbr_import; mod perf; mod polygon_fill; mod project_recovery; +mod resource_updater; mod resources_used; mod sample; mod solo; diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs new file mode 100644 index 00000000..c0d0f1dc --- /dev/null +++ b/crates/engine/tests/it/resource_updater.rs @@ -0,0 +1,227 @@ +//! The Resources Updater: image resources remember their files, a changed file shows as outdated, +//! Update reads it again (one undo step, recompositing its layers) and Relink follows another file + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{ResourceStatus, Session, execute}; + +const RESOLUTION: u32 = 64; +const SAMPLE_STRIDE: usize = 4; +const RED: [u8; 4] = [255, 0, 0, 255]; +const GREEN: [u8; 4] = [0, 255, 0, 255]; + +/// A test folder removed when dropped +struct TempDir(PathBuf); + +impl TempDir { + fn new(test: &str) -> TempDir { + let path = std::env::temp_dir().join(format!("tc-resource-updater-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + TempDir(path) + } + + fn file(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap() +} + +/// Write a `size` × `size` PNG of one colour (sizes differ between versions, so the file size changes too) +fn write_png(path: &Path, size: u32, color: [u8; 4]) { + image::RgbaImage::from_pixel(size, size, image::Rgba(color)).save(path).unwrap(); +} + +fn text(path: &Path) -> &str { + path.to_str().unwrap() +} + +/// Import `path` and show it as a base colour fill; returns the resource name +fn import_as_fill(s: &mut Session, path: &Path) -> String { + let name = execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string(); + execute(s, "layer.add.image", &json!({"name": name})).unwrap(); + s.update(); + name +} + +fn base_colors(s: &Session) -> Vec<[f32; 3]> { + let composite = &s.caches[s.ts()].composite; + let samples = || (0..RESOLUTION).step_by(SAMPLE_STRIDE); + samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() +} + +fn status_of(s: &Session, name: &str) -> ResourceStatus { + s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status +} + +#[test] +fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() { + let dir = TempDir::new("update"); + let file = dir.file("bricks.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import_as_fill(&mut s, &file); + let before = base_colors(&s); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + + write_png(&file, 8, GREEN); + let status = execute(&mut s, "resource.status", &Value::Null).unwrap(); + + assert_eq!(status["outdated"], json!(1)); + assert_eq!(status["resources"][0]["name"], json!(name)); + assert_eq!(status["resources"][0]["status"], json!("outdated")); + + let steps = s.history_labels().len(); + let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); + s.update(); + let after = base_colors(&s); + + assert_eq!(updated["updated"], json!([name])); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(s.images[&name].width, 8, "the new pixels are decoded"); + assert_ne!(after, before, "the fill using the resource recomposited"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + + assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name"); + assert_eq!(base_colors(&s), before); + assert_eq!(status_of(&s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); + + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + s.update(); + + assert_eq!(s.images[&name].width, 8); + assert_eq!(base_colors(&s), after); +} + +#[test] +fn nothing_outdated_adds_no_undo_step() { + let dir = TempDir::new("unchanged"); + let file = dir.file("same.png"); + write_png(&file, 4, RED); + let mut s = session(); + import_as_fill(&mut s, &file); + let steps = s.history_labels().len(); + + let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); + + assert_eq!(updated["updated"], json!([])); + assert_eq!(s.history_labels().len(), steps); +} + +#[test] +fn a_missing_file_is_reported_and_updating_it_changes_nothing() { + let dir = TempDir::new("missing"); + let file = dir.file("gone.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import_as_fill(&mut s, &file); + std::fs::remove_file(&file).unwrap(); + let steps = s.history_labels().len(); + + let state = s.resource_states().into_iter().find(|state| state.name == name).unwrap(); + let error = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap_err(); + + assert_eq!(state.status, ResourceStatus::Missing); + assert!(state.error.is_some(), "the reason is shown"); + assert!(error.to_string().contains("nothing was updated"), "{error}"); + assert_eq!(s.history_labels().len(), steps); + assert_eq!(s.images[&name].width, 4, "the resource keeps its pixels"); +} + +#[test] +fn an_unreadable_file_fails_alone_while_the_others_update() { + let dir = TempDir::new("partial"); + let (kept, gone) = (dir.file("kept.png"), dir.file("gone.png")); + write_png(&kept, 4, RED); + write_png(&gone, 4, RED); + let mut s = session(); + let kept_name = import_as_fill(&mut s, &kept); + let gone_name = import_as_fill(&mut s, &gone); + write_png(&kept, 8, GREEN); + std::fs::remove_file(&gone).unwrap(); + + let result = execute(&mut s, "resource.update", &json!({"names": [kept_name, gone_name]})).unwrap(); + + assert_eq!(result["updated"], json!([kept_name])); + assert_eq!(result["failed"][0]["name"], json!(gone_name)); + assert_eq!(s.images[&kept_name].width, 8); +} + +#[test] +fn relink_reads_another_file_and_follows_it_from_then_on() { + let dir = TempDir::new("relink"); + let (first, second) = (dir.file("first.png"), dir.file("second.png")); + write_png(&first, 4, RED); + write_png(&second, 8, GREEN); + let mut s = session(); + let name = import_as_fill(&mut s, &first); + let before = base_colors(&s); + let steps = s.history_labels().len(); + + execute(&mut s, "resource.relink", &json!({"name": name, "path": text(&second)})).unwrap(); + s.update(); + + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(s.images[&name].width, 8, "the resource keeps its name and takes the new file's pixels"); + assert_ne!(base_colors(&s), before); + assert!(s.doc.project.resource_sources[&name].path.ends_with("second.png")); + + // The old file no longer matters, the new one does + write_png(&first, 16, GREEN); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + write_png(&second, 16, RED); + assert_eq!(status_of(&s, &name), ResourceStatus::Outdated); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link"); +} + +#[test] +fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() { + let dir = TempDir::new("reopen"); + let file = dir.file("kept.png"); + write_png(&file, 4, RED); + let mut s = session(); + let linked = import_as_fill(&mut s, &file); + let png = std::fs::read(&file).unwrap(); + let unlinked = s.import_resource_bytes("made.png", png).unwrap(); + + assert_eq!(status_of(&s, &unlinked), ResourceStatus::NoSource); + assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err()); + + let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + write_png(&file, 8, GREEN); + + assert_eq!(status_of(&reopened, &linked), ResourceStatus::Outdated); +} + +#[test] +fn a_removed_resource_forgets_its_file() { + let dir = TempDir::new("remove"); + let file = dir.file("old.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = execute(&mut s, "resource.import", &json!({"path": text(&file)})).unwrap()["name"].as_str().unwrap().to_string(); + + execute(&mut s, "resource.remove", &json!({"name": name})).unwrap(); + let png = std::fs::read(&file).unwrap(); + let reused = s.import_resource_bytes("old.png", png).unwrap(); + + assert_eq!(reused, name, "the name is free again"); + assert_eq!(status_of(&s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..100d07a5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -124,6 +124,8 @@ mod resolution_band; mod resource_panel; mod resource_picker; mod resource_picker_item; +#[cfg(not(target_arch = "wasm32"))] +mod resources_updater; mod round_gizmo; mod running_bake; pub mod saved_search; @@ -156,6 +158,7 @@ pub mod thumbs; mod tile_edits; mod tile_picture; pub mod titlebar; +pub mod toast_action; pub mod toolbar; pub mod ui_state_store; pub mod unavailable; @@ -235,6 +238,8 @@ pub struct Toast { pub error: bool, pub until: f64, pub show_log: bool, + /// A button after the text that acts on the notice + pub action: Option, } pub struct TextureCraftApp { @@ -317,6 +322,9 @@ pub struct TextureCraftApp { styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. focused: bool, + /// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resources_notified: std::collections::BTreeSet, /// The update check and prompt (desktop only). #[cfg(not(target_arch = "wasm32"))] pub(crate) updates_rt: updates_ui::Runtime, @@ -439,6 +447,8 @@ impl TextureCraftApp { styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] + resources_notified: std::collections::BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), @@ -590,13 +600,13 @@ impl TextureCraftApp { } pub fn toast(&mut self, text: impl Into, error: bool) { - self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false }); + self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, action: None }); } /// An error toast that stays until the user dismisses it (for a problem that persists and /// is reported once, like a texture set the GPU could not hold). pub fn toast_sticky(&mut self, text: impl Into) { - self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); + self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, action: None }); } /// Start baking texture sets in the background, one after another. Invalid set indices @@ -1117,6 +1127,10 @@ impl eframe::App for TextureCraftApp { let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; + + // Files may have been edited in another app meanwhile + #[cfg(not(target_arch = "wasm32"))] + resources_updater::check_on_focus(self); } self.focused = focused; @@ -1292,6 +1306,7 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = theme::Tokens::get(ctx); let mut dismissed = None; let mut show_log = false; + let mut clicked_action = None; // Limit toast dimensions so the dismiss button stays visible let screen = ctx.content_rect().size(); @@ -1320,6 +1335,12 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { show_log = true; dismissed = Some(i); } + if let Some(action) = t.action + && ui.button(i18n::tr(action.label())).clicked() + { + clicked_action = Some(action); + dismissed = Some(i); + } }); if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { dismissed = Some(i); @@ -1337,4 +1358,8 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.log_channel = log_panel::LogChannel::General; crate::rail_popup::open(app, crate::docking::Panel::Log); } + + if let Some(action) = clicked_action { + action.run(app); + } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..a0fd80de 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,6 +526,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); + } else if app.ui.windows.resources_updater.is_some() && !popup_open && input.key_pressed(Key::Escape) { + #[cfg(not(target_arch = "wasm32"))] + crate::resources_updater::keys_in(app, input); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs new file mode 100644 index 00000000..4bb9ce60 --- /dev/null +++ b/crates/ui-egui/src/resources_updater.rs @@ -0,0 +1,383 @@ +//! The Resources Updater: the project's image resources and whether the files they were imported +//! from changed on disk. Update reads a changed file again, Select new resource points a resource +//! at another file, and a notice offers to update when the app gets the focus back after files +//! changed. Everything runs through `resource.status`, `resource.update` and `resource.relink`. + +mod row_request; + +use std::collections::BTreeSet; + +use egui::{Key, Modifiers}; +use serde_json::json; +use texturecraft_engine::{ResourceState, ResourceStatus}; + +use crate::TextureCraftApp; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{tr, trf}; +use crate::state::ResourcesUpdater; +use crate::theme::Tokens; +use crate::toast_action::ToastAction; +use crate::web_files::IMAGE_EXTS; +use crate::widgets::primary_button; +use row_request::RowRequest; + +/// Width of the window +const WINDOW_WIDTH_POINTS: f32 = 640.0; +/// Height of the resource list +const LIST_HEIGHT_POINTS: f32 = 360.0; +// Initial space for the header, tabs, filters and footer +const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0; +/// Side of a row's thumbnail +const THUMBNAIL_POINTS: f32 = 40.0; +/// Width of the name filter field +const NAME_FILTER_WIDTH_POINTS: f32 = 160.0; +/// Width of the status dropdown +const STATUS_WIDTH_POINTS: f32 = 120.0; +/// Space inside a row's frame +const ROW_MARGIN: egui::Margin = egui::Margin::same(4); +/// Strength of the danger tint behind an outdated row (the status text says it too) +const OUTDATED_TINT: f32 = 0.18; +/// How long the "changed on disk" notice stays, in seconds: long enough to reach its button +const NOTICE_SECONDS: f64 = 12.0; + +/// Opens the window, or closes it when it is open (the shelf button) +pub(crate) fn toggle(app: &mut TextureCraftApp) { + if app.ui.windows.resources_updater.take().is_none() { + open(app); + } +} + +/// Opens the window with the resources checked now (an open window is checked again) +pub(crate) fn open(app: &mut TextureCraftApp) { + let window = app.ui.windows.resources_updater.take().unwrap_or_default(); + app.ui.windows.resources_updater = Some(ResourcesUpdater { + rows: app.session.resource_states(), + project: app.session.project_id, + checked_revision: app.session.revision, + ..window + }); +} + +/// The app has the focus back: check the files again and, when other resources than last time +/// are outdated, show a notice whose button updates them +pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { + if !app.session.project_open { + return; + } + + let rows = app.session.resource_states(); + let outdated: BTreeSet = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect(); + if let Some(window) = app.ui.windows.resources_updater.as_mut() { + window.rows = rows; + window.checked_revision = app.session.revision; + } + + if !outdated.is_empty() && outdated != app.resources_notified { + let text = if outdated.len() == 1 { + tr("1 resource changed on disk").to_string() + } else { + trf("{count} resources changed on disk", &[("count", &outdated.len())]) + }; + app.toast(text, false); + if let Some(toast) = app.toasts.last_mut() { + toast.until = app.last_time + NOTICE_SECONDS; + toast.action = Some(ToastAction::UpdateResources); + } + } + app.resources_notified = outdated; +} + +/// Read the files of `names` again (every outdated resource when None), one undo step, and say +/// what happened +pub(crate) fn update(app: &mut TextureCraftApp, names: Option>) { + let params = match names { + Some(names) => json!({ "names": names }), + None => json!({}), + }; + let Some(result) = app.run("resource.update", params) else { return }; + + let updated = result["updated"].as_array().map_or(0, Vec::len); + let failed: Vec = result["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failure| format!("{}: {}", failure["name"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default())) + .collect(); + if failed.is_empty() { + app.toast(trf("Updated {count} resources", &[("count", &updated)]), false); + } else { + app.toast(trf("Updated {count} resources; could not update {failed}", &[("count", &updated), ("failed", &failed.join("; "))]), true); + } + + // What was announced is handled; a later change is announced again + app.resources_notified.clear(); +} + +/// Ask for another file for resource `name`; the resource takes its pixels and follows it +fn select_new_resource(app: &mut TextureCraftApp, name: String) { + let dialog = FileDialog::open().filter(tr("Images"), IMAGE_EXTS); + app.ask_file(dialog, Bound::Project, move |app, paths| { + let Some(path) = paths.first() else { return }; + let Some(path) = path.to_str() else { + app.toast(trf("Could not use a path that is not UTF-8: {path}", &[("path", &path.display())]), true); + return; + }; + + if app.run("resource.relink", json!({ "name": name, "path": path })).is_some() { + app.toast(trf("{name} now reads {path}", &[("name", &name), ("path", &path)]), false); + } + }); +} + +/// Show the folder holding `path` in the system's file manager +fn show_in_folder(app: &mut TextureCraftApp, path: &str) { + let folder = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf).unwrap_or_default(); + if let Err(error) = app.file_dialogs.show_folder(&folder) { + app.toast(trf("Could not show {folder}: {error}", &[("folder", &folder.display()), ("error", &error)]), true); + } +} + +/// The keys of the open window: Escape closes it (an open dropdown takes it first, see `menus`) +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { + if input.consume_key(Modifiers::NONE, Key::Escape) { + app.ui.windows.resources_updater = None; + } +} + +/// Whether `row` passes the window's status and name filters +fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool { + let name_filter = window.name_filter.trim().to_lowercase(); + window.status_filter.is_none_or(|status| row.status == status) && (name_filter.is_empty() || row.name.to_lowercase().contains(&name_filter)) +} + +/// "(N resources, M outdated)" +fn summary(rows: &[ResourceState]) -> String { + let outdated = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).count(); + trf("({count} resources, {outdated} outdated)", &[("count", &rows.len()), ("outdated", &outdated)]) +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut window) = app.ui.windows.resources_updater.take() else { return }; + + // Resources of another project are not this one's + if window.project != app.session.project_id || !app.session.project_open { + return; + } + + // Every change (an update, undo, redo, a removed resource) is checked again + if window.checked_revision != app.session.revision { + window.rows = app.session.resource_states(); + window.checked_revision = app.session.revision; + } + + let tokens = Tokens::get(ctx); + let mut open = true; + let (mut refresh, mut update_all) = (false, false); + let mut request = None; + + crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut open) + .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS)) + .show(ctx, |ui| { + ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name)); + + // Shader resources have no equivalent here: the one tab lists image resources + let tab = ui.add(egui::Button::selectable(true, tr("Resources"))); + tab.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, true, tr("Resources"))); + ui.separator(); + + ui.horizontal(|ui| { + let status_label = ui.label(tr("Status:")); + let selected = window.status_filter.map_or(tr("All"), |status| tr(status.label())); + egui::ComboBox::from_id_salt("resources_updater_status") + .width(STATUS_WIDTH_POINTS) + .selected_text(selected) + .show_ui(ui, |ui| { + ui.selectable_value(&mut window.status_filter, None, tr("All")); + for status in ResourceStatus::ALL { + ui.selectable_value(&mut window.status_filter, Some(status), tr(status.label())); + } + }) + .response + .labelled_by(status_label.id); + + let name_label = ui.label(tr("Name filter:")); + ui.add(egui::TextEdit::singleline(&mut window.name_filter).desired_width(NAME_FILTER_WIDTH_POINTS)).labelled_by(name_label.id); + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Bottom")).clicked() { + window.jump = Some(egui::Align::Max); + } + if ui.button(tr("Top")).clicked() { + window.jump = Some(egui::Align::Min); + } + }); + }); + ui.add_space(4.0); + + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + refresh = ui.button(tr("Refresh")).clicked(); + ui.label(summary(&window.rows)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated); + let button = ui.add_enabled(outdated, primary_button(ui, tr("Update All"))); + update_all = button.on_disabled_hover_text(tr("No resource is outdated")).clicked(); + }); + }); + ui.separator(); + + let list_height = ui.available_height().max(0.0); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().max_height(list_height).auto_shrink([false, false]).show(ui, |ui| { + let jump = window.jump.take(); + if jump == Some(egui::Align::Min) { + ui.scroll_to_cursor(Some(egui::Align::Min)); + } + + let visible: Vec<&ResourceState> = window.rows.iter().filter(|row| shown(&window, row)).collect(); + if visible.is_empty() { + ui.label(tr("No resources match the filters")); + } + for (index, row) in visible.into_iter().enumerate() { + if let Some(asked) = row_ui(app, ui, &tokens, index + 1, row) { + request = Some(asked); + } + } + + if jump == Some(egui::Align::Max) { + ui.scroll_to_cursor(Some(egui::Align::Max)); + } + }); + }); + }); + }); + + if !open { + return; + } + + app.ui.windows.resources_updater = Some(window); + + if refresh { + open(app); + } + if update_all { + update(app, None); + } + match request { + Some(RowRequest::Update(name)) => update(app, Some(vec![name])), + Some(RowRequest::SelectNew(name)) => select_new_resource(app, name), + Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path), + None => {} + } +} + +/// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are +/// tinted, and their status says so in words too. +fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: usize, row: &ResourceState) -> Option { + let outdated = row.status == ResourceStatus::Outdated; + let (fill, stroke) = if outdated { + (tokens.danger.gamma_multiply(OUTDATED_TINT), egui::Stroke::new(1.0, tokens.danger)) + } else { + (egui::Color32::TRANSPARENT, egui::Stroke::NONE) + }; + let mut request = None; + + egui::Frame::NONE.fill(fill).stroke(stroke).inner_margin(ROW_MARGIN).corner_radius(crate::theme::CARD_RADIUS).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + match app.session.images.get(&row.name) { + Some(image) => { + let texture = app.thumbs.image(ui.ctx(), &row.name, image); + ui.add(egui::Image::new(&texture).fit_to_exact_size(egui::vec2(THUMBNAIL_POINTS, THUMBNAIL_POINTS))); + } + + // A file that could not be decoded has no picture; the row keeps its place + None => ui.add_space(THUMBNAIL_POINTS), + } + ui.label(number.to_string()); + + // Buttons take their room on the right first, so the texts truncate in what is left + // Each button's accessible name says which resource it acts on + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let update = ui.add_enabled(outdated, egui::Button::new(tr("Update"))); + let update_name = format!("{} {}", tr("Update"), row.name); + update.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, outdated, &update_name)); + if update.clicked() { + request = Some(RowRequest::Update(row.name.clone())); + } + + let select = ui.button(tr("Select new resource")); + let select_name = format!("{} {}", tr("Select new resource"), row.name); + select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); + if select.clicked() { + request = Some(RowRequest::SelectNew(row.name.clone())); + } + + if let Some(path) = &row.path { + let folder = ui.button(tr("Show in folder")); + let folder_name = format!("{} {}", tr("Show in folder"), row.name); + folder.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &folder_name)); + if folder.clicked() { + request = Some(RowRequest::ShowFolder(path.clone())); + } + } + + ui.vertical(|ui| { + ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate()); + let file = row.path.as_deref().unwrap_or(tr("No source file")); + ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file); + let status = ui.label(tr(row.status.label())); + if let Some(error) = &row.error { + status.on_hover_text(error); + } + }); + }); + }); + }); + + request +} + +#[cfg(test)] +mod tests { + use std::sync::PoisonError; + + use egui_kittest::Harness; + use texturecraft_engine::Session; + + use super::*; + + fn write_png(path: &std::path::Path, size: u32) { + image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap(); + } + + fn notices(app: &TextureCraftApp) -> usize { + app.toasts.iter().filter(|toast| toast.action == Some(ToastAction::UpdateResources)).count() + } + + #[test] + fn a_changed_file_is_announced_once_and_the_notice_updates_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner); + let path = std::env::temp_dir().join(format!("texturecraft-resources-notice-{}.png", std::process::id())); + write_png(&path, 4); + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); + + check_on_focus(app); + assert_eq!(notices(app), 0, "nothing changed yet"); + + write_png(&path, 8); + check_on_focus(app); + check_on_focus(app); + assert_eq!(notices(app), 1, "the same change is announced once"); + + ToastAction::UpdateResources.run(app); + std::fs::remove_file(&path).ok(); + + assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource"); + assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources")); + } +} diff --git a/crates/ui-egui/src/resources_updater/row_request.rs b/crates/ui-egui/src/resources_updater/row_request.rs new file mode 100644 index 00000000..75f0626c --- /dev/null +++ b/crates/ui-egui/src/resources_updater/row_request.rs @@ -0,0 +1,9 @@ +/// What a Resources Updater row's buttons asked for, run after the window is drawn +pub(super) enum RowRequest { + /// Update: read the resource's file again + Update(String), + /// Select new resource: ask for another file for the resource + SelectNew(String), + /// Show in folder: the folder holding this file + ShowFolder(String), +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..9f49b2e7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -14,11 +14,13 @@ mod import_row; mod library_location; mod project_config; mod resource_usage; +mod resources_updater; pub use import_resources::ImportResources; pub use import_row::ImportRow; pub use library_location::LibraryLocation; pub use project_config::ProjectConfig; pub use resource_usage::ResourceUsage; +pub use resources_updater::ResourcesUpdater; mod console_line; mod export_job; @@ -115,6 +117,9 @@ pub struct Windows { /// File > Import resources: the files added so far, imported by Import. #[serde(skip)] pub import_resources: Option, + /// The Resources Updater: the project's image resources and whether their files changed on disk. + #[serde(skip)] + pub resources_updater: Option, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs new file mode 100644 index 00000000..46fb9d12 --- /dev/null +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -0,0 +1,19 @@ +use texturecraft_engine::{ResourceState, ResourceStatus}; + +/// The Resources Updater window: the project's image resources as last checked, and the filters +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ResourcesUpdater { + /// The resources and how they compare with their files, outdated first (checked on opening, + /// Refresh, every change and when the app gets the focus back) + pub rows: Vec, + /// The status the list is narrowed to (None: all) + pub status_filter: Option, + /// Shows only resources whose name contains this, ignoring case + pub name_filter: String, + /// Top or Bottom asked the list to scroll to that end in the next frame + pub jump: Option, + /// The project that was open when this window opened + pub project: u64, + /// The session revision the rows were checked at + pub(crate) checked_revision: u64, +} diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs new file mode 100644 index 00000000..d360fd7b --- /dev/null +++ b/crates/ui-egui/src/toast_action.rs @@ -0,0 +1,34 @@ +//! A button on a toast that acts on what the toast says + +use crate::TextureCraftApp; + +/// What a toast's button does +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToastAction { + /// "Update": read every outdated resource file again (the "changed on disk" notice) + #[cfg(not(target_arch = "wasm32"))] + UpdateResources, +} + +impl ToastAction { + /// The button's text (English; translated where it is drawn) + pub fn label(self) -> &'static str { + match self { + #[cfg(not(target_arch = "wasm32"))] + ToastAction::UpdateResources => "Update", + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn run(self, app: &mut TextureCraftApp) { + match self { + ToastAction::UpdateResources => crate::resources_updater::update(app, None), + } + } + + /// The browser's toasts carry no action yet + #[cfg(target_arch = "wasm32")] + pub(crate) fn run(self, _: &mut TextureCraftApp) { + match self {} + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 27274a1d..d36f3197 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -499,15 +499,33 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.add_space(SHELF_GROUP_GAP); } - for (icon, label) in [(ic::HOURGLASS, "Snooze Autosave"), (ic::ARROWS_CLOCKWISE, "Resources Updater")] { - ui.add_enabled_ui(false, |ui| icon_button(ui, icon, tr(label), false, SHELF_BUTTON_SIZE)) - .inner - .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); - } + ui.add_enabled_ui(false, |ui| icon_button(ui, ic::HOURGLASS, tr("Snooze Autosave"), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); + resources_updater_button(app, ui); }); }); } +/// The shelf's Resources Updater button: opens or closes its window while a project is open +#[cfg(not(target_arch = "wasm32"))] +fn resources_updater_button(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let open = app.ui.windows.resources_updater.is_some(); + let label = tr("Resources Updater"); + let button = ui.add_enabled_ui(app.session.project_open, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, label, open, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(tr("Open a project to check its resources")).clicked() { + crate::resources_updater::toggle(app); + } +} + +/// The browser reads no files from disk, so there is nothing to update +#[cfg(target_arch = "wasm32")] +fn resources_updater_button(_: &mut TextureCraftApp, ui: &mut egui::Ui) { + ui.add_enabled_ui(false, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Resources Updater"), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); +} + /// Width of the icon rail beside the dock const RAIL_WIDTH: f32 = 38.0; diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f9e8fa5c..5080d2bd 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -23,6 +23,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { { crate::project_config::show(app, ctx); crate::import_resources::show(app, ctx); + crate::resources_updater::show(app, ctx); } crate::keymap::window(app, ctx); crate::export_window::show(app, ctx); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c8d7f0f3..82c21fcc 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -77,6 +77,7 @@ mod rail; mod reference_order; mod rename_anchor; mod reset_ui; +mod resources_updater; mod settings_window; mod shelf_click; mod shelf_drop; diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs new file mode 100644 index 00000000..298c1130 --- /dev/null +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -0,0 +1,137 @@ +//! The Resources Updater window, driven from the keyboard: the shelf button opens it, outdated +//! resources come first, Update reads a changed file again as one undo step and Select new resource +//! follows another file. File pickers are answered by the override, never shown. + +use std::path::{Path, PathBuf}; + +use egui::{Key, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; + +use super::temp_dir::TempDir; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + + h +} + +/// Write a `size` × `size` PNG (each size is a different file size, so a change is seen at once) +fn png(dir: &Path, name: &str, size: u32) -> PathBuf { + let file = dir.join(name); + image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(&file).unwrap(); + + file +} + +fn import(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { + h.state_mut().run("resource.import", json!({ "path": file.to_str().unwrap() })).unwrap(); + h.run_steps(2); +} + +fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) { + h.key_press(key); + h.run_steps(3); +} + +/// Move the keyboard focus to button `label` and press Enter +fn activate(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_role_and_label(Role::Button, label).focus(); + h.run_steps(2); + press(h, Key::Enter); +} + +fn shows(h: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + h.query_by_label(text).is_some() +} + +fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 { + h.state().session.images[name].width +} + +#[test] +fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() { + let dir = TempDir::new("resources-updater-update"); + let (kept, changed) = (png(&dir, "kept.png", 4), png(&dir, "changed.png", 4)); + let mut h = app(); + import(&mut h, &kept); + import(&mut h, &changed); + png(&dir, "changed.png", 8); + + activate(&mut h, "Resources Updater"); + + let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows; + assert_eq!(rows[0].name, "changed.png", "outdated resources come first"); + assert!(shows(&h, "Project : Test")); + assert!(shows(&h, "(2 resources, 1 outdated)")); + assert!(shows(&h, "Outdated"), "the status is written out, not only coloured"); + assert!(h.get_by_role_and_label(Role::Button, "Update kept.png").accesskit_node().is_disabled(), "only outdated resources update"); + + let steps = h.state().session.history_labels().len(); + activate(&mut h, "Update changed.png"); + + assert_eq!(width_of(&h, "changed.png"), 8, "the new file's pixels are in the project"); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step"); + assert!(shows(&h, "(2 resources, 0 outdated)")); + + // Undo brings the old pixels back, so the list shows the file as changed again + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + + assert_eq!(width_of(&h, "changed.png"), 4); + assert!(shows(&h, "(2 resources, 1 outdated)")); + + activate(&mut h, "Update All"); + assert_eq!(width_of(&h, "changed.png"), 8); + + press(&mut h, Key::Escape); + assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window"); +} + +#[test] +fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_list() { + let dir = TempDir::new("resources-updater-relink"); + let (first, second) = (png(&dir, "first.png", 4), png(&dir, "second.png", 4)); + let other = png(&dir, "other.png", 16); + let mut h = app(); + import(&mut h, &first); + import(&mut h, &second); + activate(&mut h, "Resources Updater"); + + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![other.clone()])))); + activate(&mut h, "Select new resource first.png"); + h.run_steps(3); + + assert_eq!(width_of(&h, "first.png"), 16, "the resource keeps its name and takes the chosen file's pixels"); + assert!(h.state().session.doc.project.resource_sources["first.png"].path.ends_with("other.png")); + + h.get_by_role_and_label(Role::TextInput, "Name filter:").focus(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Name filter:").type_text("SEC"); + h.run_steps(3); + + assert!(h.query_by_label("Update first.png").is_none(), "the filter hides other names"); + assert!(h.query_by_label("Update second.png").is_some(), "names match ignoring case"); +} + +#[test] +fn show_in_folder_shows_the_folder_of_the_resource_file() { + let dir = TempDir::new("resources-updater-folder"); + let file = png(&dir, "bricks.png", 4); + let mut h = app(); + import(&mut h, &file); + activate(&mut h, "Resources Updater"); + + activate(&mut h, "Show in folder bricks.png"); + + let shown = h.state().file_dialogs.shown_folders().to_vec(); + assert_eq!(shown.len(), 1); + assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..0cf55589 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -222,7 +222,7 @@ keeps its state in a throwaway file. | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | | `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` | -| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | +| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave button and the Resources Updater button (enabled while a project is open) stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | | `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project. The direct `project.sample` engine command still creates the generated sample for automation. | | `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled | | `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft____.txt` name, a download on the web) | @@ -348,7 +348,8 @@ with `ui.inspect`, update that field and send the full `prefs` object to `ui.set File › Save. Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and -`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in +`file.reimportMesh` without a `path`) is refused, and so are `resource.status`, `resource.update` and `resource.relink` (they read +the files a project names) and any command given a `path` or `dir`, at the top level or in a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. @@ -465,6 +466,23 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para '{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve ``` +## Resources Updater + +An image resource imported with `resource.import {path}` remembers that file (its absolute path and +modification time, saved with the project). The shelf's Resources Updater window lists the project's +image resources through these commands and checks them again when it opens, on Refresh, after every +change and when the app gets the focus back; then a notice ("N resources changed on disk", with an +Update button) appears when the set of outdated resources changed since the last notice. + +| Command | Params and result | +|---|---| +| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | +| `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | +| `resource.relink` | `{name, path}` → `{name, path}`: the resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | + +These commands read host paths stored in the project, so MCP and `serve` refuse them through +`command_run`; the desktop app's control channel and the trusted local CLI run them. + ## PBR texture folders `file.importPbrFolder` turns a folder, a `.zip` or a list of image files of PBR maps into one fill layer diff --git a/docs/features.md b/docs/features.md index 04702ee9..a3692d83 100644 --- a/docs/features.md +++ b/docs/features.md @@ -98,6 +98,13 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and alpha images become the brush alpha. Filter by role or remove selected rows before importing. Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are unavailable. The browser imports images straight from its file picker. +- **Resources Updater:** the shelf button under the tools lists the project's image resources with + their files, outdated ones first. An imported image remembers its file; when that file changes on + disk, *Update* (or *Update All*) reads it again and every layer using it recomposites, as one undo + step. *Select new resource* points a resource at another file, *Show in folder* opens its folder, + and the list filters by status and name. When the app gets the focus back after files changed, a + notice offers *Update*. Desktop only; there is no Shaders tab, since TextureCraft has no shader + resources. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. *Create smart mask* in the same menu saves just the layer's mask (all its effects, painted pixels and images); it appears under From 7a3b95e7982d06e03f7bafbe783327e380a23e0b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:38:08 +0000 Subject: [PATCH 019/190] Export: JPEG 2000 file types, lossless, as a raw codestream (j2k) or a JP2 file (jp2) Encoded by the j2k crate (MIT OR Apache-2.0, pure Rust; craft-image-codecs only reads JPEG 2000), which needs Rust 1.96, so the README asks for 1.96. --- Cargo.lock | 71 +++++++++++++++++++- Cargo.toml | 3 + README.md | 2 +- crates/engine/src/file_cmds.rs | 2 +- crates/formats/Cargo.toml | 2 + crates/formats/src/export/jpeg2000.rs | 54 +++++++++++++++ crates/formats/src/export/mod.rs | 20 +++++- crates/formats/src/export/tests.rs | 71 +++++++++++++++++++- crates/ui-egui/src/export_window.rs | 4 +- crates/ui-egui/tests/it/export_file_types.rs | 21 +++--- docs/control-protocol.md | 2 +- docs/features.md | 2 +- 12 files changed, 228 insertions(+), 26 deletions(-) create mode 100644 crates/formats/src/export/jpeg2000.rs diff --git a/Cargo.lock b/Cargo.lock index d82d26f7..c0494fe8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1832,6 +1832,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "fearless_simd" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599" + [[package]] name = "filetime" version = "0.2.29" @@ -2394,7 +2400,7 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" dependencies = [ - "fearless_simd", + "fearless_simd 0.4.1", ] [[package]] @@ -2760,6 +2766,63 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "j2k" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5dcb93d62c580930297896f25933b034bf665534568626787dbf0f03027e7b0" +dependencies = [ + "j2k-core", + "j2k-native", + "j2k-types", + "moxcms", + "thiserror 2.0.21", +] + +[[package]] +name = "j2k-codec-math" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a38b1ddbaa04c07213dba6180ed1168f0e96bfa35890542c414d872cea0c7d58" +dependencies = [ + "j2k-types", +] + +[[package]] +name = "j2k-core" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae969eb19e9b3a8d65c4342f9921717be407571cc0fbc44e4379daa0b588d01c" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "j2k-native" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "971da314ca1501363f686b6796d309ebbda7d2f88d34671c38d79132f7cb59ff" +dependencies = [ + "fearless_simd 1.3.0", + "j2k-codec-math", + "j2k-profile", + "j2k-types", + "libm", + "rayon", +] + +[[package]] +name = "j2k-profile" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c1c0cc7e85f2ab1cc85c9a6d2bad3680319c0cdf558f3be14b4ccdbd6917fca" + +[[package]] +name = "j2k-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "716edd556741a415294d955121f76d41b7d8d650554fb09f30d0654b15127ac9" + [[package]] name = "jni" version = "0.22.4" @@ -5218,6 +5281,8 @@ dependencies = [ "gltf", "half", "image", + "j2k", + "j2k-core", "png", "quick-xml 0.41.0", "rayon", @@ -5757,7 +5822,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd" dependencies = [ "bytemuck", - "fearless_simd", + "fearless_simd 0.4.1", "guillotiere", "log", "peniko", @@ -7113,7 +7178,7 @@ dependencies = [ "memchr", "nix", "typed-path", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "zeroize", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index de6fc98d..d2a340de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,9 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } half = "2" exr = { version = "1.73", default-features = false } +# JPEG 2000 writing (craft-image-codecs only reads it); j2k 0.13 needs Rust 1.99 +j2k = "0.11.3" +j2k-core = "0.11.3" eframe = { version = "0.37", default-features = false } egui = "0.37" wgpu = "30" diff --git a/README.md b/README.md index 345c32c1..29b1daea 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). +You need Rust 1.96 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). **File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none. Japanese, Chinese, Korean and Arabic interface text uses the fonts of diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 006bb979..d13dbee3 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 516e0f5d..e83f5d56 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -32,6 +32,8 @@ half = { workspace = true } quick-xml = { workspace = true } zip = { workspace = true } exr = { workspace = true } +j2k = { workspace = true } +j2k-core = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/formats/src/export/jpeg2000.rs b/crates/formats/src/export/jpeg2000.rs new file mode 100644 index 00000000..b4c2218e --- /dev/null +++ b/crates/formats/src/export/jpeg2000.rs @@ -0,0 +1,54 @@ +//! JPEG 2000, lossless (reversible 5/3 wavelet): a raw codestream (.j2k) or one in a JP2 file (.jp2) + +use j2k::{ + J2kChannelAssociation, J2kChannelDefinition, J2kChannelType, J2kFileBoxMetadata, J2kFileColorSpec, J2kFileWrapOptions, J2kLosslessEncodeOptions, + J2kLosslessSamples, encode_j2k_lossless, wrap_j2k_codestream, +}; +use j2k_core::Colorspace; + +/// Encode `bytes` (8-bit or native-endian 16-bit L, LA, RGB or RGBA samples) of a `width`×`height` image; `jp2` wraps it in a JP2 file that records `icc` +pub(super) fn write_jpeg2000( + bytes: Vec, + (width, height): (u32, u32), + component_count: usize, + depth: u8, + jp2: bool, + icc: Option<&[u8]>, +) -> Result, String> { + // The encoder reads 16-bit samples little-endian + let bytes = if depth == 16 { bytes.as_chunks::<2>().0.iter().flat_map(|sample| u16::from_ne_bytes(*sample).to_le_bytes()).collect() } else { bytes }; + let components = u16::try_from(component_count).map_err(|_| format!("{component_count} components"))?; + let input = J2kLosslessSamples { data: &bytes, width, height, components, bit_depth: depth, signed: false }; + let codestream = encode_j2k_lossless(input, &J2kLosslessEncodeOptions::default()).map_err(|error| error.to_string())?.codestream; + drop(bytes); + if !jp2 { + return Ok(codestream); + } + + // The last component of LA and RGBA is opacity, for the whole image + let color_count = if component_count >= 3 { 3 } else { 1 }; + let definitions: Vec = (0..components) + .map(|channel_index| { + if channel_index < color_count { + J2kChannelDefinition { + channel_index, + channel_type: J2kChannelType::Color, + association: J2kChannelAssociation::Color { index: channel_index + 1 }, + } + } else { + J2kChannelDefinition { channel_index, channel_type: J2kChannelType::Opacity, association: J2kChannelAssociation::WholeImage } + } + }) + .collect(); + let mut options = J2kFileWrapOptions::jp2(); + options.color = match icc { + Some(profile) if color_count == 3 => J2kFileColorSpec::IccProfile(profile), + _ if color_count == 3 => J2kFileColorSpec::Enumerated(Colorspace::SRgb), + _ => J2kFileColorSpec::Enumerated(Colorspace::Grayscale), + }; + if component_count.is_multiple_of(2) { + options.metadata = J2kFileBoxMetadata { palette: None, component_mappings: &[], channel_definitions: &definitions }; + } + + wrap_j2k_codestream(&codestream, options).map_err(|error| error.to_string()) +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f2134a0c..de1454fc 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -26,6 +26,7 @@ use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; mod encoding; +mod jpeg2000; mod map_override; use encoding::Encoding; pub use map_override::MapOverride; @@ -93,10 +94,14 @@ pub enum FileFormat { Pgm, /// A PSD containing only its merged image. Psd, + /// JPEG 2000 codestream, lossless + J2k, + /// JPEG 2000 in a JP2 file, lossless + Jp2, } impl FileFormat { - pub const ALL: [FileFormat; 11] = [ + pub const ALL: [FileFormat; 13] = [ FileFormat::Png, FileFormat::Jpeg, FileFormat::Tga, @@ -108,6 +113,8 @@ impl FileFormat { FileFormat::Jng, FileFormat::Pgm, FileFormat::Psd, + FileFormat::J2k, + FileFormat::Jp2, ]; pub fn extension(self) -> &'static str { @@ -123,6 +130,8 @@ impl FileFormat { FileFormat::Jng => "jng", FileFormat::Pgm => "pgm", FileFormat::Psd => "psd", + FileFormat::J2k => "j2k", + FileFormat::Jp2 => "jp2", } } @@ -150,7 +159,7 @@ impl FileFormat { /// float for TIFF and HDR). pub fn bit_depths(self) -> &'static [u8] { match self { - FileFormat::Png | FileFormat::Pgm | FileFormat::Psd => &[8, 16], + FileFormat::Png | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2 => &[8, 16], FileFormat::Tiff => &[8, 16, 32], FileFormat::Exr => &[16, 32], FileFormat::Hdr => &[32], @@ -1216,7 +1225,7 @@ fn encode( // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed - && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd) + && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd | FileFormat::J2k) { warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name())); } @@ -1323,6 +1332,11 @@ fn encode( FileFormat::Pgm => CodecFormat::Pnm, FileFormat::Psd => return psd(bytes, size, component_count, depth).map_err(|error| encoding_error(&error)), FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)), + FileFormat::J2k | FileFormat::Jp2 => { + let profile = embed.and_then(crate::icc::profile); + let jp2 = format == FileFormat::Jp2; + return jpeg2000::write_jpeg2000(bytes, size, component_count, depth, jp2, profile.as_deref()).map_err(|error| encoding_error(&error)); + } FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")), }; let layout = match component_count { diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 392148a1..45312b0d 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -366,8 +366,9 @@ fn every_format_encodes_and_decodes() { let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); preset.maps.push(gray_alpha); - // JNG, PGM and PSD have tests of their own (the image crate reads none of them) - for format in FileFormat::ALL.into_iter().filter(|f| !matches!(f, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd)) { + // JNG, PGM, PSD and JPEG 2000 have tests of their own (the image crate reads none of them) + let own_tests = |format: &FileFormat| matches!(format, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2); + for format in FileFormat::ALL.into_iter().filter(|format| !own_tests(format)) { for &depth in format.bit_depths() { let mut opts = ExportOptions::new(preset.clone()); opts.format_override = Some(format); @@ -917,7 +918,7 @@ fn exr_carries_the_chromaticities_of_the_space() { #[test] fn formats_without_a_place_for_a_colour_space_say_so() { let data = vec![0.25f32; 4 * 4 * 3]; - for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr] { + for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr, FileFormat::J2k] { let mut warnings = Vec::new(); encode(Encoding { format, depth: 8, dither: false }, (4, 4), 3, data.clone(), &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap(); assert!(warnings.iter().any(|w| w.contains("colour space") && w.contains("ACEScg")), "{format:?}: {warnings:?}"); @@ -1245,6 +1246,70 @@ fn jng_has_jpeg_colour_and_lossless_alpha() { assert!(!gray.bytes.windows(4).any(|w| w == b"IDAT")); } +/// A JPEG 2000 file's component planes +fn jpeg2000_planes(bytes: &[u8]) -> Vec> { + let mut decoder = j2k::J2kDecoder::new(bytes).unwrap(); + let decoded = decoder.decode_native_components().unwrap(); + decoded + .planes() + .iter() + .map(|plane| match plane.bytes_per_sample() { + 1 => plane.data().iter().map(|byte| u16::from(*byte)).collect(), + _ => plane.data().chunks(2).map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect(), + }) + .collect() +} + +#[test] +fn jpeg2000_is_lossless_at_8_and_16_bits() { + let fx = Fx::new(&[Channel::BaseColor, Channel::Opacity, Channel::Roughness, Channel::Metallic, Channel::Normal]); + let preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); + let jp2_signature = [0, 0, 0, 12, b'j', b'P', b' ', b' ']; + let codestream_signature = [0xFF, 0x4F, 0xFF, 0x51]; + for depth in [8u8, 16] { + let mut png_options = ExportOptions::new(preset.clone()); + png_options.bit_depth_override = Some(depth); + let png = fx.render(&png_options); + for format in [FileFormat::J2k, FileFormat::Jp2] { + let mut options = png_options.clone(); + options.format_override = Some(format); + let files = fx.render(&options); + assert_eq!(files.len(), png.len()); + + for (file, reference) in files.iter().zip(&png) { + assert!(file.name.ends_with(format.extension()), "{}", file.name); + let signature: &[u8] = if format == FileFormat::Jp2 { &jp2_signature } else { &codestream_signature }; + assert!(file.bytes.starts_with(signature), "{}", file.name); + + // Every sample is the PNG's, with alpha the last component + let image = decode(reference); + let components = usize::from(image.color().channel_count()); + let expected = image.to_rgba16(); + let planes = jpeg2000_planes(&file.bytes); + assert_eq!(planes.len(), components, "{}", file.name); + for (component, plane) in planes.iter().enumerate() { + let source = if components <= 2 && component == 1 { 3 } else { component }; + for (texel, sample) in expected.pixels().zip(plane) { + let want = if depth == 8 { texel[source] / 257 } else { texel[source] }; + assert_eq!(*sample, want, "{} component {component}", file.name); + } + } + } + } + } +} + +#[test] +fn jp2_records_a_chosen_colour_space_as_an_icc_profile() { + let data = vec![0.25f32; 8 * 8 * 3]; + let profile = crate::icc::profile(ColorSpace::AcesCg).unwrap(); + let mut warnings = Vec::new(); + let bytes = + encode(Encoding { format: FileFormat::Jp2, depth: 8, dither: false }, (8, 8), 3, data, &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap(); + assert!(bytes.windows(profile.len()).any(|window| window == profile.as_slice()), "the profile is in the file"); + assert!(warnings.is_empty(), "{warnings:?}"); +} + #[test] fn tiff_32f_holds_linear_floats() { let fx = Fx::new(&default_channels()); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 6a46f757..c4a07d5f 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -81,8 +81,8 @@ pub(crate) const FILE_TYPES: [(&str, Option); 14] = [ ("tiff", Some(FileFormat::Tiff)), ("hdr", Some(FileFormat::Hdr)), ("exr", Some(FileFormat::Exr)), - ("j2k", None), - ("jp2", None), + ("j2k", Some(FileFormat::J2k)), + ("jp2", Some(FileFormat::Jp2)), ("webp", Some(FileFormat::Webp)), ("psd", Some(FileFormat::Psd)), ("sbsar", None), diff --git a/crates/ui-egui/tests/it/export_file_types.rs b/crates/ui-egui/tests/it/export_file_types.rs index 8967fe80..a1a020eb 100644 --- a/crates/ui-egui/tests/it/export_file_types.rs +++ b/crates/ui-egui/tests/it/export_file_types.rs @@ -46,22 +46,21 @@ fn entries(h: &Harness<'_, TextureCraftApp>, labels: &[&str]) -> Vec { const TYPES: [&str; 14] = ["bmp", "jpeg", "jng", "pgm", "png", "targa", "tiff", "hdr", "exr", "j2k", "jp2", "webp", "psd", "sbsar"]; #[test] -fn the_file_type_list_is_the_reference_one_with_three_greyed() { +fn the_file_type_list_is_the_reference_one_with_sbsar_greyed() { let mut h = harness(); open_combo(&mut h, "Based on output template"); assert_eq!(entries(&h, &TYPES), TYPES.map(String::from).to_vec()); - // Bottom up, so no tooltip covers the next entry - for name in ["sbsar", "jp2", "j2k"] { - assert!(h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} is greyed"); - h.get_all_by_label(name).last().unwrap().scroll_to_me(); - h.run_steps(6); - let at = h.get_all_by_label(name).last().unwrap().rect().center(); - h.hover_at(at); - h.run_steps(30); - assert!(h.query_by_label("Not available yet").is_some(), "{name} at {at:?}"); + assert!(h.get_all_by_label("sbsar").last().unwrap().accesskit_node().is_disabled(), "sbsar is greyed"); + h.get_all_by_label("sbsar").last().unwrap().scroll_to_me(); + h.run_steps(6); + let at = h.get_all_by_label("sbsar").last().unwrap().rect().center(); + h.hover_at(at); + h.run_steps(30); + assert!(h.query_by_label("Not available yet").is_some(), "sbsar at {at:?}"); + for name in ["j2k", "jp2", "psd"] { + assert!(!h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} can be picked"); } - assert!(!h.get_all_by_label("psd").last().unwrap().accesskit_node().is_disabled()); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..c3a44fc8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -74,7 +74,7 @@ and names it in `warnings`. Materials omit any map with incomplete tiles or a UD shared by different sets. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, -`hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for +`hdr`, `exr`, `j2k`, `jp2`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and `export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. diff --git a/docs/features.md b/docs/features.md index 42ea07a6..3da74d2d 100644 --- a/docs/features.md +++ b/docs/features.md @@ -164,7 +164,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in - PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 + PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. - **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion, From c561a0578fcaac25490603bdb005f35d6efdddde Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:44:12 +0000 Subject: [PATCH 020/190] Export: PSD file type writes every output map of a texture set as a layer of one file The layers and the merged image are written with craft-psd's PsdBuilder. The USD asset and MaterialX leave the PSD out (with a warning for the USD asset). --- crates/engine/src/file_cmds.rs | 19 +- crates/engine/tests/it/materialx.rs | 4 +- crates/engine/tests/it/usd_asset.rs | 13 + crates/formats/src/export/layered_psd.rs | 112 +++++++ crates/formats/src/export/map_renderer.rs | 149 +++++++++ crates/formats/src/export/mod.rs | 370 +++++++++------------ crates/formats/src/export/planned_layer.rs | 10 + crates/formats/src/export/rendered_map.rs | 13 + crates/formats/src/export/tests.rs | 130 +++++--- crates/formats/src/mesh_export/usd.rs | 10 +- crates/ui-egui/src/export_templates.rs | 21 +- crates/ui-egui/src/export_window.rs | 44 ++- 12 files changed, 608 insertions(+), 287 deletions(-) create mode 100644 crates/formats/src/export/layered_psd.rs create mode 100644 crates/formats/src/export/map_renderer.rs create mode 100644 crates/formats/src/export/planned_layer.rs create mode 100644 crates/formats/src/export/rendered_map.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d13dbee3..70194399 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)", + "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name and warns about later duplicates)", always, plan ), @@ -457,6 +457,7 @@ fn plan(session: &mut Session, params: &Value) -> Result { "size": size, "sourceSize": source_size, "warnings": output.warnings, + "layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::>(), })); } } @@ -763,7 +764,7 @@ fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, s /// warning: the textures of the command are already written. #[cfg(not(target_arch = "wasm32"))] fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Option { - match build_usd_asset(session, dir, exports) { + match build_usd_asset(session, dir, exports, warnings) { Ok(path) => Some(path), Err(error) => { warnings.push(format!("{USD_ASSET_FAILED}: {error}")); @@ -773,7 +774,7 @@ fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset } #[cfg(not(target_arch = "wasm32"))] -fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result { +fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Result { use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings}; let project = &session.doc.project; let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); @@ -794,6 +795,12 @@ fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset // A map that lost any file (a tile of a UDIM map) is not bound: its `` name would read a file it does not own kept.retain(|file| !skipped_maps.contains(&file.map)); + if kept.iter().any(|file| file.format == FileFormat::Psd) { + let warning = format!("The USD asset doesn't read PSD files, so the material of texture set \"{}\" leaves out its PSD maps", texture_set.name); + if !warnings.contains(&warning) { + warnings.push(warning); + } + } by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept)); } } @@ -841,7 +848,7 @@ fn reserve_export_names( plans.retain(|plan| { let name = plan.name.to_ascii_lowercase(); if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) { - blocked_maps.insert(plan.map); + blocked_maps.extend(plan.maps()); warnings.push(format!( "\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names", plan.name @@ -854,7 +861,7 @@ fn reserve_export_names( return true; } - blocked_maps.insert(plan.map); + blocked_maps.extend(plan.maps()); if fallback { warnings.push(format!( "MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names", diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index b69391bd..3f6ba0a9 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -197,8 +197,10 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() { ) .unwrap(); + // A PSD holds every map of the texture set as a layer let all = names(&result); - assert!(all.iter().any(|f| f.ends_with(&format!("_baseColor.{ext}"))), "{format}: the template's files keep the file type: {all:?}"); + let template_file = if format == "psd" { ".psd".to_string() } else { format!("_baseColor.{ext}") }; + assert!(all.iter().any(|f| f.ends_with(&template_file)), "{format}: the template's files keep the file type: {all:?}"); let mtlx = files(&result).into_iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("{format}: no .mtlx in {all:?}")); let text = std::fs::read_to_string(mtlx).unwrap(); let wanted = if format == "tiff" { "tif" } else { "png" }; diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index e6ef7bd9..a370c7e1 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -407,3 +407,16 @@ fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { assert!(dir.join(&read.file).is_file(), "{} was written", read.file); } } + +#[test] +fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() { + let mut s = ball(); + let dir = temp("psd"); + + let r = export(&mut s, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true})); + + assert!(files(&r).iter().any(|f| f.ends_with(".psd")), "{r}"); + let materials = read_back(&s, &dir); + assert!(materials[material_of(&s, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&s, 0)]); + assert!(r["warnings"].to_string().contains("doesn't read PSD files"), "{r}"); +} diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs new file mode 100644 index 00000000..e90f8e6e --- /dev/null +++ b/crates/formats/src/export/layered_psd.rs @@ -0,0 +1,112 @@ +//! A texture set's PSD: each output map a layer, a `/` in its name a layer group + +use craft_psd::{Compression, GroupSpec, LayerSpec, PixelData, PsdBuilder}; +use texturecraft_texel::linear_to_srgb; + +use super::encoding::Encoding; +use super::map_renderer::MapRenderer; +use super::{ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, PlannedFile, quantize_integer}; +use crate::{FormatError, Result}; + +/// Where alpha sits in an RGBA texel +const ALPHA_INDEX: usize = 3; + +/// Render the layers of `planned` one at a time and write them as one PSD +pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile) -> Result { + let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned; + let size = renderer.size(tile)?; + + // Each layer as straight RGBA in 0-1, sRGB-encoded where the map's file would be, dropped once quantized + let mut composite = vec![0.0f32; size.0 as usize * size.1 as usize * PSD_RGBA_PLANES]; + let mut pixels = Vec::with_capacity(layers.len()); + let mut embedded = None; + for layer in layers.iter().rev() { + let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; + embedded = map.embed.or(embedded); + let rgba = to_rgba(&map.data, map.component_count, &map.srgb); + drop(map); + over(&mut composite, &rgba); + let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; + let bytes = quantize_integer(encoding, size.0, PSD_RGBA_PLANES, rgba.into_iter())?; + pixels.push((layer.name.as_str(), pixel_data(bytes, bit_depth))); + } + if let Some(space) = embedded { + warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name())); + } + + let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: false }; + let composite = pixel_data(quantize_integer(encoding, size.0, PSD_RGBA_PLANES, composite.into_iter())?, bit_depth); + + let bytes = write_layers(size, bit_depth, pixels, composite).map_err(|error| FormatError::Invalid(format!("psd encoding failed: {error}")))?; + if bytes.len() as u64 >= PSD_MAX_FILE_BYTES { + return Err(FormatError::Invalid(format!("\"{name}\" would reach the 2 GiB PSD file limit; use a smaller export size or fewer PSD maps"))); + } + + Ok(ExportedFile { name, bytes, width: size.0, height: size.1, warnings }) +} + +/// L, LA, RGB or RGBA samples as RGBA (gray repeated, opaque without alpha), sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 +fn to_rgba(data: &[f32], component_count: usize, srgb: &[bool]) -> Vec { + let encode = |component: usize, value: f32| if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }; + data.chunks_exact(component_count.max(1)) + .flat_map(|texel| { + let encoded = |component| encode(component, texel.get(component).copied().unwrap_or(0.0)); + match component_count { + 1 => [encoded(0), encoded(0), encoded(0), 1.0], + 2 => [encoded(0), encoded(0), encoded(0), encoded(1)], + 3 => [encoded(0), encoded(1), encoded(2), 1.0], + _ => [encoded(0), encoded(1), encoded(2), encoded(3)], + } + }) + .collect() +} + +/// Lay straight-alpha RGBA `layer` over `below`, in place +fn over(below: &mut [f32], layer: &[f32]) { + for (under, top) in below.as_chunks_mut::().0.iter_mut().zip(layer.as_chunks::().0) { + let (top_alpha, under_alpha) = (top[ALPHA_INDEX], under[ALPHA_INDEX]); + let alpha = top_alpha + under_alpha * (1.0 - top_alpha); + if alpha <= 0.0 { + continue; + } + + for (value, top_value) in under.iter_mut().zip(top).take(ALPHA_INDEX) { + *value = (top_value * top_alpha + *value * under_alpha * (1.0 - top_alpha)) / alpha; + } + under[ALPHA_INDEX] = alpha; + } +} + +/// Native-endian quantized RGBA samples as the PSD builder takes them +fn pixel_data(bytes: Vec, depth: u8) -> PixelData { + if depth == 16 { PixelData::Rgba16(bytes.as_chunks::<2>().0.iter().map(|sample| u16::from_ne_bytes(*sample)).collect()) } else { PixelData::Rgba8(bytes) } +} + +/// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front +pub(super) fn write_layers((width, height): (u32, u32), depth: u8, layers: Vec<(&str, PixelData)>, composite: PixelData) -> craft_psd::Result> { + let mut builder = PsdBuilder::new(width, height).depth(u16::from(depth)).compression(Compression::Raw); + + // The builder stacks bottom up, so the groups open and close in that order too + let mut open: Vec<&str> = Vec::new(); + for (path, pixels) in layers { + let mut parts: Vec<&str> = path.split('/').collect(); + let name = parts.pop().unwrap_or_default(); + let shared = open.iter().zip(&parts).take_while(|(open, part)| open == part).count(); + for _ in shared..open.len() { + builder.end_group()?; + } + open.truncate(shared); + for group in parts.iter().skip(shared) { + builder.begin_group(GroupSpec::new(*group)); + open.push(group); + } + + builder.push_layer(LayerSpec::new(name, 0, 0, width, height, pixels)); + } + for _ in open { + builder.end_group()?; + } + + builder.composite(composite); + builder.to_bytes() +} diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs new file mode 100644 index 00000000..c19064c5 --- /dev/null +++ b/crates/formats/src/export/map_renderer.rs @@ -0,0 +1,149 @@ +use rayon::prelude::*; +use texturecraft_core::{TextureSet, TileGrid}; +use texturecraft_texel::{ColorSpace, DilationMap}; + +use super::rendered_map::RenderedMap; +use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Padding, Sampler, diffuse_blocks, layout, resize, scale_export_side, tile_side}; +use crate::{FormatError, MAX_IMAGE_SIZE, Result}; + +/// Renders the output maps of one texture set's export: the padding and sampling every map shares +pub(super) struct MapRenderer<'a> { + options: &'a ExportOptions, + set: &'a TextureSet, + sampler: Sampler<'a>, + dilation_map: Option, + grid: Option, + /// The composite's size + width: u32, + height: u32, + /// Texels per atlas block (the width for a set without UV tiles) + tile_res: u32, +} + +impl<'a> MapRenderer<'a> { + pub(super) fn new(input: &ExportInput<'a>, options: &'a ExportOptions) -> Result> { + let set = input.project.texture_set(input.ts)?; + let (width, height) = (input.composite.resolution, input.composite.height); + let grid = set.tile_grid(); + let tile_res = width / grid.map_or(1, |g| g.cols.max(1)); + if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { + return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); + } + + if input.coverage.len() != width as usize * height as usize { + return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len()))); + } + + // Padding stays inside each UV tile + let dilation_map = match options.padding { + Padding::None => None, + Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { + Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) + } + Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), + }; + let sampler = Sampler { + set, + comp: input.composite, + baked: input.baked, + coverage: input.coverage, + res: width, + tile_res, + scales: set.block_scales(), + normal_override: options.normal_format, + project_normal: input.project.normal_format, + }; + Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) + } + + /// The export size of a file of `tile` (None: the whole set). + pub(super) fn size(&self, tile: Option) -> Result<(u32, u32)> { + let (_, _, w, h) = self.region(tile)?; + + // An atlas scales by the requested size per tile + let scale = |value| scale_export_side(value, self.tile_res, self.options.size); + Ok((scale(w), scale(h))) + } + + /// The composite texels a file of `tile` covers: one tile, or the whole set + fn region(&self, tile: Option) -> Result<(u32, u32, u32, u32)> { + match (tile, self.grid) { + (Some(t), Some(g)) => { + let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; + + // A tile smaller than its block fills the block's top-left corner + let side = tile_side(self.set, t, self.tile_res); + Ok((bx * self.tile_res, by * self.tile_res, side, side)) + } + _ => Ok((0, 0, self.width, self.height)), + } + } + + /// Map `map_index` of the preset for `tile`, as `format` at `bit_depth` holds it + pub(super) fn render(&self, map_index: usize, tile: Option, format: FileFormat, bit_depth: u8) -> Result { + let options = self.options; + let map = options.preset.maps.get(map_index).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?; + let channel_layout = layout(self.set, map); + let component_count = channel_layout.len(); + let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); + let (x0, y0, w, h) = self.region(tile)?; + let size = self.size(tile)?; + let sampler = &self.sampler; + let dilation_map = self.dilation_map.as_ref(); + let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); + + let mut data = vec![0.0f32; w as usize * h as usize * component_count]; + data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { + let y = y0 + row_y as u32; + for (column, x) in (x0..x0 + w).enumerate() { + let at = if sampler.covered(x, y) { + Some(At::Texel(x, y)) + } else { + match dilation_map.and_then(|d| d.source(x, y)) { + Some((sx, sy)) => Some(At::Texel(sx, sy)), + None => beyond_default.then_some(At::Default), + } + }; + let Some(at) = at else { continue }; + let mut cache = None; + for (component, (_, source)) in channel_layout.iter().enumerate() { + if let Some(value) = row.get_mut(column * component_count + component) { + let sample = sampler.sample(source, at, &mut cache); + *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; + } + } + } + }); + + // Diffuse into the texels the dilation did not reach + if matches!(options.padding, Padding::DilationDiffusion(_)) { + let known: Vec = (y0..y0 + h) + .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) + .map(|(x, y)| sampler.covered(x, y) || dilation_map.is_some_and(|d| d.source(x, y).is_some())) + .collect(); + + // Keep diffusion within each UV tile when rendering an atlas + let block = if tile.is_none() && self.grid.is_some() { self.tile_res } else { w.max(h) }; + diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, block as usize); + } + + let mut data = resize(data, (w, h), component_count, size); + + // Integer sRGB converts in `encode`; other color spaces convert here + let space = options.space_for_map(map, format, bit_depth); + let float = format.holds_float(bit_depth); + let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709; + if convert { + data.par_chunks_mut(component_count).for_each(|px| { + if let [r, g, b, ..] = px { + [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); + } + }); + } + let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); + + // A colour space the user chose is written into the colour maps (data maps have none) + let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space); + Ok(RenderedMap { data, size, component_count, srgb, embed }) + } +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index de1454fc..6a07413e 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -21,15 +21,21 @@ use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; +use texturecraft_texel::{ColorSpace, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; mod encoding; mod jpeg2000; +mod layered_psd; mod map_override; +mod map_renderer; +mod planned_layer; +mod rendered_map; use encoding::Encoding; pub use map_override::MapOverride; +use map_renderer::MapRenderer; +pub use planned_layer::PlannedLayer; /// Height-to-normal slope: with strength 1, a height change of 1 across 1/16 of the texture /// width tilts the normal 45°, at any resolution. @@ -37,6 +43,8 @@ const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// Planes of a PSD image or layer: red, green, blue and alpha +const PSD_RGBA_PLANES: usize = 4; /// Preset limits (user presets are untrusted JSON). const MAX_MAPS: usize = 64; const MAX_TEMPLATE: usize = 256; @@ -92,7 +100,7 @@ pub enum FileFormat { Jng, /// Portable graymap (binary). Pgm, - /// A PSD containing only its merged image. + /// Photoshop document: every output map of a texture set in this format as a layer of one file Psd, /// JPEG 2000 codestream, lossless J2k, @@ -517,6 +525,16 @@ pub struct PlannedFile { /// covers every tile refers to); None when the file isn't tiled. pub udim_name: Option, pub warnings: Vec, + /// A PSD's output maps, top layer first (`map` is the first); empty for a file of one map + pub layers: Vec, +} + +impl PlannedFile { + /// The output maps the file writes + pub fn maps(&self) -> impl Iterator + '_ { + let own = self.layers.is_empty().then_some(self.map); + own.into_iter().chain(self.layers.iter().map(|layer| layer.map)) + } } // --------------------------------------------------------------------------------------------- @@ -592,8 +610,7 @@ pub fn sanitize_file_path(s: &str) -> String { s.split('/').map(sanitize_file_stem).collect::>().join("/") } -/// The files `opts` produces for texture set `ts`, without rendering (for the export dialog). -/// Template variables: [`FILE_TOKENS`]. +/// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { opts.preset.validate()?; let set = project.texture_set(ts)?; @@ -607,9 +624,10 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let mut active_files = BTreeSet::new(); let mut active_dirs = BTreeSet::new(); let mut out = Vec::new(); + + // Maps written as PSD layers, with their tile, bit depth and warnings + let mut psd_layers: Vec<(Option, PlannedLayer, u8, Vec)> = Vec::new(); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; - let grid = set.tile_grid(); - let block_resolution = set.block_resolution(); for (i, map) in opts.preset.maps.iter().enumerate() { if !map.channels.iter().any(|(_, s)| source_present(set, s)) { continue; @@ -619,7 +637,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let format = own.and_then(|o| o.format).or(opts.format_override).unwrap_or(map.format); let bit_depth = format.depth(own.and_then(|o| o.bit_depth).or(opts.bit_depth_override).unwrap_or(map.bit_depth)); let enabled = own.is_none_or(|o| o.enabled); - let psd_channels = (enabled && format == FileFormat::Psd).then(|| layout(set, map).len()); let dither = bit_depth == 8 && !format.holds_float(bit_depth) && own.and_then(|o| o.dither).unwrap_or(opts.dither); let space = opts.space_for_map(map, format, bit_depth); let requested_space = opts.space_for_depth(format, bit_depth); @@ -636,25 +653,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export // Append `$udim` to names for separate UV tiles let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; for &tile in &tiles { - if let Some(channels) = psd_channels { - let size = match (tile, grid) { - (Some(tile), Some(_)) => { - let side = tile_side(set, tile, block_resolution); - let side = scale_export_side(side, block_resolution, opts.size); - (side, side) - } - (_, Some(grid)) => { - let side = opts.size.unwrap_or(block_resolution); - (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) - } - (_, None) => { - let side = opts.size.unwrap_or(block_resolution); - (side, side) - } - }; - check_psd_size(size, channels, bit_depth)?; - } - // A name of the project, mesh or texture set never adds a folder let no_folder = |name: &str| name.replace('/', "_"); let stem = template @@ -678,7 +676,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export }); let stem = sanitize_file_path(&stem); let ext = format.extension(); - let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); if color_map && format == FileFormat::Pgm @@ -698,51 +695,123 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export format.extension().to_uppercase() )); } + let packs_colour = |name: &str| { + (color_map && requested_space != space) + .then(|| format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())) + }; - // Compare names case-insensitively for Windows and macOS - let mut k = 2; - while used.contains(&name.to_ascii_lowercase()) { - name = format!("{stem}_{k}.{ext}"); - k += 1; + // The PSD's own name holds the tile number, so its layers are named without the one appended + if format == FileFormat::Psd { + if enabled { + let appended = tile.filter(|_| template != map.file).map(|number| format!(".{number}")); + let name = appended.as_deref().and_then(|suffix| stem.strip_suffix(suffix)).unwrap_or(&stem).to_string(); + warnings.extend(packs_colour(&name)); + psd_layers.push((tile, PlannedLayer { map: i, name, dither }, bit_depth, warnings)); + } + continue; } - if k > 2 { - warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); - } - let lower = name.to_ascii_lowercase(); - used.insert(lower.clone()); + + let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); if !enabled { continue; } - if active_dirs.contains(&lower) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); - } - let mut prefix = lower.as_str(); - while let Some((folder, _)) = prefix.rsplit_once('/') { - if active_files.contains(folder) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); - } - active_dirs.insert(folder.to_owned()); - prefix = folder; - } - active_files.insert(lower); - - if color_map && requested_space != space { - warnings.push(format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())); - } + claim_path(&mut active_files, &mut active_dirs, &name)?; + warnings.extend(packs_colour(&name)); // Use a UDIM name only when substituting its tile recovers the output name // Truncation or literal placeholder text can make that substitution ambiguous - let udim_name = token_stem.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)).map(|t| { - let renamed = if k > 2 { format!("_{}", k - 1) } else { String::new() }; - format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "") - }); - out.push(PlannedFile { name, map: i, format, bit_depth, dither, tile, udim_name, warnings }); + let udim_name = token_stem + .filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)) + .map(|t| format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "")); + out.push(PlannedFile { name, map: i, format, bit_depth, dither, tile, udim_name, warnings, layers: Vec::new() }); } } + + // Each tile's PSD maps are the layers of one file named after the texture set + let psd_stem = sanitize_file_stem(&format!("{mesh_name}_{}", set.name)); + for &tile in &tiles { + let in_tile: Vec<_> = psd_layers.iter().filter(|(layer_tile, ..)| *layer_tile == tile).collect(); + let Some((_, first, ..)) = in_tile.first() else { continue }; + + let bit_depth = in_tile.iter().map(|(_, _, depth, _)| *depth).max().unwrap_or(8); + let folder_count: usize = in_tile.iter().map(|(_, layer, ..)| layer.name.matches('/').count()).sum(); + check_psd_size(psd_size(set, tile, opts.size), in_tile.len(), folder_count, bit_depth)?; + + let mut warnings: Vec = Vec::new(); + for warning in in_tile.iter().flat_map(|(.., layer_warnings)| layer_warnings) { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } + let stem = sanitize_file_stem(&tile.map_or_else(|| psd_stem.clone(), |number| format!("{psd_stem}.{number}"))); + let ext = FileFormat::Psd.extension(); + let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); + claim_path(&mut active_files, &mut active_dirs, &name)?; + let udim_name = tile.filter(|number| stem == format!("{psd_stem}.{number}")).map(|_| format!("{psd_stem}.{renamed}.{ext}")); + let layers: Vec = in_tile.iter().map(|(_, layer, ..)| layer.clone()).collect(); + let dither = layers.iter().any(|layer| layer.dither); + out.push(PlannedFile { name, map: first.map, format: FileFormat::Psd, bit_depth, dither, tile, udim_name, warnings, layers }); + } Ok(out) } +/// `stem.ext`, or `stem_2.ext`… when an earlier file has the name ignoring case (as Windows and macOS file systems do): the name and the suffix added +fn unique_name(used: &mut BTreeSet, stem: &str, ext: &str, warnings: &mut Vec) -> (String, String) { + let mut name = format!("{stem}.{ext}"); + let mut renamed = String::new(); + let mut k = 2; + while used.contains(&name.to_ascii_lowercase()) { + renamed = format!("_{k}"); + name = format!("{stem}{renamed}.{ext}"); + k += 1; + } + if !renamed.is_empty() { + warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); + } + + used.insert(name.to_ascii_lowercase()); + (name, renamed) +} + +/// Record exported file `name` and its folders, refusing a name that is already a folder or a folder that is already a file, ignoring case +fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: &str) -> Result<()> { + let lower = name.to_ascii_lowercase(); + if dirs.contains(&lower) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); + } + + let mut prefix = lower.as_str(); + while let Some((folder, _)) = prefix.rsplit_once('/') { + if files.contains(folder) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); + } + dirs.insert(folder.to_owned()); + prefix = folder; + } + files.insert(lower); + Ok(()) +} + +/// The size of a texture set's PSD for `tile` (None: the whole set, an atlas of a UV-tiled one) +fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u32, u32) { + let block_resolution = set.block_resolution(); + match (tile, set.tile_grid()) { + (Some(tile), Some(_)) => { + let side = scale_export_side(tile_side(set, tile, block_resolution), block_resolution, export_size); + (side, side) + } + (_, Some(grid)) => { + let side = export_size.unwrap_or(block_resolution); + (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) + } + (_, None) => { + let side = export_size.unwrap_or(block_resolution); + (side, side) + } + } +} + /// Plan a selection in export order, keeping only the first case-insensitive use of a name. pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { let mut files = Vec::new(); @@ -906,137 +975,23 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result) -> Result> { - let set = input.project.texture_set(input.ts)?; - let (width, height) = (input.composite.resolution, input.composite.height); - let grid = set.tile_grid(); - let tile_res = width / grid.map_or(1, |g| g.cols.max(1)); - if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { - return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); - } - - if input.coverage.len() != width as usize * height as usize { - return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len()))); - } - if planned.is_empty() { return Ok(Vec::new()); } - // Padding stays inside each UV tile - let dilation_map = match options.padding { - Padding::None => None, - Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { - Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) - } - Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), - }; - let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); - let diffuse = matches!(options.padding, Padding::DilationDiffusion(_)); - let sampler = Sampler { - set, - comp: input.composite, - baked: input.baked, - coverage: input.coverage, - res: width, - tile_res, - scales: set.block_scales(), - normal_override: options.normal_format, - project_normal: input.project.normal_format, - }; - + let renderer = MapRenderer::new(input, options)?; planned .into_iter() .map(|planned_file| { - let map = options.preset.maps.get(planned_file.map).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?; - let channel_layout = layout(set, map); - let component_count = channel_layout.len(); - let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); - - // The texels written: one tile, or the whole set - let (x0, y0, w, h) = match (planned_file.tile, grid) { - (Some(t), Some(g)) => { - let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; - - // A tile smaller than its block fills the block's top-left corner - let side = tile_side(set, t, tile_res); - (bx * tile_res, by * tile_res, side, side) - } - _ => (0, 0, width, height), - }; - - // An atlas scales by the requested size per tile - let scale = |value| scale_export_side(value, tile_res, options.size); - let size = (scale(w), scale(h)); if planned_file.format == FileFormat::Psd { - check_psd_size(size, component_count, planned_file.bit_depth)?; + return layered_psd::render_psd(&renderer, planned_file); } - let mut data = vec![0.0f32; w as usize * h as usize * component_count]; - data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { - let y = y0 + row_y as u32; - for (column, x) in (x0..x0 + w).enumerate() { - let at = if sampler.covered(x, y) { - Some(At::Texel(x, y)) - } else { - match dilation_map.as_ref().and_then(|d| d.source(x, y)) { - Some((sx, sy)) => Some(At::Texel(sx, sy)), - None => beyond_default.then_some(At::Default), - } - }; - let Some(at) = at else { continue }; - let mut cache = None; - for (component, (_, source)) in channel_layout.iter().enumerate() { - if let Some(value) = row.get_mut(column * component_count + component) { - let sample = sampler.sample(source, at, &mut cache); - *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; - } - } - } - }); - - // Diffuse into the texels the dilation did not reach - if diffuse { - let known: Vec = (y0..y0 + h) - .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) - .map(|(x, y)| sampler.covered(x, y) || dilation_map.as_ref().is_some_and(|d| d.source(x, y).is_some())) - .collect(); - - // Keep diffusion within each UV tile when rendering an atlas - let block = if planned_file.tile.is_none() && grid.is_some() { tile_res } else { w.max(h) }; - diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, block as usize); - } - - let mut data = resize(data, (w, h), component_count, size); - - // Integer sRGB converts in `encode`; other color spaces convert here - let space = options.space_for_map(map, planned_file.format, planned_file.bit_depth); - let float = planned_file.format.holds_float(planned_file.bit_depth); - let rgb = component_count >= 3; + let map = renderer.render(planned_file.map, planned_file.tile, planned_file.format, planned_file.bit_depth)?; let mut warnings = planned_file.warnings; - let color_map = map.is_color(); - let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709; - - if convert { - data.par_chunks_mut(component_count).for_each(|px| { - if let [r, g, b, ..] = px { - [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); - } - }); - } - let srgb: Vec = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); - - // A colour space the user chose is written into the colour maps (data maps have none) - let embed = (options.color_space.is_some() && color_map && rgb).then_some(space); - let bytes = encode( - Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither }, - size, - component_count, - data, - &srgb, - embed, - &mut warnings, - )?; - Ok(ExportedFile { name: planned_file.name, bytes, width: size.0, height: size.1, warnings }) + let encoding = Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither }; + let bytes = encode(encoding, map.size, map.component_count, map.data, &map.srgb, map.embed, &mut warnings)?; + Ok(ExportedFile { name: planned_file.name, bytes, width: map.size.0, height: map.size.1, warnings }) }) .collect() } @@ -1225,7 +1180,7 @@ fn encode( // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed - && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd | FileFormat::J2k) + && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::J2k) { warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name())); } @@ -1330,7 +1285,6 @@ fn encode( FileFormat::Bmp => CodecFormat::Bmp, FileFormat::Webp => CodecFormat::WebP, FileFormat::Pgm => CodecFormat::Pnm, - FileFormat::Psd => return psd(bytes, size, component_count, depth).map_err(|error| encoding_error(&error)), FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)), FileFormat::J2k | FileFormat::Jp2 => { let profile = embed.and_then(crate::icc::profile); @@ -1338,6 +1292,7 @@ fn encode( return jpeg2000::write_jpeg2000(bytes, size, component_count, depth, jp2, profile.as_deref()).map_err(|error| encoding_error(&error)); } FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")), + FileFormat::Psd => return Err(encoding_error(&"a PSD holds the layers of several maps (`layered_psd`)")), }; let layout = match component_count { 1 => ChannelLayout::Gray, @@ -1384,35 +1339,38 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp Ok(bytes) } -fn check_psd_size((width, height): (u32, u32), channels: usize, depth: u8) -> Result<()> { +/// The PSD file of a texture set (its merged image and `layer_count` RGBA layers in `folder_count` groups) must fit PSD's side and 2 GiB limits +fn check_psd_size((width, height): (u32, u32), layer_count: usize, folder_count: usize, depth: u8) -> Result<()> { + // A layer record with its names, and each of a group's two records, stays below this + const PSD_RECORD_BYTES: u64 = 2048; + if width == 0 || height == 0 || width > PSD_MAX_SIDE_PIXELS || height > PSD_MAX_SIDE_PIXELS { return Err(FormatError::Invalid(format!("PSD size {width}×{height} must be between 1 and {PSD_MAX_SIDE_PIXELS} pixels per side"))); } - // Measure the flat file's overhead without allocating any pixel buffers - let overhead = flat_psd((width, height), channels, depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?; - let sample_bytes = u64::from(width) * u64::from(height) * channels as u64 * u64::from(depth / 8); - if overhead + sample_bytes >= PSD_MAX_FILE_BYTES { - return Err(FormatError::Invalid(format!("PSD size {width}×{height} would reach the 2 GiB file limit; use a smaller export size or another format"))); + // Measure the merged image's overhead without allocating any pixel buffers + let merged = flat_psd((width, height), depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?; + let records = PSD_RECORD_BYTES * (layer_count as u64 + 2 * folder_count as u64); + let planes = PSD_RGBA_PLANES as u64 * (1 + layer_count as u64); + let sample_bytes = u64::from(width) * u64::from(height) * planes * u64::from(depth / 8); + if merged + records + sample_bytes >= PSD_MAX_FILE_BYTES { + return Err(FormatError::Invalid(format!( + "a PSD of {layer_count} maps at {width}×{height} would reach the 2 GiB file limit; use a smaller export size, fewer PSD maps or another format" + ))); } Ok(()) } -fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_psd::PsdFile { - use craft_psd::{ColorMode, Compression, Header, ImageData, ImageResource, PsdFile, Version}; - - const PSD_ALPHA_NAMES_RESOURCE_ID: u16 = 1006; - let color_mode = if channels <= 2 { ColorMode::Grayscale } else { ColorMode::Rgb }; - let header = Header::new(Version::Psd, width, height, channels as u16, u16::from(depth), color_mode); - - // A Pascal name marks the extra plane as a channel separate from merged transparency - let resources = if matches!(channels, 2 | 4) { vec![ImageResource::new(PSD_ALPHA_NAMES_RESOURCE_ID, b"\x05Alpha".to_vec())] } else { Vec::new() }; +/// A PSD of only an RGBA merged image with no pixels yet, to measure +fn flat_psd((width, height): (u32, u32), depth: u8) -> craft_psd::PsdFile { + use craft_psd::{ColorMode, Compression, Header, ImageData, PsdFile, Version}; + let header = Header::new(Version::Psd, width, height, PSD_RGBA_PLANES as u16, u16::from(depth), ColorMode::Rgb); PsdFile { header, color_mode_data: Vec::new(), - resources, + resources: Vec::new(), layer_info: None, layer_info_placement: Default::default(), global_layer_mask: None, @@ -1423,26 +1381,6 @@ fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_ps } } -/// Write a merged PSD image with raw planes, including an extra alpha plane when present. -fn psd(bytes: Vec, size: (u32, u32), channels: usize, depth: u8) -> craft_psd::Result> { - let mut file = flat_psd(size, channels, depth); - let planes = &mut file.image_data.data; - planes.try_reserve_exact(bytes.len()).map_err(|_| craft_psd::PsdError::OutOfMemory("cannot allocate PSD planes"))?; - if depth == 16 { - let samples = bytes.as_chunks::<2>().0; - for channel in 0..channels { - planes.extend(samples.iter().skip(channel).step_by(channels).flat_map(|sample| u16::from_ne_bytes(*sample).to_be_bytes())); - } - } else { - for channel in 0..channels { - planes.extend(bytes.iter().skip(channel).step_by(channels).copied()); - } - } - drop(bytes); - - file.to_bytes() -} - /// A JNG file: the colour as JPEG, alpha (when present) as lossless 8-bit deflate data. fn jng(bytes: &[u8], (w, h): (u32, u32), n: usize) -> std::result::Result, String> { use std::io::Write; diff --git a/crates/formats/src/export/planned_layer.rs b/crates/formats/src/export/planned_layer.rs new file mode 100644 index 00000000..4f0adf39 --- /dev/null +++ b/crates/formats/src/export/planned_layer.rs @@ -0,0 +1,10 @@ +/// An output map written as a layer of a texture set's PSD (see [`super::list_outputs`]) +#[derive(Clone, Debug, PartialEq)] +pub struct PlannedLayer { + /// Index into the preset's maps + pub map: usize, + /// The map's file name, a `/` separating the groups the layer sits in + pub name: String, + /// 8-bit samples written with dithering + pub dither: bool, +} diff --git a/crates/formats/src/export/rendered_map.rs b/crates/formats/src/export/rendered_map.rs new file mode 100644 index 00000000..df388464 --- /dev/null +++ b/crates/formats/src/export/rendered_map.rs @@ -0,0 +1,13 @@ +use texturecraft_texel::ColorSpace; + +/// One output map's linear samples at its export size, ready to encode +pub(super) struct RenderedMap { + /// Interleaved L, LA, RGB or RGBA samples + pub data: Vec, + pub size: (u32, u32), + pub component_count: usize, + /// Per component: whether encoding applies the sRGB transfer + pub srgb: Vec, + /// The colour space recorded in the file, when the user chose one for a colour map + pub embed: Option, +} diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 45312b0d..1cdf688e 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1122,45 +1122,89 @@ fn pgm_is_a_binary_graymap() { } #[test] -fn psd_holds_the_merged_image_planar() { +fn psd_holds_every_map_as_a_layer_over_their_merged_image() { let fx = Fx::new(&default_channels()); - let f = &fx.render(&one_map(FileFormat::Psd, 8, rgba_half_alpha()))[0]; - let b = &f.bytes; - assert_eq!(&b[0..4], b"8BPS"); - assert_eq!(u16::from_be_bytes([b[12], b[13]]), 4, "channels"); - assert_eq!((u32::from_be_bytes(b[14..18].try_into().unwrap()), u32::from_be_bytes(b[18..22].try_into().unwrap())), (64, 64)); - assert_eq!((u16::from_be_bytes([b[22], b[23]]), u16::from_be_bytes([b[24], b[25]])), (8, 3), "8-bit RGB"); - let parsed = craft_psd::PsdFile::from_bytes(b).unwrap(); - assert!(!parsed.merged_has_alpha()); - assert_eq!(parsed.alpha_channel_names(), ["Alpha"]); - let samples = parsed.decode_merged().unwrap(); - assert_eq!(samples.len(), 4 * 64 * 64); - let plane = |c: usize| &samples[c * 64 * 64..(c + 1) * 64 * 64]; - assert!(plane(3).iter().all(|a| *a == 128), "alpha plane"); - let png = decode(&fx.render(&one_map(FileFormat::Png, 8, rgba_half_alpha()))[0]).to_rgba8(); - assert_eq!(plane(0)[64 * 10 + 40], png.get_pixel(40, 10)[0], "the red plane holds the same values as a PNG"); + let mut png_options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); + png_options.bit_depth_override = Some(8); + let pngs = fx.render(&png_options); + let mut options = png_options.clone(); + options.format_override = Some(FileFormat::Psd); - let f16 = &fx.render(&one_map(FileFormat::Psd, 16, roughness()))[0]; - assert_eq!((u16::from_be_bytes([f16.bytes[12], f16.bytes[13]]), u16::from_be_bytes([f16.bytes[22], f16.bytes[23]])), (1, 16)); - assert_eq!(f16.bytes.len(), 26 + 12 + 2 + 2 * 64 * 64); + let planned = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + let files = fx.render(&options); - let mut gray_alpha = roughness(); - gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); - let f16 = &fx.render(&one_map(FileFormat::Psd, 16, gray_alpha))[0]; - let parsed = craft_psd::PsdFile::from_bytes(&f16.bytes).unwrap(); - assert!(!parsed.merged_has_alpha()); - assert_eq!(parsed.alpha_channel_names(), ["Alpha"]); - let samples = parsed.decode_merged().unwrap(); - assert_eq!(samples.len(), 2 * 2 * 64 * 64); - assert!(samples[2 * 64 * 64..].as_chunks::<2>().0.iter().all(|sample| *sample == [128, 0])); + assert_eq!(planned.len(), 1, "one PSD for the texture set: {planned:?}"); + assert_eq!(planned[0].layers.len(), pngs.len()); + assert_eq!(files.len(), 1); + assert_eq!(files[0].name, "sphere_Body_Set.psd"); + let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layers: Vec<_> = parsed.iter_layers().collect(); + assert_eq!(layers.len(), pngs.len()); + + // The file stacks bottom up, so the first map is the top layer + for (layer, png) in layers.iter().rev().zip(&pngs) { + assert_eq!(format!("{}.png", layer.name()), png.name); + assert_eq!(layer.rgba8().unwrap().data, decode(png).to_rgba8().into_raw(), "{}: the layer holds the map's texels", png.name); + } + let top = layers.last().unwrap().rgba8().unwrap().data; + assert!(top.as_chunks::<4>().0.iter().all(|texel| texel[3] == u8::MAX), "the base colour is opaque"); + assert_eq!(parsed.composite_rgba8().unwrap().data, top, "the merged image shows the opaque top layer"); + + options.bit_depth_override = Some(16); + let deep = &fx.render(&options)[0]; + assert_eq!(craft_psd::PsdFile::from_bytes(&deep.bytes).unwrap().header.depth, 16); +} + +#[test] +fn psd_folder_templates_become_layer_groups_of_one_file_not_folders() { + let fx = Fx::new(&default_channels()); + let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 }); + let preset = ExportPreset { name: "t".into(), maps: vec![rough("Body/$textureSet_Rough"), rough("Top/Inner/Leaf"), rough("Mask")] }; + let mut options = ExportOptions::new(preset); + options.format_override = Some(FileFormat::Psd); + + let files = fx.render(&options); + + assert_eq!(files.iter().map(|f| f.name.as_str()).collect::>(), ["sphere_Body_Set.psd"], "no folder for a PSD's layers"); + let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name(); + let tree = parsed.layer_tree(); + + // The tree lists bottom up and the first map is the top layer + let groups: Vec<_> = tree.iter().rev().filter(|node| node.is_group()).map(name).collect(); + assert_eq!(groups, ["Body", "Top"]); + let body = tree.iter().find(|node| node.is_group() && name(node) == "Body").unwrap(); + assert_eq!(body.children().iter().map(name).collect::>(), ["Body_Set_Rough"], "$textureSet is filled in inside a layer name"); + assert!(tree.iter().any(|node| !node.is_group() && name(node) == "Mask")); +} + +#[test] +fn psd_layer_groups_follow_the_slashes_of_their_names() { + let pixel = || craft_psd::PixelData::Rgba8(vec![10, 20, 30, 255]); + let layers = vec![("Mask", pixel()), ("Body/Rough", pixel()), ("Body/Color", pixel()), ("Top/Inner/Leaf", pixel())]; + + let bytes = layered_psd::write_layers((1, 1), 8, layers, pixel()).unwrap(); + + let parsed = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name(); + let tree = parsed.layer_tree(); + assert_eq!( + tree.iter().map(|node| (name(node), node.is_group())).collect::>(), + [("Mask".to_string(), false), ("Body".to_string(), true), ("Top".to_string(), true)] + ); + assert_eq!(tree[1].children().iter().map(name).collect::>(), ["Rough", "Color"]); + let inner = &tree[2].children()[0]; + assert!(inner.is_group() && name(inner) == "Inner"); + assert_eq!(inner.children().iter().map(name).collect::>(), ["Leaf"]); } #[test] fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { let mut fx = Fx::new(&default_channels()); - fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + // Four tile columns: the atlas is 32768 wide, each tile's layer and merged image well under 2 GiB + fx.project.texture_sets[0].uv_tiles = vec![1001, 1004]; let mut options = one_map(FileFormat::Psd, 8, roughness()); - options.size = Some(16_384); + options.size = Some(8192); options.atlas = true; let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); @@ -1171,7 +1215,7 @@ fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { } #[test] -fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() { +fn psd_plan_counts_every_layer_against_the_version_one_byte_limit() { let fx = Fx::new(&default_channels()); let mut options = one_map(FileFormat::Psd, 16, rgba_half_alpha()); options.size = Some(16_384); @@ -1179,19 +1223,23 @@ fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() { let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); assert!(error.to_string().contains("PSD") && error.to_string().contains("2 GiB"), "{error}"); - options.bit_depth_override = Some(8); - assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); - options.bit_depth_override = None; - options.preset.maps[0].channels.pop(); - assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); + options.size = Some(8192); + for copy in ["second", "third"] { + assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); + let mut map = options.preset.maps[0].clone(); + map.file = copy.into(); + options.preset.maps.push(map); + } + let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); + assert!(error.to_string().contains("3 maps") && error.to_string().contains("2 GiB"), "{error}"); } #[test] -fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() { - // These RGBA16 planes are 32 bytes below 2 GiB before headers and the alpha name - let (width, height) = (10_924, 24_573); - assert!(check_psd_size((width, height), 4, 16).is_err()); - assert!(check_psd_size((width, height - 1), 4, 16).is_ok()); +fn psd_byte_limit_includes_the_merged_image_and_keeps_separate_tiles_valid() { + // One RGBA16 layer and the merged image: 87360 bytes over 2 GiB, a row less 87424 bytes below + let (width, height) = (10_924, 12_287); + assert!(check_psd_size((width, height), 1, 0, 16).is_err()); + assert!(check_psd_size((width, height - 1), 1, 0, 16).is_ok()); let mut fx = Fx::new(&default_channels()); fx.project.texture_sets[0].uv_tiles = vec![1001, 1003, 1011]; diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 49125502..db2c514d 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -386,11 +386,16 @@ fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: /// opacity, clear coat and clear coat roughness. Maps with none of them (ambient occlusion, /// height, specular/glossiness, baked maps...) bind nothing, and neither do channels the set has /// no data for. `project_normal` is the project's normal convention, used by normal maps that -/// follow it. +/// follow it. A PSD holds several maps as layers, so it binds nothing pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec { let mut out: Vec = Vec::new(); let mut seen_maps = Vec::new(); for file in files { + // A PSD's merged image is no one map's texture + if file.format == FileFormat::Psd { + continue; + } + // The first tile stands for all the tiles of a map if seen_maps.contains(&file.map) { continue; @@ -412,7 +417,7 @@ pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_norm } let Some((output, source)) = output_for_slot(slot, map, set, file.format) else { continue }; - let normal = (slot == 3).then(|| { + let normal = (SLOTS[slot].0 == "Normal").then(|| { opts.normal_format.unwrap_or(match source { SourceRef::Virtual { map: VirtualMap::NormalOpenGl, .. } => NormalFormat::OpenGl, SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. } => NormalFormat::DirectX, @@ -585,6 +590,7 @@ mod texture_binding_tests { tile: None, udim_name: None, warnings: Vec::new(), + layers: Vec::new(), } } diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index beaf660f..3e7ab2b6 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -928,10 +928,25 @@ fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result { + for layer in layers { + let name = layer.get("name").and_then(Value::as_str).unwrap_or_default(); + if let Some(slot) = index(layer).and_then(|i| names.get_mut(i)) { + *slot = Some(format!("{file} › {name}")); + } + } + } + None => { + if let Some(slot) = index(f).and_then(|i| names.get_mut(i)) { + *slot = Some(file.to_string()); + } + } } } Ok(names) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index c4a07d5f..c7f8b11f 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -533,28 +533,36 @@ fn file_type_text(t: &FileType) -> String { /// The rows of texture set `ts`'s Output maps: the template's maps the set has sources for fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { - let mut p = set_params(app, ts); - if let Some(o) = p.as_object_mut() { - o.remove("maps"); + let mut params = set_params(app, ts); + if let Some(object) = params.as_object_mut() { + object.remove("maps"); } let preset = app.session.export_preset(&set_template(app, ts)); - let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", &p) else { return Vec::new() }; + let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", ¶ms) else { return Vec::new() }; let mut rows: Vec = Vec::new(); - for f in plan.as_array().into_iter().flatten() { - let Some(map) = f.get("map").and_then(serde_json::Value::as_u64).map(|m| m as usize) else { continue }; - if rows.iter().any(|r| r.map == map) { - continue; - } + let index = |value: &serde_json::Value| value.get("map").and_then(serde_json::Value::as_u64).map(|map| map as usize); + for file in plan.as_array().into_iter().flatten() { + // A PSD writes each of its layers' maps + let layers = file.get("layers").and_then(serde_json::Value::as_array).filter(|layers| !layers.is_empty()); + let maps: Vec = match layers { + Some(layers) => layers.iter().filter_map(index).collect(), + None => index(file).into_iter().collect(), + }; + for map in maps { + if rows.iter().any(|row| row.map == map) { + continue; + } - let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); - let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; - let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let pattern = preset - .as_ref() - .and_then(|p| p.maps.get(map)) - .map(|m| m.file.replace("$channel", texturecraft_engine::formats::export::channel_label(m))) - .unwrap_or_default(); - rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); + let format = file.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); + let bit_depth = file.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; + let dithering = file.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); + let pattern = preset + .as_ref() + .and_then(|preset| preset.maps.get(map)) + .map(|map_spec| map_spec.file.replace("$channel", texturecraft_engine::formats::export::channel_label(map_spec))) + .unwrap_or_default(); + rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); + } } rows } From 269bfb02707a9961c35f3bffafcd0c7a676db9d4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:48:11 +0000 Subject: [PATCH 021/190] Export: an output map can have its own size, which wins over the export size A texture set's Output maps row has a size list (Export size, or 128x128 to 8192x8192); file.exportTextures and export.plan take it as maps[].size, and a PSD is as large as its largest layer. --- crates/engine/src/file_cmds.rs | 14 +++++-- crates/engine/tests/it/export_file_types.rs | 12 ++++++ crates/formats/src/export/layered_psd.rs | 12 +++--- crates/formats/src/export/map_override.rs | 5 ++- crates/formats/src/export/map_renderer.rs | 8 ++-- crates/formats/src/export/mod.rs | 21 +++++++--- crates/formats/src/export/tests.rs | 27 +++++++++++++ crates/ui-egui/src/export_window.rs | 22 ++++++++++- crates/ui-egui/src/state/map_export.rs | 5 ++- crates/ui-egui/src/state/set_export.rs | 6 ++- .../ui-egui/tests/it/export_map_overrides.rs | 39 ++++++++++++++++++- crates/ui-egui/tests/it/output_templates.rs | 10 ++--- 12 files changed, 151 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 70194399..f29efdf9 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -375,12 +375,12 @@ pub fn export_options(session: &Session, params: &Value, cmd: &str) -> Result Result> { let mut overrides = std::collections::BTreeMap::new(); let Some(list) = params.get("maps").filter(|value| !value.is_null()) else { return Ok(overrides) }; - let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?}"))?; + let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?, size?}"))?; for settings in list { let index = u64p(settings, "map").and_then(|value| usize::try_from(value).ok()).filter(|index| *index < map_count); let index = index.ok_or_else(|| bad(cmd, format!("`maps`: `map` must be the index of one of the preset's {map_count} maps")))?; @@ -399,6 +399,10 @@ fn map_overrides(params: &Value, map_count: usize, cmd: &str) -> Result Result { let block_size = set.block_resolution(); for (_, output) in set_outputs { let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile)); - let size = scale_export_side(source_size, block_size, options.size); + + // A map's own size wins over the export's; a PSD is the size of its largest layer + let size = output.maps().map(|map| scale_export_side(source_size, block_size, options.map_size(map))).max().unwrap_or(source_size); files.push(json!({ "ts": set_index, diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index e4f0e56f..70355b80 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -27,3 +27,15 @@ fn the_new_file_types_dithering_and_diffusion_export() { assert!(plan.as_array().unwrap().iter().all(|f| f["dithering"] == false), "float files are never dithered"); assert!(execute(&mut s, "export.plan", &json!({"padding": "smudge"})).is_err()); } + +#[test] +fn a_map_size_wins_over_the_export_size_in_the_plan() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + + let plan = execute(&mut s, "export.plan", &json!({"ts": 0, "size": 512, "maps": [{"map": 0, "size": 128}]})).unwrap(); + + let files = plan.as_array().unwrap(); + assert!(files.iter().filter(|file| file["map"] == 0).all(|file| file["size"] == 128), "{plan}"); + assert!(files.iter().filter(|file| file["map"] != 0).all(|file| file["size"] == 512), "{plan}"); + assert!(execute(&mut s, "export.plan", &json!({"ts": 0, "maps": [{"map": 0, "size": 100}]})).is_err()); +} diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index e90f8e6e..9064de7f 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -5,16 +5,17 @@ use texturecraft_texel::linear_to_srgb; use super::encoding::Encoding; use super::map_renderer::MapRenderer; -use super::{ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, PlannedFile, quantize_integer}; +use super::{ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, PlannedFile, quantize_integer, resize}; use crate::{FormatError, Result}; /// Where alpha sits in an RGBA texel const ALPHA_INDEX: usize = 3; -/// Render the layers of `planned` one at a time and write them as one PSD +/// Render the layers of `planned` one at a time and write them as one PSD the size of the largest; smaller maps are scaled up to it pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile) -> Result { let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned; - let size = renderer.size(tile)?; + let sizes = layers.iter().map(|layer| renderer.size(layer.map, tile)).collect::>>()?; + let size = sizes.into_iter().max_by_key(|(width, height)| u64::from(*width) * u64::from(*height)).unwrap_or((1, 1)); // Each layer as straight RGBA in 0-1, sRGB-encoded where the map's file would be, dropped once quantized let mut composite = vec![0.0f32; size.0 as usize * size.1 as usize * PSD_RGBA_PLANES]; @@ -23,8 +24,9 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile) -> Result for layer in layers.iter().rev() { let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; embedded = map.embed.or(embedded); - let rgba = to_rgba(&map.data, map.component_count, &map.srgb); - drop(map); + let data = resize(map.data, map.size, map.component_count, size); + let rgba = to_rgba(&data, map.component_count, &map.srgb); + drop(data); over(&mut composite, &rgba); let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; let bytes = quantize_integer(encoding, size.0, PSD_RGBA_PLANES, rgba.into_iter())?; diff --git a/crates/formats/src/export/map_override.rs b/crates/formats/src/export/map_override.rs index 5ea62f5c..aec6ef56 100644 --- a/crates/formats/src/export/map_override.rs +++ b/crates/formats/src/export/map_override.rs @@ -14,10 +14,13 @@ pub struct MapOverride { /// Instead of the export's dithering of 8-bit files. #[serde(default)] pub dither: Option, + /// Output size (power of two) instead of the export's + #[serde(default)] + pub size: Option, } impl Default for MapOverride { fn default() -> Self { - MapOverride { enabled: true, format: None, bit_depth: None, dither: None } + MapOverride { enabled: true, format: None, bit_depth: None, dither: None, size: None } } } diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs index c19064c5..e4a6e7f7 100644 --- a/crates/formats/src/export/map_renderer.rs +++ b/crates/formats/src/export/map_renderer.rs @@ -56,12 +56,12 @@ impl<'a> MapRenderer<'a> { Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) } - /// The export size of a file of `tile` (None: the whole set). - pub(super) fn size(&self, tile: Option) -> Result<(u32, u32)> { + /// The export size of map `map_index`'s file of `tile` (None: the whole set) + pub(super) fn size(&self, map_index: usize, tile: Option) -> Result<(u32, u32)> { let (_, _, w, h) = self.region(tile)?; // An atlas scales by the requested size per tile - let scale = |value| scale_export_side(value, self.tile_res, self.options.size); + let scale = |value| scale_export_side(value, self.tile_res, self.options.map_size(map_index)); Ok((scale(w), scale(h))) } @@ -87,7 +87,7 @@ impl<'a> MapRenderer<'a> { let component_count = channel_layout.len(); let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); let (x0, y0, w, h) = self.region(tile)?; - let size = self.size(tile)?; + let size = self.size(map_index, tile)?; let sampler = &self.sampler; let dilation_map = self.dilation_map.as_ref(); let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 6a07413e..26ef58fc 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -441,6 +441,11 @@ pub struct ExportOptions { } impl ExportOptions { + /// The output size of the preset's map `map`: its own, else the export's (None: the texture set's) + pub fn map_size(&self, map: usize) -> Option { + self.maps.get(&map).and_then(|own| own.size).or(self.size) + } + /// The colour space colour maps use at this format's default depth. pub fn space_for(&self, format: FileFormat) -> ColorSpace { self.space_for_depth(format, format.default_depth()) @@ -614,10 +619,10 @@ pub fn sanitize_file_path(s: &str) -> String { pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { opts.preset.validate()?; let set = project.texture_set(ts)?; - if let Some(s) = opts.size - && (!s.is_power_of_two() || s > MAX_IMAGE_SIZE) - { - return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}"))); + for s in opts.size.iter().chain(opts.maps.values().filter_map(|own| own.size.as_ref())) { + if !s.is_power_of_two() || *s > MAX_IMAGE_SIZE { + return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}"))); + } } let mut used = BTreeSet::new(); @@ -736,7 +741,11 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let bit_depth = in_tile.iter().map(|(_, _, depth, _)| *depth).max().unwrap_or(8); let folder_count: usize = in_tile.iter().map(|(_, layer, ..)| layer.name.matches('/').count()).sum(); - check_psd_size(psd_size(set, tile, opts.size), in_tile.len(), folder_count, bit_depth)?; + let size = in_tile + .iter() + .map(|(_, layer, ..)| psd_size(set, tile, opts.map_size(layer.map))) + .max_by_key(|(width, height)| u64::from(*width) * u64::from(*height)); + check_psd_size(size.unwrap_or((1, 1)), in_tile.len(), folder_count, bit_depth)?; let mut warnings: Vec = Vec::new(); for warning in in_tile.iter().flat_map(|(.., layer_warnings)| layer_warnings) { @@ -793,7 +802,7 @@ fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: & Ok(()) } -/// The size of a texture set's PSD for `tile` (None: the whole set, an atlas of a UV-tiled one) +/// The size of a PSD layer of a texture set at `export_size` for `tile` (None: the whole set, an atlas of a UV-tiled one) fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u32, u32) { let block_resolution = set.block_resolution(); match (tile, set.tile_grid()) { diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 1cdf688e..f050b2b6 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -556,6 +556,33 @@ fn gray_map(file: &str, src: SourceRef) -> MapSpec { MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)], inverted: Vec::new() } } +#[test] +fn an_output_with_its_own_size_keeps_it() { + let fx = Fx::new(&default_channels()); + let preset = ExportPreset { + name: "sizes".into(), + maps: vec![ + gray_map("small", SourceRef::Channel { channel: Channel::Roughness, component: 0 }), + gray_map("set_size", SourceRef::Channel { channel: Channel::Metallic, component: 0 }), + ], + }; + let mut options = ExportOptions::new(preset); + options.maps.insert(0, MapOverride { size: Some(32), ..MapOverride::default() }); + + for (export_size, other) in [(None, RES), (Some(128), 128)] { + let files = fx.render(&ExportOptions { size: export_size, ..options.clone() }); + assert_eq!(find(&files, "small.png").width, 32, "its own size wins over {export_size:?}"); + assert_eq!(find(&files, "set_size.png").width, other); + } + + // A PSD is as large as its largest layer + options.format_override = Some(FileFormat::Psd); + assert_eq!(fx.render(&options)[0].width, RES); + + options.maps.insert(0, MapOverride { size: Some(100), ..MapOverride::default() }); + assert!(list_outputs(&fx.project, 0, "sphere", &options).is_err(), "a size that isn't a power of two is refused"); +} + #[test] fn validation_rejects_bad_presets() { let ok = ExportPreset { name: "Mine".into(), maps: vec![gray_map("$mesh_$textureSet_$channel ($colorSpace) $project", SourceRef::Constant(1.0))] }; diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index c7f8b11f..0e6b30b1 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -507,6 +507,9 @@ pub(crate) fn set_params(app: &TextureCraftApp, set_index: usize) -> serde_json: settings["bitDepth"] = json!(file_type.bit_depth); settings["dithering"] = json!(file_type.dithering); } + if let Some(size) = map.size { + settings["size"] = json!(size); + } settings }) .collect(); @@ -608,6 +611,7 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { ui.label(file_type_text(&row.inherited)); } } + map_size_combo(ui, ("exp_map_size", ts, row.map), &mut m.size); }); ui.end_row(); } @@ -619,13 +623,29 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { Some(1) => m.enabled = false, Some(2) => m.enabled = !m.enabled, Some(3) if m.file_type.is_none() => m.file_type = Some(row.inherited.clone()), - Some(4) => m.file_type = None, + Some(4) => (m.file_type, m.size) = (None, None), _ => {} } } o.maps.retain(|_, m| *m != MapExport::default()); } +/// An output map's size: the export's, or its own, which wins over it +fn map_size_combo(ui: &mut Ui, id: (&str, usize, usize), size: &mut Option) { + let shown = size.map_or_else(|| tr("Export size").to_string(), |side| format!("{side}x{side}")); + egui::ComboBox::from_id_salt(id) + .selected_text(shown) + .show_ui(ui, |ui| { + ui.selectable_value(size, None, tr("Export size")); + ui.separator(); + for side in SIZES { + ui.selectable_value(size, Some(side), format!("{side}x{side}")); + } + }) + .response + .on_hover_text(tr("This map's own size, which wins over the export size")); +} + /// Count the files planned across all selected texture sets. fn selected_texture_count(app: &mut TextureCraftApp) -> usize { let mut count = 0; diff --git a/crates/ui-egui/src/state/map_export.rs b/crates/ui-egui/src/state/map_export.rs index 339ee1bb..2b8a3e37 100644 --- a/crates/ui-egui/src/state/map_export.rs +++ b/crates/ui-egui/src/state/map_export.rs @@ -10,6 +10,9 @@ pub struct MapExport { pub enabled: bool, #[serde(default)] pub file_type: Option, + /// The map's own size in texels per side, which wins over the export size + #[serde(default)] + pub size: Option, } fn enabled_by_default() -> bool { @@ -18,6 +21,6 @@ fn enabled_by_default() -> bool { impl Default for MapExport { fn default() -> Self { - MapExport { enabled: true, file_type: None } + MapExport { enabled: true, file_type: None, size: None } } } diff --git a/crates/ui-egui/src/state/set_export.rs b/crates/ui-egui/src/state/set_export.rs index 0fb05522..7bb10770 100644 --- a/crates/ui-egui/src/state/set_export.rs +++ b/crates/ui-egui/src/state/set_export.rs @@ -26,7 +26,11 @@ pub struct SetExport { impl SetExport { /// Whether anything is overridden (the set is marked "*"). pub fn any(&self) -> bool { - self.preset.is_some() || self.file_type.is_some() || self.size.is_some() || self.padding.is_some() || self.maps.values().any(|m| m.file_type.is_some()) + self.preset.is_some() + || self.file_type.is_some() + || self.size.is_some() + || self.padding.is_some() + || self.maps.values().any(|m| m.file_type.is_some() || m.size.is_some()) } /// Whether the set exports as the global settings say (no override, every map ticked). diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 937ce100..0aefd54e 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -119,7 +119,7 @@ fn export_writes_a_map_with_its_own_file_type() { let _ = std::fs::remove_dir_all(&dir); let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }) }); + o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None }); let e = &mut h.state_mut().ui.export; e.dir = dir.display().to_string(); e.sets.insert(0, o); @@ -147,7 +147,7 @@ fn a_map_the_template_no_longer_has_is_ignored() { let before = selected(&h); let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(999, MapExport { enabled: false, file_type: None }); + o.maps.insert(999, MapExport { enabled: false, file_type: None, size: None }); h.state_mut().ui.export.sets.insert(0, o); h.run_steps(3); assert_eq!(selected(&h), before, "the export still plans every file"); @@ -163,3 +163,38 @@ fn each_row_names_its_own_map() { assert!(h.query_all_by_label_contains(&format!("_{id}")).next().is_some(), "a row for {id}"); } } + +#[test] +fn a_map_picks_its_own_size_and_the_export_writes_it_at_that_size() { + let mut h = harness(); + let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize; + let combo = h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map's size list"); + combo.click(); + h.run_steps(4); + click(&mut h, "128x128"); + assert_eq!(maps(&h).get(&first).and_then(|map| map.size), Some(128), "{:?}", maps(&h)); + assert!(h.query_by_label("*").is_some(), "the set is marked"); + + let dir = std::env::temp_dir().join(format!("tc-export-map-sizes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let set_count = h.state().session.set_count(); + let export = &mut h.state_mut().ui.export; + export.dir = dir.display().to_string(); + export.skip = (1..set_count).collect(); + h.run_steps(3); + click(&mut h, "Export"); + for _ in 0..64 { + if h.state().ui.export.job.is_none() { + break; + } + + h.run_steps(1); + } + h.run_steps(2); + + let sizes: Vec = + std::fs::read_dir(&dir).unwrap().flatten().filter_map(|entry| image::image_dimensions(entry.path()).ok()).map(|(width, _)| width).collect(); + assert_eq!(sizes.iter().filter(|width| **width == 128).count(), 1, "the map at its own size: {sizes:?}"); + assert!(sizes.iter().filter(|width| **width != 128).all(|width| *width == 256), "the others at the set's: {sizes:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 061c2779..fb791acb 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -188,7 +188,7 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { h.state_mut().run("export.preset.save", json!({ "preset": two })).unwrap(); let own = "Unreal Engine (Packed)".to_string(); let mut o = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() }; - o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None }); + o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); let ts = h.state().session.ts(); h.state_mut().ui.export.sets.insert(ts, o); h.state_mut().ui.export.preset = "Two".into(); @@ -208,7 +208,7 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { let library = TemplateLibrary::new("follow"); let mut h = harness(&library); let mut o = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() }; - o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None }); + o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); // The override is there when the window opens h.state_mut().ui.windows.export = false; @@ -270,7 +270,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { let mut h = harness(&library); // The first texture set leaves out the template's first map - let off = MapExport { enabled: false, file_type: None }; + let off = MapExport { enabled: false, file_type: None, size: None }; h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let first = h.state().session.export_preset("Mine").unwrap().maps[0].file.clone(); @@ -284,7 +284,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { let library = TemplateLibrary::new("stale"); let mut h = harness(&library); - let off = MapExport { enabled: false, file_type: None }; + let off = MapExport { enabled: false, file_type: None, size: None }; h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let saved = h.state().session.export_preset("Mine").unwrap(); @@ -321,7 +321,7 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { let mut external = saved.clone(); external.maps.swap(0, 1); harness.state_mut().run("export.preset.save", json!({"preset": external})).unwrap(); - let disabled = MapExport { enabled: false, file_type: None }; + let disabled = MapExport { enabled: false, file_type: None, size: None }; harness.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, disabled.clone())].into(), ..SetExport::default() }); harness.run_steps(3); From b569f3dbe8825008d719ae1abff77157451a7a8d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:50:37 +0000 Subject: [PATCH 022/190] Export textures: Export shader settings writes _shaders.json, the shader's model and settings and the texture sets using it The tick is saved with the export settings like Export USD asset; the window sends every texture set of the export with its last command (shaderParameters of file.exportTextures), and the browser adds the file to its download. --- crates/engine/src/file_cmds.rs | 14 +++- crates/engine/src/lib.rs | 1 + crates/engine/src/shader_parameters.rs | 73 +++++++++++++++++++ crates/engine/tests/it/export_file_types.rs | 34 +++++++++ crates/ui-egui/src/export_window.rs | 26 +++++-- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/state/export_job.rs | 2 + crates/ui-egui/src/web_files.rs | 7 ++ .../tests/it/export_shader_parameters.rs | 39 ++++++++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/side_panels.rs | 5 +- 11 files changed, 198 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/shader_parameters.rs create mode 100644 crates/ui-egui/tests/it/export_shader_parameters.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f29efdf9..2688061c 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write _shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -670,6 +670,7 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { let reserved_patterns: Vec<_> = taken_names.keys().filter(|name| name.contains("")).cloned().collect(); let material = params.get("materialX").and_then(Value::as_bool).unwrap_or(false); let usd_asset = usd_asset_param(session, params, &options, &sets)?; + let shader_sets = crate::shader_parameters::shader_parameters_param(&session.doc.project, params, &sets, "file.exportTextures")?; let mut warnings = Vec::new(); let mut udim_patterns = Vec::new(); @@ -729,6 +730,17 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { if let Some(exports) = &usd_asset { written.extend(write_usd_asset(session, dir, exports, &mut warnings)); } + if let Some(shader_sets) = shader_sets { + let path = dir.join(crate::shader_parameters::shader_parameters_file(&session.doc.project.name)); + let parameters = crate::shader_parameters::shader_parameters(&session.doc.project, &shader_sets); + + // The textures are written by now: a shaders file that fails is a warning, as a failed USD asset is + let text = serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string()); + match text.and_then(|text| texturecraft_formats::write_atomic(&path, &text).map_err(|error| error.to_string())) { + Ok(()) => written.push(path), + Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), + } + } session.log.info("MapExporter", format!("Exported {} textures to {}", written.len(), dir.display())); let mut response = json!({ "files": written.iter().map(|path| path.display().to_string()).collect::>(), "warnings": warnings }); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..8248263b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -72,6 +72,7 @@ pub mod resource_cmds; pub mod session; mod session_log; pub mod set_cmds; +pub mod shader_parameters; pub mod smart_masks; mod solo; mod stylized_lighting_params; diff --git a/crates/engine/src/shader_parameters.rs b/crates/engine/src/shader_parameters.rs new file mode 100644 index 00000000..a090ecb8 --- /dev/null +++ b/crates/engine/src/shader_parameters.rs @@ -0,0 +1,73 @@ +//! Export shaders parameters: the project's shader, its settings and the texture sets using it, as JSON + +use serde_json::{Value, json}; +use texturecraft_core::Project; + +use crate::Result; +use crate::commands::bad; + +/// The project's one shader, its parameters and the names of `sets` (they all use it) +pub fn shader_parameters(project: &Project, sets: &[usize]) -> Value { + let display = &project.display; + let model = if display.spec_gloss { "specularGlossiness" } else { "metallicRoughness" }; + let names: Vec<&str> = sets.iter().filter_map(|ts| project.texture_sets.get(*ts)).map(|set| set.name.as_str()).collect(); + + json!({ + "shaders": [{ + "model": model, + "parameters": { + "aoIntensity": display.ao_intensity, + "ior": display.ior, + "scatterColor": display.scatter_color, + "scatterRadius": display.scatter_radius, + "displacement": display.displacement, + "parallax": display.parallax, + }, + "textureSets": names, + }] + }) +} + +/// The JSON file's name for project `name` +pub fn shader_parameters_file(name: &str) -> String { + format!("{}_shaders.json", texturecraft_formats::export::sanitize_file_stem(name)) +} + +/// The texture sets `shaderParameters` asks to list: `true` takes the command's own `sets`, a list gives them all; None when it asks for no file +pub fn shader_parameters_param(project: &Project, params: &Value, sets: &[usize], cmd: &str) -> Result>> { + match params.get("shaderParameters") { + None | Some(Value::Null | Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(sets.to_vec())), + Some(Value::Array(indexes)) => indexes + .iter() + .map(|index| { + index + .as_u64() + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < project.texture_sets.len()) + .ok_or_else(|| bad(cmd, "`shaderParameters` lists texture set indexes")) + }) + .collect::>>() + .map(Some), + Some(_) => Err(bad(cmd, "`shaderParameters` must be true, false or a list of texture set indexes")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_json_names_the_shader_its_settings_and_its_texture_sets() { + let mut s = crate::sample_session(128, 32).unwrap(); + s.doc.project.display.ior = 1.33; + + let value = shader_parameters(&s.doc.project, &[1]); + + let shader = &value["shaders"][0]; + assert_eq!(shader["model"], "metallicRoughness"); + assert!((shader["parameters"]["ior"].as_f64().unwrap() - 1.33).abs() < 1e-6); + assert_eq!(shader["textureSets"], json!([s.doc.project.texture_sets[1].name])); + assert!(shader_parameters_file("Material Ball").ends_with("_shaders.json")); + } +} diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index 70355b80..6f9638c8 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -39,3 +39,37 @@ fn a_map_size_wins_over_the_export_size_in_the_plan() { assert!(files.iter().filter(|file| file["map"] != 0).all(|file| file["size"] == 512), "{plan}"); assert!(execute(&mut s, "export.plan", &json!({"ts": 0, "maps": [{"map": 0, "size": 100}]})).is_err()); } + +#[test] +fn shader_parameters_write_the_shaders_json_next_to_the_textures() { + let mut s = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = std::env::temp_dir().join(format!("tc_export_shader_parameters_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "ts": 1, "shaderParameters": [0, 1]})).unwrap(); + + let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&s.doc.project.name)); + assert!(r["files"].as_array().unwrap().iter().any(|f| f.as_str() == Some(file.to_str().unwrap())), "{r}"); + let written: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let names: Vec<&str> = s.doc.project.texture_sets.iter().take(2).map(|set| set.name.as_str()).collect(); + assert_eq!(written["shaders"][0]["textureSets"], json!(names)); + assert!(execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "shaderParameters": "yes"})).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_shaders_json_that_cannot_be_written_is_a_warning_after_the_textures() { + let mut s = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = std::env::temp_dir().join(format!("tc_export_shader_parameters_blocked_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&s.doc.project.name)); + std::fs::create_dir_all(&file).unwrap(); + + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "ts": 0, "shaderParameters": true})).unwrap(); + + let files = r["files"].as_array().unwrap(); + assert!(!files.is_empty() && files.iter().all(|f| f.as_str() != Some(file.to_str().unwrap())), "{r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("The shader settings file was not written"))), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 0e6b30b1..1c1d2db4 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -272,7 +272,15 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, usd_asset: e.usd_asset, ..Default::default() }); + e.job = Some(crate::state::ExportJob { + total: pending.len(), + pending, + preview, + directory: dir, + usd_asset: e.usd_asset, + shader_parameters: e.shader_parameters, + ..Default::default() + }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -373,6 +381,11 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { } } + // The last command writes the shader parameters, listing every texture set of the export + if let Some(job) = app.ui.export.job.as_ref().filter(|job| job.shader_parameters && job.pending.is_empty()) { + params["shaderParameters"] = job.preview.iter().filter_map(|plan| plan.index).collect(); + } + let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; @@ -394,8 +407,8 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { }; let files: Vec = response_strings(&response, "files").map(relative).collect(); let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; - // The USD asset is no texture: it stays in the list of written files only - for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { + // The USD asset and the shader parameters are no textures: they stay in the list of written files only + for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd") && !file.to_ascii_lowercase().ends_with(".json")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); @@ -772,6 +785,7 @@ fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { } /// A greyed checkbox with its tooltip and the "not available" hint +#[cfg(target_arch = "wasm32")] fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { let mut off = false; ui.add_enabled(false, egui::Checkbox::new(&mut off, label)).on_disabled_hover_ui(|ui| { @@ -801,6 +815,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] settings.color_space, settings.usd_asset, settings.materialx, + settings.shader_parameters, ) = ( defaults.dir, defaults.format, @@ -813,6 +828,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] defaults.color_space, defaults.usd_asset, defaults.materialx, + defaults.shader_parameters, ); crate::export_templates::select(app, defaults.preset); } @@ -874,8 +890,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] #[cfg(target_arch = "wasm32")] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); - // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); + ui.checkbox(&mut app.ui.export.shader_parameters, tr("Export shader settings")) + .on_hover_text(tr("Save the settings of each shader instance in a JSON file")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..570fb3ab 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -368,6 +368,9 @@ pub struct ExportUi { /// `file.exportTextures`). #[serde(default)] pub materialx: bool, + /// Also write `_shaders.json`: the shader's settings and the texture sets using it (`shaderParameters` of `file.exportTextures`) + #[serde(default)] + pub shader_parameters: bool, /// Texture sets excluded from export. pub skip: Vec, /// Per texture set (by index) overrides of the settings above. @@ -442,6 +445,7 @@ impl Default for ExportUi { color_space: String::new(), usd_asset: false, materialx: false, + shader_parameters: false, skip: Vec::new(), sets: Default::default(), owner: Vec::new(), diff --git a/crates/ui-egui/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index cf4a87de..853ca813 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -20,6 +20,8 @@ pub struct ExportJob { /// Also write the mesh and materials as a USD asset with the last texture set, as ticked when /// Export was clicked. pub usd_asset: bool, + /// Also write the shader parameters with the last texture set, listing every texture set of the export, as ticked when Export was clicked + pub shader_parameters: bool, /// The params of the texture sets written so far, for the USD asset. pub sent: Vec, /// Warning messages already shown in this export. diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 3991e3c8..8daad344 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -364,6 +364,13 @@ mod web { // Keep one file for each case-insensitive name in the download texturecraft_engine::formats::skip_repeated_names(&mut files); + if app.ui.export.shader_parameters { + let sets: Vec = jobs.iter().map(|(set_index, _)| *set_index).collect(); + let parameters = texturecraft_engine::shader_parameters::shader_parameters(&app.session.doc.project, &sets); + let name = texturecraft_engine::shader_parameters::shader_parameters_file(&app.session.doc.project.name); + let bytes = serde_json::to_vec_pretty(¶meters).map_err(|e| e.to_string())?; + files.push(ExportedFile { name, bytes, width: 0, height: 0, warnings: Vec::new() }); + } app.session.log.warnings("MapExporter", files.iter().flat_map(|file| file.warnings.iter().cloned())); let file_count = files.len(); diff --git a/crates/ui-egui/tests/it/export_shader_parameters.rs b/crates/ui-egui/tests/it/export_shader_parameters.rs new file mode 100644 index 00000000..60d561e7 --- /dev/null +++ b/crates/ui-egui/tests/it/export_shader_parameters.rs @@ -0,0 +1,39 @@ +//! Export textures › SETTINGS: Export shader settings writes `_shaders.json`, the +//! shader's settings and every texture set of the export, with the export's last texture set + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use texturecraft_ui_egui::TextureCraftApp; + +#[test] +fn ticking_export_shader_settings_writes_the_json_listing_every_exported_set() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + let dir = std::env::temp_dir().join(format!("tc-export-shader-parameters-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + + h.get_by_role_and_label(egui::Role::CheckBox, "Export shader settings").click(); + h.run_steps(4); + assert!(h.state().ui.export.shader_parameters); + h.get_all_by_label("Export").last().unwrap().click(); + for _ in 0..64 { + h.run_steps(1); + if h.state().ui.export.job.is_none() { + break; + } + } + h.run_steps(2); + + let project = &h.state().session.doc.project; + let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&project.name)); + let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap_or_else(|_| panic!("{} was written", file.display()))).unwrap(); + let names: Vec<&str> = project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + assert_eq!(json["shaders"][0]["textureSets"], serde_json::json!(names), "every texture set of the export, written once: {json}"); + assert!(json["shaders"][0]["parameters"]["ior"].is_number()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c8d7f0f3..d24faf45 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -28,6 +28,7 @@ mod export_overrides; mod export_progress; mod export_reference_texts; mod export_settings; +mod export_shader_parameters; mod export_template_guards; mod export_usd_asset; mod file_dialogs; diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index aab7c36d..8d5162d5 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -118,8 +118,9 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { assert!(harness.query_by_label(label).is_some(), "{label}"); } assert!(harness.query_by_label_contains("textures selected for export").is_some()); - assert!(!says_not_available(&mut harness, "Export USD asset")); - assert!(says_not_available(&mut harness, "Export shader settings")); + for label in ["Export USD asset", "Export shader settings"] { + assert!(!says_not_available(&mut harness, label), "{label}"); + } harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); From 20270b4f38a6fa9bbfde34067692a6e409452919 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:36:43 +0000 Subject: [PATCH 023/190] Export textures: Esc closes the window as Cancel does, after an open list, rename or channel question Fixes #284 --- crates/ui-egui/src/export_window.rs | 16 +++++++++++++ crates/ui-egui/src/menus.rs | 3 +++ crates/ui-egui/src/state.rs | 4 ++++ crates/ui-egui/tests/it/export_settings.rs | 26 +++++++++++++++++++++ crates/ui-egui/tests/it/output_templates.rs | 26 +++++++++++++++++++++ 5 files changed, 75 insertions(+) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 1c1d2db4..aa005e46 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1466,6 +1466,19 @@ fn cancel(app: &mut TextureCraftApp) { app.ui.windows.export = false; } +/// Escape closes the window as Cancel does, read in `menus::shortcuts`; an open dropdown, channel question, template rename or text field takes it first +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, popup_open: bool) { + let export = &app.ui.export; + if popup_open || export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some() { + return; + } + + if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { + app.ui.export.job = None; + cancel(app); + } +} + pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.export { // The window opens on SETTINGS again; an export stops with it @@ -1651,6 +1664,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); crate::export_templates::ask(app, ctx); + // egui drops a field's focus on Escape before the next frame's shortcuts run, so keep whether one had the keyboard + app.ui.export.field_had_keyboard = ctx.egui_wants_keyboard_input(); + // Dismissal must run before the next write if canceled || !open { app.ui.export.job = None; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..dec4bc37 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,6 +526,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); + } else if app.ui.windows.export { + // Escape is the window's Cancel; nothing behind the window reads it + crate::export_window::keys_in(app, input, !escape_is_free); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 570fb3ab..fbcd6053 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -414,6 +414,9 @@ pub struct ExportUi { /// Output templates tab: F2 asked to rename the selected preset. #[serde(skip)] pub rename_key: bool, + /// A text field of the window had the keyboard when the last frame ended + #[serde(skip)] + pub field_had_keyboard: bool, /// Output templates tab: the question waiting for an answer (delete, or drop an unsaved edit). #[serde(skip)] pub ask: Option, @@ -460,6 +463,7 @@ impl Default for ExportUi { pending_drop: None, renaming: None, rename_key: false, + field_had_keyboard: false, ask: None, opened_with: None, job: None, diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 98af3660..6f1212e0 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -72,6 +72,32 @@ fn closing_the_window_is_cancel() { assert_eq!(h.state().ui.export.size, 0); } +#[test] +fn escape_is_cancel() { + let mut h = harness(); + h.state_mut().ui.export.size = 2048; + h.run_steps(3); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(h.state().ui.export.size, 0, "the opening settings are back"); +} + +#[test] +fn escape_in_an_open_dropdown_closes_only_the_dropdown() { + let mut h = harness(); + open_combo(&mut h, "Based on output template"); + assert!(h.query_by_label("png").is_some()); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.query_by_label("png").is_none(), "the dropdown closed"); + assert!(h.state().ui.windows.export, "the window stays open"); +} + #[test] fn the_lists_hold_the_reference_entries() { let mut h = harness(); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index fb791acb..2dacd6cd 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -152,6 +152,8 @@ fn the_right_click_menu_renames_and_removes_user_templates_only() { assert_eq!(h.state().ui.export.renaming.as_deref(), Some("Mine")); h.key_press(egui::Key::Escape); h.run_steps(4); + assert!(h.state().ui.export.renaming.is_none(), "Escape ends the rename"); + assert!(h.state().ui.windows.export, "and leaves the window open"); right_click(&mut h, "Mine"); click(&mut h, "Remove"); @@ -491,6 +493,29 @@ fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() { assert!(h.query_all_by_label("RGB: Base color, RGB").next().is_some()); } +#[test] +fn escape_in_a_file_name_field_leaves_the_field_and_keeps_the_window() { + let library = TemplateLibrary::new("escape-in-a-field"); + let mut h = harness(&library); + let field = name_field(&h, 0).center(); + h.hover_at(field); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: field, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(4); + assert!(h.ctx.egui_wants_keyboard_input(), "the field has the keyboard"); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.state().ui.windows.export, "the window stays open"); + assert!(!h.ctx.egui_wants_keyboard_input(), "the field let go of the keyboard"); + h.key_press(egui::Key::Escape); + h.run_steps(4); + assert!(!h.state().ui.windows.export, "a second Escape is Cancel"); +} + #[test] fn escape_closes_the_from_popup_without_assigning() { let library = TemplateLibrary::new("drop-escape"); @@ -510,6 +535,7 @@ fn escape_closes_the_from_popup_without_assigning() { assert!(h.query_by_label("Which part of Metallic?").is_none(), "Escape closes the popup"); assert!(h.state().ui.export.pending_drop.is_none()); + assert!(h.state().ui.windows.export, "the window stays open"); assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned"); } From 276f5d9f78b9e464227713392cc03c56ce6295d8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:41:32 +0000 Subject: [PATCH 024/190] Output templates: hovering a channel swatch shows the file its output writes, small, with each channel and its source; export.preview samples one output map --- crates/engine/src/file_cmds.rs | 77 +++++++-- crates/engine/tests/it/export_maps.rs | 19 +++ crates/formats/src/export/map_preview.rs | 69 ++++++++ crates/formats/src/export/map_renderer.rs | 12 +- crates/formats/src/export/mod.rs | 19 +++ crates/formats/src/export/tests.rs | 25 +++ crates/formats/src/lib.rs | 4 +- crates/ui-egui/src/export_templates.rs | 156 ++++++++++++++---- .../src/export_templates/map_preview_cache.rs | 59 +++++++ .../export_templates/map_preview_pictures.rs | 43 +++++ .../src/export_templates/planned_output.rs | 12 ++ .../ui-egui/src/export_templates/row_edit.rs | 2 + crates/ui-egui/tests/it/output_templates.rs | 20 +++ docs/control-protocol.md | 2 +- 14 files changed, 454 insertions(+), 65 deletions(-) create mode 100644 crates/formats/src/export/map_preview.rs create mode 100644 crates/ui-egui/src/export_templates/map_preview_cache.rs create mode 100644 crates/ui-egui/src/export_templates/map_preview_pictures.rs create mode 100644 crates/ui-egui/src/export_templates/planned_output.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 2688061c..b1d6ac31 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -12,13 +12,16 @@ use serde_json::{Value, json}; use texturecraft_core::{NormalFormat, PROJECT_EXT}; use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::PlannedFile; -use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile}; +use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, MapPreview, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}; use crate::session::{Document, Session}; use crate::{EngineError, Result, cmd}; +/// export.preview's picture width when the params name none +const DEFAULT_PREVIEW_SIDE_PIXELS: u32 = 128; + pub fn specs() -> Vec { vec![ cmd!( @@ -80,6 +83,15 @@ pub fn specs() -> Vec { always, plan ), + cmd!( + "export.preview", + "Preview an output map", + [], + None, + "{map: index into the preset's maps, side?: px (default 128, at most 512), plus the params of export.plan (the first texture set `ts` names)} → {width, height, channels: [\"R\", ...], pixels: [8-bit values as an sRGB file stores them, channels interleaved, row by row]}, or null when the texture set writes no file for the map", + always, + preview + ), ] } @@ -289,31 +301,50 @@ impl Session { let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); - let empty = Default::default(); for &set_index in sets { - let cache = self.caches.get(set_index).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; let plans = texturecraft_formats::list_outputs(&self.doc.project, set_index, &mesh_name, options).map_err(fe)?; let plans = select(set_index, plans); if plans.is_empty() { continue; } - let composite = - self.document_composite(set_index, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; - let coverage = cache.gbuf.coverage_mask(); - let input = ExportInput { - project: &self.doc.project, - ts: set_index, - composite: &composite, - baked: self.doc.baked.get(&set_index).unwrap_or(&empty), - coverage: &coverage, - mesh_name: &mesh_name, - }; - out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?); + let files = + self.with_export_input(set_index, &mesh_name, |input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe))?; + out.extend(files); } Ok(out) } + + /// Run `with` on texture set `set_index`'s export input: its document composite, coverage and baked maps + fn with_export_input(&self, set_index: usize, mesh_name: &str, with: impl FnOnce(&ExportInput) -> Result) -> Result { + let missing = || EngineError::Other(format!("no texture set {set_index}")); + let cache = self.caches.get(set_index).ok_or_else(missing)?; + let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(missing)?; + let coverage = cache.gbuf.coverage_mask(); + let empty = Default::default(); + let input = ExportInput { + project: &self.doc.project, + ts: set_index, + composite: &composite, + baked: self.doc.baked.get(&set_index).unwrap_or(&empty), + coverage: &coverage, + mesh_name, + }; + with(&input) + } + + /// A picture at most `side` pixels wide of output map `map` for the first texture set `params` names; None when it writes no file for the map + pub fn export_preview(&mut self, params: &Value, map: usize, side: u32) -> Result> { + let options = export_options(self, params, "export.preview")?; + let Some(&set_index) = sets_param(self, params, "export.preview")?.first() else { return Ok(None) }; + + if self.solo.is_none() { + self.update(); + } + let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); + self.with_export_input(set_index, &mesh_name, |input| MapPreview::sample(input, &options, map, side).map_err(fe)) + } } fn check_materials(p: &texturecraft_core::Project, mesh: &Mesh) -> Result<()> { @@ -432,6 +463,22 @@ fn set_index(s: &Session, v: &Value, cmd: &str) -> Result { v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`")) } +fn preview(session: &mut Session, params: &Value) -> Result { + let map = u64p(params, "map").and_then(|map| usize::try_from(map).ok()); + let map = map.ok_or_else(|| bad("export.preview", "`map` (an output map index) is required"))?; + let side = u64p(params, "side").map_or(DEFAULT_PREVIEW_SIDE_PIXELS, |side| side.clamp(1, u64::from(texturecraft_formats::MAX_PREVIEW_SIDE)) as u32); + + Ok(match session.export_preview(params, map, side)? { + Some(preview) => json!({ + "width": preview.width, + "height": preview.height, + "channels": preview.channels.iter().map(|dest| format!("{dest:?}")).collect::>(), + "pixels": preview.pixels, + }), + None => Value::Null, + }) +} + fn plan(session: &mut Session, params: &Value) -> Result { use texturecraft_formats::export::{list_set_outputs, scale_export_side}; diff --git a/crates/engine/tests/it/export_maps.rs b/crates/engine/tests/it/export_maps.rs index 991b5f32..30ec6b0a 100644 --- a/crates/engine/tests/it/export_maps.rs +++ b/crates/engine/tests/it/export_maps.rs @@ -105,3 +105,22 @@ fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() { } assert_eq!(result["files"].as_array().unwrap().len(), names.len()); } + +#[test] +fn export_preview_shows_a_packed_map_small_and_nothing_for_a_left_out_one() { + let mut s = session(); + let preset = s.export_preset("Unity HDRP (Mask Map)").unwrap(); + let mask = preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap(); + let params = json!({"preset": preset.name, "ts": 0, "map": mask, "side": 16}); + + let preview = execute(&mut s, "export.preview", ¶ms).unwrap(); + let (width, height) = (preview["width"].as_u64().unwrap(), preview["height"].as_u64().unwrap()); + assert!(width <= 16 && height > 0, "{preview}"); + assert_eq!(preview["channels"], json!(["R", "G", "B", "A"]), "the mask map packs four channels"); + assert_eq!(preview["pixels"].as_array().unwrap().len() as u64, width * height * 4); + + let left_out = json!({"preset": preset.name, "ts": 0, "map": mask, "maps": [{"map": mask, "enabled": false}]}); + assert!(execute(&mut s, "export.preview", &left_out).unwrap().is_null(), "a map the export leaves out has no file to show"); + assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name})).is_err(), "the map is required"); + assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name, "map": preset.maps.len()})).is_err()); +} diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs new file mode 100644 index 00000000..a72202d7 --- /dev/null +++ b/crates/formats/src/export/map_preview.rs @@ -0,0 +1,69 @@ +//! A small picture of one output map, sampled from the texture set as the export samples it + +use rayon::prelude::*; +use texturecraft_texel::linear_to_srgb; + +use super::{At, Dest, ExportInput, ExportOptions, Sampler, layout, list_outputs}; +use crate::{FormatError, Result}; + +/// The largest preview side: a preview is a glance, never a second export +pub const MAX_PREVIEW_SIDE: u32 = 512; + +/// One output map, small: its channels in file order and the 8-bit values an sRGB file of it stores (colour channels sRGB-encoded, data as is) +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MapPreview { + pub width: u32, + pub height: u32, + pub channels: Vec, + /// `channels.len()` values per pixel, row by row + pub pixels: Vec, +} + +impl MapPreview { + /// Output map `map` of `options`' template for `input`'s set, at most `side` wide; None when it writes no file; texels off the UV islands show the default + pub fn sample(input: &ExportInput, options: &ExportOptions, map: usize, side: u32) -> Result> { + let set = input.project.texture_set(input.ts)?; + let spec = options.preset.maps.get(map).ok_or_else(|| FormatError::Invalid(format!("the template has no output map {map}")))?; + let planned = list_outputs(input.project, input.ts, input.mesh_name, options)?; + if !planned.iter().any(|file| file.maps().any(|written| written == map)) { + return Ok(None); + } + + let (composite_width, height) = (input.composite.resolution, input.composite.height); + if composite_width == 0 || height == 0 || input.coverage.len() != composite_width as usize * height as usize { + return Err(FormatError::Invalid(format!("composite size {composite_width}×{height} does not match its coverage"))); + } + + let width = side.clamp(1, MAX_PREVIEW_SIDE).min(composite_width); + let rows = ((u64::from(width) * u64::from(height) / u64::from(composite_width)) as u32).max(1); + let tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1); + let sampler = Sampler::new(input, options, set, tile_res); + let channel_layout = layout(set, spec); + let count = channel_layout.len(); + let color = spec.is_color(); + let max_sample = f32::from(u8::MAX); + + // The texel under the centre of preview pixel `i` of `out` pixels across `of` texels + let texel = |i: u32, out: u32, of: u32| ((u64::from(i) * 2 + 1) * u64::from(of) / (2 * u64::from(out))).min(u64::from(of) - 1) as u32; + + let mut pixels = vec![0u8; width as usize * rows as usize * count]; + pixels.par_chunks_mut(width as usize * count).enumerate().for_each(|(row, values)| { + let y = texel(row as u32, rows, height); + for column in 0..width { + let x = texel(column, width, composite_width); + let at = if sampler.covered(x, y) { At::Texel(x, y) } else { At::Default }; + let mut cache = None; + for (component, (dest, source)) in channel_layout.iter().enumerate() { + let sample = sampler.sample(source, at, &mut cache); + let value = if spec.inverted.contains(dest) { 1.0 - sample } else { sample }; + let stored = if color && *dest != Dest::A { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }; + if let Some(slot) = values.get_mut(column as usize * count + component) { + *slot = (stored * max_sample + 0.5) as u8; + } + } + } + }); + + Ok(Some(MapPreview { width, height: rows, channels: channel_layout.iter().map(|(dest, _)| *dest).collect(), pixels })) + } +} diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs index e4a6e7f7..71dfba2e 100644 --- a/crates/formats/src/export/map_renderer.rs +++ b/crates/formats/src/export/map_renderer.rs @@ -42,17 +42,7 @@ impl<'a> MapRenderer<'a> { } Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), }; - let sampler = Sampler { - set, - comp: input.composite, - baked: input.baked, - coverage: input.coverage, - res: width, - tile_res, - scales: set.block_scales(), - normal_override: options.normal_format, - project_normal: input.project.normal_format, - }; + let sampler = Sampler::new(input, options, set, tile_res); Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 26ef58fc..f21dbf66 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -29,11 +29,13 @@ mod encoding; mod jpeg2000; mod layered_psd; mod map_override; +mod map_preview; mod map_renderer; mod planned_layer; mod rendered_map; use encoding::Encoding; pub use map_override::MapOverride; +pub use map_preview::{MAX_PREVIEW_SIDE, MapPreview}; use map_renderer::MapRenderer; pub use planned_layer::PlannedLayer; @@ -870,6 +872,23 @@ pub fn rnm(base: Vec3, detail: Vec3) -> Vec3 { (t * t.dot(u) / t.z.max(1e-4) - u).try_normalize().unwrap_or(base) } +impl<'a> Sampler<'a> { + /// The sampler of `input`'s texture set `set`, whose atlas blocks are `tile_res` texels wide + fn new(input: &ExportInput<'a>, options: &ExportOptions, set: &'a TextureSet, tile_res: u32) -> Sampler<'a> { + Sampler { + set, + comp: input.composite, + baked: input.baked, + coverage: input.coverage, + res: input.composite.resolution, + tile_res, + scales: set.block_scales(), + normal_override: options.normal_format, + project_normal: input.project.normal_format, + } + } +} + impl Sampler<'_> { fn channel(&self, c: Channel, at: At) -> [f32; 3] { match at { diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index f050b2b6..14bb5238 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1715,3 +1715,28 @@ fn write_files_accepts_a_long_nested_folder_and_stem() { assert!(paths[0].is_file()); std::fs::remove_dir_all(&dir).unwrap(); } + +#[test] +fn a_map_preview_holds_the_values_its_file_stores() { + let mut fx = Fx::new(&default_channels()); + fx.set_all(Channel::Metallic, |x, _| [x as f32 / 63.0; 3]); + fx.set_all(Channel::Roughness, |_, y| [y as f32 / 63.0; 3]); + let mut options = ExportOptions::new(builtin_preset("Unity HDRP (Mask Map)").unwrap()); + let mask = options.preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap(); + let base = options.preset.maps.iter().position(|map| map.file.contains("BaseMap")).unwrap(); + options.preset.maps[mask].inverted.push(Dest::R); + let files = fx.render(&options); + + // The packed data map, one channel inverted, and the sRGB colour map + for (index, suffix) in [(mask, "MaskMap"), (base, "BaseMap")] { + let file = decode(find(&files, suffix)); + let preview = MapPreview::sample(&fx.input(), &options, index, RES).unwrap().unwrap(); + assert_eq!((preview.width, preview.height), file.dimensions()); + assert_eq!(preview.channels.len(), usize::from(file.color().channel_count()), "{suffix}"); + assert!(preview.pixels == file.into_bytes(), "{suffix}: the preview shows what the file stores"); + } + + let small = MapPreview::sample(&fx.input(), &options, mask, 8).unwrap().unwrap(); + assert!(small.width < RES && small.pixels.len() == (small.width * small.height) as usize * 4, "a smaller preview samples the same map"); + assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error"); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a46a6f62..274f3a10 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -42,8 +42,8 @@ pub mod project_file; pub mod zip_read; pub use export::{ - Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, - render_maps, skip_repeated_names, + Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MAX_PREVIEW_SIDE, MapOverride, MapPreview, MapSpec, Padding, PlannedFile, + SourceRef, VirtualMap, list_outputs, render_maps, skip_repeated_names, }; pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource}; pub use mesh_export::{ diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 3e7ab2b6..532d4a3c 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -20,7 +20,10 @@ use crate::widgets::{chip, icon_button_without_tooltip}; mod channel_target; mod map_drag; mod map_lists; +mod map_preview_cache; +mod map_preview_pictures; mod pending_drop; +mod planned_output; mod row_edit; mod source_pick; mod swatch_look; @@ -28,7 +31,10 @@ mod swatch_look; pub use channel_target::ChannelTarget; use map_drag::MapDrag; use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; +use map_preview_cache::MapPreviewCache; +use map_preview_pictures::MapPreviewPictures; pub use pending_drop::PendingDrop; +use planned_output::PlannedOutput; use row_edit::RowEdit; use source_pick::SourcePick; use swatch_look::SwatchLook; @@ -86,6 +92,9 @@ const DROP_HIGHLIGHT_STROKE_POINTS: f32 = 1.5; const DROP_HIGHLIGHT_GAP_POINTS: f32 = 2.0; /// Side of the corner mark of an inverted swatch const INVERTED_MARK_POINTS: f32 = 8.0; +/// A swatch's file preview: the file's width, and the side of each channel's picture beside it +const PREVIEW_FILE_WIDTH_POINTS: f32 = 150.0; +const PREVIEW_CHANNEL_WIDTH_POINTS: f32 = 34.0; /// A channel swatch: its side, the label's size and offset from the top, and the bars that show /// which channels of the source it reads @@ -762,7 +771,11 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { return; } }; - let preview = preview_names(app, &preset); + let params = plan_params(app, &preset); + let preview = params.as_ref().map_err(String::clone).and_then(|params| planned_outputs(app, params)); + if let Ok(params) = ¶ms { + MapPreviewCache::keep_current(app, ui.ctx(), params); + } let mut edit = RowEdit::default(); // The selected template in a strip, "Current preset:" in bold @@ -815,21 +828,22 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { // Every row takes the column's width, not the width a wider row before it left let row_width = ui.available_width(); for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { - let file = preview.as_ref().ok().and_then(|names| names.get(index).cloned().flatten()); - let planned = match file { - Some(file) => format!("{} {file}", ic::ARROW_RIGHT), - None => tr("Not exported: no source in this texture set").to_string(), - }; - changed |= ui.allocate_ui(vec2(row_width, 0.0), |ui| output_row(ui, index, map_count, map, row_split, &planned, &mut edit)).inner; + let planned = preview.as_ref().ok().and_then(|outputs| outputs.get(index)).and_then(Option::as_ref); + changed |= ui.allocate_ui(vec2(row_width, 0.0), |ui| output_row(ui, index, map_count, map, row_split, planned, &mut edit)).inner; ui.add_space(ROW_GAP_POINTS); } }); }); ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); + // The hovered output's pictures show from the next frame on + if let (Some(index), Ok(params)) = (edit.hovered_output, ¶ms) { + MapPreviewCache::fill(app, ui.ctx(), params, index); + } + // Count only maps that have sources in the current set - if let Ok(names) = &preview { - let exported = names.iter().flatten().count(); + if let Ok(planned) = &preview { + let exported = planned.iter().flatten().count(); egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); @@ -916,45 +930,57 @@ fn commit(app: &mut TextureCraftApp, preset: ExportPreset, mut origin: Vec Result>, String> { - let mut p = crate::export_window::set_params(app, app.session.ts()); - p["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?; +/// The `export.plan` and `export.preview` params of `preset` for the current texture set with the window's settings +fn plan_params(app: &TextureCraftApp, preset: &ExportPreset) -> Result { + let mut params = crate::export_window::set_params(app, app.session.ts()); + params["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?; // The set's map overrides apply only to its own template - if let Some(p) = p.as_object_mut() { - p.remove("maps"); + if let Some(params) = params.as_object_mut() { + params.remove("maps"); } - let plan = texturecraft_engine::execute(&mut app.session, "export.plan", &p).map_err(|e| e.to_string())?; - let mut names = vec![None; preset.maps.len()]; + Ok(params) +} + +/// The file each map of `params`' template writes for the texture set (None: no sources), via `export.plan`; a PSD's maps each get the file and their layer +fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result>, String> { + let plan = texturecraft_engine::execute(&mut app.session, "export.plan", params).map_err(|e| e.to_string())?; + let map_count = params.pointer("/preset/maps").and_then(Value::as_array).map_or(0, Vec::len); let index = |value: &Value| value.get("map").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); - for f in plan.as_array().into_iter().flatten() { - let Some(file) = f.get("file").and_then(Value::as_str) else { continue }; - let layers = f.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty()); - match layers { - // A PSD's maps each show the file and their layer + + let mut outputs = vec![None; map_count]; + for file in plan.as_array().into_iter().flatten() { + let Some(name) = file.get("file").and_then(Value::as_str) else { continue }; + + let output = PlannedOutput { + file: name.to_string(), + size: file.get("size").and_then(Value::as_u64).unwrap_or(0), + format: file.get("format").and_then(Value::as_str).and_then(FileFormat::from_extension), + bit_depth: file.get("bitDepth").and_then(Value::as_u64).and_then(|depth| u8::try_from(depth).ok()).unwrap_or(0), + dithering: file.get("dithering").and_then(Value::as_bool).unwrap_or(false), + }; + match file.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty()) { Some(layers) => { for layer in layers { - let name = layer.get("name").and_then(Value::as_str).unwrap_or_default(); - if let Some(slot) = index(layer).and_then(|i| names.get_mut(i)) { - *slot = Some(format!("{file} › {name}")); + let layer_name = layer.get("name").and_then(Value::as_str).unwrap_or_default(); + if let Some(slot) = index(layer).and_then(|i| outputs.get_mut(i)) { + *slot = Some(PlannedOutput { file: format!("{name} › {layer_name}"), ..output.clone() }); } } } None => { - if let Some(slot) = index(f).and_then(|i| names.get_mut(i)) { - *slot = Some(file.to_string()); + if let Some(slot) = index(file).and_then(|i| outputs.get_mut(i)) { + *slot = Some(output); } } } } - Ok(names) + Ok(outputs) } /// One output map row: drag grip, file name, "$", the channel swatches, then file type, bit depth, /// duplicate and remove. `planned` is the file it writes for the current texture set. -fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: &mut bool, planned: &str, edit: &mut RowEdit) -> bool { +fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { @@ -971,11 +997,11 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: grip(ui, index, count, edit); let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(name_width)).on_hover_ui(|ui| { ui.label(tr("File name without extension; variables insert names")); - ui.label(planned); + ui.label(planned_text(planned)); }); changed |= name.changed(); changed |= token_menu(ui, &mut map.file); - changed |= channel_swatches(ui, index, map, split, edit); + changed |= channel_swatches(ui, index, map, split, planned, edit); // The lists and icons at the row's right end: file format and duplicate, bit depth and remove ui.add_space((ui.available_width() - ROW_LISTS_WIDTH_POINTS).max(0.0)); @@ -1280,9 +1306,61 @@ fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: } } +/// "→ ", or why the output writes nothing +fn planned_text(planned: Option<&PlannedOutput>) -> String { + match planned { + Some(planned) => format!("{} {}", ic::ARROW_RIGHT, planned.file), + None => tr("Not exported: no source in this texture set").to_string(), + } +} + +/// Below a swatch's tooltip: the file its output writes, each channel with its source, then the file's size and type (built-in templates' swatches show it too) +fn output_preview(ui: &mut Ui, index: usize, map: &MapSpec, planned: Option<&PlannedOutput>) { + let tokens = Tokens::get(ui.ctx()); + ui.separator(); + let Some(planned) = planned else { + ui.label(RichText::new(planned_text(None)).color(tokens.text_dim)); + return; + }; + + ui.label(RichText::new(&planned.file).color(tokens.text_strong)); + if let Some(Some(pictures)) = MapPreviewCache::get(ui.ctx(), index) { + preview_pictures(ui, map, &pictures); + } + let file_type = planned.format.map_or("", FileFormat::extension); + let depth = crate::export_window::depth_label(planned.format, planned.bit_depth, planned.dithering); + ui.label(RichText::new(format!("{size} x {size} · {file_type} {depth}", size = planned.size)).color(tokens.text_dim)); +} + +/// The file's picture with each channel's grey picture, letter and source beside it +fn preview_pictures(ui: &mut Ui, map: &MapSpec, pictures: &MapPreviewPictures) { + let tokens = Tokens::get(ui.ctx()); + let picture = |texture, width: f32| egui::Image::new(texture).fit_to_exact_size(vec2(width, width * pictures.aspect)).corner_radius(tokens.radius); + ui.horizontal_top(|ui| { + ui.add(picture(&pictures.file, PREVIEW_FILE_WIDTH_POINTS)); + if pictures.channels.is_empty() { + return; + } + + ui.vertical(|ui| { + for (dest, texture) in &pictures.channels { + let target = ChannelTarget::One(*dest); + let source = source_of(map, target).cloned().unwrap_or(SourceRef::Constant(CLEARED_VALUE)); + let inverted = map.inverted.contains(dest); + ui.horizontal(|ui| { + ui.add(picture(texture, PREVIEW_CHANNEL_WIDTH_POINTS)); + ui.label(RichText::new(target_label(target)).color(tokens.text_strong)); + ui.label(RichText::new(swatch_tooltip(map, &source, target, inverted)).color(tokens.text_dim)); + }); + } + }); + }); +} + /// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel -/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. -fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { +/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. Hovering one +/// shows the file the output writes. +fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; let shows_split = *split || !rgb_collapsed(map); @@ -1297,12 +1375,18 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo name = trf("{swatch}, inverted", &[("swatch", &name)]); } let look = SwatchLook { fill: source_color(&source, &tokens), bars: swatch_bars(map, &source, target, &tokens), inverted }; - let response = swatch(ui, label, &name, &look).on_hover_ui(|ui| { + let response = swatch(ui, label, &name, &look); + if response.contains_pointer() { + edit.hovered_output = Some(index); + } + let hover = |ui: &mut Ui| { ui.label(&tooltip); if inverted { ui.label(tr("Inverted")); } - }); + output_preview(ui, index, map, planned); + }; + let response = response.on_hover_ui(hover).on_disabled_hover_ui(hover); // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row let map_dragged_over = response.dnd_hover_payload::().is_some(); diff --git a/crates/ui-egui/src/export_templates/map_preview_cache.rs b/crates/ui-egui/src/export_templates/map_preview_cache.rs new file mode 100644 index 00000000..c35a0c58 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_preview_cache.rs @@ -0,0 +1,59 @@ +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use serde_json::Value; + +use super::map_preview_pictures::MapPreviewPictures; +use crate::TextureCraftApp; + +/// Pixels across an output map's hover preview: enough to read the packing, cheap to sample +const PREVIEW_SIDE_PIXELS: u32 = 150; + +/// The output maps' hover pictures for one set of export params and one document revision, by output map index (None: no file for that map) +#[derive(Clone, Default)] +pub(super) struct MapPreviewCache { + key: u64, + pictures: HashMap>>, +} + +impl MapPreviewCache { + fn id() -> egui::Id { + egui::Id::unique("export_map_preview_cache") + } + + fn key(app: &TextureCraftApp, params: &Value) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + params.to_string().hash(&mut hasher); + app.session.revision.hash(&mut hasher); + hasher.finish() + } + + /// Output map `index`'s pictures once made; None until then + pub(super) fn get(ctx: &egui::Context, index: usize) -> Option>> { + ctx.data(|data| data.get_temp::(Self::id()).and_then(|cache| cache.pictures.get(&index).cloned())) + } + + /// Forget pictures made for other params or an older document, so `get` never shows them + pub(super) fn keep_current(app: &TextureCraftApp, ctx: &egui::Context, params: &Value) { + let key = Self::key(app, params); + ctx.data_mut(|data| { + let cache = data.get_temp_mut_or_default::(Self::id()); + if cache.key != key { + *cache = MapPreviewCache { key, pictures: HashMap::new() }; + } + }); + } + + /// Make output map `index`'s pictures for `params` unless they are made, and draw again to show them + pub(super) fn fill(app: &mut TextureCraftApp, ctx: &egui::Context, params: &Value, index: usize) { + if Self::get(ctx, index).is_some() { + return; + } + + let preview = app.session.export_preview(params, index, PREVIEW_SIDE_PIXELS).ok().flatten(); + let pictures = preview.map(|preview| Arc::new(MapPreviewPictures::new(ctx, &preview, index))); + ctx.data_mut(|data| data.get_temp_mut_or_default::(Self::id()).pictures.insert(index, pictures)); + ctx.request_repaint(); + } +} diff --git a/crates/ui-egui/src/export_templates/map_preview_pictures.rs b/crates/ui-egui/src/export_templates/map_preview_pictures.rs new file mode 100644 index 00000000..817cf3e8 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_preview_pictures.rs @@ -0,0 +1,43 @@ +use egui::{Color32, ColorImage, TextureHandle, TextureOptions}; +use texturecraft_engine::formats::{Dest, MapPreview}; + +/// An output map's file, small, then each of its channels in grey, as textures to draw +pub(super) struct MapPreviewPictures { + pub(super) file: TextureHandle, + /// Empty for a one-channel file, whose picture is its channel + pub(super) channels: Vec<(Dest, TextureHandle)>, + /// Height over width + pub(super) aspect: f32, +} + +impl MapPreviewPictures { + /// The pictures of `preview`, the preview of output map `index` + pub(super) fn new(ctx: &egui::Context, preview: &MapPreview, index: usize) -> MapPreviewPictures { + let size = [preview.width as usize, preview.height as usize]; + let pixel_count = size[0] * size[1]; + let count = preview.channels.len().max(1); + let value = |pixel: usize, channel: usize| preview.pixels.get(pixel * count + channel).copied().unwrap_or(0); + let load = |name: String, image: ColorImage| ctx.load_texture(name, image, TextureOptions::LINEAR); + + // The file as a viewer shows it: its colour, or its first channel in grey; alpha left out + let color = preview.channels.starts_with(&[Dest::R, Dest::G, Dest::B]); + let file = (0..pixel_count) + .map(|pixel| if color { Color32::from_rgb(value(pixel, 0), value(pixel, 1), value(pixel, 2)) } else { Color32::from_gray(value(pixel, 0)) }) + .collect(); + let channels = if preview.channels.len() > 1 { + let channel = |(k, dest): (usize, &Dest)| { + let image = ColorImage::from_gray_iter(size, (0..pixel_count).map(|pixel| value(pixel, k))); + (*dest, load(format!("export_map_preview_{index}_{k}"), image)) + }; + preview.channels.iter().enumerate().map(channel).collect() + } else { + Vec::new() + }; + + MapPreviewPictures { + file: load(format!("export_map_preview_{index}"), ColorImage::new(size, file)), + channels, + aspect: preview.height as f32 / preview.width.max(1) as f32, + } + } +} diff --git a/crates/ui-egui/src/export_templates/planned_output.rs b/crates/ui-egui/src/export_templates/planned_output.rs new file mode 100644 index 00000000..e81666d4 --- /dev/null +++ b/crates/ui-egui/src/export_templates/planned_output.rs @@ -0,0 +1,12 @@ +use texturecraft_engine::formats::FileFormat; + +/// A file an output map writes for the current texture set, as `export.plan` lists it +#[derive(Clone)] +pub(super) struct PlannedOutput { + pub(super) file: String, + /// Pixels per side (export.plan never plans an atlas, so every file is square) + pub(super) size: u64, + pub(super) format: Option, + pub(super) bit_depth: u8, + pub(super) dithering: bool, +} diff --git a/crates/ui-egui/src/export_templates/row_edit.rs b/crates/ui-egui/src/export_templates/row_edit.rs index 6568dac9..2143edfb 100644 --- a/crates/ui-egui/src/export_templates/row_edit.rs +++ b/crates/ui-egui/src/export_templates/row_edit.rs @@ -6,4 +6,6 @@ pub(super) struct RowEdit { pub(super) action: Option, /// A map dropped on a channel swatch, to ask which of its channels to use. pub(super) pending: Option, + /// The output map whose channel swatch the pointer is on, for its file preview + pub(super) hovered_output: Option, } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 2dacd6cd..92a3847b 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -639,3 +639,23 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}"); assert!(converted.left() < export.right() && converted.right() <= export.right() + 1.0, "{converted:?} {export:?}"); } + +#[test] +fn hovering_a_channel_swatch_shows_the_file_its_output_writes() { + let library = TemplateLibrary::new("map-preview"); + let mut h = harness(&library); + let swatch = + h.get_all_by_role(egui::Role::Button).find(|b| b.accesskit_node().label().is_some_and(|l| l.starts_with("B: Metallic"))).unwrap().rect().center(); + let pictures = h.query_all_by_role(egui::Role::Image).count(); + let roughness_lines = h.query_all_by_label("Roughness, gray value").count(); + let file_names = h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count(); + assert!(h.query_by_label_contains(" · png").is_none(), "nothing shows before the hover"); + + h.hover_at(swatch); + h.run_steps(30); + + assert!(h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count() > file_names, "the file's name"); + assert!(h.query_by_label_contains(" · png").is_some(), "the file's size and type"); + assert!(h.query_all_by_role(egui::Role::Image).count() > pictures, "the file and its channels, small"); + assert!(h.query_all_by_label("Roughness, gray value").count() > roughness_lines, "another channel's source is named"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c3a44fc8..6c51fb6c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -76,7 +76,7 @@ shared by different sets. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `j2k`, `jp2`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and -`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by +`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `export.preview` takes the same params plus `map` (an index into the template's maps) and `side` (pixels, at most 512) and returns that map for the first texture set `ts` names, small: `{width, height, channels, pixels}` with the 8-bit values an sRGB file stores, or null when the set writes no file for it. `padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its From a0d996fc0c954b1bff9e8d5abd3b959e3346a289 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:19:39 +0000 Subject: [PATCH 025/190] Export textures: the window's look and the Settings tab on the reference's columns, with sentence-case tabs and the bottom bar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The window's own look (export_window/export_look, drawn): controls a step darker than the window with a light edge, hovered and lit faces a step lighter, boxed checks, rounded sentence-case tabs that open into the body, orange only on Export, scroll bars in a 12 px strip beside each list. Settings lays out on the reference's columns and pitches: the texture set list (the selected row in the frame colour with a light edge), General Export Parameters with Normal map format and Color space under Padding (Color space says in its tooltip that data maps stay linear), the output directory as a field with "…", the extra-file ticks under the parameters, and a set's page with one pen column for its parameters and its Output maps rows. The tab row's right-hand control sits 9 px above the divider. ui_snapshots export_window_snapshots captures every tab at the reference window size. --- crates/ui-egui/src/export_window.rs | 1227 +++++++++-------- crates/ui-egui/src/export_window/drawn.rs | 305 ++++ .../ui-egui/src/export_window/export_look.rs | 118 ++ .../ui-egui/src/export_window/page_place.rs | 26 + .../ui-egui/tests/it/export_map_overrides.rs | 26 +- crates/ui-egui/tests/it/export_overrides.rs | 2 +- .../tests/it/export_reference_texts.rs | 2 +- crates/ui-egui/tests/it/export_settings.rs | 10 +- .../tests/it/export_template_guards.rs | 17 +- crates/ui-egui/tests/it/output_templates.rs | 11 +- crates/ui-egui/tests/it/side_panels.rs | 7 +- crates/ui-egui/tests/ui_snapshots.rs | 86 ++ 12 files changed, 1266 insertions(+), 571 deletions(-) create mode 100644 crates/ui-egui/src/export_window/drawn.rs create mode 100644 crates/ui-egui/src/export_window/export_look.rs create mode 100644 crates/ui-egui/src/export_window/page_place.rs diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index aa005e46..86635088 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -14,42 +14,151 @@ use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; use crate::theme::{Tokens, caption, semibold}; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::icon_button; +pub(crate) mod drawn; +pub(crate) mod export_look; mod inherited_settings; mod map_row; +mod page_place; +pub(crate) use export_look::ExportLook; use inherited_settings::InheritedSettings; use map_row::MapRow; +use page_place::PagePlace; /// The reference window's size; a smaller screen gets a smaller window const REFERENCE_WINDOW_SIZE_POINTS: egui::Vec2 = egui::vec2(1100.0, 740.0); /// Space kept free around the content on a small screen: the title bar, the frame and a gap const WINDOW_VIEWPORT_MARGIN_POINTS: f32 = 72.0; -/// Width of the texture set list -const LIST_WIDTH: f32 = 250.0; -const ICON: f32 = 20.0; -/// Width of the label column of the parameter rows, as in the reference -const LABEL_COLUMN_WIDTH: f32 = 200.0; -/// Width of the value column of the parameter rows -const VALUE_WIDTH: f32 = 360.0; -/// Width of the first File type list; the bit depth list fills the rest of the row -const FILE_TYPE_WIDTH: f32 = 166.0; -/// Width of the dilation button, with room for its drop-down arrow -const DILATION_BUTTON_WIDTH: f32 = 60.0; -/// Size of a drop-down arrow, and its distance from the button's right edge -const CARET_SIZE: f32 = 10.0; -const CARET_INSET: f32 = 6.0; -/// A tab: padding around its name, the accent line on top of the open one, the name's size -const TAB_PADDING: egui::Vec2 = egui::vec2(10.0, 6.0); -const TAB_ACCENT_HEIGHT: f32 = 2.0; -const TAB_TEXT_SIZE: f32 = 12.5; -/// Height of a full-width row of the texture set list and where its text starts -const LIST_ROW_HEIGHT: f32 = 24.0; -const LIST_ROW_INDENT: f32 = 16.0; +/// The content runs nearly to the window's frame: one point inside its edge +const CONTENT_INSET: i8 = 1; +/// The widest dilation the slider offers, the cap `export.run` puts on its `dilation` +const MAX_DILATION_PIXELS: u32 = 256; + +// Layout in points from the window content's top left corner, measured on the locked mocks + +/// The tab row's height, down to the divider under it +pub(crate) const TAB_ROW_HEIGHT: f32 = 42.0; +/// The tabs' top edge +const TAB_TOP: f32 = 16.0; +/// The first tab's left edge +const TABS_LEFT: f32 = 7.5; +/// Middle of the controls at the tab row's right end, 9 points of air above the divider +const TAB_ROW_CONTROLS_Y: f32 = 19.5; +/// From the window's left edge to the buttons there +const LEFT_MARGIN: f32 = 7.5; +/// From the window's right edge to the buttons there +const RIGHT_MARGIN: f32 = 10.5; +/// The bottom bar's height under its divider +const FOOTER_HEIGHT: f32 = 46.0; +/// Middle of the bottom bar's buttons, from the window's bottom +const FOOTER_MIDDLE_FROM_BOTTOM: f32 = 22.5; /// Width of the bottom bar's buttons, the same for all as in the reference -const FOOTER_BUTTON_WIDTH: f32 = 126.0; -/// Width of the keyboard focus outline on the window's drawn controls -const FOCUS_OUTLINE_WIDTH: f32 = 2.0; +const FOOTER_BUTTON_WIDTH: f32 = 117.5; +/// Gap between the bottom bar's buttons +const FOOTER_BUTTON_GAP: f32 = 6.5; +/// Air between the texture count and Cancel +const COUNT_GAP: f32 = 14.5; +/// Open output directory: the air around its name +const OPEN_DIRECTORY_PADDING: f32 = 24.0; +/// Open output directory: its distance from the window's right edge +const OPEN_DIRECTORY_FROM_RIGHT: f32 = 12.0; +/// The strip at a list's right edge that holds its scroll bar +pub(crate) const GUTTER: f32 = 12.0; +/// Size of the menu (≡) and reset glyphs of the lists and pages +const MENU_ICON_SIZE: f32 = 14.0; + +/// Width of the texture set list +const SET_LIST_WIDTH: f32 = 240.7; +/// Centre of the set list's menu, x +const SET_MENU_X: f32 = 227.5; +/// Centre of the set list's menu, y +const SET_MENU_Y: f32 = 57.0; +/// Top of the set list's first row, Global settings +const SET_ROWS_TOP: f32 = 70.0; +/// Height of a set list row +const SET_ROW_HEIGHT: f32 = 25.0; +/// Where a set row's check box starts +const SET_CHECK_LEFT: f32 = 18.8; +/// Where a set row's name starts +const SET_NAME_LEFT: f32 = 36.7; +/// Where Global settings starts, having no check box +const GLOBAL_NAME_LEFT: f32 = 16.0; +/// The override mark's distance from its row's end +const OVERRIDE_MARK_FROM_RIGHT: f32 = 14.0; +/// Side of a check box's click area +const CHECK_HIT_SIZE: f32 = 20.0; +/// How far a check box's click area reaches past its box on each side +const CHECK_HIT_OVERHANG: f32 = 3.5; + +/// A page's label column +const LABEL_LEFT: f32 = 257.6; +/// Where a page's controls start +const CONTROLS_LEFT: f32 = 455.0; +/// Where a page's controls end, from the window's right edge +const CONTROLS_RIGHT_MARGIN: f32 = 112.8; +/// A page header's glyph, from the window's right edge +const PAGE_ICON_FROM_RIGHT: f32 = 22.6; +/// Middle of the Global settings page's header +const GLOBAL_HEADER_Y: f32 = 71.0; +/// Middle of its reset glyph +const GLOBAL_ICON_Y: f32 = 70.0; +/// Middle of its first parameter row +const GLOBAL_FIRST_ROW_Y: f32 = 115.0; +/// Pitch of its parameter rows +const GLOBAL_ROW_PITCH: f32 = 35.5; +/// From the last parameter row to the first tick +const CHECKS_GAP: f32 = 30.0; +/// Pitch of the ticks +const CHECK_PITCH: f32 = 24.0; +/// The page's least width before it scrolls +const MIN_PAGE_WIDTH: f32 = 640.0; +/// The Global settings page's height under the tab row +const GLOBAL_PAGE_HEIGHT: f32 = 376.0; +/// The ticks sit a point in from the labels +const CHECK_INDENT: f32 = 1.0; +/// A tick's label starts after its box and the gap +const CHECK_LABEL_ROOM: f32 = 18.0; +/// Width of the output directory's "…" and reset buttons +const BROWSE_WIDTH: f32 = 22.0; +/// Gap before them +const BROWSE_GAP: f32 = 4.0; +/// Room the file type list keeps for its chevron past its longest entry +const FILE_TYPE_ROOM: f32 = 36.0; +/// Gap between two controls on one row +const PAIR_GAP: f32 = 6.6; +/// Width of the dilation width's dropdown +const DILATION_WIDTH: f32 = 56.4; + +/// Middle of a texture set page's header +const SET_HEADER_Y: f32 = 74.0; +/// Middle of its first override row +const SET_FIRST_ROW_Y: f32 = 121.0; +/// Pitch of its override rows +const SET_ROW_PITCH: f32 = 36.0; +/// Centre of the override pens +const PEN_CENTRE: f32 = 464.4; +/// Where an inherited value's text starts +const VALUE_LEFT: f32 = 479.4; +/// Where an override's control starts +const OVERRIDE_LEFT: f32 = 480.3; +/// The divider above Output maps +const SET_DIVIDER_Y: f32 = 257.0; +/// Middle of the Output maps header +const MAPS_HEADER_Y: f32 = 288.0; +/// Top of the first Output maps row +const MAPS_TOP: f32 = 318.0; +/// Pitch of the Output maps rows +const MAP_ROW_PITCH: f32 = 34.0; +/// Where an Output maps row's tick starts +const MAP_CHECK_LEFT: f32 = 258.6; +/// Where its file name starts +const MAP_NAME_LEFT: f32 = 280.1; +/// The inherited bit depth's text, after the file type's +const BITS_TEXT_OFFSET: f32 = 32.0; +/// Width of a map's file type list +const MAP_FORMAT_WIDTH: f32 = 61.2; +/// Width of a map's own size list +const MAP_SIZE_WIDTH: f32 = 100.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -104,9 +213,16 @@ pub(crate) fn depth_label(format: Option, bit_depth: u8, dithering: } } -/// A file type list and its bit depth list; `from_template` adds "Based on output template" -/// (an empty `format`), which leaves the bit depth to the template. -fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, format: &mut String, bit_depth: &mut u8, dithering: &mut bool) { +/// A file type list and its bit depth list in `rects`; `from_template` adds "Based on output template" (an empty `format`) +fn file_type_lists( + ui: &mut Ui, + id: (&str, usize, usize), + from_template: bool, + rects: [egui::Rect; 2], + format: &mut String, + bit_depth: &mut u8, + dithering: &mut bool, +) { let parsed = FileFormat::from_extension(format); // A depth the type does not have (or none) becomes its default @@ -116,10 +232,7 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f (*bit_depth, *dithering) = (f.default_depth(), false); } let shown = if format.is_empty() { tr("Based on output template").to_string() } else { file_type_name(format) }; - - // Tall enough for the whole list - let list = egui::ComboBox::from_id_salt(("type", id)).width(if from_template { FILE_TYPE_WIDTH } else { 90.0 }).height(f32::INFINITY); - list.selected_text(shown).show_ui(ui, |ui| { + drawn::combo(ui, rects[0], ("type", id), shown, |ui| { if from_template { if ui.selectable_label(format.is_empty(), tr("Based on output template")).clicked() { format.clear(); @@ -141,18 +254,21 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f } } }); + + // A file type with one bit depth (or none) shows its bit depth list greyed let options = parsed.map(depth_options).unwrap_or_default(); let shown = if parsed.is_some() { depth_label(parsed, *bit_depth, *dithering) } else { String::new() }; - ui.add_enabled_ui(options.len() > 1, |ui| { - // On the global page the bit depth list fills the row - let width = if from_template { VALUE_WIDTH - FILE_TYPE_WIDTH - ui.spacing().item_spacing.x } else { 120.0 }; - egui::ComboBox::from_id_salt(("bits", id)).width(width).selected_text(shown).show_ui(ui, |ui| { - for (d, dither) in options { - if ui.selectable_label((*bit_depth, *dithering) == (d, dither), depth_label(parsed, d, dither)).clicked() { - (*bit_depth, *dithering) = (d, dither); - } + if options.len() < 2 { + drawn::disabled_combo(ui, rects[1], &shown, tr("Bit depth")); + return; + } + + drawn::combo(ui, rects[1], ("bits", id), shown, |ui| { + for (depth, dither) in options { + if ui.selectable_label((*bit_depth, *dithering) == (depth, dither), depth_label(parsed, depth, dither)).clicked() { + (*bit_depth, *dithering) = (depth, dither); } - }); + } }); } @@ -190,10 +306,10 @@ pub(crate) fn template_groups(app: &TextureCraftApp, builtins: &[ExportPreset]) (first, rest) } -/// A template dropdown over `first` and `rest`; true when `current` changed -fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, bool)], rest: &[String]) -> bool { +/// A template dropdown in `rect` over `first` and `rest`; true when `current` changed +fn template_combo(ui: &mut Ui, rect: egui::Rect, id: &str, current: &mut String, first: &[(&str, bool)], rest: &[String]) -> bool { let mut changed = false; - egui::ComboBox::from_id_salt(id).width(VALUE_WIDTH).selected_text(current.clone()).show_ui(ui, |ui| { + drawn::combo(ui, rect, id, current.clone(), |ui| { for (name, have) in first { if *have { changed |= ui.selectable_value(current, (*name).to_string(), *name).on_hover_text(*name).changed(); @@ -535,16 +651,14 @@ fn set_template(app: &TextureCraftApp, ts: usize) -> String { app.ui.export.sets.get(&ts).and_then(|o| o.preset.clone()).unwrap_or_else(|| app.ui.export.preset.clone()) } -/// Shorten a long file name pattern at the front, as the reference's Output maps rows do -fn elide_front(text: &str) -> String { - const SHOWN: usize = 26; - let n = text.chars().count(); - if n <= SHOWN { text.to_string() } else { format!("…{}", text.chars().skip(n - (SHOWN - 1)).collect::()) } +/// A file type and bit depth as an Output maps row shows them ("png 8 bits"), and the two apart +fn file_type_text(t: &FileType) -> String { + let (format, bits) = file_type_parts(t); + format!("{format} {bits}") } -/// A file type and bit depth as an Output maps row shows them ("png 8 bits") -fn file_type_text(t: &FileType) -> String { - format!("{} {}", file_type_name(&t.format), depth_label(FileFormat::from_extension(&t.format), t.bit_depth, t.dithering)) +fn file_type_parts(t: &FileType) -> (String, String) { + (file_type_name(&t.format), depth_label(FileFormat::from_extension(&t.format), t.bit_depth, t.dithering)) } /// The rows of texture set `ts`'s Output maps: the template's maps the set has sources for @@ -583,80 +697,114 @@ fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { rows } -/// The Output maps section of texture set `ts`'s page -fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { +/// The Output maps section of texture set `ts`'s page: its header, then its rows scrolling in `area` +fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, area: egui::Rect) { + let look = ExportLook::get(ui.ctx()); let rows = map_rows(app, ts); let template = set_template(app, ts); - let o = app.ui.export.sets.entry(ts).or_default(); - if o.maps_template != template { - o.maps.clear(); - o.maps_template = template; + let overrides = app.ui.export.sets.entry(ts).or_default(); + if overrides.maps_template != template { + overrides.maps.clear(); + overrides.maps_template = template; } + let mut menu = None; - header(ui, tr("Output maps"), |ui| { - list_menu(ui, |ui| { - for (i, label) in [tr("Check all"), tr("Uncheck all"), tr("Invert all")].into_iter().enumerate() { - if ui.button(label).clicked() { - menu = Some(i); - } + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(MAPS_HEADER_Y), tr("Output maps"), look.text, true); + list_menu(ui, place.right_inset(PAGE_ICON_FROM_RIGHT, MAPS_HEADER_Y), tr("Output maps menu"), |ui| { + for (i, label) in [tr("Check all"), tr("Uncheck all"), tr("Invert all")].into_iter().enumerate() { + if ui.button(label).clicked() { + menu = Some(i); } - ui.separator(); - for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { - if ui.button(label).clicked() { - menu = Some(3 + i); - } + } + ui.separator(); + for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { + if ui.button(label).clicked() { + menu = Some(3 + i); + } + } + ui.separator(); + }); + + // The rows scroll under the header, the scroll bar in its strip at the window's right edge + ui.scope_builder(egui::UiBuilder::new().max_rect(area), |ui| { + egui::ScrollArea::vertical().id_salt(("exp_maps_scroll", ts)).auto_shrink([false; 2]).show(ui, |ui| { + let height = rows.len() as f32 * MAP_ROW_PITCH; + let (rows_rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::hover()); + for (index, row) in rows.iter().enumerate() { + let y = rows_rect.top() + (index as f32 + 0.5) * MAP_ROW_PITCH; + map_row(ui, place, y, ts, row, overrides.maps.entry(row.map).or_default()); } - ui.separator(); }); }); - egui::Grid::new(("exp_maps", ts)).num_columns(3).spacing(vec2(8.0, 6.0)).show(ui, |ui| { - for row in &rows { - let m = o.maps.entry(row.map).or_default(); - ui.checkbox(&mut m.enabled, ""); - ui.add(egui::Label::new(elide_front(&row.pattern)).selectable(false)).on_hover_text(&row.pattern); - ui.horizontal(|ui| { - if icon_button(ui, ic::PENCIL_SIMPLE, tr("Enable override"), m.file_type.is_some(), ICON).clicked() { - m.file_type = if m.file_type.is_some() { None } else { Some(row.inherited.clone()) }; - } - match &mut m.file_type { - Some(t) => file_type_combo(ui, ("exp_map", ts, row.map), t), - None => { - ui.label(file_type_text(&row.inherited)); - } - } - map_size_combo(ui, ("exp_map_size", ts, row.map), &mut m.size); - }); - ui.end_row(); - } - }); + for row in &rows { - let m = o.maps.entry(row.map).or_default(); + let map_export = overrides.maps.entry(row.map).or_default(); match menu { - Some(0) => m.enabled = true, - Some(1) => m.enabled = false, - Some(2) => m.enabled = !m.enabled, - Some(3) if m.file_type.is_none() => m.file_type = Some(row.inherited.clone()), - Some(4) => (m.file_type, m.size) = (None, None), + Some(0) => map_export.enabled = true, + Some(1) => map_export.enabled = false, + Some(2) => map_export.enabled = !map_export.enabled, + Some(3) if map_export.file_type.is_none() => map_export.file_type = Some(row.inherited.clone()), + Some(4) => (map_export.file_type, map_export.size) = (None, None), _ => {} } } - o.maps.retain(|_, m| *m != MapExport::default()); + overrides.maps.retain(|_, map_export| *map_export != MapExport::default()); } -/// An output map's size: the export's, or its own, which wins over it -fn map_size_combo(ui: &mut Ui, id: (&str, usize, usize), size: &mut Option) { +/// One Output maps row at `y`: tick, file name cut at the front, override pen, file type, the map's own size +fn map_row(ui: &mut Ui, place: PagePlace, y: f32, ts: usize, row: &MapRow, map_export: &mut MapExport) { + let look = ExportLook::get(ui.ctx()); + let check_left = place.x(MAP_CHECK_LEFT); + let hit = egui::Rect::from_center_size(egui::pos2(check_left + CHECK_HIT_SIZE / 2.0 - CHECK_HIT_OVERHANG, y), vec2(CHECK_HIT_SIZE, CHECK_HIT_SIZE)); + let name_left = place.x(MAP_NAME_LEFT); + let shown = drawn::fitted(ui, &row.pattern, place.x(CONTROLS_LEFT) - name_left, true, false); + drawn::check(ui, ui.scope_id().with(("exp_map_tick", ts, row.map)), hit, egui::pos2(check_left, y), &mut map_export.enabled, None, &shown); + let color = if map_export.enabled { look.text } else { look.text_dim }; + drawn::label_at(ui, name_left, y, &shown, color, false).on_hover_text(&row.pattern); + + let pen = egui::pos2(place.x(PEN_CENTRE), y); + if drawn::icon_button(ui, pen, ic::PENCIL_SIMPLE, drawn::CHEVRON_SIZE, tr("Enable override"), true, map_export.file_type.is_some()).clicked() { + map_export.file_type = if map_export.file_type.is_some() { None } else { Some(row.inherited.clone()) }; + } + + // The map's size list keeps the row's right end; the file type and bit depth come before it + let right = place.right - CONTROLS_RIGHT_MARGIN; + let size_rect = drawn::control_rect(right - MAP_SIZE_WIDTH, right, y); + match &mut map_export.file_type { + Some(FileType { format, bit_depth, dithering }) => { + let format_rect = drawn::control_rect(place.x(OVERRIDE_LEFT), place.x(OVERRIDE_LEFT) + MAP_FORMAT_WIDTH, y); + let bits_rect = drawn::control_rect(format_rect.right() + PAIR_GAP, size_rect.left() - PAIR_GAP, y); + file_type_lists(ui, ("exp_map", ts, row.map), false, [format_rect, bits_rect], format, bit_depth, dithering); + } + None => inherited_file_type(ui, place, y, &row.inherited), + } + map_size_combo(ui, size_rect, ("exp_map_size", ts, row.map), &mut map_export.size); +} + +/// A map's inherited file type: "png" and "8 bits" in their columns, one text to assistive technology +fn inherited_file_type(ui: &mut Ui, place: PagePlace, y: f32, inherited: &FileType) { + let look = ExportLook::get(ui.ctx()); + let (format, bits) = file_type_parts(inherited); + let format_rect = drawn::text_at(ui, place.x(VALUE_LEFT), y, &format, look.text, false); + let bits_rect = drawn::text_at(ui, place.x(VALUE_LEFT + BITS_TEXT_OFFSET), y, &bits, look.text, false); + let text = file_type_text(inherited); + let response = + ui.interact(format_rect.union(bits_rect), ui.scope_id().with(("exp_map_inherited", place.y(0.0).to_bits(), y.to_bits())), egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &text)); +} + +/// An output map's size in `rect`: the export's, or its own, which wins over it +fn map_size_combo(ui: &mut Ui, rect: egui::Rect, id: (&str, usize, usize), size: &mut Option) { let shown = size.map_or_else(|| tr("Export size").to_string(), |side| format!("{side}x{side}")); - egui::ComboBox::from_id_salt(id) - .selected_text(shown) - .show_ui(ui, |ui| { - ui.selectable_value(size, None, tr("Export size")); - ui.separator(); - for side in SIZES { - ui.selectable_value(size, Some(side), format!("{side}x{side}")); - } - }) - .response - .on_hover_text(tr("This map's own size, which wins over the export size")); + drawn::combo(ui, rect, id, shown, |ui| { + ui.selectable_value(size, None, tr("Export size")); + ui.separator(); + for side in SIZES { + ui.selectable_value(size, Some(side), format!("{side}x{side}")); + } + }) + .response + .on_hover_text(tr("This map's own size, which wins over the export size")); } /// Count the files planned across all selected texture sets. @@ -670,54 +818,10 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } -/// The keyboard focus outline of a drawn control: inside `response`'s rect, in the strong text -/// colour, so it differs from the accent of the selected one and the fill of the hovered one -fn paint_focus(ui: &Ui, response: &egui::Response) { - if response.has_focus() { - let stroke = egui::Stroke::new(FOCUS_OUTLINE_WIDTH, Tokens::get(ui.ctx()).text_strong); - ui.painter().rect_stroke(response.rect, 0.0, stroke, egui::StrokeKind::Inside); - } -} - -/// A window tab: a box, lighter and with an accent line on top when open -fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let color = if selected { tokens.text_strong } else { tokens.text }; - let galley = ui.painter().layout_no_wrap(label.to_string(), semibold(TAB_TEXT_SIZE), color); - let (rect, response) = ui.allocate_exact_size(galley.size() + 2.0 * TAB_PADDING, egui::Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, selected, label)); - - let painter = ui.painter(); - let fill = match (selected, response.hovered()) { - (true, _) => tokens.panel, - (false, true) => tokens.row_hover, - (false, false) => tokens.row, - }; - painter.rect(rect, 0.0, fill, egui::Stroke::new(1.0, tokens.separator), egui::StrokeKind::Inside); - if selected { - painter.rect_filled(egui::Rect::from_min_size(rect.min, vec2(rect.width(), TAB_ACCENT_HEIGHT)), 0.0, tokens.accent); - } - painter.galley(rect.min + TAB_PADDING, galley, color); - paint_focus(ui, &response); - response -} - -/// A bottom bar button, as wide as the others -fn footer_button(text: &str) -> egui::Button<'_> { - egui::Button::new(text).min_size(vec2(FOOTER_BUTTON_WIDTH, 0.0)) -} - -/// A header with a menu or tool at its right end -fn header(ui: &mut Ui, title: &str, right: impl FnOnce(&mut Ui)) { - ui.horizontal(|ui| { - ui.label(caption(title)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), right); - }); -} - -/// The menu button of a list header -fn list_menu(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { - ui.menu_button(RichText::new(ic::LIST_CHECKS).size(15.0), add); +/// The menu button (≡) of a list or page header centred on `centre`, called `name` for assistive technology; its menu holds `add` +fn list_menu(ui: &mut Ui, centre: egui::Pos2, name: &str, add: impl FnOnce(&mut Ui)) { + let response = drawn::icon_button(ui, centre, ic::LIST, MENU_ICON_SIZE, name, true, false); + egui::Popup::menu(&response).show(add); } /// Check all, Uncheck all, Invert all over the texture sets @@ -736,52 +840,53 @@ fn set_checks_menu(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); } -/// Output directory: the path as a button that opens the folder picker, and a reset -#[cfg(not(target_arch = "wasm32"))] -fn output_directory(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(tr("Output directory")); - ui.horizontal(|ui| { - let dir = app.ui.export.dir.clone(); - let button = egui::Button::new(dir.as_str()).truncate(); - if ui.add_sized(vec2(VALUE_WIDTH - 24.0, 20.0), button).on_hover_text(dir.as_str()).clicked() { - app.ask_file(FileDialog::folder().directory(dir), Bound::App, |app, paths| { - if let Some(d) = paths.first() { - app.ui.export.dir = d.display().to_string(); - } - }); - } - if ui.small_button("R").on_hover_text(tr("Reset to default")).clicked() { - app.ui.export.dir = ExportUi::default().dir; - } - }); - ui.end_row(); +/// A parameter's name at the label column, its middle at `y` +fn row_label(ui: &mut Ui, place: PagePlace, y: f32, text: &str) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, place.x(LABEL_LEFT), y, text, look.text, false); } -/// The dilation width: a button showing it, with a slider in its menu (only for paddings that -/// have a width) -fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { +/// Output directory at `y`: the path as a field that opens the folder picker, "…" and a reset +#[cfg(not(target_arch = "wasm32"))] +fn output_directory(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, y: f32) { + row_label(ui, place, y, tr("Output directory")); + let right = place.right - CONTROLS_RIGHT_MARGIN; + let dir = app.ui.export.dir.clone(); + let field = drawn::control_rect(place.x(CONTROLS_LEFT), right - BROWSE_WIDTH - BROWSE_GAP, y); + let path = drawn::field_button(ui, field, ui.scope_id().with("exp_dir"), &dir).on_hover_text(dir.as_str()); + let browse_rect = drawn::control_rect(right - BROWSE_WIDTH, right, y); + let browse_name = tr("Choose the output folder"); + let browse = drawn::button_with_id(ui, ui.scope_id().with("exp_dir_browse"), browse_rect, "…", browse_name, false, true).on_hover_text(browse_name); + if path.clicked() || browse.clicked() { + app.ask_file(FileDialog::folder().directory(dir), Bound::App, |app, paths| { + if let Some(directory) = paths.first() { + app.ui.export.dir = directory.display().to_string(); + } + }); + } + let reset = drawn::control_rect(right + BROWSE_GAP, right + BROWSE_GAP + BROWSE_WIDTH, y); + let reset_id = ui.scope_id().with("exp_dir_reset"); + let reset_name = tr("Reset to default"); + if drawn::button_with_id(ui, reset_id, reset, ic::ARROW_COUNTER_CLOCKWISE, reset_name, false, true).on_hover_text(reset_name).clicked() { + app.ui.export.dir = ExportUi::default().dir; + } +} + +/// The dilation width in `rect`: a dropdown with a slider in its menu, greyed for paddings without a width +fn dilation_button(ui: &mut Ui, rect: egui::Rect, id_salt: &str, padding: &str, dilation: &mut u32) { let enabled = has_width(padding); + let response = drawn::combo_button(ui, rect, ui.scope_id().with(("exp_dilation", id_salt)), &dilation.to_string(), enabled); + if !enabled { + response.on_hover_text(tr("This padding mode does not use a dilation width")); + return; + } // The menu stays open while the slider is used - let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); - let r = ui.add_enabled_ui(enabled, |ui| { - let button = egui::Button::new(dilation.to_string()).min_size(vec2(DILATION_BUTTON_WIDTH, 0.0)); - egui::containers::menu::MenuButton::from_button(button).config(config).ui(ui, |ui| { - ui.label(tr("Dilation (pixels)")); - ui.add(egui::Slider::new(dilation, 0..=256).step_by(1.0)); - }) + let response = response.on_hover_text(tr("Dilation in pixels")); + egui::Popup::menu(&response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.label(tr("Dilation (pixels)")); + ui.add(egui::Slider::new(dilation, 0..=MAX_DILATION_PIXELS).step_by(1.0)); }); - - // The drop-down arrow is drawn apart, so the button's name stays the number - let tokens = Tokens::get(ui.ctx()); - let arrow_color = if enabled { tokens.text } else { tokens.text_dim }; - let arrow_at = r.response.rect.right_center() - vec2(CARET_INSET, 0.0); - ui.painter().text(arrow_at, egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_SIZE), arrow_color); - if enabled { - r.response.on_hover_text(tr("Dilation in pixels")); - } else { - r.response.on_disabled_hover_text(tr("This padding mode does not use a dilation width")); - } } /// A greyed checkbox with its tooltip and the "not available" hint @@ -794,13 +899,21 @@ fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { }); } -/// The Global settings page -fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { - let mut reset = false; - header(ui, tr("General Export Parameters"), |ui| { - reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); - }); - if reset { +/// A tick of the global page at `y` with its label after it +fn page_check(ui: &mut Ui, place: PagePlace, y: f32, on: &mut bool, label: &str) -> egui::Response { + let left = place.x(LABEL_LEFT + CHECK_INDENT); + let width = CHECK_LABEL_ROOM + drawn::text_width(ui, label, false); + let hit = egui::Rect::from_min_max(egui::pos2(left, y - CHECK_HIT_SIZE / 2.0), egui::pos2(left + width, y + CHECK_HIT_SIZE / 2.0)); + drawn::check(ui, ui.scope_id().with(("exp_check", label)), hit, egui::pos2(left, y), on, Some(label), label) +} + +/// The Global settings page, laid out from `place` +fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, builtins: &[ExportPreset]) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(GLOBAL_HEADER_Y), tr("General Export Parameters"), look.text, true); + let reset_at = place.right_inset(PAGE_ICON_FROM_RIGHT, GLOBAL_ICON_Y); + let reset_tip = tr("Restore the default export parameters"); + if drawn::icon_button(ui, reset_at, ic::ARROW_COUNTER_CLOCKWISE, MENU_ICON_SIZE, reset_tip, true, false).on_hover_text(reset_tip).clicked() { let defaults = ExportUi::default(); let settings = &mut app.ui.export; ( @@ -832,167 +945,186 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] ); crate::export_templates::select(app, defaults.preset); } + + // One row per parameter at the reference's pitch; the browser has no output directory + let mut rows = (0..).map(|k| place.y(GLOBAL_FIRST_ROW_Y + k as f32 * GLOBAL_ROW_PITCH)); + let mut next_row = || rows.next().unwrap_or_default(); + let (left, right) = (place.x(CONTROLS_LEFT), place.right - CONTROLS_RIGHT_MARGIN); + #[cfg(not(target_arch = "wasm32"))] + output_directory(app, ui, place, next_row()); + + let y = next_row(); + row_label(ui, place, y, tr("Output template")); let (first, rest) = template_groups(app, builtins); - egui::Grid::new("exp_grid").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - // The browser downloads the files instead - #[cfg(not(target_arch = "wasm32"))] - output_directory(app, ui); - ui.label(tr("Output template")); - let mut picked = app.ui.export.preset.clone(); - if template_combo(ui, "exp_preset", &mut picked, &first, &rest) { - crate::export_templates::select(app, picked); + let mut picked = app.ui.export.preset.clone(); + if template_combo(ui, drawn::control_rect(left, right, y), "exp_preset", &mut picked, &first, &rest) { + crate::export_templates::select(app, picked); + } + + // The file type list fits its longest entry, the bit depth list fills the rest + let y = next_row(); + row_label(ui, place, y, tr("File type")); + let type_right = left + drawn::text_width(ui, tr("Based on output template"), false) + FILE_TYPE_ROOM; + let rects = [drawn::control_rect(left, type_right, y), drawn::control_rect(type_right + PAIR_GAP, right, y)]; + let settings = &mut app.ui.export; + file_type_lists(ui, ("exp_global", 0, 0), true, rects, &mut settings.format, &mut settings.bit_depth, &mut settings.dithering); + + let y = next_row(); + row_label(ui, place, y, tr("Size")); + drawn::combo(ui, drawn::control_rect(left, right, y), "exp_size", size_label(settings.size), |ui| { + ui.selectable_value(&mut settings.size, 0, size_label(0)); + ui.separator(); + ui.selectable_value(&mut settings.size, SIZE_OF_LARGEST_SET, size_label(SIZE_OF_LARGEST_SET)); + for size in SIZES { + ui.selectable_value(&mut settings.size, size, size_label(size)); } - ui.end_row(); - ui.label(tr("File type")); - ui.horizontal(|ui| { - let settings = &mut app.ui.export; - file_type_lists(ui, ("exp_global", 0, 0), true, &mut settings.format, &mut settings.bit_depth, &mut settings.dithering); - }); - ui.end_row(); - ui.label(tr("Size")); - let settings = &mut app.ui.export; - egui::ComboBox::from_id_salt("exp_size").width(VALUE_WIDTH).selected_text(size_label(settings.size)).show_ui(ui, |ui| { - ui.selectable_value(&mut settings.size, 0, size_label(0)); - ui.separator(); - ui.selectable_value(&mut settings.size, SIZE_OF_LARGEST_SET, size_label(SIZE_OF_LARGEST_SET)); - for size in SIZES { - ui.selectable_value(&mut settings.size, size, size_label(size)); - } - }); - ui.end_row(); - ui.label(tr("Padding")); - ui.horizontal(|ui| { - let width = VALUE_WIDTH - DILATION_BUTTON_WIDTH - ui.spacing().item_spacing.x; - egui::ComboBox::from_id_salt("exp_pad").width(width).selected_text(tr(padding_label(&settings.padding))).show_ui(ui, |ui| { - for (value, label) in PADDINGS { - ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); - } - }); - dilation_button(ui, &settings.padding, &mut settings.dilation); - }); - ui.end_row(); }); - // The browser downloads the textures only, so it has no USD asset to add - #[cfg(not(target_arch = "wasm32"))] - ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")) - .on_hover_text(tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures")); - #[cfg(target_arch = "wasm32")] - unavailable_checkbox( - ui, - tr("Export USD asset"), - tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"), - ); + let y = next_row(); + row_label(ui, place, y, tr("Padding")); + let padding_rect = drawn::control_rect(left, right - DILATION_WIDTH - PAIR_GAP, y); + drawn::combo(ui, padding_rect, "exp_pad", tr(padding_label(&settings.padding)), |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); + } + }); + dilation_button(ui, drawn::control_rect(right - DILATION_WIDTH, right, y), "global", &settings.padding, &mut settings.dilation); - // The MaterialX export sits below the USD one; the browser downloads the textures only - #[cfg(not(target_arch = "wasm32"))] - ui.checkbox(&mut app.ui.export.materialx, tr("Export MaterialX")); - #[cfg(target_arch = "wasm32")] - crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); + let y = next_row(); + row_label(ui, place, y, tr("Normal map format")); + let normal_label = match settings.normal_format.as_str() { + "openGl" => "OpenGL", + "directX" => "DirectX", + _ => tr("From template / project"), + }; + drawn::combo(ui, drawn::control_rect(left, right, y), "exp_nf", normal_label, |ui| { + for (value, label) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { + ui.selectable_value(&mut settings.normal_format, value.to_string(), label); + } + }); - ui.checkbox(&mut app.ui.export.shader_parameters, tr("Export shader settings")) - .on_hover_text(tr("Save the settings of each shader instance in a JSON file")); - ui.add_space(8.0); - egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - let settings = &mut app.ui.export; - ui.label(tr("Normal map format")); - let normal_label = match settings.normal_format.as_str() { - "openGl" => "OpenGL", - "directX" => "DirectX", - _ => tr("From template / project"), + let y = next_row(); + row_label(ui, place, y, tr("Color space")); + let shown = if settings.color_space.is_empty() { tr("Default").to_string() } else { settings.color_space.clone() }; + let color_space = drawn::combo(ui, drawn::control_rect(left, right, y), "exp_cs", shown, |ui| { + ui.selectable_value(&mut settings.color_space, String::new(), tr("Default")); + for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { + ui.selectable_value(&mut settings.color_space, name.to_string(), name); + } + }); + color_space.response.on_hover_text(tr("Color maps only: normal, roughness, metallic and other data maps stay linear")); + + // The extra files, ticked under the parameters + let mut checks = (0..).map(|k| y + CHECKS_GAP + k as f32 * CHECK_PITCH); + let mut next_check = || checks.next().unwrap_or_default(); + let usd_tip = tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"); + #[cfg(not(target_arch = "wasm32"))] + page_check(ui, place, next_check(), &mut settings.usd_asset, tr("Export USD asset")).on_hover_text(usd_tip); + #[cfg(not(target_arch = "wasm32"))] + page_check(ui, place, next_check(), &mut settings.materialx, tr("Export MaterialX")); + #[cfg(target_arch = "wasm32")] + { + let at = |y: f32| { + egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(egui::pos2(place.x(LABEL_LEFT), y - CHECK_HIT_SIZE / 2.0), vec2(right, CHECK_HIT_SIZE))) }; - egui::ComboBox::from_id_salt("exp_nf").selected_text(normal_label).show_ui(ui, |ui| { - for (value, label) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { - ui.selectable_value(&mut settings.normal_format, value.to_string(), label); - } - }); - ui.end_row(); - ui.label(tr("Color space")); - let shown = if settings.color_space.is_empty() { tr("Default") } else { settings.color_space.as_str() }; - egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| { - ui.selectable_value(&mut settings.color_space, String::new(), tr("Default")); - for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { - ui.selectable_value(&mut settings.color_space, name.to_string(), name); - } - }); - ui.end_row(); - }); + ui.scope_builder(at(next_check()), |ui| unavailable_checkbox(ui, tr("Export USD asset"), usd_tip)); + ui.scope_builder(at(next_check()), |ui| crate::unavailable::checkbox(ui, false, tr("Export MaterialX"))); + } + page_check(ui, place, next_check(), &mut settings.shader_parameters, tr("Export shader settings")) + .on_hover_text(tr("Save the settings of each shader instance in a JSON file")); } -/// The left column: Global settings, then a row per texture set with its export tick; a click -/// on a row shows the set's page, "*" marks a set with overrides -fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| list_menu(ui, |ui| set_checks_menu(app, ui))); - }); - let header = list_row(ui, tr("Global settings"), app.ui.export.page.is_none()); - if header.clicked() { +/// The texture set list in `area`: Global settings, then a tick and a page per texture set, "*" on one with overrides +fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, area: egui::Rect) { + let top = area.top() - TAB_ROW_HEIGHT; + list_menu(ui, egui::pos2(area.left() + SET_MENU_X, top + SET_MENU_Y), tr("Texture set list menu"), |ui| set_checks_menu(app, ui)); + let rows_right = area.right() - GUTTER; + let header = egui::Rect::from_min_max(egui::pos2(area.left(), top + SET_ROWS_TOP), egui::pos2(rows_right, top + SET_ROWS_TOP + SET_ROW_HEIGHT)); + if list_row(ui, header, tr("Global settings"), app.ui.export.page.is_none()).clicked() { app.ui.export.page = None; } - // Many texture sets scroll inside the list; the footer stays in view - let list_height = ui.available_height(); - egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); + // Many texture sets scroll under Global settings, the scroll bar in its strip at the list's right + let rows = egui::Rect::from_min_max(egui::pos2(area.left(), header.bottom()), area.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + egui::ScrollArea::vertical().id_salt("export_texture_sets").auto_shrink([false; 2]).show(ui, |ui| set_rows(app, ui, rows.width() - GUTTER)); + }); } -/// A row across the whole list, its name in bold; the selected one framed -fn list_row(ui: &mut Ui, text: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), LIST_ROW_HEIGHT), egui::Sense::click()); +/// A list row across `rect`, its name in bold +fn list_row(ui: &mut Ui, rect: egui::Rect, text: &str, selected: bool) -> egui::Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("exp_list_row", text)), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, text)); - - let painter = ui.painter(); - if selected { - painter.rect(rect, 0.0, tokens.row_selected, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); - } else if response.hovered() { - painter.rect_filled(rect, 0.0, tokens.row_hover); - } - let font = semibold(egui::TextStyle::Body.resolve(ui.style()).size); - painter.text(rect.left_center() + vec2(LIST_ROW_INDENT, 0.0), egui::Align2::LEFT_CENTER, text, font, tokens.text_strong); - paint_focus(ui, &response); + paint_row(ui, rect, selected, response.hovered()); + drawn::text_at(ui, rect.left() + GLOBAL_NAME_LEFT, rect.center().y, text, look.text, true); + drawn::paint_focus(ui, &response); response } -/// A row per texture set: its export tick, its name and the override mark -fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui) { +/// A list row's face: the selected one in the frame colour with a light edge; a hairline under every row +fn paint_row(ui: &Ui, rect: egui::Rect, selected: bool, hovered: bool) { + let look = ExportLook::get(ui.ctx()); + let painter = ui.painter(); + if selected { + painter.rect(rect, 0.0, look.chrome, egui::Stroke::new(1.0, look.outline), egui::StrokeKind::Inside); + } else if hovered { + painter.rect_filled(rect, 0.0, look.raised); + } + painter.rect_filled(egui::Rect::from_min_max(rect.left_bottom(), rect.right_bottom() + vec2(0.0, 1.0)), 0.0, look.chrome); +} + +/// A row per texture set, `width` wide: its export tick, its name and the override mark +fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32) { + let look = ExportLook::get(ui.ctx()); + ui.spacing_mut().item_spacing.y = 0.0; for i in 0..app.session.set_count() { let name = app.session.doc.project.texture_sets.get(i).map(|t| t.name.clone()).unwrap_or_default(); + let (row, _) = ui.allocate_exact_size(vec2(width, SET_ROW_HEIGHT), egui::Sense::hover()); + let y = row.center().y; + + // The tick leaves the set in or out, the name after it opens the set's page + let name_area = egui::Rect::from_min_max(egui::pos2(row.left() + SET_NAME_LEFT - drawn::CHECK_LABEL_GAP, row.top()), row.max); + let selected = app.ui.export.page == Some(i); + paint_row(ui, row, selected, ui.rect_contains_pointer(name_area)); let mut on = !app.ui.export.skip.contains(&i); - ui.horizontal(|ui| { - if ui.checkbox(&mut on, "").changed() { - if on { - app.ui.export.skip.retain(|x| *x != i); - } else { - app.ui.export.skip.push(i); - } + let tick_area = egui::Rect::from_min_max(row.min, egui::pos2(name_area.left(), row.bottom())); + let tick_name = trf("Include {set}", &[("set", &name)]); + if drawn::check(ui, ui.scope_id().with(("exp_set_tick", i)), tick_area, egui::pos2(row.left() + SET_CHECK_LEFT, y), &mut on, None, &tick_name).changed() + { + if on { + app.ui.export.skip.retain(|x| *x != i); + } else { + app.ui.export.skip.push(i); } - if ui.selectable_label(app.ui.export.page == Some(i), name).clicked() { - app.ui.export.page = Some(i); - } - if app.ui.export.sets.get(&i).is_some_and(SetExport::any) { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label("*").on_hover_text(tr("Override(s) active")); - }); - } - }); - ui.separator(); + } + + let page = ui.interact(name_area, ui.scope_id().with(("exp_set_row", i)), egui::Sense::click()); + page.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &name)); + if page.clicked() { + app.ui.export.page = Some(i); + } + + let color = if on { look.text } else { look.text_dim }; + drawn::text_at(ui, row.left() + SET_NAME_LEFT, y, &name, color, true); + drawn::paint_focus(ui, &page); + if app.ui.export.sets.get(&i).is_some_and(SetExport::any) { + drawn::label_at(ui, row.right() - OVERRIDE_MARK_FROM_RIGHT, y, "*", look.text_dim, true).on_hover_text(tr("Override(s) active")); + } } } -/// A texture set page row: the label, the override toggle, then the inherited value as text or, -/// overridden, `edit`; true when the toggle was clicked -fn override_row(ui: &mut Ui, label: &str, on: bool, inherited: &str, edit: impl FnOnce(&mut Ui)) -> bool { - ui.label(label); - let mut toggled = false; - ui.horizontal(|ui| { - toggled = icon_button(ui, ic::PENCIL_SIMPLE, tr("Enable override"), on, ICON).clicked(); - if on { - edit(ui); - } else { - ui.label(inherited); - } - }); - ui.end_row(); +/// A texture set page row at `y`: label, pen, then the inherited value or `edit`; true when the pen was clicked +fn override_row(ui: &mut Ui, place: PagePlace, y: f32, label: &str, on: bool, inherited: &str, edit: impl FnOnce(&mut Ui, egui::Rect)) -> bool { + let look = ExportLook::get(ui.ctx()); + row_label(ui, place, y, label); + let pen = egui::pos2(place.x(PEN_CENTRE), y); + let toggled = drawn::icon_button(ui, pen, ic::PENCIL_SIMPLE, drawn::CHEVRON_SIZE, tr("Enable override"), true, on).clicked(); + if on { + edit(ui, drawn::control_rect(place.x(OVERRIDE_LEFT), place.right - CONTROLS_RIGHT_MARGIN, y)); + } else { + drawn::label_at(ui, place.x(VALUE_LEFT), y, inherited, look.text, false); + } toggled } @@ -1016,23 +1148,18 @@ fn toggle(o: &mut SetExport, row: usize, from: &InheritedSettings) { } } -/// A file type dropdown (without "Based on output template") and its bit depth -fn file_type_combo(ui: &mut Ui, id: (&str, usize, usize), t: &mut FileType) { - file_type_lists(ui, id, false, &mut t.format, &mut t.bit_depth, &mut t.dithering); -} - -/// A texture set's page: its overrides of the global settings -fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[ExportPreset]) { +/// A texture set's page from `place`: its overrides, then its output maps scrolling down to `bottom` +fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, bottom: f32, builtins: &[ExportPreset]) { let Some(set) = app.session.doc.project.texture_sets.get(ts) else { return }; let own = set.block_resolution(); let mut from = InheritedSettings::for_texture_set(app, own); // "Based on output template": the override starts from what the template writes - if app.ui.export.format.is_empty() && app.ui.export.sets.get(&ts).is_none_or(|o| o.file_type.is_none()) { + if app.ui.export.format.is_empty() && app.ui.export.sets.get(&ts).is_none_or(|set_export| set_export.file_type.is_none()) { from.file_type = template_file_type(app, ts); } let (first, rest) = template_groups(app, builtins); - let first: Vec<(&str, bool)> = first.into_iter().filter(|(n, _)| !NOT_PER_SET.contains(n)).collect(); + let first: Vec<(&str, bool)> = first.into_iter().filter(|(name, _)| !NOT_PER_SET.contains(name)).collect(); let global = &app.ui.export; let inherited_file_type = if global.format.is_empty() { tr("Based on output template").to_string() } else { file_type_text(&from.file_type) }; let inherited_size = match global.size { @@ -1041,86 +1168,87 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor }; let inherited_padding = tr(padding_label(&global.padding)).to_string(); - let o = app.ui.export.sets.entry(ts).or_default(); + let look = ExportLook::get(ui.ctx()); + let overrides = app.ui.export.sets.entry(ts).or_default(); let mut all = None; - header(ui, tr("General Export Parameters"), |ui| { - list_menu(ui, |ui| { - if ui.button(tr("Override every item")).clicked() { - all = Some(true); - } - if ui.button(tr("Clear all overrides")).clicked() { - all = Some(false); - } - ui.separator(); - }); + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(SET_HEADER_Y), tr("General Export Parameters"), look.text, true); + list_menu(ui, place.right_inset(PAGE_ICON_FROM_RIGHT, SET_HEADER_Y), tr("General Export Parameters menu"), |ui| { + if ui.button(tr("Override every item")).clicked() { + all = Some(true); + } + if ui.button(tr("Clear all overrides")).clicked() { + all = Some(false); + } + ui.separator(); }); + + let row_y = |row: usize| place.y(SET_FIRST_ROW_Y + row as f32 * SET_ROW_PITCH); let mut toggled = None; - egui::Grid::new(("exp_set_grid", ts)).num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - let on = o.preset.is_some(); - if override_row(ui, tr("Output template"), on, &from.preset, |ui| { - if let Some(p) = &mut o.preset { - template_combo(ui, "exp_set_preset", p, &first, &rest); - } - }) { - toggled = Some(0); + if override_row(ui, place, row_y(0), tr("Output template"), overrides.preset.is_some(), &from.preset, |ui, rect| { + if let Some(preset) = &mut overrides.preset { + template_combo(ui, rect, "exp_set_preset", preset, &first, &rest); } - let on = o.file_type.is_some(); - if override_row(ui, tr("File type"), on, &inherited_file_type, |ui| { - if let Some(t) = &mut o.file_type { - file_type_combo(ui, ("exp_set", ts, usize::MAX), t); - } - }) { - toggled = Some(1); + }) { + toggled = Some(0); + } + if override_row(ui, place, row_y(1), tr("File type"), overrides.file_type.is_some(), &inherited_file_type, |ui, rect| { + if let Some(file_type) = &mut overrides.file_type { + let type_rect = rect.with_max_x(rect.left() + MAP_FORMAT_WIDTH); + let rects = [type_rect, rect.with_min_x(type_rect.right() + PAIR_GAP)]; + file_type_lists(ui, ("exp_set", ts, usize::MAX), false, rects, &mut file_type.format, &mut file_type.bit_depth, &mut file_type.dithering); } - let on = o.size.is_some(); - if override_row(ui, tr("Size"), on, &inherited_size, |ui| { - if let Some(size) = &mut o.size { - egui::ComboBox::from_id_salt("exp_set_size").width(VALUE_WIDTH).selected_text(set_size_label(*size, own)).show_ui(ui, |ui| { - for r in SIZES { - ui.selectable_value(size, r, set_size_label(r, own)); - } - }); - } - }) { - toggled = Some(2); + }) { + toggled = Some(1); + } + if override_row(ui, place, row_y(2), tr("Size"), overrides.size.is_some(), &inherited_size, |ui, rect| { + if let Some(size) = &mut overrides.size { + drawn::combo(ui, rect, "exp_set_size", set_size_label(*size, own), |ui| { + for side in SIZES { + ui.selectable_value(size, side, set_size_label(side, own)); + } + }); } - let on = o.padding.is_some(); - if override_row(ui, tr("Padding"), on, &inherited_padding, |ui| { - if let Some((padding, dilation)) = &mut o.padding { - egui::ComboBox::from_id_salt("exp_set_pad").width(260.0).selected_text(tr(padding_label(padding))).show_ui(ui, |ui| { - for (v, l) in PADDINGS { - ui.selectable_value(padding, v.to_string(), tr(l)); - } - }); - dilation_button(ui, padding, dilation); - } - }) { - toggled = Some(3); + }) { + toggled = Some(2); + } + if override_row(ui, place, row_y(3), tr("Padding"), overrides.padding.is_some(), &inherited_padding, |ui, rect| { + if let Some((padding, dilation)) = &mut overrides.padding { + drawn::combo(ui, rect.with_max_x(rect.right() - DILATION_WIDTH - PAIR_GAP), "exp_set_pad", tr(padding_label(padding)), |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(padding, value.to_string(), tr(label)); + } + }); + dilation_button(ui, rect.with_min_x(rect.right() - DILATION_WIDTH), "set", padding, dilation); } - }); + }) { + toggled = Some(3); + } if let Some(row) = toggled { - toggle(o, row, &from); + toggle(overrides, row, &from); } match all { Some(true) => { for row in 0..4 { - let on = [o.preset.is_some(), o.file_type.is_some(), o.size.is_some(), o.padding.is_some()]; + let on = [overrides.preset.is_some(), overrides.file_type.is_some(), overrides.size.is_some(), overrides.padding.is_some()]; if !on.get(row).copied().unwrap_or(true) { - toggle(o, row, &from); + toggle(overrides, row, &from); } } } Some(false) => { - o.preset = None; - o.file_type = None; - o.size = None; - o.padding = None; + overrides.preset = None; + overrides.file_type = None; + overrides.size = None; + overrides.padding = None; } None => {} } - ui.add_space(8.0); - ui.separator(); - egui::ScrollArea::vertical().id_salt("exp_maps_scroll").auto_shrink([false; 2]).show(ui, |ui| output_maps(app, ui, ts)); + + // A divider across the page, then the output maps + let page_left = place.x(SET_LIST_WIDTH + 1.0); + drawn::divider(ui, egui::Rect::from_min_max(egui::pos2(page_left, place.y(SET_DIVIDER_Y)), egui::pos2(place.right, place.y(SET_DIVIDER_Y) + 1.0))); + let maps_area = egui::Rect::from_min_max(egui::pos2(page_left, place.y(MAPS_TOP)), egui::pos2(place.right, bottom)); + output_maps(app, ui, ts, place, maps_area); if app.ui.export.sets.get(&ts).is_some_and(SetExport::is_default) { app.ui.export.sets.remove(&ts); } @@ -1169,7 +1297,7 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; ui.painter().rect_filled(strip, 0.0, tk.chrome); ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); - paint_focus(ui, &response); + drawn::paint_focus(ui, &response); let response = response.on_hover_text(tooltip); if !hidden && (response.hovered() || response.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); @@ -1479,6 +1607,87 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, p } } +/// The bottom bar: Export, Save settings, Cancel and the texture count, Reset all on SETTINGS; while exporting, progress +fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do_export: &mut bool, canceled: &mut bool) { + let slot = |k: f32| { + let right = window.right() - RIGHT_MARGIN - k * (FOOTER_BUTTON_WIDTH + FOOTER_BUTTON_GAP); + drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, y) + }; + if let Some(job) = &app.ui.export.job { + let done = job.total - job.pending.len(); + let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; + if drawn::button(ui, slot(0.0), tr("Cancel Export"), false, true).clicked() { + app.ui.export.job = None; + } + let bar = drawn::control_rect(window.left() + LEFT_MARGIN, slot(0.0).left() - FOOTER_BUTTON_GAP, y); + let look = ExportLook::get(ui.ctx()); + ui.put(bar, egui::ProgressBar::new(progress).fill(look.outline).text(format!("{:.0}%", progress * 100.0))); + return; + } + + // OUTPUT TEMPLATES shows no count; a template edit that does not validate holds Save and Export + let templates_tab = app.ui.export.tab == 1; + let draft_valid = app.ui.export.draft.as_ref().is_none_or(|draft| draft.validate().is_ok()); + let any = !export_selection(app).is_empty() && draft_valid; + let export = drawn::button(ui, slot(0.0), tr("Export"), true, any); + if export.on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")).clicked() { + *do_export = true; + } + + // Saving closes the window without starting an export + let save = drawn::button(ui, slot(1.0), tr("Save settings"), false, draft_valid); + if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { + app.ui.windows.export = false; + } + let cancel = drawn::button(ui, slot(2.0), tr("Cancel"), false, true); + if cancel.on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { + *canceled = true; + } + if !templates_tab { + let look = ExportLook::get(ui.ctx()); + let count = trf("{n} textures selected for export", &[("n", &selected_texture_count(app))]); + let left = slot(2.0).left() - COUNT_GAP - drawn::text_width(ui, &count, false); + drawn::label_at(ui, left, y, &count, look.text_dim, false); + } + + // Only on SETTINGS + let reset_rect = drawn::control_rect(window.left() + LEFT_MARGIN, window.left() + LEFT_MARGIN + FOOTER_BUTTON_WIDTH, y); + if app.ui.export.tab == 0 + && drawn::button(ui, reset_rect, tr("Reset all"), false, true).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() + { + // Keep ownership so Cancel can restore the opening settings + let e = &mut app.ui.export; + let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); + app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; + } +} + +/// The SETTINGS tab in `body`: the texture set list, a divider, then the selected page +fn settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, body: egui::Rect, presets: &[ExportPreset]) { + let list = body.with_max_x(body.left() + SET_LIST_WIDTH); + set_list(app, ui, list); + drawn::divider(ui, egui::Rect::from_min_max(list.right_top(), list.right_bottom() + vec2(1.0, 0.0))); + let page = body.with_min_x(list.right() + 1.0); + match app.ui.export.page { + Some(ts) if ts < app.session.set_count() => { + let place = PagePlace { left: window.left(), top: window.top(), right: window.right() }; + set_page(app, ui, ts, place, body.bottom(), presets); + } + + // A short or narrow window scrolls the page, so every control stays reachable + _ => { + ui.scope_builder(egui::UiBuilder::new().max_rect(page), |ui| { + egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false; 2]).show(ui, |ui| { + let size = vec2(ui.available_width().max(MIN_PAGE_WIDTH), GLOBAL_PAGE_HEIGHT); + let (content, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + let place = PagePlace { left: content.left() - list.width() - 1.0, top: content.top() - TAB_ROW_HEIGHT, right: content.right() }; + global_page(app, ui, place, presets); + }); + }); + } + } +} + pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.export { // The window opens on SETTINGS again; an export stops with it @@ -1515,14 +1724,18 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let mut canceled = false; let presets = texturecraft_engine::formats::builtin_presets(); - // The reference size on a screen that has room for it, smaller on a smaller one; resizable from there. - // The window's size counts its frame and title bar, the reference size only the content + let look = ExportLook::get(ctx); + + // The reference size where the screen has room, resizable from there; the size counts the frame and title bar let style = ctx.global_style(); + let title_frame = egui::Frame::window(&style); + let frame = title_frame.inner_margin(CONTENT_INSET); let title_height = ctx.fonts_mut(|fonts| fonts.row_height(&egui::TextStyle::Heading.resolve(&style))) + style.spacing.item_spacing.y; - let chrome = egui::Frame::window(&style).total_margin().sum() + vec2(0.0, title_height); + let chrome = vec2(frame.total_margin().sum().x, title_frame.total_margin().sum().y + title_height); let window_size = (REFERENCE_WINDOW_SIZE_POINTS + chrome).min(ctx.content_rect().size() - vec2(WINDOW_VIEWPORT_MARGIN_POINTS, WINDOW_VIEWPORT_MARGIN_POINTS)); - let dialog = crate::windows::dialog(ctx, "export_textures", tr("Export Textures"), &mut open).default_size(window_size); + let dialog = + crate::windows::dialog(ctx, "export_textures", tr("Export textures"), &mut open).title_frame(title_frame).frame(frame).default_size(window_size); dialog.show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { @@ -1530,137 +1743,67 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - // While exporting: the progress and Cancel Export - if let Some(job) = &app.ui.export.job { - let done = job.total - job.pending.len(); - let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Cancel Export")).clicked() { - app.ui.export.job = None; - } - let percent = format!("{:.0}%", progress * 100.0); - ui.add(egui::ProgressBar::new(progress).text(percent)); - }); - }); - } else { - // OUTPUT TEMPLATES edits the templates only: no count, nothing to reset, save or export there - let templates_tab = app.ui.export.tab == 1; - let selected = if templates_tab { 0 } else { selected_texture_count(app) }; - ui.horizontal(|ui| { - // Only on SETTINGS - if app.ui.export.tab == 0 - && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() - { - // Keep ownership so Cancel can restore the opening settings - let e = &mut app.ui.export; - let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); - app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Nothing to write without a ticked texture set - let any = !export_selection(app).is_empty() && !templates_tab; - if ui - .add_enabled(any, footer_button(tr("Export"))) - .on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")) - .clicked() - { - do_export = true; - } + look.apply(ui.style_mut()); + let window = ui.max_rect(); + ui.allocate_rect(window, egui::Sense::hover()); + let body = + egui::Rect::from_min_max(egui::pos2(window.left(), window.top() + TAB_ROW_HEIGHT), egui::pos2(window.right(), window.bottom() - FOOTER_HEIGHT)); - // Saving closes the window without starting an export - let save = ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))); - if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { - app.ui.windows.export = false; - } - if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { - canceled = true; - } - if !templates_tab { - ui.label(trf("{n} textures selected for export", &[("n", &selected)])); - } - }); - }); + // The tabs, and the tab's own control at the row's right end + let tab_strip = egui::Rect::from_min_max(egui::pos2(window.left(), window.top() + TAB_TOP), egui::pos2(window.right(), body.top())); + let labels = [tr("Settings"), tr("Output templates"), tr("List of exports")]; + if let Some(tab) = drawn::tabs(ui, tab_strip, window.left() + TABS_LEFT, &labels, usize::from(app.ui.export.tab)) { + app.ui.export.tab = tab as u8; + } + let right = window.right() - RIGHT_MARGIN; + let row_y = window.top() + TAB_ROW_CONTROLS_Y; + match app.ui.export.tab { + 1 => { + let strip = egui::Rect::from_min_max(egui::pos2(window.center().x, window.top()), egui::pos2(right, body.top())); + ui.scope_builder( + egui::UiBuilder::new().max_rect(strip).layout(egui::Layout::right_to_left(egui::Align::Center)), + crate::export_templates::naming_pattern, + ); } - ui.separator(); - ui.add_space(8.0); - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.horizontal(|ui| { - // Boxed tabs side by side - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { - if tab_button(ui, &t.to_uppercase(), app.ui.export.tab == i as u8).clicked() { - app.ui.export.tab = i as u8; - } - } - }); + 2 => { + let width = drawn::text_width(ui, tr("Open output directory"), false) + OPEN_DIRECTORY_PADDING; + let rect = drawn::control_rect(window.right() - OPEN_DIRECTORY_FROM_RIGHT - width, window.right() - OPEN_DIRECTORY_FROM_RIGHT, row_y); - // The file list opens the destination folder - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if app.ui.export.tab == 2 { - // The browser downloads the files instead - #[cfg(target_arch = "wasm32")] - crate::unavailable::greyed(ui, |ui| ui.button(tr("Open output directory"))); - #[cfg(not(target_arch = "wasm32"))] - if ui.button(tr("Open output directory")).clicked() { - open_output_directory(app); - } - } else if app.ui.export.tab == 1 { - crate::export_templates::naming_pattern(ui); - } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { - app.ui.export.skip.clear(); - for o in app.ui.export.sets.values_mut() { - o.maps.values_mut().for_each(|m| m.enabled = true); - } - app.ui.export.sets.retain(|_, o| !o.is_default()); - } - }); - }); - ui.separator(); - let body = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), ui.available_height().max(0.0))); - - // The tabs size their columns from the body's width. A child that cannot widen the - // resizable window holds them, so an overflow is clipped instead of growing the window each frame - let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); - body_ui.shrink_clip_rect(body); - ui.advance_cursor_after_rect(body); - let ui = &mut body_ui; - 'tab: { - ui.set_height(body.height()); - match app.ui.export.tab { - 1 => { - crate::export_templates::tab(app, ui, &presets); - break 'tab; - } - 2 => { - list_tab(app, ui); - break 'tab; - } - _ => {} - } - - ui.vertical(|ui| { - ui.set_width(LIST_WIDTH); - set_list(app, ui); - }); - ui.separator(); - - // A short or narrow window scrolls the settings, so the footer and every control stay reachable - ui.vertical(|ui| { - egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false, false]).min_scrolled_height(0.0).show(ui, |ui| match app - .ui - .export - .page - { - Some(ts) if ts < app.session.set_count() => set_page(app, ui, ts, &presets), - _ => global_page(app, ui, &presets), - }); - }); + // The browser downloads the files instead + #[cfg(target_arch = "wasm32")] + drawn::button(ui, rect, tr("Open output directory"), false, false).on_hover_text(tr(NOT_AVAILABLE)); + #[cfg(not(target_arch = "wasm32"))] + if drawn::button(ui, rect, tr("Open output directory"), false, true).clicked() { + open_output_directory(app); } - }); - }); + } + _ => { + let rect = drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, row_y); + if drawn::button(ui, rect, tr("Include all"), false, true).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { + app.ui.export.skip.clear(); + for o in app.ui.export.sets.values_mut() { + o.maps.values_mut().for_each(|m| m.enabled = true); + } + app.ui.export.sets.retain(|_, o| !o.is_default()); + } + } + } + + let footer_y = window.bottom() - FOOTER_MIDDLE_FROM_BOTTOM; + drawn::divider(ui, egui::Rect::from_min_max(body.left_bottom(), body.right_bottom() + vec2(0.0, 1.0))); + footer(app, ui, window, footer_y, &mut do_export, &mut canceled); + + // The tabs lay out from the body; a child clips what an overflow would draw past it + let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); + body_ui.shrink_clip_rect(body); + let ui = &mut body_ui; + let mut row = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); + row.set_height(body.height()); + match app.ui.export.tab { + 1 => crate::export_templates::tab(app, &mut row, &presets), + 2 => list_tab(app, &mut row), + _ => settings_tab(app, ui, window, body, &presets), + } }); crate::export_templates::ask(app, ctx); diff --git a/crates/ui-egui/src/export_window/drawn.rs b/crates/ui-egui/src/export_window/drawn.rs new file mode 100644 index 00000000..fe55c374 --- /dev/null +++ b/crates/ui-egui/src/export_window/drawn.rs @@ -0,0 +1,305 @@ +//! The Export textures window's own controls, drawn at the places its layout gives them: tabs, +//! checks, dropdowns, buttons and icon buttons in the window's colours ([`ExportLook`]) + +use egui::{Align2, Color32, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::export_look::{CONTROL_HEIGHT, CONTROL_RADIUS, ExportLook, TEXT_SIZE}; +use crate::theme::semibold; + +/// Side and corner radius of a check box +const CHECK_SIZE: f32 = 13.0; +const CHECK_RADIUS: u8 = 2; + +/// The tick inside a check box: its three points from the box's left edge and centre, and its width +const TICK_POINTS: [(f32, f32); 3] = [(3.2, 0.2), (5.6, 2.6), (9.8, -2.6)]; +const TICK_WIDTH: f32 = 1.7; + +/// Air between a check box and its label +pub(crate) const CHECK_LABEL_GAP: f32 = 5.0; + +/// From a dropdown's left edge to its value, and from its right edge to its chevron's centre +pub(crate) const VALUE_INSET: f32 = 7.0; +pub(crate) const CHEVRON_INSET: f32 = 11.0; + +/// Size of a chevron and of the window's icons +pub(crate) const CHEVRON_SIZE: f32 = 12.0; + +/// The air on either side of a tab's name +const TAB_PADDING: f32 = 14.0; +/// A tab's corner radius +const TAB_RADIUS: u8 = 4; +/// Gap between tabs +const TAB_GAP: f32 = 3.0; +/// How far a tab reaches under the divider, where the body's colour covers its lower corners +const TAB_OVERLAP: f32 = 4.0; + +/// Hit area of an icon button around its glyph +const ICON_HIT_SIZE: f32 = 20.0; + +/// Width of the keyboard focus outline on the window's drawn controls +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; + +/// Whether a control that cannot be used looks greyed; a built-in template's cards keep their look +pub(crate) fn looks_disabled(ui: &Ui, enabled: bool) -> bool { + !enabled && ui.visuals().disabled_alpha() < 1.0 +} + +/// The window's regular and semibold text +pub(crate) fn font(bold: bool) -> FontId { + if bold { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) } +} + +/// Width of `text` in the window's font +pub(crate) fn text_width(ui: &Ui, text: &str, bold: bool) -> f32 { + ui.painter().layout_no_wrap(text.to_owned(), font(bold), Color32::WHITE).size().x +} + +/// `text` with its left edge at `left` and its middle at `y` +pub(crate) fn text_at(ui: &Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Rect { + ui.painter().text(pos2(left, y), Align2::LEFT_CENTER, text, font(bold), color) +} + +/// `text` cut with "…" at its end (or its start, for file names) to fit `room` +pub(crate) fn fitted(ui: &Ui, text: &str, room: f32, from_start: bool, bold: bool) -> String { + if text_width(ui, text, bold) <= room { + return text.to_owned(); + } + + let chars: Vec = text.chars().collect(); + (1..chars.len()) + .map(|cut| { + if from_start { + format!("…{}", chars[cut..].iter().collect::()) + } else { + format!("{}…", chars[..chars.len() - cut].iter().collect::()) + } + }) + .find(|shown| text_width(ui, shown, bold) <= room) + .unwrap_or_else(|| "…".to_owned()) +} + +/// A glyph centred on `centre` +pub(crate) fn glyph(ui: &Ui, centre: Pos2, glyph: &str, size: f32, color: Color32) { + ui.painter().text(centre, Align2::CENTER_CENTER, glyph, FontId::proportional(size), color); +} + +/// The keyboard focus outline of a drawn control, in the text colour +pub(crate) fn paint_focus(ui: &Ui, response: &Response) { + if response.has_focus() { + let stroke = Stroke::new(FOCUS_OUTLINE_WIDTH, ExportLook::get(ui.ctx()).text); + ui.painter().rect_stroke(response.rect, CONTROL_RADIUS, stroke, StrokeKind::Inside); + } +} + +/// A horizontal or vertical divider line, one point thick +pub(crate) fn divider(ui: &Ui, rect: Rect) { + ui.painter().rect_filled(rect, 0.0, ExportLook::get(ui.ctx()).divider); +} + +/// Sentence-case rounded tabs along `strip`'s bottom from `left`, the open one joined to the body; returns the clicked one +pub(crate) fn tabs(ui: &mut Ui, strip: Rect, left: f32, labels: &[&str], open: usize) -> Option { + let look = ExportLook::get(ui.ctx()); + let bottom = strip.bottom(); + divider(ui, Rect::from_min_max(pos2(strip.left(), bottom - 1.0), pos2(strip.right(), bottom))); + let mut clicked = None; + let mut x = left; + for (index, label) in labels.iter().enumerate() { + let selected = index == open; + let width = text_width(ui, label, selected) + 2.0 * TAB_PADDING; + let rect = Rect::from_min_max(pos2(x, strip.top()), pos2(x + width, bottom)); + let response = ui.interact(rect, ui.scope_id().with(("export_tab", index)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, selected, *label)); + + // The tab's lower corners reach under the divider and are covered by the body's colour + let painter = ui.painter(); + let face = Rect::from_min_max(rect.min, pos2(rect.right(), bottom + TAB_OVERLAP)); + let below = Rect::from_min_max(pos2(rect.left(), bottom - 1.0), pos2(rect.right(), bottom + TAB_OVERLAP + 1.0)); + if selected { + painter.rect(face, TAB_RADIUS, look.window, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.rect_filled(below.shrink2(vec2(1.0, 0.0)), 0.0, look.window); + } else { + let fill = if response.hovered() { look.raised } else { look.chrome }; + painter.rect_filled(face.with_min_y(face.top() + 1.0), TAB_RADIUS, fill); + painter.rect_filled(below, 0.0, look.window); + painter.rect_filled(below.with_max_y(bottom), 0.0, look.divider); + } + let color = if selected { look.text } else { look.text_dim }; + painter.text(rect.center() + vec2(0.0, 1.0), Align2::CENTER_CENTER, *label, font(selected), color); + paint_focus(ui, &response); + if response.clicked() { + clicked = Some(index); + } + x += width + TAB_GAP; + } + clicked +} + +/// A check box from `left` with its middle at `y`: dim and ticked when on, dark with a light edge when off +pub(crate) fn paint_check(ui: &Ui, left: f32, y: f32, on: bool) { + let look = ExportLook::get(ui.ctx()); + let rect = Rect::from_min_size(pos2(left, y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); + let painter = ui.painter(); + if on { + painter.rect_filled(rect, CHECK_RADIUS, look.text_dim); + let points = TICK_POINTS.iter().map(|(dx, dy)| pos2(left + dx, y + dy)).collect(); + painter.add(egui::Shape::line(points, Stroke::new(TICK_WIDTH, look.window))); + } else { + painter.rect(rect, CHECK_RADIUS, look.control, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + } +} + +/// A check box at `at` (its left edge's middle) with `label` after it, toggled by a click in `hit` +pub(crate) fn check(ui: &mut Ui, id: Id, hit: Rect, at: Pos2, on: &mut bool, label: Option<&str>, name: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let mut response = ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + response.mark_changed(); + } + let checked = *on; + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, checked, name)); + paint_check(ui, at.x, at.y, checked); + if let Some(label) = label { + text_at(ui, at.x + CHECK_SIZE + CHECK_LABEL_GAP, at.y, label, look.text, false); + } + paint_focus(ui, &response); + response +} + +/// The rect of a control `left`..`right` with its middle at `y` +pub(crate) fn control_rect(left: f32, right: f32, y: f32) -> Rect { + Rect::from_min_max(pos2(left, y - CONTROL_HEIGHT / 2.0), pos2(right, y + CONTROL_HEIGHT / 2.0)) +} + +/// A dropdown's chevron, pointing up while its list is open, drawn just inside the right edge of the button `rect` +pub(crate) fn chevron_icon(ui: &Ui, rect: Rect, visuals: &egui::style::WidgetVisuals, open: bool) { + let centre = pos2(rect.right() + VALUE_INSET - CHEVRON_INSET, rect.center().y); + glyph(ui, centre, if open { ic::CARET_UP } else { ic::CARET_DOWN }, CHEVRON_SIZE, visuals.fg_stroke.color); +} + +/// A dropdown filling `rect`, showing `shown`, its list as wide as it and flush under it +pub(crate) fn combo( + ui: &mut Ui, + rect: Rect, + id: impl std::hash::Hash + std::fmt::Debug, + shown: impl Into, + list: impl FnOnce(&mut Ui) -> R, +) -> egui::InnerResponse> { + let look = ExportLook::get(ui.ctx()); + let shown: String = shown.into(); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + egui::ComboBox::from_id_salt(id) + .width(rect.width()) + .height(f32::INFINITY) + .selected_text(shown) + .wrap_mode(egui::TextWrapMode::Truncate) + .icon(chevron_icon) + .popup_style(look.list_style()) + .show_ui(ui, list) + }) + .inner +} + +/// A button drawn as a dropdown showing `shown`, for a menu that is no option list; lighter when it cannot be used +pub(crate) fn combo_button(ui: &mut Ui, rect: Rect, id: Id, shown: &str, enabled: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, id, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, shown)); + let (fill, color) = match (enabled, response.hovered()) { + (false, _) => (look.raised, look.text_dim), + (true, true) => (look.raised, look.text), + (true, false) => (look.control, look.text), + }; + let painter = ui.painter(); + painter.rect(rect, CONTROL_RADIUS, fill, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), color); + glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, color); + paint_focus(ui, &response); + response +} + +/// A field showing `text` cut with "…" at its end that acts as a button, as the output directory does +pub(crate) fn field_button(ui: &mut Ui, rect: Rect, id: Id, text: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, text)); + let border = if response.hovered() { look.outline } else { look.control_border }; + ui.painter().rect(rect, CONTROL_RADIUS, look.control, Stroke::new(1.0, border), StrokeKind::Inside); + let shown = fitted(ui, text, rect.width() - 2.0 * VALUE_INSET, false, false); + text_at(ui, rect.left() + VALUE_INSET, rect.center().y, &shown, look.text, false); + paint_focus(ui, &response); + response +} + +/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim +pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, shown: &str, name: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", name)), Sense::hover()); + response.widget_info(|| { + let mut info = WidgetInfo::labeled(Role::ComboBox, false, name); + info.current_text_value = Some(shown.to_owned()); + info + }); + let painter = ui.painter(); + painter.rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), look.text_dim); + glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, look.text_dim); + response +} + +/// Text that reads as a label to assistive technology and tests: `text` from `left`, its middle at `y`; its response takes a tooltip +pub(crate) fn label_at(ui: &mut Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Response { + let rect = text_at(ui, left, y, text, color, bold); + let response = ui.interact(rect, ui.scope_id().with(("export_label", text, left.to_bits(), y.to_bits())), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, text)); + response +} + +/// A button filling `rect`: a step darker than the window with a light edge, or the accent for the one primary action +pub(crate) fn button(ui: &mut Ui, rect: Rect, label: &str, primary: bool, enabled: bool) -> Response { + let id = ui.scope_id().with(("export_button", label)); + button_with_id(ui, id, rect, label, label, primary, enabled) +} + +/// [`button`] for one of several buttons with the same label (each output map card's "$") +pub(crate) fn button_with_id(ui: &mut Ui, id: Id, rect: Rect, label: &str, name: &str, primary: bool, enabled: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, id, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, name)); + let (fill, border) = match (primary, enabled && response.hovered()) { + (true, _) => (look.accent, look.accent), + (false, true) => (look.raised, look.outline), + (false, false) => (look.control, look.control_border), + }; + let painter = ui.painter(); + let fade = if enabled { 1.0 } else { ui.visuals().disabled_alpha() }; + painter.rect(rect, CONTROL_RADIUS, fill.gamma_multiply(fade), Stroke::new(1.0, border.gamma_multiply(fade)), StrokeKind::Inside); + let color = if looks_disabled(ui, enabled) { look.text_dim } else { look.text }; + painter.text(rect.center(), Align2::CENTER_CENTER, label, font(primary), color); + paint_focus(ui, &response); + response +} + +/// A glyph that acts as a button, centred on `centre`; `lit` frames it as switched on +pub(crate) fn icon_button(ui: &mut Ui, centre: Pos2, icon: &str, size: f32, name: &str, enabled: bool, lit: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let rect = Rect::from_center_size(centre, vec2(ICON_HIT_SIZE, ICON_HIT_SIZE)); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, ui.scope_id().with(("export_icon", name, centre.x as i32, centre.y as i32)), sense); + response.widget_info(|| WidgetInfo::selected(Role::Button, enabled, lit, name)); + if lit { + ui.painter().rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + } + let color = match (enabled, lit || response.hovered()) { + (false, _) if looks_disabled(ui, enabled) => look.control_border, + (false, _) => look.text_dim, + (true, true) => look.text, + (true, false) => look.text_dim, + }; + glyph(ui, centre, icon, size, color); + paint_focus(ui, &response); + response +} diff --git a/crates/ui-egui/src/export_window/export_look.rs b/crates/ui-egui/src/export_window/export_look.rs new file mode 100644 index 00000000..866dad2f --- /dev/null +++ b/crates/ui-egui/src/export_window/export_look.rs @@ -0,0 +1,118 @@ +use egui::{Color32, CornerRadius, Stroke, Style, TextStyle, style::StyleModifier}; + +use crate::theme::{Tokens, lerp_color}; + +/// Text size of the whole window, labels and values alike +pub(crate) const TEXT_SIZE: f32 = 12.0; + +/// Height and corner radius of the window's controls: dropdowns, fields and buttons +pub(crate) const CONTROL_HEIGHT: f32 = 25.0; +pub(crate) const CONTROL_RADIUS: u8 = 3; + +/// Height of an option in an open list +const OPTION_HEIGHT: f32 = 22.0; +/// An open list's margin round its options +const LIST_MARGIN: i8 = 3; +/// An option's text inset, lining up with the dropdown's value above it +const OPTION_INSET: f32 = 3.0; + +/// A scroll bar's strip beside its list: the bar and the air on either side of it +const SCROLL_BAR_WIDTH: f32 = 4.0; +const SCROLL_BAR_MARGIN: f32 = 4.0; + +/// How far the dividers sit below the frame colour, so they read on it +const DIVIDER_DARKENING: f32 = 0.26; + +/// The Export textures window's colours from the theme: controls a step darker than the window, raised faces a step lighter +#[derive(Clone, Copy)] +pub(crate) struct ExportLook { + pub(crate) window: Color32, + pub(crate) control: Color32, + pub(crate) control_border: Color32, + /// A step lighter than controls: hover, lit and unusable faces + pub(crate) raised: Color32, + pub(crate) chrome: Color32, + pub(crate) divider: Color32, + pub(crate) outline: Color32, + pub(crate) text: Color32, + pub(crate) text_dim: Color32, + pub(crate) accent: Color32, +} + +impl ExportLook { + pub(crate) fn get(ctx: &egui::Context) -> Self { + let tokens = Tokens::get(ctx); + Self { + window: tokens.panel, + control: tokens.row, + control_border: tokens.field_border, + raised: tokens.separator, + chrome: tokens.chrome, + divider: lerp_color(tokens.chrome, Color32::BLACK, DIVIDER_DARKENING), + outline: tokens.button_border, + text: tokens.text, + text_dim: tokens.text_dim, + accent: tokens.accent, + } + } + + /// 12 point text, the window's control colours, scroll bars in their own strip beside the list + pub(crate) fn apply(&self, style: &mut Style) { + for text_style in [TextStyle::Body, TextStyle::Button] { + if let Some(font) = style.text_styles.get_mut(&text_style) { + font.size = TEXT_SIZE; + } + } + style.spacing.interact_size.y = CONTROL_HEIGHT; + style.spacing.button_padding.x = super::drawn::VALUE_INSET; + style.spacing.scroll = egui::style::ScrollStyle { + bar_width: SCROLL_BAR_WIDTH, + bar_inner_margin: SCROLL_BAR_MARGIN, + bar_outer_margin: SCROLL_BAR_MARGIN, + ..egui::style::ScrollStyle::solid() + }; + + // The scroll strip shows no track, only the bar + style.visuals.extreme_bg_color = Color32::TRANSPARENT; + let widgets = &mut style.visuals.widgets; + for (state, fill, border) in [ + (&mut widgets.inactive, self.control, self.control_border), + (&mut widgets.hovered, self.raised, self.outline), + (&mut widgets.active, self.raised, self.outline), + (&mut widgets.open, self.control, self.control_border), + ] { + state.weak_bg_fill = fill; + state.bg_stroke = Stroke::new(1.0, border); + state.corner_radius = CornerRadius::same(CONTROL_RADIUS); + state.expansion = 0.0; + } + + // Scroll bars and checks use the strong fill: the raised grey + widgets.inactive.bg_fill = self.raised; + widgets.hovered.bg_fill = self.outline; + widgets.active.bg_fill = self.outline; + widgets.inactive.fg_stroke.color = self.text; + widgets.open.fg_stroke.color = self.text; + style.visuals.selection.bg_fill = self.chrome; + style.visuals.selection.stroke = Stroke::new(1.0, self.text); + } + + /// An open list: flush under its button, one light edge, the chosen option in the frame colour + pub(crate) fn list_style(&self) -> StyleModifier { + let look = *self; + StyleModifier::new(move |style: &mut Style| { + look.apply(style); + style.spacing.interact_size.y = OPTION_HEIGHT; + style.spacing.menu_margin = egui::Margin::same(LIST_MARGIN); + style.spacing.button_padding.x = OPTION_INSET; + style.spacing.item_spacing.y = 0.0; + style.visuals.window_fill = look.control; + style.visuals.window_stroke = Stroke::new(1.0, look.control_border); + style.visuals.menu_corner_radius = CornerRadius::same(CONTROL_RADIUS); + style.visuals.widgets.hovered.weak_bg_fill = look.raised; + style.visuals.widgets.hovered.bg_stroke = Stroke::NONE; + style.visuals.widgets.inactive.bg_stroke = Stroke::NONE; + style.visuals.widgets.active.bg_stroke = Stroke::NONE; + }) + } +} diff --git a/crates/ui-egui/src/export_window/page_place.rs b/crates/ui-egui/src/export_window/page_place.rs new file mode 100644 index 00000000..7a8c8269 --- /dev/null +++ b/crates/ui-egui/src/export_window/page_place.rs @@ -0,0 +1,26 @@ +use egui::{Pos2, pos2}; + +/// Where a Settings page lays out from: the window's left edge, the tab row's top and the page's right edge +#[derive(Clone, Copy)] +pub(super) struct PagePlace { + pub(super) left: f32, + pub(super) top: f32, + pub(super) right: f32, +} + +impl PagePlace { + /// `x` from the window's left edge + pub(super) fn x(&self, x: f32) -> f32 { + self.left + x + } + + /// `y` from the top of the tab row + pub(super) fn y(&self, y: f32) -> f32 { + self.top + y + } + + /// A point `from_right` in from the page's right edge, at `y` from the tab row's top + pub(super) fn right_inset(&self, from_right: f32, y: f32) -> Pos2 { + pos2(self.right - from_right, self.top + y) + } +} diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 0aefd54e..80fec55b 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -2,7 +2,7 @@ //! name pattern, and its own file type and bit depth. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable as _; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{FileType, MapExport, SetExport}; @@ -52,13 +52,17 @@ fn the_rows_show_each_map_with_its_pattern_and_file_type() { assert!(h.query_all_by_label("png 8 bits").next().is_some()); assert!(h.query_all_by_label("png 16 bits").next().is_some(), "height is 16-bit in the default template"); - // A pattern longer than the column is cut at the front, the whole one is its tooltip + // A pattern longer than the column (the packed template's) is cut at the front, the whole one is its tooltip + h.state_mut().ui.export.preset = "Unreal Engine (Packed)".into(); + h.run_steps(4); let preset = texturecraft_engine::formats::builtin_preset(&h.state().ui.export.preset).unwrap(); - let long = - plan(&mut h).iter().map(|f| preset.maps[f["map"].as_u64().unwrap() as usize].file.clone()).find(|p| p.chars().count() > 26).expect("a long pattern"); - let cut: String = format!("…{}", long.chars().skip(long.chars().count() - 25).collect::()); + let long = preset.maps.iter().map(|map| map.file.clone()).max_by_key(|file| file.chars().count()).unwrap(); + let cut = h + .query_all_by_label_contains("…") + .find_map(|node| node.accesskit_node().value().filter(|text| long.ends_with(text.trim_start_matches('…')))) + .expect("the pattern's end, cut at the front"); assert!(h.query_by_label(&long).is_none(), "{long} is cut"); - let at = h.get_all_by_label(&cut).next().unwrap().rect().center(); + let at = h.get_all_by_role_and_label(egui::Role::Label, &cut).next().unwrap().rect().center(); h.hover_at(at); h.run_steps(30); assert!(h.query_by_label(&long).is_some(), "the tooltip has the whole {long}"); @@ -78,15 +82,15 @@ fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() { assert_eq!(maps(&h).values().filter(|m| !m.enabled).count(), 1); assert!(h.query_by_label("*").is_none(), "a left-out map is not an override"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Uncheck all"); assert_eq!(selected(&h), before - rows); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Invert all"); assert_eq!(selected(&h), before); assert!(!h.state().ui.export.sets.contains_key(&0), "nothing left to remember"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Uncheck all"); click(&mut h, "Include all"); assert_eq!(selected(&h), before, "Include all ticks the output maps too"); @@ -103,10 +107,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { assert!(first.file_type.is_some(), "{m:?}"); assert!(h.query_by_label("*").is_some(), "the set is marked"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Override every item"); assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Clear all overrides"); assert!(maps(&h).is_empty()); } diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 9edb2ee5..30454094 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -30,7 +30,7 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { /// Open the General Export Parameters menu fn page_menu(h: &mut Harness<'_, TextureCraftApp>) { - h.get_all_by_label(egui_phosphor::regular::LIST_CHECKS).nth(1).unwrap().click(); + h.get_by_label("General Export Parameters menu").click(); h.run_steps(4); } diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 6dd4c494..94e77c81 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -49,7 +49,7 @@ fn the_window_has_the_reference_size() { let h = harness(egui::vec2(1600.0, 960.0)); let reset = window_button_rect(&h, "Reset all", 1600.0); let export = window_button_rect(&h, "Export", 1600.0); - let tabs = h.get_by_label("SETTINGS").rect(); + let tabs = h.get_by_role_and_label(egui::Role::Tab, "Settings").rect(); let width = export.max.x - reset.min.x; let height = export.max.y - tabs.min.y; diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 6f1212e0..3fbf0e4e 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -145,14 +145,14 @@ fn a_saved_legacy_preset_name_resolves_to_its_current_name() { fn the_set_list_menu_checks_unchecks_and_inverts() { let mut h = harness(); let sets = h.state().session.set_count(); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Uncheck all"); assert_eq!(h.state().ui.export.skip.len(), sets); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Invert all"); assert!(h.state().ui.export.skip.is_empty()); h.state_mut().ui.export.skip = vec![0]; - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Check all"); assert!(h.state().ui.export.skip.is_empty()); } @@ -163,9 +163,7 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { let default = h.state().ui.export.dir.clone(); h.state_mut().ui.export.dir = "/somewhere/else".into(); h.run_steps(3); - hover(&mut h, "R"); - assert!(h.query_by_label("Reset to default").is_some()); - click(&mut h, "R"); + click(&mut h, "Reset to default"); assert_eq!(h.state().ui.export.dir, default); hover(&mut h, "16"); diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 3290256a..f92f5fe5 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -3,7 +3,7 @@ use egui::Key; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; @@ -166,3 +166,18 @@ fn the_settings_dropdown_asks_about_an_unfinished_edit_too() { texturecraft_ui_egui::export_templates::select(h.state_mut(), "Beta tpl".into()); assert_eq!(selected(&h), "Beta tpl", "a valid edit switches at once"); } + +#[test] +fn output_templates_keeps_export_and_save_until_an_edit_does_not_validate() { + let library = Library::new("footer-on-templates"); + let mut h = harness(&library); + // The window's footer is drawn after the app's own menus, which have an Export too + let disabled = |h: &Harness<'_, TextureCraftApp>, label: &str| h.get_all_by_label(label).last().unwrap().accesskit_node().is_disabled(); + assert!(!disabled(&h, "Export"), "Export works from the templates tab"); + assert!(!disabled(&h, "Save settings"), "Save settings works from the templates tab"); + + break_draft(&mut h); + + assert!(disabled(&h, "Export"), "an invalid edit holds Export"); + assert!(disabled(&h, "Save settings"), "an invalid edit holds Save settings"); +} diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 92a3847b..d11fe0d8 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -338,12 +338,12 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { } #[test] -fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { +fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_has_no_count_or_reset() { let library = TemplateLibrary::new("bottom-bar"); let h = harness(&library); let naming = h.get_by_label("Naming pattern").rect(); - let tabs = h.get_by_label("OUTPUT TEMPLATES").rect(); + let tabs = h.get_by_role_and_label(egui::Role::Tab, "Output templates").rect(); let presets = h.get_by_label("Presets").rect(); assert!(naming.center().y < presets.top() && (naming.center().y - tabs.center().y).abs() < tabs.height(), "on the tab row: {naming:?}"); @@ -352,13 +352,12 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { assert!(h.query_by_label(absent).is_none(), "{absent}"); } assert!(h.query_by_label_contains("textures selected for export").is_none()); - for greyed in ["Save settings", "Export"] { + for active in ["Save settings", "Export", "Cancel"] { // The rail at the right edge has an Export button of its own let button = - h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)).unwrap(); - assert!(button.accesskit_node().is_disabled(), "{greyed}"); + h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(active)).unwrap(); + assert!(!button.accesskit_node().is_disabled(), "{active}"); } - assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); } #[test] diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 8d5162d5..84238f84 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -112,9 +112,10 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { harness.run_steps(SETTLE_FRAMES); assert!(harness.state().ui.windows.export, "Export Textures... opens the Export textures window"); - for label in - ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS", "Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] - { + for tab in ["Settings", "Output templates", "List of exports"] { + assert!(harness.query_by_role_and_label(egui::Role::Tab, tab).is_some(), "{tab}"); + } + for label in ["Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] { assert!(harness.query_by_label(label).is_some(), "{label}"); } assert!(harness.query_by_label_contains("textures selected for export").is_some()); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..b7370ceb 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3000,3 +3000,89 @@ fn sheet_scroll_end_snapshots() { harness.run_steps(30); save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); } + +/// The Export textures window on each tab at its mocks' size; TC_SNAPSHOT_THEME=medium (default), dark or light +#[test] +#[ignore] +fn export_window_snapshots() { + use texturecraft_ui_egui::state::{FileType, MapExport, SetExport}; + + // Below General Export Parameters, where the 1112x662 window draws nothing + const EMPTY_SPOT: egui::Pos2 = egui::pos2(736.0, 530.0); + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let (brightness, theme) = match std::env::var("TC_SNAPSHOT_THEME").as_deref() { + Ok("dark") => (Brightness::Dark, "dark"), + Ok("light") => (Brightness::Light, "light"), + _ => (Brightness::MediumDark, "medium"), + }; + + // Ball and Base, then enough texture sets that the set list scrolls + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let template = session.doc.project.texture_sets[0].clone(); + while session.doc.project.texture_sets.len() < 60 { + let mut set = template.clone(); + set.name = format!("Set {}", session.doc.project.texture_sets.len() + 1); + session.doc.project.texture_sets.push(set); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1112.0, 662.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.prefs.brightness = brightness; + harness.set_render_cursor(false); + { + let e = &mut harness.state_mut().ui.export; + e.dir = "/home/user/Documents/TextureCraft/export".into(); + e.preset = "Document channels + Normal + AO (No Alpha)".into(); + e.padding = "infinite".into(); + e.skip = vec![4]; + } + harness.state_mut().ui.windows.export = true; + harness.run_steps(4); + let color_space = harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Default")).unwrap().rect(); + harness.hover_at(color_space.center()); + harness.run_steps(30); + save(&mut harness, &output_dir, &format!("ep-settings-global-{theme}")); + harness.hover_at(egui::pos2(1.0, 1.0)); + + harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Based on output template")).unwrap().click(); + harness.run_steps(3); + save(&mut harness, &output_dir, &format!("ep-settings-file-type-open-{theme}")); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The closed list keeps the keyboard focus (and its ring) until a click lands on the page's empty column + harness.hover_at(EMPTY_SPOT); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: EMPTY_SPOT, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + harness.hover_at(egui::pos2(1.0, 1.0)); + harness.run_steps(3); + + // Base with its own size and its height map as 32-bit exr + { + let e = &mut harness.state_mut().ui.export; + e.page = Some(1); + let mut set = SetExport { size: Some(1024), ..SetExport::default() }; + set.maps_template = e.preset.clone(); + let template = texturecraft_engine::formats::builtin_preset(&e.preset).unwrap(); + let height = template.maps.iter().position(|map| texturecraft_engine::formats::export::channel_label(map) == "height").unwrap(); + set.maps.insert(height, MapExport { file_type: Some(FileType { format: "exr".into(), bit_depth: 32, dithering: false }), ..MapExport::default() }); + set.maps.insert(2, MapExport { enabled: false, ..MapExport::default() }); + e.sets.insert(1, set); + } + save(&mut harness, &output_dir, &format!("ep-settings-set-{theme}")); + + harness.state_mut().ui.export.page = None; + harness.state_mut().ui.export.tab = 1; + harness.state_mut().ui.export.preset = "Unreal Engine (Packed)".into(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Unreal Engine (Packed)").scroll_to_me(); + save(&mut harness, &output_dir, &format!("ep-templates-unreal-{theme}")); + + harness.state_mut().ui.export.preset = "Document channels + Normal + AO (No Alpha)".into(); + harness.state_mut().ui.export.tab = 2; + save(&mut harness, &output_dir, &format!("ep-list-{theme}")); +} From bde768fdf7c7c05bac1bb4daf3bef638cb709c2e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:20:10 +0000 Subject: [PATCH 026/190] Output templates: the reference's columns and swatch colours, aligned map cards and a used map's square The tab lays out on the reference's columns: Presets (built-in templates with a locked file glyph, the selected one in the frame colour and bold, no accent), the outputs 10 px from both dividers, and the Input maps and Mesh/Converted maps panes keeping their width at the window's right. Output map cards are 48 px with a 6 px inset: grip, name field cut at the front while not typed in, "$", the channel swatches in the reference's colours moved onto TextureCraft's window colour with their channel's underline, then file type over bit depth on one column beside duplicate and remove. A built-in template's cards keep their full look (its lock says it is read-only). A map an output reads shows a small square of its colour; Converted maps are plain text. The drag hint is the map entries' tooltip, and the count strip reads "N output maps will be exported". --- crates/ui-egui/src/export_templates.rs | 935 ++++++++++-------- .../src/export_templates/output_card.rs | 6 + .../src/export_templates/swatch_look.rs | 4 +- crates/ui-egui/src/export_window.rs | 10 +- crates/ui-egui/src/export_window/drawn.rs | 27 +- .../ui-egui/src/export_window/export_look.rs | 7 + crates/ui-egui/tests/it/output_templates.rs | 16 +- 7 files changed, 602 insertions(+), 403 deletions(-) create mode 100644 crates/ui-egui/src/export_templates/output_card.rs diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 532d4a3c..22bdf182 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -4,7 +4,9 @@ //! Maps dragged from the Input maps, Mesh maps and Converted maps panes onto an output map's //! channel swatches fill its channels. -use egui::{Color32, RichText, Ui, vec2}; +use std::sync::LazyLock; + +use egui::{Color32, Rect, RichText, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{BakedMap, Channel}; @@ -12,16 +14,18 @@ use texturecraft_engine::formats::export::{FILE_TOKENS, MAX_PRESET_NAME, sanitiz use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef, VirtualMap}; use crate::TextureCraftApp; +use crate::export_window::{ExportLook, GUTTER, TAB_ROW_HEIGHT, drawn}; use crate::i18n::{n_, tr, trf}; -use crate::theme::{Tokens, caption}; +use crate::theme::Tokens; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::{chip, icon_button_without_tooltip}; +use crate::widgets::chip; mod channel_target; mod map_drag; mod map_lists; mod map_preview_cache; mod map_preview_pictures; +mod output_card; mod pending_drop; mod planned_output; mod row_edit; @@ -33,61 +37,159 @@ use map_drag::MapDrag; use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; use map_preview_cache::MapPreviewCache; use map_preview_pictures::MapPreviewPictures; +use output_card::OutputCard; pub use pending_drop::PendingDrop; use planned_output::PlannedOutput; use row_edit::RowEdit; use source_pick::SourcePick; use swatch_look::SwatchLook; -const ICON_POINTS: f32 = 20.0; -/// Width of the Presets list -const LIST_WIDTH_POINTS: f32 = 220.0; -/// The tab's width in the reference-size window: a narrower window narrows the side panes in -/// proportion, so the output rows keep their room -const REFERENCE_TAB_WIDTH_POINTS: f32 = 1085.0; -/// The middle column's least width, and room for the separators and their spacing -const MIN_OUTPUTS_WIDTH_POINTS: f32 = 200.0; -const SEPARATOR_ALLOWANCE_POINTS: f32 = 6.0; -/// Width of the Input maps pane -const INPUTS_WIDTH_POINTS: f32 = 170.0; -/// Width of the pane with Mesh maps above Converted maps -const SIDE_MAPS_WIDTH_POINTS: f32 = 165.0; -/// Share of the side pane's height that Mesh maps take; Converted maps get the rest -const MESH_MAPS_SHARE: f32 = 0.45; const RENAME_ID: &str = "exp_rename"; /// The name "+" gives a new template, as in the reference const NEW_PRESET: &str = "new_export_preset"; -/// Height of a Presets list row, and where its icon and name start -const PRESET_ROW_HEIGHT_POINTS: f32 = 18.0; -const PRESET_ICON_INDENT_POINTS: f32 = 2.0; -const PRESET_TEXT_INDENT_POINTS: f32 = 20.0; +// Layout in points from the window content's top left corner, the side panes from its right edge, measured on the locked mock -/// Height of a map list entry, the gap between entries, and where its marker and name sit -const ENTRY_HEIGHT_POINTS: f32 = 21.0; -const ENTRY_GAP_POINTS: f32 = 2.0; -const ENTRY_TEXT_INDENT_POINTS: f32 = 22.0; -const ENTRY_TEXT_SIZE_POINTS: f32 = 12.0; -const MARKER_INDENT_POINTS: f32 = 10.0; -const MARKER_SIZE_POINTS: f32 = 10.0; +/// Width of the Presets column +const PRESETS_WIDTH: f32 = 216.2; +/// Middle of the column titles +const HEADER_Y: f32 = 73.0; +/// Centre of the Presets header's first glyph, from the column's right edge +const PRESET_ICON_FROM_RIGHT: f32 = 14.0; +/// Step between the Presets header's glyphs +const PRESET_ICON_STEP: f32 = 22.0; +/// Size of the Presets header's glyphs +const PRESET_ICON_SIZE: f32 = 13.0; +/// Top of the lists under the titles +const LIST_TOP: f32 = 88.0; +/// Height of a Presets row +const PRESET_ROW_HEIGHT: f32 = 20.0; +/// Centre of a Presets row's file glyph +const PRESET_ICON_X: f32 = 16.0; +/// Where a Presets row's name starts +const PRESET_NAME_LEFT: f32 = 26.3; +/// Size of a Presets row's file glyph +const PRESET_ROW_ICON_SIZE: f32 = 12.0; +/// The column titles' left edge, inside their column +const TITLE_INDENT: f32 = 7.5; + +/// The middle column's margin to the dividers on both sides +const MIDDLE_MARGIN: f32 = 10.0; +/// Middle of the Current preset line +const CURRENT_PRESET_Y: f32 = 69.0; +/// Gap after "Current preset:" +const NAME_GAP: f32 = 5.0; +/// From the template's name to its lock's centre +const LOCK_GAP: f32 = 12.0; +/// Middle of the Output maps row +const OUTPUT_MAPS_Y: f32 = 106.0; +/// The air around a Create button's name +const CREATE_PADDING: f32 = 22.0; +/// Gap between the Create buttons +const CREATE_GAP: f32 = 6.0; +/// Gap before "Create:" +const CREATE_LABEL_GAP: f32 = 2.0; +/// Top of the first output map card +const CARDS_TOP: f32 = 127.0; +/// The count strip's top, above the body's bottom +const COUNT_TOP_ABOVE_BOTTOM: f32 = 24.0; +/// The count strip's bottom, above the body's bottom +const COUNT_BOTTOM_ABOVE_BOTTOM: f32 = 1.0; +/// The count's indent in its strip +const COUNT_TEXT_INDENT: f32 = 6.0; + +/// Height of an output map card +const CARD_HEIGHT: f32 = 48.0; +/// Gap below a card +const CARD_GAP: f32 = 6.0; +/// Corner radius of a card +const CARD_RADIUS: u8 = 3; +/// Inset of a card's swatches from its top and bottom +const CARD_INSET: f32 = 6.0; +/// Centre of a card's grip +const GRIP_X: f32 = 10.0; +/// Width of the grip's click area +const GRIP_WIDTH: f32 = 16.0; +/// Size of the grip's glyph +const GRIP_SIZE: f32 = 14.0; +/// Where a card's file name field starts +const NAME_FIELD_LEFT: f32 = 20.0; +/// Width of the file name field +const NAME_FIELD_WIDTH: f32 = 150.0; +/// The file name field's least width in a narrow window +const MIN_NAME_FIELD_WIDTH: f32 = 60.0; +/// Gap before the "$" button +const DOLLAR_GAP: f32 = 4.0; +/// Width of the "$" button +const DOLLAR_WIDTH: f32 = 22.0; +/// Gap between "$" and the swatches +const SWATCHES_GAP: f32 = 8.0; +/// The lists' and icons' rows, above and below the card's middle +const CARD_ROW_OFFSET: f32 = 10.0; +/// Centre of a card's icons, from its right edge +const CARD_ICON_FROM_RIGHT: f32 = 14.0; +/// From the icons to the lists' chevrons +const CARD_CHEVRON_STEP: f32 = 22.0; +/// Gap between a list's value and its chevron +const CARD_VALUE_GAP: f32 = 8.0; +/// Size of a card's icons +const CARD_ICON_SIZE: f32 = 12.0; +/// Values the cards' lists line up on, so cards with shorter ones keep the same column +const CARD_VALUE_SAMPLES: [&str; 3] = ["png", "8 bits", "16 bits"]; + +/// The Input maps divider, from the window's right edge +const INPUTS_DIVIDER_FROM_RIGHT: f32 = 342.3; +/// The Mesh maps divider, from the window's right edge +const SIDE_DIVIDER_FROM_RIGHT: f32 = 161.9; +/// Where the Input maps pane starts after its divider +const PANE_FROM_DIVIDER: f32 = 2.0; +/// Where it ends before the next one +const INPUTS_END_BEFORE_DIVIDER: f32 = 3.5; +/// Where the Mesh maps pane starts after its divider +const SIDE_PANE_FROM_DIVIDER: f32 = 4.0; +/// The divider between Mesh maps and Converted maps, below the body's middle +const SIDE_SPLIT_BELOW_MIDDLE: f32 = 10.0; +/// Gap between Mesh maps' last row and that divider +const MESH_BOTTOM_GAP: f32 = 6.0; +/// Middle of Converted maps' title, below the divider +const CONVERTED_TITLE_Y: f32 = 18.0; +/// Top of Converted maps' rows, below the divider +const CONVERTED_ROWS_TOP: f32 = 33.0; +/// A map entry's inset in its pane +const ENTRY_INSET: f32 = 3.0; +/// Height of a map entry +const ENTRY_HEIGHT: f32 = 20.0; +/// Pitch of the map entries +const ENTRY_PITCH: f32 = 21.0; +/// Height of a group's name row +const GROUP_HEIGHT: f32 = 18.0; +/// Indent of the titles and group names +const GROUP_INDENT: f32 = 4.0; +/// Where a used map's square starts +const MARKER_LEFT: f32 = 9.0; +/// Side of that square +const MARKER_SIZE: f32 = 10.0; +/// Its corner radius +const MARKER_RADIUS: u8 = 1; +/// How much lighter its edge is than its fill +const MARKER_EDGE_LIGHTEN: u8 = 40; +/// Where a map entry's name starts +const ENTRY_NAME_LEFT: f32 = 25.0; /// How strongly a map TextureCraft does not have yet is dimmed const UNAVAILABLE_FADE: f32 = 0.6; -/// An output map row: padding, gap below it, grip width, file name field width, icon size -const ROW_MARGIN_POINTS: f32 = 6.0; -const ROW_GAP_POINTS: f32 = 4.0; -const GRIP_WIDTH_POINTS: f32 = 5.0; -const NAME_FIELD_WIDTH_POINTS: f32 = 150.0; -const ROW_ICON_POINTS: f32 = 16.0; -/// Width the "Output maps" title and the Create buttons need on one row -const OUTPUT_MAPS_ROW_WIDTH_POINTS: f32 = 420.0; -/// The narrowest file name field, the "$" button and the format, bit depth and icon columns at a -/// row's right end, and the gaps between a row's controls (besides the swatches') -const MIN_NAME_FIELD_WIDTH_POINTS: f32 = 60.0; -const DOLLAR_BUTTON_WIDTH_POINTS: f32 = 22.0; -const ROW_LISTS_WIDTH_POINTS: f32 = 100.0; -const ROW_GAPS: f32 = 4.0; -/// The accent frame around a drop target: its stroke and its gap to the target +/// Naming pattern's info glyph, from the window's right edge +const NAMING_INFO_FROM_RIGHT: f32 = 20.8; +/// Its dropdown's left edge, from the window's right edge +const NAMING_COMBO_LEFT_FROM_RIGHT: f32 = 182.4; +/// Its dropdown's right edge, from the window's right edge +const NAMING_COMBO_RIGHT_FROM_RIGHT: f32 = 34.0; +/// Its label's right edge, from the window's right edge +const NAMING_LABEL_FROM_RIGHT: f32 = 188.0; +/// Size of the info glyph +const INFO_SIZE: f32 = 14.0; + +/// The accent-free frame around a drop target: its stroke and its gap to the target const DROP_HIGHLIGHT_STROKE_POINTS: f32 = 1.5; const DROP_HIGHLIGHT_GAP_POINTS: f32 = 2.0; /// Side of the corner mark of an inverted swatch @@ -96,24 +198,49 @@ const INVERTED_MARK_POINTS: f32 = 8.0; const PREVIEW_FILE_WIDTH_POINTS: f32 = 150.0; const PREVIEW_CHANNEL_WIDTH_POINTS: f32 = 34.0; -/// A channel swatch: its side, the label's size and offset from the top, and the bars that show -/// which channels of the source it reads -const SWATCH_SIZE_POINTS: f32 = 32.0; -const SWATCH_TEXT_SIZE_POINTS: f32 = 11.0; -const SWATCH_TEXT_TOP_POINTS: f32 = 3.0; -const SWATCH_BAR_WIDTH_POINTS: f32 = 18.0; -const SWATCH_BAR_HEIGHT_POINTS: f32 = 2.0; -const SWATCH_BAR_BOTTOM_POINTS: f32 = 9.0; +/// Width of a channel swatch; its height is the card's less its inset +const SWATCH_WIDTH: f32 = 34.0; +/// Gap between swatches +const SWATCH_GAP: f32 = 2.0; +/// Middle of a swatch's letters, from its top +const SWATCH_LABEL_Y: f32 = 11.0; +/// A swatch's underline: its inset from the sides +const SWATCH_BAR_INSET: f32 = 6.0; +/// Its top, from the swatch's bottom +const SWATCH_BAR_BOTTOM: f32 = 10.0; +/// Its height +const SWATCH_BAR_HEIGHT: f32 = 2.0; -/// Swatch colours: one hue per map, spread by the golden ratio so neighbours differ, muted to -/// keep the white label readable -const HUE_STEP: f32 = 0.618_034; -const SWATCH_SATURATION: f32 = 0.45; -const SWATCH_VALUE_DARK: f32 = 0.42; -const SWATCH_VALUE_LIGHT: f32 = 0.62; +/// The reference's swatch colours mix channel levels 31, 71 and 111 +const SWATCH_LEVELS: [u8; 3] = [31, 71, 111]; +/// The shift from the reference's darker window to TextureCraft's window colour +const SWATCH_SHIFT: [u8; 3] = [1, 6, 16]; +/// The maps the reference shows keep its own colours +const REFERENCE_SWATCHES: [(SourceRef, [u8; 3]); 6] = [ + (SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, [71, 31, 31]), + (SourceRef::Channel { channel: Channel::Opacity, component: 0 }, [71, 71, 71]), + (SourceRef::Virtual { map: VirtualMap::AoMixed, component: 0 }, [111, 71, 31]), + (SourceRef::Channel { channel: Channel::Roughness, component: 0 }, [111, 111, 71]), + (SourceRef::Channel { channel: Channel::Metallic, component: 0 }, [31, 71, 111]), + (SourceRef::Virtual { map: VirtualMap::NormalDirectX, component: 0 }, [111, 31, 111]), +]; -/// The bars of the R, G and B channels a swatch reads -const COMPONENT_COLORS: [Color32; 3] = [Color32::from_rgb(220, 70, 70), Color32::from_rgb(80, 190, 90), Color32::from_rgb(80, 120, 230)]; +/// Every mix of the swatch levels that is no grey and no reference colour, taken in turn by the other maps +static FREE_SWATCHES: LazyLock> = LazyLock::new(|| { + let levels = SWATCH_LEVELS.iter().flat_map(|&r| SWATCH_LEVELS.iter().flat_map(move |&g| SWATCH_LEVELS.iter().map(move |&b| [r, g, b]))); + levels.filter(|rgb| !(rgb[0] == rgb[1] && rgb[1] == rgb[2]) && REFERENCE_SWATCHES.iter().all(|(_, known)| known != rgb)).collect() +}); + +/// The underline of R +const BAR_RED: Color32 = Color32::from_rgb(230, 70, 70); +/// The underline of G +const BAR_GREEN: Color32 = Color32::from_rgb(80, 200, 90); +/// The underline of B +const BAR_BLUE: Color32 = Color32::from_rgb(80, 130, 240); +/// The underline of A +const BAR_ALPHA: Color32 = Color32::from_rgb(220, 220, 220); +/// The underline of RGB and gray +const BAR_WHOLE: Color32 = Color32::WHITE; /// What a cleared channel writes: black, or opaque in the alpha channel const CLEARED_VALUE: f32 = 0.0; @@ -188,8 +315,6 @@ const CONSTANT_DRAG_SPEED: f64 = 0.005; /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; -/// Width of the Naming pattern list -const NAMING_PATTERN_WIDTH_POINTS: f32 = 150.0; /// `s` reading component `k` (only 3-component sources have more than one). fn with_component(s: &SourceRef, k: u8) -> SourceRef { @@ -345,43 +470,28 @@ enum MapAction { Remove(usize), } -/// The Output templates tab: template list, the selected template's outputs, then the Input maps -/// pane and the pane with Mesh maps above Converted maps. -pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { +/// The Output templates tab in `body`: presets, outputs, Input maps, then Mesh maps above Converted maps +pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, body: Rect, builtins: &[ExportPreset]) { sync_draft(app); - let height = ui.available_height(); + let top = body.top() - TAB_ROW_HEIGHT; let names = crate::export_window::template_groups(app, builtins).1; - let scale = (ui.available_width() / REFERENCE_TAB_WIDTH_POINTS).min(1.0); - let (list_width, inputs_width, side_width) = (LIST_WIDTH_POINTS * scale, INPUTS_WIDTH_POINTS * scale, SIDE_MAPS_WIDTH_POINTS * scale); - let mut list_action = None; - ui.vertical(|ui| { - ui.set_width(list_width); - ui.set_height(height); - list_action = preset_list(app, ui, &names); - }); - ui.separator(); - ui.vertical(|ui| { - // Leave room for the two map panes and three separators - let panes = inputs_width + side_width + 8.0 * ui.spacing().item_spacing.x + SEPARATOR_ALLOWANCE_POINTS; - ui.set_width((ui.available_width() - panes).max(MIN_OUTPUTS_WIDTH_POINTS)); - ui.set_height(height); - outputs(app, ui); - }); + let presets_right = body.left() + PRESETS_WIDTH; + let inputs_divider = body.right() - INPUTS_DIVIDER_FROM_RIGHT; + let side_divider = body.right() - SIDE_DIVIDER_FROM_RIGHT; + for x in [presets_right, inputs_divider, side_divider] { + drawn::divider(ui, Rect::from_min_max(pos2(x, body.top()), pos2(x + 1.0, body.bottom()))); + } + + let list_action = preset_list(app, ui, Rect::from_min_max(body.min, pos2(presets_right, body.bottom())), top, &names); + let middle = Rect::from_min_max(pos2(presets_right + 1.0 + MIDDLE_MARGIN, body.top()), pos2(inputs_divider - MIDDLE_MARGIN, body.bottom())); + ui.scope(|ui| outputs(app, ui, middle, top)); // The panes mark the maps the selected template's outputs read - let marked = marked_sources(app, &Tokens::get(ui.ctx())); - ui.separator(); - ui.vertical(|ui| { - ui.set_width(inputs_width); - ui.set_height(height); - input_maps(ui, &marked); - }); - ui.separator(); - ui.vertical(|ui| { - ui.set_width(side_width); - ui.set_height(height); - mesh_and_converted_maps(ui, height, &marked); - }); + let marked = marked_sources(app); + let inputs = Rect::from_min_max(pos2(inputs_divider + PANE_FROM_DIVIDER, body.top()), pos2(side_divider - INPUTS_END_BEFORE_DIVIDER, body.bottom())); + input_maps(ui, inputs, top, &marked); + let side = Rect::from_min_max(pos2(side_divider + SIDE_PANE_FROM_DIVIDER, body.top()), body.max); + mesh_and_converted_maps(ui, side, top, &marked); if let Some(a) = list_action { apply(app, ui.ctx(), a); } @@ -397,93 +507,104 @@ pub fn select(app: &mut TextureCraftApp, name: String) { } } -/// "Naming pattern" with its info icon, at the right end of the tab row (laid out right to left) -pub(crate) fn naming_pattern(ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { +/// "Naming pattern", its list and its info glyph at the tab row's right end +pub(crate) fn naming_pattern(ui: &mut Ui, window_right: f32, y: f32) { + let look = ExportLook::get(ui.ctx()); + let info_at = pos2(window_right - NAMING_INFO_FROM_RIGHT, y); + drawn::glyph(ui, info_at, ic::INFO, INFO_SIZE, look.text_dim); + let info = ui.interact(Rect::from_center_size(info_at, vec2(INFO_SIZE, INFO_SIZE)), ui.scope_id().with("exp_naming_info"), egui::Sense::hover()); + info.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, ic::INFO)); + info.on_hover_ui(|ui| { ui.label(tr("Choose how the input maps are named in this editor.")); ui.label(tr("The active texture set’s shader can affect the available map names.")); }); - egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH_POINTS).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { + let combo = drawn::control_rect(window_right - NAMING_COMBO_LEFT_FROM_RIGHT, window_right - NAMING_COMBO_RIGHT_FROM_RIGHT, y); + drawn::combo(ui, combo, "exp_naming", NAMING_PATTERNS[0], |ui| { for p in NAMING_PATTERNS { let _ = ui.selectable_label(true, p); } }); - ui.label(tr("Naming pattern")); + let label = tr("Naming pattern"); + let left = window_right - NAMING_LABEL_FROM_RIGHT - drawn::text_width(ui, label, false); + drawn::label_at(ui, left, y, label, look.text, false); } -/// The Presets list: the templates sorted by name (built-in and user); a right click offers -/// Rename, Duplicate and Remove, F2 renames -fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Option { +/// The Presets list in `column` with its header's tools; a right click offers Rename, Duplicate and Remove, F2 renames +fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32, names: &[String]) -> Option { + let look = ExportLook::get(ui.ctx()); let mut act = None; - let sel = app.ui.export.preset.clone(); + let selected_name = app.ui.export.preset.clone(); let user = app.ui.export.draft.is_some(); - ui.horizontal(|ui| { - ui.label(caption(tr("Presets"))); + drawn::label_at(ui, column.left() + TITLE_INDENT, top + HEADER_Y, tr("Presets"), look.text, true); - // Copy, "−" and "+" from left to right, without tooltips as in the reference - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON_POINTS).clicked() { - act = Some(ListAction::New); - } - if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON_POINTS)).inner.clicked() - { - act = Some(ListAction::Remove(sel.clone())); - } - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON_POINTS).clicked() { - act = Some(ListAction::Duplicate(sel.clone())); - } - - // TextureCraft's template files: a focusable menu, as the row's right click is pointer only - let actions = icon_button_without_tooltip(ui, ic::DOTS_THREE, tr("Template actions"), false, ICON_POINTS); - let opened_now = actions.clicked(); - egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); - }); - }); - ui.add_space(2.0); - if std::mem::take(&mut app.ui.export.rename_key) && user { - act = Some(ListAction::StartRename(sel.clone())); + // Template actions, Duplicate, "−" and "+" from left to right, without tooltips as in the reference + let icon_at = |slot_from_right: f32| pos2(column.right() - PRESET_ICON_FROM_RIGHT - slot_from_right * PRESET_ICON_STEP, top + HEADER_Y); + if drawn::icon_button(ui, icon_at(0.0), ic::PLUS, PRESET_ICON_SIZE, tr("New template"), true, false).clicked() { + act = Some(ListAction::New); } - egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| { - for name in names { - let is_user = app.session.export_presets.list.iter().any(|p| p.name == *name); - match app.ui.export.renaming.as_mut().filter(|_| *name == sel) { - Some(buf) => { - let r = ui.add(egui::TextEdit::singleline(buf).id(egui::Id::unique(RENAME_ID)).desired_width(f32::INFINITY)); - if r.lost_focus() { - act = Some(if ui.input(|i| i.key_pressed(egui::Key::Escape)) { - ListAction::Select(name.clone()) - } else { - ListAction::Rename(buf.clone()) + if drawn::icon_button(ui, icon_at(1.0), ic::MINUS, PRESET_ICON_SIZE, tr("Delete the selected template"), user, false).clicked() { + act = Some(ListAction::Remove(selected_name.clone())); + } + if drawn::icon_button(ui, icon_at(2.0), ic::COPY, PRESET_ICON_SIZE, tr("Duplicate the selected template"), true, false).clicked() { + act = Some(ListAction::Duplicate(selected_name.clone())); + } + + // TextureCraft's template files: a focusable menu, as the row's right click is pointer only + let actions = drawn::icon_button(ui, icon_at(3.0), ic::DOTS_THREE, PRESET_ICON_SIZE, tr("Template actions"), true, false); + let opened_now = actions.clicked(); + egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); + if std::mem::take(&mut app.ui.export.rename_key) && user { + act = Some(ListAction::StartRename(selected_name.clone())); + } + + // The rows scroll, the scroll bar in its strip at the column's right + let rows = Rect::from_min_max(pos2(column.left(), top + LIST_TOP), column.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + let width = rows.width() - GUTTER; + for name in names { + let is_user = app.session.export_presets.list.iter().any(|preset| preset.name == *name); + let (rect, _) = ui.allocate_exact_size(vec2(width, PRESET_ROW_HEIGHT), egui::Sense::hover()); + match app.ui.export.renaming.as_mut().filter(|_| *name == selected_name) { + Some(name_buffer) => { + let field = egui::TextEdit::singleline(name_buffer).id(egui::Id::unique(RENAME_ID)).margin(vec2(PRESET_NAME_LEFT, 0.0)); + let rename_field = ui.put(rect, field); + if rename_field.lost_focus() { + act = Some(if ui.input(|input| input.key_pressed(egui::Key::Escape)) { + ListAction::Select(name.clone()) + } else { + ListAction::Rename(name_buffer.clone()) + }); + } + } + None => { + let response = preset_row(ui, rect, name, *name == selected_name, is_user).on_hover_text(name); + if response.double_clicked() && is_user { + act = Some(ListAction::StartRename(name.clone())); + } else if response.clicked() { + act = Some(ListAction::Select(name.clone())); + } + response.context_menu(|ui| { + let read_only = tr("Built-in templates are read-only: duplicate one to edit it"); + if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() { + act = Some(ListAction::StartRename(name.clone())); + } + if ui.button(tr("Duplicate")).clicked() { + act = Some(ListAction::Duplicate(name.clone())); + } + if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { + act = Some(ListAction::Remove(name.clone())); + } + + // TextureCraft's template files, after the reference's entries + ui.separator(); + template_file_items(ui, &mut act, *name == selected_name, false); }); } } - None => { - let r = preset_row(ui, name, *name == sel).on_hover_text(name); - if r.double_clicked() && is_user { - act = Some(ListAction::StartRename(name.clone())); - } else if r.clicked() { - act = Some(ListAction::Select(name.clone())); - } - r.context_menu(|ui| { - let read_only = tr("Built-in templates are read-only: duplicate one to edit it"); - if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() { - act = Some(ListAction::StartRename(name.clone())); - } - if ui.button(tr("Duplicate")).clicked() { - act = Some(ListAction::Duplicate(name.clone())); - } - if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { - act = Some(ListAction::Remove(name.clone())); - } - - // TextureCraft's template files, after the reference's entries - ui.separator(); - template_file_items(ui, &mut act, *name == sel, false); - }); - } } - } + }); }); act } @@ -506,25 +627,23 @@ fn template_file_items(ui: &mut Ui, act: &mut Option, with_export: b } } -/// A Presets list row: a document icon and the name (cut with "…" when long), the selected one in -/// the accent colour -fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT_POINTS), egui::Sense::click()); +/// A Presets row: a locked file glyph for a built-in template, the name cut with "…", the selected one in bold +fn preset_row(ui: &mut Ui, rect: Rect, name: &str, selected: bool, is_user: bool) -> egui::Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("exp_preset_row", name)), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); - let painter = ui.painter(); - if response.hovered() { - painter.rect_filled(rect, tokens.radius, tokens.row_hover); + if selected { + painter.rect_filled(rect, 0.0, look.chrome); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, look.raised); } - let font = egui::TextStyle::Body.resolve(ui.style()); - painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT_POINTS, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); - let color = if selected { tokens.accent } else { tokens.text }; - let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); - job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT_POINTS); - let galley = painter.layout_job(job); - let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT_POINTS, rect.center().y - galley.size().y / 2.0); - painter.galley(top_left, galley, color); + let icon = if is_user { ic::FILE_TEXT } else { ic::FILE_LOCK }; + drawn::glyph(ui, pos2(rect.left() + PRESET_ICON_X, rect.center().y), icon, PRESET_ROW_ICON_SIZE, look.text_dim); + let shown = drawn::fitted(ui, name, rect.width() - PRESET_NAME_LEFT, false, selected); + let color = if selected { look.text } else { look.list_text }; + drawn::text_at(ui, rect.left() + PRESET_NAME_LEFT, rect.center().y, &shown, color, selected); + drawn::paint_focus(ui, &response); response } @@ -760,14 +879,15 @@ pub fn save_library(app: &TextureCraftApp, storage: &mut dyn eframe::Storage) { let _ = (app, storage); } -/// The selected template's output maps (editable for user templates). -fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The selected template's output maps in `column`, editable for user templates +fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { + let look = ExportLook::get(ui.ctx()); let tokens = Tokens::get(ui.ctx()); let (mut preset, editable) = match (&app.ui.export.draft, selected(app)) { (Some(d), _) => (d.clone(), true), (None, Some(b)) => (b, false), (None, None) => { - ui.label(RichText::new(tr("Select an output template")).color(tokens.text_dim)); + drawn::label_at(ui, column.left(), top + CURRENT_PRESET_Y, tr("Select an output template"), look.text_dim, false); return; } }; @@ -778,76 +898,80 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } let mut edit = RowEdit::default(); - // The selected template in a strip, "Current preset:" in bold - egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Current preset:")).strong().color(tokens.text_strong)); - ui.label(&preset.name); - if !editable { - ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); - } - }); - }); + // "Current preset:" in bold, the template's name, a lock on a built-in one + let y = top + CURRENT_PRESET_Y; + let title = tr("Current preset:"); + let name_left = column.left() + drawn::text_width(ui, title, true) + NAME_GAP; + drawn::label_at(ui, column.left(), y, title, look.text, true); + let name = drawn::label_at(ui, name_left, y, &preset.name, look.text, false); + if !editable { + let lock_at = pos2(name.rect.right() + LOCK_GAP, y); + drawn::glyph(ui, lock_at, ic::LOCK_SIMPLE, CARD_ICON_SIZE, look.text_dim); + let lock = + ui.interact(Rect::from_center_size(lock_at, vec2(CARD_ICON_SIZE, CARD_ICON_SIZE)), ui.scope_id().with("exp_preset_lock"), egui::Sense::hover()); + lock.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, ic::LOCK_SIMPLE)); + lock.on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); + } - // "Output maps", with the Create buttons at the right end of the same row, or of the next one - // when the column is too narrow for both - let create_buttons = |ui: &mut Ui, edit: &mut RowEdit| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add_enabled_ui(editable, |ui| { - for (label, layout, split, file) in CREATE.iter().rev() { - if ui.button(tr(label)).clicked() { - edit.action = Some(MapAction::Add(*layout, *split, file)); - } - } - ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); - }); - }); - }; - if ui.available_width() >= OUTPUT_MAPS_ROW_WIDTH_POINTS { - ui.horizontal(|ui| { - ui.label(caption(tr("Output maps"))); - create_buttons(ui, &mut edit); - }); - } else { - ui.label(caption(tr("Output maps"))); - ui.horizontal(|ui| create_buttons(ui, &mut edit)); - } - if let Err(e) = &preview { - ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0)); + // A built-in template's cards and buttons keep their full look: the lock says they are read-only + ui.visuals_mut().disabled_alpha = 1.0; + let y = top + OUTPUT_MAPS_Y; + drawn::label_at(ui, column.left(), y, tr("Output maps"), look.text, true); + let mut right = column.right(); + for (label, layout, split, file) in CREATE.iter().rev() { + let width = drawn::text_width(ui, tr(label), false) + CREATE_PADDING; + if drawn::button(ui, drawn::control_rect(right - width, right, y), tr(label), false, editable).clicked() { + edit.action = Some(MapAction::Add(*layout, *split, file)); + } + right -= width + CREATE_GAP; } + let create = tr("Create:"); + drawn::label_at(ui, right - CREATE_LABEL_GAP - drawn::text_width(ui, create, false), y, create, look.text, false); + let mut changed = false; let map_count = preset.maps.len(); let mut split = app.ui.export.draft_split.clone(); split.resize(map_count, false); - // Leave room for the footer text and the framed count below - let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN_POINTS; - egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| { - ui.add_enabled_ui(editable, |ui| { - // Every row takes the column's width, not the width a wider row before it left - let row_width = ui.available_width(); - for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { - let planned = preview.as_ref().ok().and_then(|outputs| outputs.get(index)).and_then(Option::as_ref); - changed |= ui.allocate_ui(vec2(row_width, 0.0), |ui| output_row(ui, index, map_count, map, row_split, planned, &mut edit)).inner; - ui.add_space(ROW_GAP_POINTS); - } + // The cards scroll between the header and the count strip; their lists line up on one column + let strip = + Rect::from_min_max(pos2(column.left(), column.bottom() - COUNT_TOP_ABOVE_BOTTOM), pos2(column.right(), column.bottom() - COUNT_BOTTOM_ABOVE_BOTTOM)); + let cards = Rect::from_min_max(pos2(column.left(), top + CARDS_TOP), pos2(column.right(), strip.top() - CARD_GAP)); + let values = + preset.maps.iter().flat_map(|map| [map.format.extension().to_string(), crate::export_window::depth_label(Some(map.format), map.bit_depth, false)]); + let value_width = values.chain(CARD_VALUE_SAMPLES.map(str::to_string)).map(|value| drawn::text_width(ui, &value, false)).fold(0.0, f32::max); + ui.scope_builder(egui::UiBuilder::new().max_rect(cards), |ui| { + egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).show(ui, |ui| { + let height = map_count as f32 * (CARD_HEIGHT + CARD_GAP); + let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::hover()); + ui.add_enabled_ui(editable, |ui| { + for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { + let planned = preview.as_ref().ok().and_then(|outputs| outputs.get(index)).and_then(Option::as_ref); + let top = area.top() + index as f32 * (CARD_HEIGHT + CARD_GAP); + let card = Rect::from_min_size(pos2(area.left(), top), vec2(area.width(), CARD_HEIGHT)); + let row = OutputCard { index, count: map_count, value_width }; + changed |= output_row(ui, card, &row, map, row_split, planned, &mut edit); + } + }); }); }); - ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); // The hovered output's pictures show from the next frame on if let (Some(index), Ok(params)) = (edit.hovered_output, ¶ms) { MapPreviewCache::fill(app, ui.ctx(), params, index); } - // Count only maps that have sources in the current set - if let Ok(planned) = &preview { - let exported = planned.iter().flatten().count(); - egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); - }); + // Count only maps that have sources in the current set; an edit that cannot be saved says why there + ui.painter().rect_filled(strip, 0.0, look.control); + let text_left = strip.left() + COUNT_TEXT_INDENT; + match &preview { + Ok(planned) => { + let exported = planned.iter().flatten().count(); + drawn::label_at(ui, text_left, strip.center().y, &trf("{n} output maps will be exported", &[("n", &exported)]), look.text, false); + } + Err(e) => { + drawn::label_at(ui, text_left, strip.center().y, &trf("Not saved: {error}", &[("error", e)]), tokens.danger, false); + } } if !editable { return; @@ -978,71 +1102,83 @@ fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result, edit: &mut RowEdit) -> bool { - let tokens = Tokens::get(ui.ctx()); +/// One output map card: grip, file name, "$", swatches, then file type over bit depth beside duplicate and remove +fn output_row(ui: &mut Ui, card: Rect, row: &OutputCard, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { + let look = ExportLook::get(ui.ctx()); + let index = row.index; + + // The card takes a dragged row before its controls, which sit above it + let card_response = ui.interact(card, ui.scope_id().with(("exp_card", index)), egui::Sense::hover()); + ui.painter().rect_filled(card, CARD_RADIUS, look.control); + let mid = card.center().y; let mut changed = false; - let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + grip(ui, Rect::from_center_size(pos2(card.left() + GRIP_X, mid), vec2(GRIP_WIDTH, card.height())), index, row.count, edit); - // The name field gives way in a narrow window, so the swatches and lists stay in the row - let swatches = swatch_targets(map, *split).len() as f32; - let spacing = ui.spacing().item_spacing.x; - let others = GRIP_WIDTH_POINTS + DOLLAR_BUTTON_WIDTH_POINTS + swatches * (SWATCH_SIZE_POINTS + spacing) + ROW_LISTS_WIDTH_POINTS; - let name_width = (ui.available_width() - others - ROW_GAPS * spacing).clamp(MIN_NAME_FIELD_WIDTH_POINTS, NAME_FIELD_WIDTH_POINTS); + // The name field gives way in a narrow window, so the swatches and lists keep their room + let swatches_width = swatch_targets(map, *split).len() as f32 * (SWATCH_WIDTH + SWATCH_GAP); + let lists_width = CARD_ICON_FROM_RIGHT + CARD_CHEVRON_STEP + CARD_VALUE_GAP + row.value_width + SWATCHES_GAP; + let room = card.width() - NAME_FIELD_LEFT - DOLLAR_GAP - DOLLAR_WIDTH - SWATCHES_GAP - swatches_width - lists_width; + let name_width = room.clamp(MIN_NAME_FIELD_WIDTH, NAME_FIELD_WIDTH); + let name_rect = drawn::control_rect(card.left() + NAME_FIELD_LEFT, card.left() + NAME_FIELD_LEFT + name_width, mid); + changed |= name_field(ui, name_rect, index, &mut map.file, planned); + let dollar = drawn::control_rect(name_rect.right() + DOLLAR_GAP, name_rect.right() + DOLLAR_GAP + DOLLAR_WIDTH, mid); + changed |= token_menu(ui, dollar, index, &mut map.file); + let swatches = Rect::from_min_max(pos2(dollar.right() + SWATCHES_GAP, card.top() + CARD_INSET), pos2(card.right(), card.bottom() - CARD_INSET)); + changed |= channel_swatches(ui, swatches, index, map, split, planned, edit); - grip(ui, index, count, edit); - let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(name_width)).on_hover_ui(|ui| { - ui.label(tr("File name without extension; variables insert names")); - ui.label(planned_text(planned)); - }); - changed |= name.changed(); - changed |= token_menu(ui, &mut map.file); - changed |= channel_swatches(ui, index, map, split, planned, edit); - - // The lists and icons at the row's right end: file format and duplicate, bit depth and remove - ui.add_space((ui.available_width() - ROW_LISTS_WIDTH_POINTS).max(0.0)); - ui.vertical(|ui| { - ui.horizontal(|ui| { - changed |= format_menu(ui, map); - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON_POINTS).clicked() { - edit.action = Some(MapAction::Duplicate(index)); - } - }); - ui.horizontal(|ui| { - changed |= depth_menu(ui, map); - if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON_POINTS).clicked() { - edit.action = Some(MapAction::Remove(index)); - } - }); - }); - }); - }); - - // Another row's grip dropped here moves that row here (the type check keeps a map list drop) - let row = frame.response; - let row_dragged_over = row.dnd_hover_payload::().is_some_and(|from| from.0 != index); - if row_dragged_over { - drop_highlight(ui, row.rect, &tokens); + // The right block: file type over bit depth on one column, duplicate over remove beside them + let icon_x = card.right() - CARD_ICON_FROM_RIGHT; + let chevron_x = icon_x - CARD_CHEVRON_STEP; + let value_left = chevron_x - CARD_VALUE_GAP - row.value_width; + let (upper, lower) = (mid - CARD_ROW_OFFSET, mid + CARD_ROW_OFFSET); + changed |= format_menu(ui, (value_left, chevron_x, upper), index, map); + changed |= depth_menu(ui, (value_left, chevron_x, lower), index, map); + if drawn::icon_button(ui, pos2(icon_x, upper), ic::COPY, CARD_ICON_SIZE, tr("Duplicate this output"), ui.is_enabled(), false).clicked() { + edit.action = Some(MapAction::Duplicate(index)); } - if row_dragged_over && let Some(from) = row.dnd_release_payload::() { + if drawn::icon_button(ui, pos2(icon_x, lower), ic::X, CARD_ICON_SIZE, tr("Remove this output"), ui.is_enabled(), false).clicked() { + edit.action = Some(MapAction::Remove(index)); + } + + // Another card's grip dropped here moves that card here (the type check keeps a map list drop) + let row_dragged_over = card_response.dnd_hover_payload::().is_some_and(|from| from.0 != index); + if row_dragged_over { + drop_highlight(ui, card); + } + if row_dragged_over && let Some(from) = card_response.dnd_release_payload::() { edit.action = Some(MapAction::Move { from: from.0, to: index }); } changed } -/// The grip at a row's left: drag it onto another row to move the map there; the arrow keys and -/// its right-click menu move it one place -fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { - let tokens = Tokens::get(ui.ctx()); +/// The file name field; until it is typed in it shows the name's end, cut with "…"; true when it changed +fn name_field(ui: &mut Ui, rect: Rect, index: usize, file: &mut String, planned: Option<&PlannedOutput>) -> bool { + let look = ExportLook::get(ui.ctx()); + let id = ui.scope_id().with(("exp_map_name", index)); + let typing = ui.memory(|memory| memory.has_focus(id)); + let text_color = if typing { look.text } else { Color32::TRANSPARENT }; + let field = egui::TextEdit::singleline(file).id(id).margin(vec2(drawn::VALUE_INSET, 0.0)).background_color(look.control).text_color(text_color); + let response = ui.put(rect, field).on_hover_ui(|ui| { + ui.label(tr("File name without extension; variables insert names")); + ui.label(planned_text(planned)); + }); + if !typing { + let shown = drawn::fitted(ui, file, rect.width() - 2.0 * drawn::VALUE_INSET, true, false); + let color = if drawn::looks_disabled(ui, ui.is_enabled()) { look.text_dim } else { look.text }; + drawn::text_at(ui, rect.left() + drawn::VALUE_INSET, rect.center().y, &shown, color, false); + } + response.changed() +} + +/// A card's grip: drag it onto another card, or use the arrow keys or its menu, to move the map +fn grip(ui: &mut Ui, rect: Rect, index: usize, count: usize, edit: &mut RowEdit) { + let look = ExportLook::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click_and_drag()); + let response = ui.interact(rect, ui.scope_id().with(("exp_grip", index)), if enabled { egui::Sense::click_and_drag() } else { egui::Sense::hover() }); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tr("Reorder"))); - let color = if response.hovered() || response.dragged() { tokens.text } else { tokens.text_dim }; - ui.painter().rect_filled(rect, 1.0, color); + let color = if enabled && (response.hovered() || response.dragged()) { look.text } else { look.text_dim }; + drawn::glyph(ui, rect.center(), ic::DOTS_SIX_VERTICAL, GRIP_SIZE, color); + drawn::paint_focus(ui, &response); let response = response.on_hover_cursor(egui::CursorIcon::Grab); response.dnd_set_drag_payload(MapDrag(index)); @@ -1071,10 +1207,12 @@ fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { } } -/// The "$" button: the file name variables in the reference's order, then $channel -fn token_menu(ui: &mut Ui, file: &mut String) -> bool { +/// The "$" button in `rect`: the file name variables in the reference's order, then $channel +fn token_menu(ui: &mut Ui, rect: Rect, index: usize, file: &mut String) -> bool { let mut changed = false; - let menu = ui.menu_button("$", |ui| { + let id = ui.scope_id().with(("exp_tokens", index)); + let button = drawn::button_with_id(ui, id, rect, "$", "$", false, ui.is_enabled()).on_hover_text(tr("Insert a variable")); + egui::Popup::menu(&button).show(|ui| { let mut add = |ui: &mut Ui, token: &str| { if ui.button(RichText::new(token).monospace()).clicked() { file.push_str(token); @@ -1093,14 +1231,15 @@ fn token_menu(ui: &mut Ui, file: &mut String) -> bool { add(ui, token); } }); - menu.response.on_hover_text(tr("Insert a variable")); changed } -/// The file type menu of an output map ("png˅") -fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { +/// The file type menu of an output map ("png ⌄") at `place`: (value's left, chevron's centre, middle) +fn format_menu(ui: &mut Ui, (left, chevron, y): (f32, f32, f32), index: usize, map: &mut MapSpec) -> bool { let mut changed = false; - let menu = ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { + let id = ui.scope_id().with(("exp_map_format", index)); + let menu = drawn::text_dropdown(ui, id, left, chevron, y, map.format.extension()).on_hover_text(tr("File format")); + egui::Popup::menu(&menu).show(|ui| { for extension in MAP_FILE_TYPES { let Some(format) = FileFormat::from_extension(extension) else { ui.add_enabled(false, egui::Button::selectable(false, extension)).on_disabled_hover_text(tr(NOT_AVAILABLE)); @@ -1118,16 +1257,17 @@ fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); - menu.response.on_hover_text(tr("File format")); changed } -/// The bit depth menu of an output map ("8 bits˅"); templates do not keep dithering yet -fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { +/// The bit depth menu of an output map ("8 bits ⌄"); templates do not keep dithering yet +fn depth_menu(ui: &mut Ui, (left, chevron, y): (f32, f32, f32), index: usize, map: &mut MapSpec) -> bool { let format = map.format; let mut changed = false; let shown = crate::export_window::depth_label(Some(format), map.bit_depth, false); - let menu = ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { + let id = ui.scope_id().with(("exp_map_depth", index)); + let menu = drawn::text_dropdown(ui, id, left, chevron, y, &shown).on_hover_text(tr("Bit depth")); + egui::Popup::menu(&menu).show(|ui| { for (depth, dithering) in crate::export_window::depth_options(format) { let label = crate::export_window::depth_label(Some(format), depth, dithering); if dithering { @@ -1139,7 +1279,6 @@ fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); - menu.response.on_hover_text(tr("Bit depth")); changed } @@ -1280,8 +1419,8 @@ fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget, inve } } -/// The colour of a map on swatches and list markers (None for constants) -fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { +/// A map's colour on swatches and list markers (None for constants), the reference's own where it has one +fn source_color(source: &SourceRef) -> Option { let channels = Channel::ALL.len(); let converted = VirtualMap::ALL.len(); let index = match source { @@ -1290,19 +1429,19 @@ fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { SourceRef::Baked { map, .. } => channels + converted + BakedMap::ALL.iter().position(|m| m == map)?, SourceRef::Constant(_) => return None, }; - let hue = (index as f32 * HUE_STEP).fract(); - let value = if tokens.dark { SWATCH_VALUE_DARK } else { SWATCH_VALUE_LIGHT }; - Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, value, 1.0).into()) + let reference = REFERENCE_SWATCHES.iter().find(|(known, _)| same_source(known, source)).map(|(_, rgb)| *rgb); + let [r, g, b] = reference.or_else(|| FREE_SWATCHES.get(index % FREE_SWATCHES.len().max(1)).copied())?; + Some(Color32::from_rgb(r + SWATCH_SHIFT[0], g + SWATCH_SHIFT[1], b + SWATCH_SHIFT[2])) } -/// The bars under a swatch's letters: red, green and blue for a colour map's RGB, else the one -/// channel read (white for gray) -fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { - match source { - SourceRef::Constant(_) => Vec::new(), - _ if source.components() == 3 && target == ChannelTarget::Rgb && rgb_spread(map) => COMPONENT_COLORS.to_vec(), - _ if source.components() == 3 => COMPONENT_COLORS.get(usize::from(component_of(source))).copied().into_iter().collect(), - _ => vec![tokens.text_strong], +/// The underline of a swatch: the colour of the channel its letters name (white for RGB and gray) +fn swatch_bar(target: ChannelTarget) -> Color32 { + match target { + ChannelTarget::One(Dest::R) => BAR_RED, + ChannelTarget::One(Dest::G) => BAR_GREEN, + ChannelTarget::One(Dest::B) => BAR_BLUE, + ChannelTarget::One(Dest::A) => BAR_ALPHA, + ChannelTarget::Rgb | ChannelTarget::One(Dest::L) => BAR_WHOLE, } } @@ -1357,13 +1496,11 @@ fn preview_pictures(ui: &mut Ui, map: &MapSpec, pictures: &MapPreviewPictures) { }); } -/// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel -/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. Hovering one -/// shows the file the output writes. -fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { - let tokens = Tokens::get(ui.ctx()); +/// A card's channel swatches from `area`'s left: drop targets for the map lists, with click and right-click menus +fn channel_swatches(ui: &mut Ui, area: Rect, index: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { let mut changed = false; let shows_split = *split || !rgb_collapsed(map); + let mut left = area.left(); for (slot, target) in swatch_targets(map, *split).into_iter().enumerate() { let Some(source) = source_of(map, target).cloned() else { continue }; @@ -1374,8 +1511,11 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo if inverted { name = trf("{swatch}, inverted", &[("swatch", &name)]); } - let look = SwatchLook { fill: source_color(&source, &tokens), bars: swatch_bars(map, &source, target, &tokens), inverted }; - let response = swatch(ui, label, &name, &look); + let constant = matches!(source, SourceRef::Constant(_)); + let look = SwatchLook { fill: source_color(&source), bar: (!constant).then(|| swatch_bar(target)), inverted }; + let rect = Rect::from_min_max(pos2(left, area.top()), pos2(left + SWATCH_WIDTH, area.bottom())); + left += SWATCH_WIDTH + SWATCH_GAP; + let response = swatch(ui, ui.scope_id().with(("exp_swatch", index, slot)), rect, label, &name, &look); if response.contains_pointer() { edit.hovered_output = Some(index); } @@ -1391,7 +1531,7 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row let map_dragged_over = response.dnd_hover_payload::().is_some(); if map_dragged_over { - drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS), &tokens); + drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS)); } if map_dragged_over && let Some(input) = response.dnd_release_payload::() { edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); @@ -1471,35 +1611,41 @@ fn set_constant(map: &mut MapSpec, target: ChannelTarget, value: f32) { } } -/// The accent frame around a drop target under a dragged map or row -fn drop_highlight(ui: &Ui, rect: egui::Rect, tokens: &Tokens) { - ui.painter().rect_stroke(rect, tokens.radius, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, tokens.accent), egui::StrokeKind::Outside); +/// The frame round a drop target, in the text colour: the accent is Export's alone +fn drop_highlight(ui: &Ui, rect: Rect) { + let look = ExportLook::get(ui.ctx()); + ui.painter().rect_stroke(rect, CARD_RADIUS, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, look.text), egui::StrokeKind::Outside); } -/// One channel swatch: `label` on top, filled with the source's colour, bars below for the -/// channels it reads, a corner mark when inverted -fn swatch(ui: &mut Ui, label: &str, name: &str, look: &SwatchLook) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); +/// One channel swatch `id`: its letters, the source's colour, its channel's underline, a corner mark when inverted +fn swatch(ui: &mut Ui, id: egui::Id, rect: Rect, label: &str, name: &str, swatch_look: &SwatchLook) -> egui::Response { + let look = ExportLook::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click()); + let response = ui.interact(rect, id, egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name)); + // Light lettering on the dark swatches in every theme let painter = ui.painter(); - let border = if response.hovered() { tokens.accent } else { tokens.button_border }; - painter.rect(rect, tokens.radius, look.fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); - let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE_POINTS); - painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP_POINTS), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); - let bar_width = SWATCH_BAR_WIDTH_POINTS / look.bars.len().max(1) as f32; - let left = rect.center().x - SWATCH_BAR_WIDTH_POINTS / 2.0; - for (k, color) in look.bars.iter().enumerate() { - let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM_POINTS); - painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT_POINTS)), 0.0, *color); + painter.rect_filled(rect, 0.0, swatch_look.fill.unwrap_or(look.raised)); + if response.hovered() { + painter.rect_stroke(rect, 0.0, egui::Stroke::new(1.0, look.text_dim), egui::StrokeKind::Inside); } - if look.inverted { + let lettering = if look.dark { look.text } else { look.window }; + painter.text(pos2(rect.center().x, rect.top() + SWATCH_LABEL_Y), egui::Align2::CENTER_CENTER, label, drawn::font(false), lettering); + if let Some(bar) = swatch_look.bar { + let bottom = rect.bottom() - SWATCH_BAR_BOTTOM; + painter.rect_filled( + Rect::from_min_max(pos2(rect.left() + SWATCH_BAR_INSET, bottom), pos2(rect.right() - SWATCH_BAR_INSET, bottom + SWATCH_BAR_HEIGHT)), + 0.0, + bar, + ); + } + if swatch_look.inverted { let corner = rect.right_top(); let mark = vec![corner, corner - vec2(INVERTED_MARK_POINTS, 0.0), corner + vec2(0.0, INVERTED_MARK_POINTS)]; - painter.add(egui::Shape::convex_polygon(mark, tokens.text_strong, egui::Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(mark, lettering, egui::Stroke::NONE)); } + drawn::paint_focus(ui, &response); response } @@ -1585,79 +1731,92 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ } /// The maps the selected template's outputs read, with their colours, for the panes' markers -fn marked_sources(app: &TextureCraftApp, tokens: &Tokens) -> Vec<(SourceRef, Color32)> { +fn marked_sources(app: &TextureCraftApp) -> Vec<(SourceRef, Color32)> { let Some(preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { return Vec::new() }; let sources = preset.maps.iter().flat_map(|map| map.channels.iter().map(|(_, source)| source)); - sources.filter_map(|source| source_color(source, tokens).map(|color| (source.clone(), color))).collect() + sources.filter_map(|source| source_color(source).map(|color| (source.clone(), color))).collect() } -/// The Input maps pane: the input maps in their groups -fn input_maps(ui: &mut Ui, marked: &[(SourceRef, Color32)]) { - ui.label(caption(tr("Input maps"))); - egui::ScrollArea::vertical().id_salt("exp_inputs").auto_shrink([false; 2]).show(ui, |ui| { +/// A pane's title at `left`, on the column titles' line +fn pane_title(ui: &mut Ui, left: f32, y: f32, title: &str) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, left + GROUP_INDENT, y, title, look.text, true); +} + +/// A pane's entries scrolling in `area`, the scroll bar in its strip at the right +fn pane_list(ui: &mut Ui, area: Rect, id: &str, add: impl FnOnce(&mut Ui, f32)) { + ui.scope_builder(egui::UiBuilder::new().max_rect(area), |ui| { + egui::ScrollArea::vertical().id_salt(id).auto_shrink([false; 2]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + add(ui, area.width() - GUTTER); + }); + }); +} + +/// The Input maps pane in `pane`: the input maps in their groups +fn input_maps(ui: &mut Ui, pane: Rect, top: f32, marked: &[(SourceRef, Color32)]) { + let look = ExportLook::get(ui.ctx()); + pane_title(ui, pane.left(), top + HEADER_Y, tr("Input maps")); + let list = Rect::from_min_max(pos2(pane.left(), top + LIST_TOP), pane.max); + pane_list(ui, list, "exp_inputs", |ui, width| { for (group, entries) in INPUT_MAPS.iter() { - ui.label(RichText::new(tr(group)).italics()); - map_entries(ui, entries, marked, false); + let (rect, _) = ui.allocate_exact_size(vec2(width, GROUP_HEIGHT), egui::Sense::hover()); + drawn::label_at(ui, rect.left() + GROUP_INDENT, rect.center().y, tr(group), look.text_dim, false); + map_entries(ui, width, entries, marked); } }); } -/// The side pane: Mesh maps above Converted maps (in the highlight colour, as in the reference) -fn mesh_and_converted_maps(ui: &mut Ui, height: f32, marked: &[(SourceRef, Color32)]) { - ui.label(caption(tr("Mesh maps"))); - egui::ScrollArea::vertical() - .id_salt("exp_mesh_maps") - .auto_shrink([false; 2]) - .max_height(height * MESH_MAPS_SHARE) - .show(ui, |ui| map_entries(ui, &MESH_MAPS, marked, false)); - ui.separator(); - ui.label(caption(tr("Converted maps"))); - egui::ScrollArea::vertical().id_salt("exp_converted_maps").auto_shrink([false; 2]).show(ui, |ui| map_entries(ui, &CONVERTED_MAPS, marked, true)); +/// The side pane in `pane`: Mesh maps above Converted maps, a divider between them +fn mesh_and_converted_maps(ui: &mut Ui, pane: Rect, top: f32, marked: &[(SourceRef, Color32)]) { + pane_title(ui, pane.left(), top + HEADER_Y, tr("Mesh maps")); + let split = pane.center().y + SIDE_SPLIT_BELOW_MIDDLE; + let mesh = Rect::from_min_max(pos2(pane.left(), top + LIST_TOP), pos2(pane.right(), split - MESH_BOTTOM_GAP)); + pane_list(ui, mesh, "exp_mesh_maps", |ui, width| map_entries(ui, width, &MESH_MAPS, marked)); + drawn::divider(ui, Rect::from_min_max(pos2(pane.left() - 1.0, split), pos2(pane.right(), split + 1.0))); + pane_title(ui, pane.left(), split + CONVERTED_TITLE_Y, tr("Converted maps")); + let converted = Rect::from_min_max(pos2(pane.left(), split + CONVERTED_ROWS_TOP), pane.max); + pane_list(ui, converted, "exp_converted_maps", |ui, width| map_entries(ui, width, &CONVERTED_MAPS, marked)); } -fn map_entries(ui: &mut Ui, entries: &[MapEntry], marked: &[(SourceRef, Color32)], converted: bool) { - let tokens = Tokens::get(ui.ctx()); - let text_color = if converted { tokens.warning } else { tokens.text }; +fn map_entries(ui: &mut Ui, width: f32, entries: &[MapEntry], marked: &[(SourceRef, Color32)]) { for (name, source) in entries { let marker = source.as_ref().and_then(|source| marked.iter().find(|(used, _)| same_source(used, source)).map(|(_, color)| *color)); - map_entry(ui, tr(name), source.as_ref(), text_color, marker); + map_entry(ui, width, tr(name), source.as_ref(), marker); } } -/// A map list entry to drag onto an output channel, with the colour marker of an output map that -/// reads it; a map TextureCraft does not have yet is greyed and cannot be dragged -fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Color32, marker: Option) { - let tokens = Tokens::get(ui.ctx()); +/// A map list entry to drag onto a channel; a used map shows a square of its colour, a missing one is greyed +fn map_entry(ui: &mut Ui, width: f32, name: &str, source: Option<&SourceRef>, marker: Option) { + let look = ExportLook::get(ui.ctx()); let available = source.is_some(); let sense = if available { egui::Sense::drag() } else { egui::Sense::hover() }; - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT_POINTS), sense); + let (rect, response) = ui.allocate_exact_size(vec2(width, ENTRY_PITCH), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, available, name)); + let row = Rect::from_min_max(pos2(rect.left() + ENTRY_INSET, rect.top()), pos2(rect.right(), rect.top() + ENTRY_HEIGHT)); let painter = ui.painter(); - let row = rect.shrink2(vec2(0.0, ENTRY_GAP_POINTS / 2.0)); - painter.rect_filled(row, 0.0, if available && response.hovered() { tokens.row_hover } else { tokens.row }); + painter.rect_filled(row, 0.0, if available && response.hovered() { look.raised } else { look.control }); if let Some(color) = marker { - painter.rect_filled( - egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT_POINTS, 0.0), egui::Vec2::splat(MARKER_SIZE_POINTS)), - 1.0, - color, + let square = Rect::from_min_size(pos2(rect.left() + MARKER_LEFT, row.center().y - MARKER_SIZE / 2.0), vec2(MARKER_SIZE, MARKER_SIZE)); + let edge = Color32::from_rgb( + color.r().saturating_add(MARKER_EDGE_LIGHTEN), + color.g().saturating_add(MARKER_EDGE_LIGHTEN), + color.b().saturating_add(MARKER_EDGE_LIGHTEN), ); + painter.rect(square, MARKER_RADIUS, color, egui::Stroke::new(1.0, edge), egui::StrokeKind::Inside); } - let color = if available { text_color } else { tokens.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; - painter.text( - row.left_center() + vec2(ENTRY_TEXT_INDENT_POINTS, 0.0), - egui::Align2::LEFT_CENTER, - name, - egui::FontId::proportional(ENTRY_TEXT_SIZE_POINTS), - color, - ); + let color = if available { look.text } else { look.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; + let shown = drawn::fitted(ui, name, row.right() - rect.left() - ENTRY_NAME_LEFT, false, false); + drawn::text_at(ui, rect.left() + ENTRY_NAME_LEFT, row.center().y, &shown, color, false); let Some(source) = source else { response.on_hover_text(tr(NOT_AVAILABLE)); return; }; - let response = response.on_hover_cursor(egui::CursorIcon::Grab); + // How to use the entry is its tooltip, not a line under the cards + let response = response.on_hover_cursor(egui::CursorIcon::Grab).on_hover_text(tr("Drop an input map onto a channel to assign it to that output.")); response.dnd_set_drag_payload(source.clone()); if response.dragged() && let Some(at) = response.interact_pointer_pos() diff --git a/crates/ui-egui/src/export_templates/output_card.rs b/crates/ui-egui/src/export_templates/output_card.rs new file mode 100644 index 00000000..a7f1eddc --- /dev/null +++ b/crates/ui-egui/src/export_templates/output_card.rs @@ -0,0 +1,6 @@ +/// An output map card's index, the card count (for the grip's moves) and the width its lists' values line up on +pub(super) struct OutputCard { + pub(super) index: usize, + pub(super) count: usize, + pub(super) value_width: f32, +} diff --git a/crates/ui-egui/src/export_templates/swatch_look.rs b/crates/ui-egui/src/export_templates/swatch_look.rs index 99d81b19..f33e86d8 100644 --- a/crates/ui-egui/src/export_templates/swatch_look.rs +++ b/crates/ui-egui/src/export_templates/swatch_look.rs @@ -4,7 +4,7 @@ use egui::Color32; pub(super) struct SwatchLook { /// The source map's colour (None: empty or a constant). pub(super) fill: Option, - /// One bar per channel of the source the swatch reads. - pub(super) bars: Vec, + /// The underline in the colour of the channel the swatch's letters name (None: a constant) + pub(super) bar: Option, pub(super) inverted: bool, } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 86635088..04bb8243 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1758,13 +1758,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let right = window.right() - RIGHT_MARGIN; let row_y = window.top() + TAB_ROW_CONTROLS_Y; match app.ui.export.tab { - 1 => { - let strip = egui::Rect::from_min_max(egui::pos2(window.center().x, window.top()), egui::pos2(right, body.top())); - ui.scope_builder( - egui::UiBuilder::new().max_rect(strip).layout(egui::Layout::right_to_left(egui::Align::Center)), - crate::export_templates::naming_pattern, - ); - } + 1 => crate::export_templates::naming_pattern(ui, window.right(), row_y), 2 => { let width = drawn::text_width(ui, tr("Open output directory"), false) + OPEN_DIRECTORY_PADDING; let rect = drawn::control_rect(window.right() - OPEN_DIRECTORY_FROM_RIGHT - width, window.right() - OPEN_DIRECTORY_FROM_RIGHT, row_y); @@ -1800,7 +1794,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut row = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); row.set_height(body.height()); match app.ui.export.tab { - 1 => crate::export_templates::tab(app, &mut row, &presets), + 1 => crate::export_templates::tab(app, ui, body, &presets), 2 => list_tab(app, &mut row), _ => settings_tab(app, ui, window, body, &presets), } diff --git a/crates/ui-egui/src/export_window/drawn.rs b/crates/ui-egui/src/export_window/drawn.rs index fe55c374..e6fd3a4e 100644 --- a/crates/ui-egui/src/export_window/drawn.rs +++ b/crates/ui-egui/src/export_window/drawn.rs @@ -1,7 +1,7 @@ //! The Export textures window's own controls, drawn at the places its layout gives them: tabs, //! checks, dropdowns, buttons and icon buttons in the window's colours ([`ExportLook`]) -use egui::{Align2, Color32, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use super::export_look::{CONTROL_HEIGHT, CONTROL_RADIUS, ExportLook, TEXT_SIZE}; @@ -34,6 +34,10 @@ const TAB_GAP: f32 = 3.0; /// How far a tab reaches under the divider, where the body's colour covers its lower corners const TAB_OVERLAP: f32 = 4.0; +/// A quiet dropdown's hover face: its padding round the value and chevron, and half its height +const TEXT_DROPDOWN_PADDING: f32 = 3.0; +const TEXT_DROPDOWN_HALF_HEIGHT: f32 = 9.0; + /// Hit area of an icon button around its glyph const ICON_HIT_SIZE: f32 = 20.0; @@ -303,3 +307,24 @@ pub(crate) fn icon_button(ui: &mut Ui, centre: Pos2, icon: &str, size: f32, name paint_focus(ui, &response); response } + +/// A card's quiet dropdown: its value from `value_left` and a chevron at `chevron_x`, no box +pub(crate) fn text_dropdown(ui: &mut Ui, id: Id, value_left: f32, chevron_x: f32, y: f32, value: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let enabled = ui.is_enabled(); + let rect = Rect::from_min_max( + pos2(value_left - TEXT_DROPDOWN_PADDING, y - TEXT_DROPDOWN_HALF_HEIGHT), + pos2(chevron_x + CHEVRON_SIZE / 2.0 + TEXT_DROPDOWN_PADDING, y + TEXT_DROPDOWN_HALF_HEIGHT), + ); + let response = ui.interact(rect, id, if enabled { Sense::click() } else { Sense::hover() }); + let name = format!("{value} {}", ic::CARET_DOWN); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &name)); + if response.hovered() && enabled { + ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), look.raised); + } + let color = if looks_disabled(ui, enabled) { look.text_dim } else { look.text }; + text_at(ui, value_left, y, value, color, false); + glyph(ui, pos2(chevron_x, y), ic::CARET_DOWN, CHEVRON_SIZE, color); + paint_focus(ui, &response); + response +} diff --git a/crates/ui-egui/src/export_window/export_look.rs b/crates/ui-egui/src/export_window/export_look.rs index 866dad2f..ef7e04c4 100644 --- a/crates/ui-egui/src/export_window/export_look.rs +++ b/crates/ui-egui/src/export_window/export_look.rs @@ -23,6 +23,9 @@ const SCROLL_BAR_MARGIN: f32 = 4.0; /// How far the dividers sit below the frame colour, so they read on it const DIVIDER_DARKENING: f32 = 0.26; +/// How far the Presets list's names sit from the text colour towards the dim one +const LIST_TEXT_DIMMING: f32 = 0.37; + /// The Export textures window's colours from the theme: controls a step darker than the window, raised faces a step lighter #[derive(Clone, Copy)] pub(crate) struct ExportLook { @@ -36,7 +39,9 @@ pub(crate) struct ExportLook { pub(crate) outline: Color32, pub(crate) text: Color32, pub(crate) text_dim: Color32, + pub(crate) list_text: Color32, pub(crate) accent: Color32, + pub(crate) dark: bool, } impl ExportLook { @@ -52,7 +57,9 @@ impl ExportLook { outline: tokens.button_border, text: tokens.text, text_dim: tokens.text_dim, + list_text: lerp_color(tokens.text, tokens.text_dim, LIST_TEXT_DIMMING), accent: tokens.accent, + dark: tokens.dark, } } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index d11fe0d8..ff614407 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -95,15 +95,23 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { fn the_tab_shows_the_preset_tools_and_map_editor() { let library = TemplateLibrary::new("layout"); let mut h = harness(&library); - for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] { + for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:"] { assert!(h.query_by_label(text).is_some(), "{text}"); } + let hint = "Drop an input map onto a channel to assign it to that output."; + assert!(h.query_by_label(hint).is_none(), "the drag hint is no line under the cards"); + let metallic = h.get_by_role_and_label(egui::Role::ListItem, "Metallic").rect().center(); + h.hover_at(metallic); + h.run_steps(30); + assert!(h.query_by_label(hint).is_some(), "a map entry's tooltip says how to use it"); + h.hover_at(egui::pos2(1.0, 1.0)); + h.run_steps(4); assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); let maps = h.state().session.export_preset("Mine").unwrap().maps.len(); let ts = h.state().session.ts(); let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); let exported = plan.as_array().unwrap().len(); - assert!(h.query_by_label(&format!("{exported} output maps will be exported.")).is_some()); + assert!(h.query_by_label(&format!("{exported} output maps will be exported")).is_some()); for create in ["Gray", "RGB", "R+G+B", "RGB+A", "R+G+B+A"] { assert!(h.query_by_label(create).is_some(), "{create}"); } @@ -262,8 +270,8 @@ fn the_footer_counts_only_the_maps_the_texture_set_exports() { assert_eq!(plan.as_array().unwrap().len(), 1, "the sample set has no sheen: {plan}"); hover_name_field(&mut h, 1); assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen row says so"); - assert!(h.query_by_label("1 output maps will be exported.").is_some()); - assert!(h.query_by_label("2 output maps will be exported.").is_none()); + assert!(h.query_by_label("1 output maps will be exported").is_some()); + assert!(h.query_by_label("2 output maps will be exported").is_none()); } #[test] From e2db799bece9cbbc676196422b1419ed36ad1dbd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:21:28 +0000 Subject: [PATCH 027/190] List of exports: the file tree on the frame colour beside the console MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tree sits on the frame colour, its scroll bar in a strip at its right: each set a bold name after its chevron, its files indented and the size, file type and bit depth columns placed after the longest file name, each file's path as tooltip. The fold strip (») has the window's colour with a divider before the console; the console's "Console" header sits on the window colour, its lines on the frame colour. Open output directory sits at the tab row's right, 9 px above the divider. The console's least and starting width is the reference's at TextureCraft's window width. --- crates/ui-egui/src/export_window.rs | 273 +++++++++++------- crates/ui-egui/src/export_window/tree_file.rs | 8 + crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/tests/it/export_progress.rs | 4 +- 4 files changed, 181 insertions(+), 106 deletions(-) create mode 100644 crates/ui-egui/src/export_window/tree_file.rs diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 04bb8243..10c08fce 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -12,7 +12,7 @@ use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; -use crate::theme::{Tokens, caption, semibold}; +use crate::theme::{Tokens, semibold}; use crate::unavailable::NOT_AVAILABLE; pub(crate) mod drawn; @@ -20,10 +20,12 @@ pub(crate) mod export_look; mod inherited_settings; mod map_row; mod page_place; +mod tree_file; pub(crate) use export_look::ExportLook; use inherited_settings::InheritedSettings; use map_row::MapRow; use page_place::PagePlace; +use tree_file::TreeFile; /// The reference window's size; a smaller screen gets a smaller window const REFERENCE_WINDOW_SIZE_POINTS: egui::Vec2 = egui::vec2(1100.0, 740.0); @@ -160,6 +162,39 @@ const MAP_FORMAT_WIDTH: f32 = 61.2; /// Width of a map's own size list const MAP_SIZE_WIDTH: f32 = 100.0; +/// The console's least width: the reference's 300 at TextureCraft's narrower window +pub(crate) const CONSOLE_WIDTH: f32 = 284.0; +/// The file tree's least width +const MIN_TREE_WIDTH: f32 = 300.0; +/// Width of the strip that folds the console +const STRIP_WIDTH: f32 = 17.9; +/// Gap between the file tree and the strip +const STRIP_GAP: f32 = 1.9; +/// Size of the strip's glyph +const STRIP_GLYPH_SIZE: f32 = 13.0; +/// The console text's indent +const CONSOLE_TEXT_INDENT: f32 = 18.0; +/// Middle of the console's header +const CONSOLE_HEADER_Y: f32 = 66.0; +/// Where the console's lines start +const CONSOLE_BODY_TOP: f32 = 89.0; +/// Air above and below the console's lines +const CONSOLE_PADDING: f32 = 6.0; +/// Air above the file tree's first row +const TREE_TOP_PADDING: f32 = 3.0; +/// Height of a file tree row +const TREE_ROW_HEIGHT: f32 = 21.0; +/// Centre of a set's chevron +const TREE_CHEVRON_X: f32 = 13.2; +/// Where a set's name starts +const TREE_NAME_INDENT: f32 = 26.3; +/// Where its files start +const TREE_FILE_INDENT: f32 = 45.1; +/// Gap after the name and size columns +const TREE_COLUMN_GAP: f32 = 28.0; +/// Gap after the file type column +const TREE_BITS_GAP: f32 = 14.0; + /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -1254,49 +1289,36 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, } } -/// The LIST OF EXPORTS console's and file tree's least width, as in the reference -const CONSOLE_WIDTH: f32 = 300.0; -const MIN_TREE_WIDTH: f32 = 300.0; -/// Width of the strip between the file tree and the console -const SPLITTER_WIDTH: f32 = 14.0; -/// Padding of the CONSOLE header band, about 45 points high as in the reference -const CONSOLE_HEADER_MARGIN_X: i8 = 12; -const CONSOLE_HEADER_MARGIN_Y: i8 = 14; -/// The file tree: indent of the file rows under their texture set, and the row height -const TREE_INDENT: f32 = 35.0; -const TREE_ROW_HEIGHT: f32 = 17.0; -/// Half the width of the tree's chevron -const CHEVRON_HALF_WIDTH: f32 = 4.0; - /// Green of the console's success lines fn success(tk: &Tokens) -> egui::Color32 { if tk.dark { egui::Color32::from_rgb(110, 200, 120) } else { egui::Color32::from_rgb(30, 130, 50) } } -/// The LIST OF EXPORTS tab: a tree of the files each ticked texture set exports (file, size, -/// file type, bit depth; the full path as tooltip), and the console -fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The LIST OF EXPORTS tab in `body`: the file tree with each file's path as tooltip, the fold strip and the console +fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { + let look = ExportLook::get(ui.ctx()); let tk = Tokens::get(ui.ctx()); let hidden = app.ui.export.console_hidden; - // Tree and console keep at least their reference width - let spacing = ui.spacing().item_spacing.x; - let room = ui.available_width() - SPLITTER_WIDTH - 2.0 * spacing; + // The console keeps at least its least width, the tree at least its own + let room = body.width() - STRIP_WIDTH - STRIP_GAP - 1.0; let console_width = app.ui.export.console_width.min(room - MIN_TREE_WIDTH).max(CONSOLE_WIDTH); - let tree_width = if hidden { room } else { room - console_width }; - ui.vertical(|ui| { - ui.set_width(tree_width); + let console_left = if hidden { body.right() + 1.0 } else { body.right() - console_width }; + let strip = egui::Rect::from_min_max(egui::pos2(console_left - 1.0 - STRIP_WIDTH, body.top() + 1.0), egui::pos2(console_left - 1.0, body.bottom())); + let tree = egui::Rect::from_min_max(egui::pos2(body.left(), body.top() + 1.0), egui::pos2(strip.left() - STRIP_GAP, body.bottom())); + ui.painter().rect_filled(tree, 0.0, look.chrome); + ui.scope_builder(egui::UiBuilder::new().max_rect(tree), |ui| { egui::ScrollArea::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); // The strip at the console's left edge: a click hides or shows the console, a drag resizes it - let (strip, response) = ui.allocate_exact_size(vec2(SPLITTER_WIDTH, ui.available_height()), egui::Sense::click_and_drag()); + drawn::divider(ui, egui::Rect::from_min_max(strip.right_top(), egui::pos2(strip.right() + 1.0, strip.bottom()))); + let response = ui.interact(strip, ui.scope_id().with("exp_console_strip"), egui::Sense::click_and_drag()); let tooltip = if hidden { tr("Show Console") } else { tr("Hide Console") }; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tooltip)); let glyph = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; - let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; - ui.painter().rect_filled(strip, 0.0, tk.chrome); - ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); + let glyph_color = if response.hovered() { look.text } else { look.text_dim }; + drawn::glyph(ui, strip.center(), glyph, STRIP_GLYPH_SIZE, glyph_color); drawn::paint_focus(ui, &response); let response = response.on_hover_text(tooltip); if !hidden && (response.hovered() || response.dragged()) { @@ -1307,31 +1329,35 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { } else if response.clicked() { app.ui.export.console_hidden = !hidden; } - if !hidden { - ui.vertical(|ui| { - ui.set_width(console_width); - egui::Frame::new().fill(tk.row).inner_margin(egui::Margin::symmetric(CONSOLE_HEADER_MARGIN_X, CONSOLE_HEADER_MARGIN_Y)).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(caption(&tr("Console").to_uppercase()).strong()); - }); - let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); - console.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show(ui, |ui| { - for line in &app.ui.export.console { - match line { - ConsoleLine::Step(t) => { - ui.label(t); - } - ConsoleLine::Done(t) => { - ui.label(RichText::new(t).color(success(&tk))); - } - ConsoleLine::Set(name) => { - ui.label(set_line(ui, name, &tk)); - } + if hidden { + return; + } + + // The console: its header on the window colour, its lines on the frame colour below + let top = body.top() - TAB_ROW_HEIGHT; + let console = egui::Rect::from_min_max(egui::pos2(console_left, body.top() + 1.0), body.max); + drawn::label_at(ui, console.left() + CONSOLE_TEXT_INDENT, top + CONSOLE_HEADER_Y, tr("Console"), look.text, true); + let lines = egui::Rect::from_min_max(egui::pos2(console.left(), top + CONSOLE_BODY_TOP), console.max); + ui.painter().rect_filled(lines, 0.0, look.chrome); + let inner = lines.shrink2(vec2(0.0, CONSOLE_PADDING)).with_min_x(lines.left() + CONSOLE_TEXT_INDENT); + ui.scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| { + let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); + console.show(ui, |ui| { + for line in &app.ui.export.console { + match line { + ConsoleLine::Step(t) => { + ui.label(t); + } + ConsoleLine::Done(t) => { + ui.label(RichText::new(t).color(success(&tk))); + } + ConsoleLine::Set(name) => { + ui.label(set_line(ui, name, &tk)); } } - }); + } }); - } + }); } /// "Texture set " with the name in bold @@ -1347,22 +1373,53 @@ fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { job } -/// One expandable node per ticked texture set, a row per file +/// One foldable node per ticked texture set, a row per file; the columns start after the longest file name fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { - if let Some(job) = &app.ui.export.job - && !job.preview.is_empty() - { - for (index, set) in job.preview.iter().enumerate() { - export_tree_set(ui, index, set, &job.directory, tk); + let (sets, directory): (Vec<(usize, ExportSetPlan)>, String) = match &app.ui.export.job { + Some(job) if !job.preview.is_empty() => (job.preview.iter().cloned().enumerate().collect(), job.directory.clone()), + _ => { + let planned = export_selection(app).into_iter().filter_map(|ts| { + let params = set_params(app, ts); + plan_set(app, ts, ¶ms).map(|set| (ts, set)) + }); + (planned.collect(), app.ui.export.dir.clone()) } - return; - } + }; + let rows: Vec> = sets.iter().map(|(_, set)| tree_files(set, &directory)).collect(); + let longest = |text: fn(&TreeFile) -> &str| rows.iter().flatten().map(|file| drawn::text_width(ui, text(file), false)).fold(0.0, f32::max); + let columns = { + let size = TREE_FILE_INDENT + longest(|f| &f.name) + TREE_COLUMN_GAP; + let format = size + longest(|f| &f.size) + TREE_COLUMN_GAP; + [size, format, format + longest(|f| &f.format) + TREE_BITS_GAP] + }; - for ts in export_selection(app) { - let params = set_params(app, ts); - if let Some(set) = plan_set(app, ts, ¶ms) { - export_tree_set(ui, ts, &set, &app.ui.export.dir, tk); + // Each set takes its header row, its files when open and a blank row + let open: Vec = sets.iter().map(|(index, _)| ui.data(|d| d.get_temp::(tree_id(ui, *index))).unwrap_or(true)).collect(); + let row_count: usize = sets + .iter() + .zip(&rows) + .zip(&open) + .map(|(((_, set), files), open)| 1 + 1 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) + .sum(); + let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT), egui::Sense::hover()); + let mut y = area.top() + TREE_TOP_PADDING; + for (((index, set), files), open) in sets.iter().zip(&rows).zip(open) { + let header = egui::Rect::from_min_max(egui::pos2(area.left(), y), egui::pos2(area.right(), y + TREE_ROW_HEIGHT)); + if tree_header(ui, header, &set.name, open, tree_id(ui, *index)) { + ui.data_mut(|d| d.insert_temp(tree_id(ui, *index), !open)); } + y += TREE_ROW_HEIGHT; + if open { + if let Err(error) = &set.files { + drawn::label_at(ui, area.left() + TREE_FILE_INDENT, y + TREE_ROW_HEIGHT / 2.0, error, tk.danger, false); + y += TREE_ROW_HEIGHT; + } + for file in files { + tree_file(ui, area.left(), y + TREE_ROW_HEIGHT / 2.0, columns, file); + y += TREE_ROW_HEIGHT; + } + } + y += TREE_ROW_HEIGHT; } } @@ -1374,47 +1431,59 @@ fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) Some(ExportSetPlan { index: Some(index), name, files }) } -fn export_tree_set(ui: &mut Ui, index: usize, set: &ExportSetPlan, directory: &str, tokens: &Tokens) { - ui.spacing_mut().indent = TREE_INDENT; - let header = egui::CollapsingHeader::new(&set.name).id_salt(("exp_tree", index)).default_open(true).icon(chevron); - header.show(ui, |ui| match &set.files { - Ok(files) => { - egui::Grid::new(("exp_tree_grid", index)).num_columns(4).min_row_height(TREE_ROW_HEIGHT).spacing(vec2(12.0, 4.0)).show(ui, |ui| { - for output in files.as_array().into_iter().flatten() { - let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); - let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); - let depth = output.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; - let dithering = output.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let size = output["size"].as_u64().unwrap_or_default() as u32; - let source_size = output["sourceSize"].as_u64().unwrap_or_default() as u32; - let path = std::path::Path::new(directory).join(file).display().to_string(); - ui.label(file).on_hover_text(&path); - ui.label(set_size_label(size, source_size)).on_hover_text(&path); - ui.label(format.map_or("", FileFormat::name)).on_hover_text(&path); - ui.label(depth_label(format, depth, dithering)).on_hover_text(&path); - ui.end_row(); - } - }); - } - Err(error) => { - ui.label(RichText::new(error).color(tokens.danger)); - } - }); +/// Where a texture set's node keeps whether it is open +fn tree_id(ui: &Ui, index: usize) -> egui::Id { + ui.scope_id().with(("exp_tree", index)) } -/// The tree's outline chevron: pointing down when open, right (left in right-to-left) when closed -fn chevron(ui: &mut Ui, openness: f32, response: &egui::Response) { - let color = Tokens::get(ui.ctx()).text; - let center = response.rect.center(); - let half = CHEVRON_HALF_WIDTH; - let points = if openness > 0.5 { - [center + vec2(-half, -half / 2.0), center + vec2(0.0, half / 2.0), center + vec2(half, -half / 2.0)] - } else if ui.style().right_to_left { - [center + vec2(half / 2.0, -half), center + vec2(-half / 2.0, 0.0), center + vec2(half / 2.0, half)] - } else { - [center + vec2(-half / 2.0, -half), center + vec2(half / 2.0, 0.0), center + vec2(-half / 2.0, half)] +/// The texts of each file `set` plans: name, size, file type, bit depth and its whole path +fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { + let Ok(files) = &set.files else { return Vec::new() }; + + let to_text = |output: &serde_json::Value| { + let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); + let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); + let depth = output.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; + let dithering = output.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); + let size = output["size"].as_u64().unwrap_or_default() as u32; + let source_size = output["sourceSize"].as_u64().unwrap_or_default() as u32; + TreeFile { + name: file.to_string(), + size: set_size_label(size, source_size), + format: format.map_or("", FileFormat::name).to_string(), + bits: depth_label(format, depth, dithering), + path: std::path::Path::new(directory).join(file).display().to_string(), + } }; - ui.painter().add(egui::Shape::line(points.to_vec(), egui::Stroke::new(1.5, color))); + files.as_array().into_iter().flatten().map(to_text).collect() +} + +/// A texture set's node row: the chevron and its name in bold; true when clicked +fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui::Id) -> bool { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, id, egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name)); + let y = rect.center().y; + let chevron = if open { + ic::CARET_DOWN + } else if ui.style().right_to_left { + ic::CARET_LEFT + } else { + ic::CARET_RIGHT + }; + drawn::glyph(ui, egui::pos2(rect.left() + TREE_CHEVRON_X, y), chevron, drawn::CHEVRON_SIZE, look.text); + drawn::text_at(ui, rect.left() + TREE_NAME_INDENT, y, name, look.text, true); + drawn::paint_focus(ui, &response); + response.clicked() +} + +/// A file's row at `y`: its name, then size, file type and bit depth in `columns`, each with the whole path as tooltip +fn tree_file(ui: &mut Ui, left: f32, y: f32, columns: [f32; 3], file: &TreeFile) { + let look = ExportLook::get(ui.ctx()); + let texts = [(TREE_FILE_INDENT, &file.name), (columns[0], &file.size), (columns[1], &file.format), (columns[2], &file.bits)]; + for (x, text) in texts { + drawn::label_at(ui, left + x, y, text, look.text, false).on_hover_text(&file.path); + } } /// Show the output folder in the system's file manager (created first when missing) @@ -1791,11 +1860,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); body_ui.shrink_clip_rect(body); let ui = &mut body_ui; - let mut row = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); - row.set_height(body.height()); match app.ui.export.tab { 1 => crate::export_templates::tab(app, ui, body, &presets), - 2 => list_tab(app, &mut row), + 2 => list_tab(app, ui, body), _ => settings_tab(app, ui, window, body, &presets), } }); diff --git a/crates/ui-egui/src/export_window/tree_file.rs b/crates/ui-egui/src/export_window/tree_file.rs new file mode 100644 index 00000000..8b3f64fb --- /dev/null +++ b/crates/ui-egui/src/export_window/tree_file.rs @@ -0,0 +1,8 @@ +/// A file row of LIST OF EXPORTS: the texts of its columns and its whole path +pub(super) struct TreeFile { + pub(super) name: String, + pub(super) size: String, + pub(super) format: String, + pub(super) bits: String, + pub(super) path: String, +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index fbcd6053..59900a4a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -475,7 +475,7 @@ impl Default for ExportUi { /// The LIST OF EXPORTS console's width when the window opens, as in the reference fn default_console_width() -> f32 { - 300.0 + crate::export_window::CONSOLE_WIDTH } fn default_export_dir() -> String { diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index b46b84a1..b027549b 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -128,7 +128,7 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some()); assert!(h.query_all_by_label("png").next().is_some() && h.query_all_by_label("16 bits").next().is_some()); assert!(h.query_by_label("Include all").is_none() && h.query_by_label("Reset all").is_none()); - assert!(h.query_by_label("CONSOLE").is_some()); + assert!(h.query_by_label("Console").is_some()); // A row's tooltip is the full path let preset = h.state().ui.export.preset.clone(); @@ -142,7 +142,7 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { // The strip at the console's edge hides it, then shows it again h.get_by_role_and_label(egui::Role::Button, "Hide Console").click(); h.run_steps(4); - assert!(h.state().ui.export.console_hidden && h.query_by_label("CONSOLE").is_none()); + assert!(h.state().ui.export.console_hidden && h.query_by_label("Console").is_none()); h.get_by_role_and_label(egui::Role::Button, "Show Console").click(); h.run_steps(4); assert!(!h.state().ui.export.console_hidden); From f165f47699bfb327006be3c510bfbcc90c0f4c82 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:39:59 +0000 Subject: [PATCH 028/190] Export: Unreal Engine Subsurface Profile (Packed) template, the packed Unreal maps plus a SubsurfaceMask map of the scatter weight for the material's Opacity input Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 45 ++++++++++++++++++++++++++++++ crates/formats/src/presets.rs | 10 +++++++ docs/features.md | 2 +- 4 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index ca377337..acfe2f53 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -137,6 +137,7 @@ Built-in presets (each one lists the public specification its packing follows in | OpenPBR (separate maps) | one map per OpenPBR Surface input the set has: `base_color`, `base_metalness`, `specular_roughness`, `specular_roughness_anisotropy`, `coat_weight`, `coat_roughness`, `fuzz_weight`, `fuzz_color`, `fuzz_roughness`, `transmission_weight`, `subsurface_weight`, `emission_color`, `geometry_opacity`, `geometry_normal` (OpenGL), `height` (16-bit) | | Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` | | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | +| Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 14bb5238..ab398c0f 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1740,3 +1740,48 @@ fn a_map_preview_holds_the_values_its_file_stores() { assert!(small.width < RES && small.pixels.len() == (small.width * small.height) as usize * 4, "a smaller preview samples the same map"); assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error"); } + +/// The 8-bit value of an image position as RGBA +fn pixel(file: &ExportedFile) -> [i32; 4] { + decode(file).to_rgba8().get_pixel(3, 3).0.map(i32::from) +} + +fn byte(value: f32) -> i32 { + (value * 255.0).round() as i32 +} + +fn assert_close(actual: [i32; 4], expected: [i32; 4], what: &str) { + assert!(actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= 1), "{what}: {actual:?} instead of {expected:?}"); +} + +/// Tilts every normal of `fx` and returns the green byte an OpenGL normal map stores for it +fn tilt_normals(fx: &mut Fx) -> i32 { + let tilt = Vec3::new(0.3, 0.4, 0.0); + let tilt = Vec3::new(tilt.x, tilt.y, (1.0 - tilt.length_squared()).sqrt()); + fx.set_all(Channel::Normal, |_, _| (tilt * 0.5 + Vec3::splat(0.5)).to_array()); + byte(tilt.y * 0.5 + 0.5) +} + +#[test] +fn the_unreal_subsurface_template_writes_the_scatter_mask_beside_the_packed_maps() { + let mut channels = default_channels(); + channels.extend([Channel::AmbientOcclusion, Channel::Opacity, Channel::ScatterWeight]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::AmbientOcclusion, |_, _| [0.6; 3]); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Unreal Engine Subsurface Profile (Packed)"); + + let mask = find(&files, "_SubsurfaceMask.png"); + assert_eq!(decode(mask).color(), image::ColorType::L8, "the mask is one 8-bit channel"); + assert_close(pixel(mask), [byte(0.7), byte(0.7), byte(0.7), 255], "scatter weight in the mask"); + let [r, g, b, _] = pixel(find(&files, "_OcclusionRoughnessMetallic.png")); + assert_close([r, g, b, 0], [byte(0.6), byte(0.4), byte(0.8), 0], "R occlusion, G roughness, B metallic"); + assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "opacity feeds the mask, not the base color's alpha"); + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 2f2879a4..5fcf0ef0 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -219,6 +219,16 @@ pub fn builtin_presets() -> Vec { map("clearcoatRoughness", 8, gray(ch(Channel::CoatRoughness, 0))), ], ), + // Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine (the Opacity input masks the scattering, so the base color has no alpha) + preset( + "Unreal Engine Subsurface Profile (Packed)", + vec![ + map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("OcclusionRoughnessMetallic", 8, orm()), + map("Normal", 8, normal(VirtualMap::NormalDirectX)), + map("SubsurfaceMask", 8, gray(ch(Channel::ScatterWeight, 0))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index 3da74d2d..3d0ff36a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From 0d1df0580e54797c0121f0e49a3e964459df2c57 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:40:34 +0000 Subject: [PATCH 029/190] Export: glTF Specular Glossiness (archived extension) template, a specular/glossiness set's diffuse with opacity and its specular with glossiness in alpha, as Khronos' archived extension lays them out Spec: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md Only the set's own Specular and Glossiness channels are written; converting a metallic/roughness set is left out, since no target documents that conversion. --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 21 +++++++++++++++++++++ crates/formats/src/presets.rs | 15 +++++++++++++++ docs/features.md | 2 +- 4 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index acfe2f53..1e7f3bdc 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -138,6 +138,7 @@ Built-in presets (each one lists the public specification its packing follows in | Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` | | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | | Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | +| glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index ab398c0f..05929b9e 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1785,3 +1785,24 @@ fn the_unreal_subsurface_template_writes_the_scatter_mask_beside_the_packed_maps let green = pixel(find(&files, "_Normal.png"))[1]; assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); } + +#[test] +fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_channels() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::Normal, Channel::Height, Channel::Opacity]); + let specular = [0.2, 0.5, 0.8]; + fx.set_all(Channel::Specular, |_, _| specular); + fx.set_all(Channel::Glossiness, |_, _| [0.3; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("glTF Specular Glossiness (archived extension)"); + + let specular_glossiness = find(&files, "_SpecularGlossiness.png"); + assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8); + let srgb = specular.map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(specular_glossiness), [srgb[0], srgb[1], srgb[2], byte(0.3)], "sRGB specular, linear glossiness in alpha"); + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(find(&files, "_Diffuse.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB diffuse, opacity in alpha"); + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 5fcf0ef0..e1aedf9f 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -229,6 +229,21 @@ pub fn builtin_presets() -> Vec { map("SubsurfaceMask", 8, gray(ch(Channel::ScatterWeight, 0))), ], ), + // Spec: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md (diffuse with alpha, specular RGB with glossiness in A) + preset( + "glTF Specular Glossiness (archived extension)", + vec![ + map("Diffuse", 8, base_with_alpha()), + map("SpecularGlossiness", 8, { + let mut specular_glossiness = rgb(|k| ch(Channel::Specular, k)); + specular_glossiness.push((Dest::A, ch(Channel::Glossiness, 0))); + specular_glossiness + }), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + map("Occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("Emissive", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index 3d0ff36a..fde5812e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From 498394a11df40ba1b603736d8babca99537e12f9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:40:53 +0000 Subject: [PATCH 030/190] Export: Redshift Standard Material (separate maps) template, one map per Standard Material input the texture set has, normals in OpenGL as Redshift expects Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Standard_Material.html and https://help.maxon.net/r3d/maya/en-us/Content/html/Bump+Map.html --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 24 ++++++++++++++++++++++++ crates/formats/src/presets.rs | 20 ++++++++++++++++++++ docs/features.md | 2 +- 4 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index 1e7f3bdc..4817d0e8 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -139,6 +139,7 @@ Built-in presets (each one lists the public specification its packing follows in | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | | Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | | glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | +| Redshift Standard Material (separate maps) | one map per Standard Material input the set has: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 05929b9e..2b6e604e 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1806,3 +1806,27 @@ fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_ch let green = pixel(find(&files, "_Normal.png"))[1]; assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); } + +#[test] +fn the_redshift_template_writes_one_map_per_input_the_set_has() { + let mut channels = default_channels(); + channels.extend([Channel::ScatterWeight, Channel::CoatWeight]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]); + fx.set_all(Channel::CoatWeight, |_, _| [0.2; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Redshift Standard Material (separate maps)"); + + let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect(); + for (input, expected) in [("Metalness", 0.8), ("ReflectionRoughness", 0.4), ("SubsurfaceWeight", 0.7), ("CoatWeight", 0.2)] { + let file = find(&files, &format!("_{input}.png")); + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is one 8-bit channel: {names:?}"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); + assert!(!names.iter().any(|name| name.contains("Sheen") || name.contains("CoatRoughness")), "inputs the set lacks write no maps: {names:?}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index e1aedf9f..5b870db3 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -244,6 +244,26 @@ pub fn builtin_presets() -> Vec { map("Emissive", 8, rgb(|k| ch(Channel::Emissive, k))), ], ), + // Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Standard_Material.html (the Standard Material inputs) + // Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Bump+Map.html (normal maps in OpenGL format) + preset("Redshift Standard Material (separate maps)", { + let gray8 = |name: &str, c: Channel| map(name, 8, gray(ch(c, 0))); + let rgb8 = |name: &str, c: Channel| map(name, 8, rgb(|k| ch(c, k))); + vec![ + rgb8("BaseColor", Channel::BaseColor), + gray8("Metalness", Channel::Metallic), + gray8("ReflectionRoughness", Channel::Roughness), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + rgb8("EmissionColor", Channel::Emissive), + gray8("Opacity", Channel::Opacity), + gray8("SubsurfaceWeight", Channel::ScatterWeight), + gray8("CoatWeight", Channel::CoatWeight), + gray8("CoatRoughness", Channel::CoatRoughness), + gray8("SheenWeight", Channel::SheenWeight), + rgb8("SheenColor", Channel::SheenColor), + gray8("SheenRoughness", Channel::SheenRoughness), + ] + }), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index fde5812e..facc1ea0 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From ba6dcf5240ba7dfc651c5ef9a401ee1e084aedf0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:41:09 +0000 Subject: [PATCH 031/190] Export: Roblox SurfaceAppearance (separate maps) template, colour with opacity in alpha, OpenGL normal, metalness and roughness, named with the suffixes Roblox's reimport assigns Based on #258 by Aalzard. Spec: https://create.roblox.com/docs/art/modeling/surface-appearance, https://create.roblox.com/docs/art/modeling/texture-specifications and https://create.roblox.com/docs/art/modeling/reimport Roblox's MaterialVariant gets no template of its own: its docs don't say whether it reads the colour map's alpha, the only difference the old one made. --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 31 +++++++++++++++++------------- crates/formats/src/presets.rs | 12 ++++++++++++ docs/features.md | 2 +- 4 files changed, 32 insertions(+), 14 deletions(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index 4817d0e8..8cd9e1cd 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -140,6 +140,7 @@ Built-in presets (each one lists the public specification its packing follows in | Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | | glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | | Redshift Standard Material (separate maps) | one map per Standard Material input the set has: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | +| Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 2b6e604e..30b8f6ec 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1741,19 +1741,6 @@ fn a_map_preview_holds_the_values_its_file_stores() { assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error"); } -/// The 8-bit value of an image position as RGBA -fn pixel(file: &ExportedFile) -> [i32; 4] { - decode(file).to_rgba8().get_pixel(3, 3).0.map(i32::from) -} - -fn byte(value: f32) -> i32 { - (value * 255.0).round() as i32 -} - -fn assert_close(actual: [i32; 4], expected: [i32; 4], what: &str) { - assert!(actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= 1), "{what}: {actual:?} instead of {expected:?}"); -} - /// Tilts every normal of `fx` and returns the green byte an OpenGL normal map stores for it fn tilt_normals(fx: &mut Fx) -> i32 { let tilt = Vec3::new(0.3, 0.4, 0.0); @@ -1830,3 +1817,21 @@ fn the_redshift_template_writes_one_map_per_input_the_set_has() { assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); assert!(!names.iter().any(|name| name.contains("Sheen") || name.contains("CoatRoughness")), "inputs the set lacks write no maps: {names:?}"); } + +#[test] +fn the_roblox_template_writes_opacity_in_the_colour_alpha_and_opengl_normals() { + let mut fx = packing_fixture(); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Roblox SurfaceAppearance (separate maps)"); + + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(find(&files, "_Color.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB colour, opacity in alpha"); + for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4)] { + let file = find(&files, &format!("_{input}.png")); + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is grayscale"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 5b870db3..e510a7c1 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -264,6 +264,18 @@ pub fn builtin_presets() -> Vec { gray8("SheenRoughness", Channel::SheenRoughness), ] }), + // Spec: https://create.roblox.com/docs/art/modeling/surface-appearance (ColorMap alpha is opacity) + // Spec: https://create.roblox.com/docs/art/modeling/texture-specifications (OpenGL normals only; grayscale metalness and roughness) + // Spec: https://create.roblox.com/docs/art/modeling/reimport (the file name suffix it assigns to each map) + preset( + "Roblox SurfaceAppearance (separate maps)", + vec![ + map("Color", 8, base_with_alpha()), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + map("Metalness", 8, gray(ch(Channel::Metallic, 0))), + map("Roughness", 8, gray(ch(Channel::Roughness, 0))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index facc1ea0..212894c6 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From 3b56a8e6b3f85500df9a2bfeb2b971df4332d237 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:41:24 +0000 Subject: [PATCH 032/190] Export: Sketchfab Metalness (separate maps) template, one map per Sketchfab metalness channel with DirectX normals, Sketchfab's default Based on #258 by Aalzard. Spec: https://help.sketchfab.com/en/articles/16152630-pbr-maps, https://help.sketchfab.com/en/articles/16152634-materials-pbr and https://help.sketchfab.com/en/articles/16152621-normal-map-bump-map The base color has no alpha: Sketchfab's docs don't say its opacity reads it. --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 17 +++++++++++++++++ crates/formats/src/presets.rs | 14 ++++++++++++++ docs/features.md | 2 +- 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index 8cd9e1cd..89482c00 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -141,6 +141,7 @@ Built-in presets (each one lists the public specification its packing follows in | glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | | Redshift Standard Material (separate maps) | one map per Standard Material input the set has: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | | Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` | +| Sketchfab Metalness (separate maps) | `BaseColor` (no alpha), `Metalness`, `Roughness`, `Normal` (DirectX), `AmbientOcclusion`, `Emission` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 30b8f6ec..e9eb5a63 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1835,3 +1835,20 @@ fn the_roblox_template_writes_opacity_in_the_colour_alpha_and_opengl_normals() { let green = pixel(find(&files, "_Normal.png"))[1]; assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); } + +#[test] +fn the_sketchfab_template_writes_directx_normals_and_one_map_per_channel() { + let mut fx = packing_fixture(); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Sketchfab Metalness (separate maps)"); + + assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "no alpha on the base color"); + for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4), ("AmbientOcclusion", 0.6)] { + let file = find(&files, &format!("_{input}.png")); + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is linear grayscale"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index e510a7c1..e41c4094 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -276,6 +276,20 @@ pub fn builtin_presets() -> Vec { map("Roughness", 8, gray(ch(Channel::Roughness, 0))), ], ), + // Spec: https://help.sketchfab.com/en/articles/16152630-pbr-maps (sRGB base color, linear grayscale metalness; no alpha, the docs don't say opacity reads it) + // Spec: https://help.sketchfab.com/en/articles/16152634-materials-pbr (roughness, AO and emission channels) + // Spec: https://help.sketchfab.com/en/articles/16152621-normal-map-bump-map (DirectX normals by default) + preset( + "Sketchfab Metalness (separate maps)", + vec![ + map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("Metalness", 8, gray(ch(Channel::Metallic, 0))), + map("Roughness", 8, gray(ch(Channel::Roughness, 0))), + map("Normal", 8, normal(VirtualMap::NormalDirectX)), + map("AmbientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("Emission", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index 212894c6..edc6c265 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, Sketchfab (metalness), separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From cf54cc20de92861e246975e760d1595fd7c07dd7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 11:16:41 +0100 Subject: [PATCH 033/190] Resources Updater: review fixes Remember file verdicts per size and time so an unchanged file is read once; recheck the open window at most twice a second; outdated rows first. Record image files from PBR folder, MaterialX and mesh map imports too, and resample an imported mesh map from its changed file while it still holds that file's pixels. Relink only image resources; decode updated bytes the way undo and reopening do. Notices carry their project and are reset when another project opens, which is checked once. Escape closes the window only while it has the keyboard. Keep the reference's Shelf line and show the file on its own line. A dedicated automation refusal message, translated status labels, tempfile in tests. --- Cargo.lock | 1 + crates/automation/src/workspace.rs | 13 +- crates/core/src/lib.rs | 2 + crates/core/src/mesh_map_slot.rs | 15 ++ crates/core/src/resource_source.rs | 4 + crates/engine/src/lib.rs | 5 +- crates/engine/src/materialx_cmds.rs | 21 +- crates/engine/src/meshmap_cmds.rs | 17 +- crates/engine/src/meshmap_import_cmds.rs | 5 +- crates/engine/src/pbr_cmds.rs | 39 ++- crates/engine/src/pbr_cmds/native/found.rs | 10 + crates/engine/src/reloaded_file.rs | 9 +- crates/engine/src/resource_check.rs | 23 ++ crates/engine/src/resource_cmds.rs | 4 +- crates/engine/src/resource_state.rs | 1 + crates/engine/src/resource_update_cmds.rs | 203 ++++++++++----- crates/engine/src/session.rs | 5 + crates/engine/tests/it/resource_updater.rs | 232 +++++++++++++----- crates/ui-egui/Cargo.toml | 2 + crates/ui-egui/src/i18n.rs | 3 + crates/ui-egui/src/lib.rs | 21 +- crates/ui-egui/src/menus.rs | 3 - crates/ui-egui/src/resources_updater.rs | 103 +++++--- crates/ui-egui/src/state/resources_updater.rs | 4 + crates/ui-egui/src/toast_action.rs | 33 ++- crates/ui-egui/tests/it/resources_updater.rs | 57 ++++- docs/control-protocol.md | 17 +- docs/features.md | 16 +- 28 files changed, 637 insertions(+), 231 deletions(-) create mode 100644 crates/core/src/mesh_map_slot.rs create mode 100644 crates/engine/src/resource_check.rs diff --git a/Cargo.lock b/Cargo.lock index 59d9a90a..45aedc2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5313,6 +5313,7 @@ dependencies = [ "skera", "skrifa 0.48.0", "sys-locale", + "tempfile", "texturecraft-engine", "texturecraft-render", "wasm-bindgen", diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 2e590e15..64897380 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -132,15 +132,19 @@ const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"]; /// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { + // The Resources Updater reads the files a project names, which may lie outside the read root + if matches!(id, "resource.status" | "resource.update" | "resource.relink") { + return Err(bad(format!( + "`{id}` reads the image files the project names on this machine, so it is disabled for automation; re-import changed files with resource_import" + ))); + } + let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path)); // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, - - // The Resources Updater reads the files a project names, which may lie outside the read root - "resource.status" | "resource.update" | "resource.relink" => false, _ => !id.starts_with("file.") && !has_path, }; if allowed { @@ -249,7 +253,8 @@ mod tests { assert!(authorize_command("file.reimportMesh", &json!({})).is_ok()); assert!(authorize_command("file.close", &json!({})).is_ok()); for id in ["resource.status", "resource.update", "resource.relink"] { - assert!(authorize_command(id, &json!({})).is_err(), "{id} reads the host paths a project names"); + let error = authorize_command(id, &json!({})).unwrap_err().to_string(); + assert!(error.contains("reads the image files"), "{id}: {error}"); } assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 2c5db23b..e6f7a5ce 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -39,6 +39,7 @@ pub mod image_input; pub mod layer; pub mod lighting_output; pub mod mask_outline; +pub mod mesh_map_slot; pub mod mirror; pub mod mirror_corner; pub mod mirror_mode; @@ -120,6 +121,7 @@ pub use layer::{ }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; +pub use mesh_map_slot::MeshMapSlot; pub use mirror::Mirror; pub use mirror_corner::MirrorCorner; pub use mirror_mode::MirrorMode; diff --git a/crates/core/src/mesh_map_slot.rs b/crates/core/src/mesh_map_slot.rs new file mode 100644 index 00000000..7cade977 --- /dev/null +++ b/crates/core/src/mesh_map_slot.rs @@ -0,0 +1,15 @@ +//! The mesh map an imported image file was resampled into + +use serde::{Deserialize, Serialize}; + +use crate::BakedMap; + +/// A mesh map of a texture set, and the UV tile one image of it covers. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct MeshMapSlot { + /// Index of the texture set. + pub texture_set: usize, + pub map: BakedMap, + /// The UV tile the image covers (1001 on a set without UV tiles). + pub tile: u32, +} diff --git a/crates/core/src/resource_source.rs b/crates/core/src/resource_source.rs index 793122cf..6a8627ed 100644 --- a/crates/core/src/resource_source.rs +++ b/crates/core/src/resource_source.rs @@ -14,4 +14,8 @@ pub struct ResourceSource { /// (0 when unknown). An unchanged time and size skip reading the file again. #[serde(default)] pub modified_ms: u64, + /// The mesh map the file was imported as (`textureSet.meshMap.import`): an update resamples it + /// again while the map still holds what this file gave it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mesh_map: Option, } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0d2f8d3c..0a87537a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -71,6 +71,9 @@ pub mod quick_mask; // Reloading resource files reads paths on native targets only #[cfg(not(target_arch = "wasm32"))] mod reloaded_file; +// Remembered file comparisons exist on native targets only +#[cfg(not(target_arch = "wasm32"))] +mod resource_check; pub mod resource_cmds; pub mod resource_state; pub mod resource_status; @@ -103,9 +106,9 @@ pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use log::{LogEntry, LogLevel, SessionLog}; pub use path_tool::PathState; +pub use project_cmds::sample_session; pub use resource_state::ResourceState; pub use resource_status::ResourceStatus; -pub use project_cmds::sample_session; pub use session::{ CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label, stroke_template, diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 68792d5c..5529b778 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -31,8 +31,9 @@ pub fn specs() -> Vec { )] } -/// 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>; +/// Loads an image file named in the document (relative to it): its bytes and the file they were +/// read from (for the Resources Updater; None when not read from disk), or why not. +pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<(Vec, Option), String>; impl Session { /// Add `material` as a fill layer on the active texture set, loading its images with `load`. @@ -45,6 +46,7 @@ impl Session { // 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 sources = Vec::new(); let mut names: BTreeMap = BTreeMap::new(); let mut channels: Vec = Vec::new(); for (channel, value) in &material.channels { @@ -58,9 +60,10 @@ impl Session { 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 { + let loaded = load(file).and_then(|(bytes, source)| { + texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image, source)).map_err(|e| e.to_string()) + }); + let (bytes, image, source) = match loaded { Ok(v) => v, Err(e) => { warnings.push(format!("{} was skipped: {file}: {e}", channel.id())); @@ -74,6 +77,7 @@ impl Session { unique = format!("{n}_{base}"); n += 1; } + sources.extend(source.map(|source| (unique.clone(), source))); added.push((unique.clone(), Arc::new(bytes))); decoded.push((unique.clone(), crate::resource_cmds::decoded(image))); names.insert(file.clone(), unique.clone()); @@ -96,6 +100,7 @@ impl Session { for (n, bytes) in &added { s.doc.resources.insert(n.clone(), bytes.clone()); } + s.doc.project.resource_sources.extend(sources); let id = s.doc.project.alloc_id(); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels)) })?; @@ -123,7 +128,7 @@ fn import(s: &mut Session, p: &Value) -> Result { 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> { + let load = |file: &str| -> std::result::Result<(Vec, Option), String> { // `` stands for a tile number; the first tile is read. let file = file.replace("", "1001"); let rel = Path::new(&file); @@ -144,7 +149,9 @@ fn import(s: &mut Session, p: &Value) -> Result { 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()) + let source = full.to_str().map(crate::resource_update_cmds::file_source); + let bytes = std::fs::read(&full).map_err(|e| e.to_string())?; + Ok((bytes, source)) }; s.import_material(material, strp(p, "name"), &load) } diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index f08d34c4..4b2a209b 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -54,6 +54,17 @@ pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let (width, data) = resampled(s, cmd, ts, map, images)?; + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = width; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(width) +} + +/// The pixels [`use_images`] would give mesh map `map` of set `ts`, and their width +pub(crate) fn resampled(s: &Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result<(u32, Vec)> { let texture_set = s.doc.project.texture_set(ts)?; let grid = texture_set.tile_grid(); if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { @@ -74,11 +85,7 @@ pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, i }), }; - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = width; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(width) + Ok((width, data)) } /// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 20913de2..2c9f9b56 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -4,12 +4,13 @@ use std::collections::BTreeMap; use std::path::Path; use serde_json::{Value, json}; -use texturecraft_core::BakedMap; +use texturecraft_core::{BakedMap, MeshMapSlot, ResourceSource}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images}; use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; use crate::resource_cmds::read_image_file; +use crate::resource_update_cmds::file_source; use crate::{Result, Session, cmd}; const CMD: &str = "textureSet.meshMap.import"; @@ -84,11 +85,13 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result() as u64; let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + s.doc.project.resource_sources.insert(name.clone(), source); let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?; reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?; images.insert(*tile, image.clone()); diff --git a/crates/engine/src/pbr_cmds.rs b/crates/engine/src/pbr_cmds.rs index d5b3d4aa..09a0a9e9 100644 --- a/crates/engine/src/pbr_cmds.rs +++ b/crates/engine/src/pbr_cmds.rs @@ -80,6 +80,9 @@ pub fn specs() -> Vec { pub type FileList = Vec<(String, u64)>; /// Reads a file of the list by name. pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; +/// The file on disk a file of the list is read from (None: an archive entry or bytes in memory), +/// asked right before reading it. +type Locator<'a> = &'a dyn Fn(&str) -> Option; mod pbr_options; mod take; @@ -137,10 +140,16 @@ impl Session { /// Import the maps found among `files` as one fill layer on the active texture set; `load` /// reads a file by name. Returns the reply of `file.importPbrFolder`. pub fn import_pbr(&mut self, files: &FileList, load: Loader, options: &PbrOptions) -> Result { - self.import_pbr_with_budget(files, load, options, import_memory_budget()) + self.import_pbr_with_budget(files, load, &|_| None, options, import_memory_budget()) } - fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, options: &PbrOptions, memory_budget: u64) -> Result { + /// [`Session::import_pbr`] that records the disk files `locate` names, so the Resources Updater can read them again + #[cfg(not(target_arch = "wasm32"))] + fn import_pbr_located(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions) -> Result { + self.import_pbr_with_budget(files, load, locate, options, import_memory_budget()) + } + + fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions, memory_budget: u64) -> Result { let set = detect_with(files, &options.choose)?; if set.is_empty() { return Err(EngineError::Other(format!( @@ -193,6 +202,10 @@ impl Session { let mut fill = Fill { projection: options.projection.clone(), ..Fill::default() }; let mut added: Vec<(String, Arc>)> = Vec::new(); let mut decoded = Vec::new(); + + // Disk files read by name, and the resources that hold one of them unchanged + let mut file_sources: BTreeMap = BTreeMap::new(); + let mut resource_sources: Vec<(String, texturecraft_core::ResourceSource)> = Vec::new(); let mut channels: Vec = Vec::new(); let mut total_texels = 0u64; let mut retained_bytes = 0u64; @@ -231,6 +244,9 @@ impl Session { let loaded = if allowed_texels == 0 { Err("not enough memory is available to import more textures".to_string()) } else { + if let Some(source) = locate(&file) { + file_sources.insert(file.clone(), source); + } load(&file).and_then(|bytes| { if bytes.len() as u64 > MAX_FILE_BYTES { return Err(format!("the file is over {} MB", MAX_FILE_BYTES >> 20)); @@ -294,6 +310,13 @@ impl Session { suffix_index += 1; } + // Only a resource holding the file's own bytes can be compared with it later + if take == Take::Whole + && let Some(source) = file_sources.get(&file) + { + resource_sources.push((unique.clone(), source.clone())); + } + added.push((unique.clone(), resource_bytes)); decoded.push((unique.clone(), crate::resource_cmds::decoded(resource_image))); made.insert((file.clone(), take), unique.clone()); @@ -316,6 +339,7 @@ impl Session { for (n, bytes) in &added { s.doc.resources.insert(n.clone(), bytes.clone()); } + s.doc.project.resource_sources.extend(resource_sources); let id = s.doc.project.alloc_id(); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name.clone(), LayerKind::Fill(fill), &channels)) })?; @@ -420,7 +444,12 @@ fn import(s: &mut Session, p: &Value) -> Result { if options.name.is_none() { options.name = found.name.clone(); } - s.import_pbr(&found.files, &|name| found.load(name), &options) + s.import_pbr_located( + &found.files, + &|name| found.load(name), + &|name| found.disk_path(name).map(|path| crate::resource_update_cmds::file_source(&path)), + &options, + ) } #[cfg(not(target_arch = "wasm32"))] @@ -462,7 +491,7 @@ mod tests { let mut session = Session::new_project("test", crate::geom::primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); let load = |_: &str| Ok(bytes.clone()); - let result = session.import_pbr_with_budget(&files, &load, &PbrOptions::default(), 64); + let result = session.import_pbr_with_budget(&files, &load, &|_| None, &PbrOptions::default(), 64); assert!(result.unwrap_err().to_string().contains("more than 1 texels")); assert!(session.doc.resources.is_empty()); @@ -471,7 +500,7 @@ mod tests { assert_eq!(allowed_source_texels(256, 64, 3), 2); let never_load = |_: &str| -> std::result::Result, String> { panic!("no source should load after the budget is spent") }; - let result = session.import_pbr_with_budget(&files, &never_load, &PbrOptions::default(), 0); + let result = session.import_pbr_with_budget(&files, &never_load, &|_| None, &PbrOptions::default(), 0); assert!(result.unwrap_err().to_string().contains("not enough memory")); } diff --git a/crates/engine/src/pbr_cmds/native/found.rs b/crates/engine/src/pbr_cmds/native/found.rs index 454203a6..4f056d92 100644 --- a/crates/engine/src/pbr_cmds/native/found.rs +++ b/crates/engine/src/pbr_cmds/native/found.rs @@ -13,6 +13,16 @@ pub(in crate::pbr_cmds) struct Found { impl Found { /// Reads one file of the list. Archive entries are read through a limit, since their /// declared size can lie. + /// The file on disk `name` is read from (None for an archive entry or a name not in the list) + pub(in crate::pbr_cmds) fn disk_path(&self, name: &str) -> Option { + let path = match &self.source { + Origin::Folder { root } => root.join(name), + Origin::Files(paths) => paths.iter().find(|p| p.file_name().is_some_and(|n| n.to_string_lossy() == name))?.clone(), + Origin::Zip(_) => return None, + }; + path.to_str().map(str::to_string) + } + pub(in crate::pbr_cmds) fn load(&self, name: &str) -> std::result::Result, String> { match &self.source { Origin::Folder { root } => read_regular(&root.join(name), MAX_FILE_BYTES), diff --git a/crates/engine/src/reloaded_file.rs b/crates/engine/src/reloaded_file.rs index b65582d2..048161c1 100644 --- a/crates/engine/src/reloaded_file.rs +++ b/crates/engine/src/reloaded_file.rs @@ -16,13 +16,10 @@ pub(crate) struct ReloadedFile { impl ReloadedFile { /// Read and decode `path` for resource `name` within the resource limits (`cmd` names errors) pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result { - let file_path = std::path::Path::new(path); - - // Taken before reading, so a write during the read still shows as a change later - let modified_ms = crate::resource_update_cmds::modified_ms_of(file_path); - let bytes = crate::resource_cmds::read_resource_file(cmd, file_path, crate::resource_cmds::MAX_BYTES as u64)?; + let source = crate::resource_update_cmds::file_source(path); + let bytes = crate::resource_cmds::read_resource_file(cmd, std::path::Path::new(path), crate::resource_cmds::MAX_BYTES as u64)?; let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{path}: {error}")))?; - Ok(ReloadedFile { name, bytes, image, source: ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms } }) + Ok(ReloadedFile { name, bytes, image, source }) } } diff --git a/crates/engine/src/resource_check.rs b/crates/engine/src/resource_check.rs new file mode 100644 index 00000000..f7505daa --- /dev/null +++ b/crates/engine/src/resource_check.rs @@ -0,0 +1,23 @@ +//! A remembered comparison of a resource with its file, so an unchanged file is not read again + +use std::sync::{Arc, Weak}; + +use crate::resource_status::ResourceStatus; + +/// What reading a resource's file found, kept while the file's size and time stay the same +#[derive(Clone, Debug)] +pub(crate) struct ResourceCheck { + pub path: String, + pub size: u64, + pub modified_ms: u64, + /// The resource bytes the file was compared with (an update or undo replaces them) + pub bytes: Weak>, + pub status: ResourceStatus, +} + +impl ResourceCheck { + /// Whether this verdict still holds for the file and the resource's bytes + pub(crate) fn holds_for(&self, path: &str, size: u64, modified_ms: u64, bytes: &Arc>) -> bool { + self.path == path && self.size == size && self.modified_ms == modified_ms && std::ptr::eq(self.bytes.as_ptr(), Arc::as_ptr(bytes)) + } +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index d20cb60e..2c708501 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -184,10 +184,8 @@ fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; let prefix = strp(p, "prefix").unwrap_or(""); - // Taken before reading, so a write during the read still shows as a change in the Resources Updater - let modified_ms = crate::resource_update_cmds::modified_ms_of(std::path::Path::new(path)); + let source = crate::resource_update_cmds::file_source(path); let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let source = texturecraft_core::ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms }; let name = s.edit("Import resource", |session| { let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?; diff --git a/crates/engine/src/resource_state.rs b/crates/engine/src/resource_state.rs index 1a3e427c..2e33cb63 100644 --- a/crates/engine/src/resource_state.rs +++ b/crates/engine/src/resource_state.rs @@ -7,6 +7,7 @@ use crate::resource_status::ResourceStatus; pub struct ResourceState { /// The resource's name in the project. pub name: String, + /// How the resource compares with its file now. pub status: ResourceStatus, /// The file it was imported from or relinked to (None: made in the app or imported without a path). pub path: Option, diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs index ea69042d..0fc56e7d 100644 --- a/crates/engine/src/resource_update_cmds.rs +++ b/crates/engine/src/resource_update_cmds.rs @@ -1,6 +1,7 @@ //! The Resources Updater: compare image resources with the files they came from, read changed //! files again and point a resource at another file. Each change is one undo step, and every -//! layer, mask and view using a changed resource recomposites. +//! layer, mask and view using a changed resource recomposites; a mesh map imported from a changed +//! file is resampled while it still holds what the file gave it. use serde_json::{Value, json}; use texturecraft_core::ResourceSource; @@ -35,7 +36,7 @@ pub fn specs() -> Vec { "Relink resource", [], None, - "{name, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", + "{name: image resource, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", always, relink ), @@ -44,63 +45,134 @@ pub fn specs() -> Vec { impl Session { /// The image resources with their files and how they compare, outdated first, then by name. - /// Reads a file only when its size matches the stored bytes but its modification time does not. - pub fn resource_states(&self) -> Vec { - let sources = &self.doc.project.resource_sources; - let mut states: Vec = self - .doc - .resources - .iter() - .filter(|(name, _)| self.images.contains_key(*name) || sources.contains_key(*name)) - .map(|(name, bytes)| { - let source = sources.get(name); - let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(source, bytes)); - ResourceState { name: name.clone(), status, path: source.map(|source| source.path.clone()), error } - }) - .collect(); - + /// A file is read only when its size matches the stored bytes but its modification time does + /// not, and that verdict is kept until the file's size or time changes again. + pub fn resource_states(&mut self) -> Vec { + let mut states = self.compare_resources(); states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); states } - /// Put reloaded files in place of their resources' bytes and pixels as one undo step + /// Whether `name` is an image resource the Resources Updater lists + fn is_image_resource(&self, name: &str) -> bool { + self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name)) + } + + #[cfg(not(target_arch = "wasm32"))] + fn compare_resources(&mut self) -> Vec { + let mut checks = std::mem::take(&mut self.resource_checks); + let names: Vec = self.doc.resources.keys().filter(|name| self.is_image_resource(name)).cloned().collect(); + let mut states = Vec::with_capacity(names.len()); + for name in names { + let (Some(bytes), source) = (self.doc.resources.get(&name), self.doc.project.resource_sources.get(&name)) else { continue }; + let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(&name, source, bytes, &mut checks)); + states.push(ResourceState { path: source.map(|source| source.path.clone()), name, status, error }); + } + + checks.retain(|name, _| self.doc.resources.contains_key(name)); + self.resource_checks = checks; + states + } + + #[cfg(target_arch = "wasm32")] + fn compare_resources(&mut self) -> Vec { + let sources = &self.doc.project.resource_sources; + let browser = "file paths are not available in the browser"; + let names = self.doc.resources.keys().filter(|name| self.is_image_resource(name)); + names + .map(|name| match sources.get(name) { + Some(source) => { + ResourceState { name: name.clone(), status: ResourceStatus::Missing, path: Some(source.path.clone()), error: Some(browser.into()) } + } + None => ResourceState { name: name.clone(), status: ResourceStatus::NoSource, path: None, error: None }, + }) + .collect() + } + + /// Put reloaded files in place of their resources' bytes as one undo step, resample the mesh + /// maps imported from them, then decode the stored bytes as undo, redo and reopening do #[cfg(not(target_arch = "wasm32"))] fn install_reloaded(&mut self, label: &str, files: Vec) -> Result> { + use std::collections::{BTreeMap, BTreeSet}; + if files.is_empty() { return Ok(Vec::new()); } - let decoded = self.edit(label, |session| { - let mut decoded = Vec::with_capacity(files.len()); + let names: Vec = files.iter().map(|file| file.name.clone()).collect(); + self.edit(label, |session| { + let mut fresh = BTreeMap::new(); + let mut slots = BTreeSet::new(); for file in files { + slots.extend(file.source.mesh_map.map(|slot| (slot.texture_set, slot.map))); session.doc.resources.insert(file.name.clone(), std::sync::Arc::new(file.bytes)); session.doc.project.resource_sources.insert(file.name.clone(), file.source); - decoded.push((file.name, file.image)); + fresh.insert(file.name, crate::resource_cmds::decoded(file.image)); } - Ok(decoded) + for (texture_set, map) in slots { + session.refresh_mesh_map(texture_set, map, &fresh)?; + } + + Ok(()) })?; - // The edit marked every set using a replaced resource for recompositing; the new pixels are read then - let mut names = Vec::with_capacity(decoded.len()); - for (name, image) in decoded { - if crate::fill_alpha::matches_saved_picture(&name, &image) { - self.library_alphas.insert(name.clone()); - } else { - self.library_alphas.remove(&name); - } + for name in &names { + self.images.remove(name); + } + self.sync_images(); + Ok(names) + } - self.images.insert(name.clone(), crate::resource_cmds::decoded(image)); - names.push(name); + /// Resample mesh map `map` of set `texture_set` from the new pixels of the files it was + /// imported from, unless a bake or another image has replaced it since (it no longer equals + /// what the old pixels give) + #[cfg(not(target_arch = "wasm32"))] + fn refresh_mesh_map( + &mut self, + texture_set: usize, + map: texturecraft_core::BakedMap, + fresh: &std::collections::BTreeMap>, + ) -> Result<()> { + const CMD: &str = "resource.update"; + + let tiles: Vec<(u32, String)> = self + .doc + .project + .resource_sources + .iter() + .filter_map(|(name, source)| { + source.mesh_map.filter(|slot| slot.texture_set == texture_set && slot.map == map).map(|slot| (slot.tile, name.clone())) + }) + .collect(); + let (mut before, mut after) = (std::collections::BTreeMap::new(), std::collections::BTreeMap::new()); + for (tile, name) in tiles { + let Some(old) = self.images.get(&name) else { return Ok(()) }; + + before.insert(tile, old.clone()); + after.insert(tile, fresh.get(&name).unwrap_or(old).clone()); } - Ok(names) + let current = self.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)); + let unchanged = crate::meshmap_cmds::resampled(self, CMD, texture_set, map, &before).ok(); + let from_these_files = current.zip(unchanged).is_some_and(|(current, (_, unchanged))| current.as_slice() == unchanged.as_slice()); + if from_these_files { + crate::meshmap_cmds::use_images(self, CMD, texture_set, map, &after)?; + } + + Ok(()) } } -/// How `stored` (a resource's bytes) compares with the file `source` names now +/// How `stored` (a resource's bytes) compares with the file `source` names now, reusing the +/// remembered verdict in `checks` while the file's size and time stay the same #[cfg(not(target_arch = "wasm32"))] -fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Option) { +fn compare_with_file( + name: &str, + source: &ResourceSource, + stored: &std::sync::Arc>, + checks: &mut std::collections::HashMap, +) -> (ResourceStatus, Option) { let path = std::path::Path::new(&source.path); let metadata = match std::fs::metadata(path) { Ok(metadata) if metadata.is_file() => metadata, @@ -108,7 +180,8 @@ fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))), }; - if metadata.len() != stored.len() as u64 { + let size = metadata.len(); + if size != stored.len() as u64 { return (ResourceStatus::Outdated, None); } @@ -117,17 +190,21 @@ fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, return (ResourceStatus::UpToDate, None); } - // A newer time alone is not a change: the file may have been saved again unchanged - match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { - Ok(bytes) if bytes == stored => (ResourceStatus::UpToDate, None), - Ok(_) => (ResourceStatus::Outdated, None), - Err(error) => (ResourceStatus::Missing, Some(error.to_string())), + if let Some(check) = checks.get(name) + && check.holds_for(&source.path, size, modified_ms, stored) + { + return (check.status, None); } -} -#[cfg(target_arch = "wasm32")] -fn compare_with_file(_: &ResourceSource, _: &[u8]) -> (ResourceStatus, Option) { - (ResourceStatus::Missing, Some("file paths are not available in the browser".to_string())) + // A newer time alone is not a change: the file may have been saved again unchanged + let status = match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { + Ok(bytes) if bytes == **stored => ResourceStatus::UpToDate, + Ok(_) => ResourceStatus::Outdated, + Err(error) => return (ResourceStatus::Missing, Some(error.to_string())), + }; + let bytes = std::sync::Arc::downgrade(stored); + checks.insert(name.to_string(), crate::resource_check::ResourceCheck { path: source.path.clone(), size, modified_ms, bytes, status }); + (status, None) } /// A file's modification time in milliseconds since the Unix epoch (0 when the system has none) @@ -137,19 +214,22 @@ fn modified_ms(metadata: &std::fs::Metadata) -> u64 { since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)) } -/// [`modified_ms`] of the file at `path` (0 when it cannot be read) +/// The record for an image about to be read from `path`: its absolute path and its current +/// modification time, taken before reading so a write during the read still shows as a change #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn modified_ms_of(path: &std::path::Path) -> u64 { - std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)) +pub(crate) fn file_source(path: &str) -> ResourceSource { + let absolute = std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()); + let modified_ms = std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)); + ResourceSource { path: absolute, modified_ms, mesh_map: None } } -/// `path` made absolute against the working folder, so the record does not depend on where the app started -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn absolute_path(path: &str) -> String { - std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()) +/// The browser reads no paths; the record keeps the name it was given +#[cfg(target_arch = "wasm32")] +pub(crate) fn file_source(path: &str) -> ResourceSource { + ResourceSource { path: path.to_string(), modified_ms: 0, mesh_map: None } } -fn status(s: &Session) -> Value { +fn status(s: &mut Session) -> Value { let states = s.resource_states(); let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count(); let resources: Vec = states @@ -195,11 +275,14 @@ fn update(s: &mut Session, p: &Value) -> Result { // A file that cannot be read fails alone; the others still update let (mut files, mut failed) = (Vec::new(), Vec::new()); for name in names { - let Some(path) = s.doc.project.resource_sources.get(&name).map(|source| source.path.clone()) else { continue }; - match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &path) { + let Some(previous) = s.doc.project.resource_sources.get(&name).cloned() else { continue }; + match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &previous.path) { // Unchanged contents need no undo step Ok(file) if s.doc.resources.get(&name).is_some_and(|stored| **stored == file.bytes) => {} - Ok(file) => files.push(file), + Ok(mut file) => { + file.source.mesh_map = previous.mesh_map; + files.push(file); + } Err(error) => failed.push(json!({"name": name, "error": error.to_string()})), } } @@ -219,11 +302,13 @@ fn relink(s: &mut Session, p: &Value) -> Result { let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string(); let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; - if !s.doc.resources.contains_key(&name) { - return Err(bad(CMD, format!("no resource `{name}`"))); + if !s.is_image_resource(&name) { + return Err(bad(CMD, format!("no image resource `{name}`"))); } - let file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + // A relinked mesh map file still feeds its mesh map + let mut file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + file.source.mesh_map = s.doc.project.resource_sources.get(&name).and_then(|source| source.mesh_map); let path = file.source.path.clone(); s.install_reloaded("Relink resource", vec![file])?; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index beb20ab0..4bce1792 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -462,6 +462,9 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Resource names whose decoded pixels match a library alpha. pub(crate) library_alphas: BTreeSet, + /// Resources whose file was read for the Resources Updater, by name: the verdict stays while the file's size and time do + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resource_checks: std::collections::HashMap, /// Temporary texel mask limiting paint strokes (not saved, not in the history). pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). @@ -547,6 +550,8 @@ impl Session { blending_clipboard: None, images: Default::default(), library_alphas: BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] + resource_checks: std::collections::HashMap::new(), quick_mask: Default::default(), painting_paths: false, path_cache: None, diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index c0d0f1dc..93b26908 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -1,40 +1,20 @@ //! The Resources Updater: image resources remember their files, a changed file shows as outdated, //! Update reads it again (one undo step, recompositing its layers) and Relink follows another file -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; use serde_json::{Value, json}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{BakedMap, Channel}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{ResourceStatus, Session, execute}; -const RESOLUTION: u32 = 64; -const SAMPLE_STRIDE: usize = 4; +const RESOLUTION: u32 = 128; +const SAMPLE_STRIDE: usize = 8; const RED: [u8; 4] = [255, 0, 0, 255]; const GREEN: [u8; 4] = [0, 255, 0, 255]; -/// A test folder removed when dropped -struct TempDir(PathBuf); - -impl TempDir { - fn new(test: &str) -> TempDir { - let path = std::env::temp_dir().join(format!("tc-resource-updater-{test}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - TempDir(path) - } - - fn file(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - fn session() -> Session { Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap() } @@ -48,9 +28,22 @@ fn text(path: &Path) -> &str { path.to_str().unwrap() } +/// Give the file at `path` the modification time `time` without changing its contents +fn set_modified(path: &Path, time: SystemTime) { + std::fs::File::options().write(true).open(path).unwrap().set_modified(time).unwrap(); +} + +fn modified(path: &Path) -> SystemTime { + std::fs::metadata(path).unwrap().modified().unwrap() +} + +fn import(s: &mut Session, path: &Path) -> String { + execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string() +} + /// Import `path` and show it as a base colour fill; returns the resource name fn import_as_fill(s: &mut Session, path: &Path) -> String { - let name = execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string(); + let name = import(s, path); execute(s, "layer.add.image", &json!({"name": name})).unwrap(); s.update(); name @@ -62,19 +55,19 @@ fn base_colors(s: &Session) -> Vec<[f32; 3]> { samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() } -fn status_of(s: &Session, name: &str) -> ResourceStatus { +fn status_of(s: &mut Session, name: &str) -> ResourceStatus { s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status } #[test] fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() { - let dir = TempDir::new("update"); - let file = dir.file("bricks.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("bricks.png"); write_png(&file, 4, RED); let mut s = session(); let name = import_as_fill(&mut s, &file); let before = base_colors(&s); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); write_png(&file, 8, GREEN); let status = execute(&mut s, "resource.status", &Value::Null).unwrap(); @@ -90,7 +83,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() assert_eq!(updated["updated"], json!([name])); assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); assert_eq!(s.images[&name].width, 8, "the new pixels are decoded"); assert_ne!(after, before, "the fill using the resource recomposited"); @@ -99,7 +92,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name"); assert_eq!(base_colors(&s), before); - assert_eq!(status_of(&s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); execute(&mut s, "edit.redo", &Value::Null).unwrap(); s.update(); @@ -109,24 +102,60 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() } #[test] -fn nothing_outdated_adds_no_undo_step() { - let dir = TempDir::new("unchanged"); - let file = dir.file("same.png"); +fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { + let dir = tempfile::tempdir().unwrap(); + let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name)); + for file in [&fine, &gone, &changed] { + write_png(file, 4, RED); + } + let mut s = session(); + let png = std::fs::read(&fine).unwrap(); + s.import_resource_bytes("a_unlinked.png", png).unwrap(); + for file in [&fine, &gone, &changed] { + import(&mut s, file); + } + std::fs::remove_file(&gone).unwrap(); + write_png(&changed, 8, GREEN); + + let order: Vec = s.resource_states().into_iter().map(|state| state.name).collect(); + + assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png"], "by status first, against the name order"); +} + +#[test] +fn a_same_size_file_is_compared_by_contents_once_per_time() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("same.png"); write_png(&file, 4, RED); let mut s = session(); - import_as_fill(&mut s, &file); + let name = import(&mut s, &file); + let original = std::fs::read(&file).unwrap(); + let later = modified(&file) + Duration::from_secs(10); + + // Saved again unchanged: a new time alone is no change, and updating adds no step + set_modified(&file, later); let steps = s.history_labels().len(); - - let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); - - assert_eq!(updated["updated"], json!([])); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); + assert_eq!(execute(&mut s, "resource.update", &json!({})).unwrap()["updated"], json!([])); assert_eq!(s.history_labels().len(), steps); + + // Different bytes of the same size and time are not read again: the verdict for that size and time stands + let mut edited = original.clone(); + let last = edited.len() - 1; + edited[last] ^= 0xff; + std::fs::write(&file, &edited).unwrap(); + set_modified(&file, later); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate, "the remembered verdict is used"); + + // Another time reads the file, and its bytes differ + set_modified(&file, later + Duration::from_secs(10)); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated); } #[test] fn a_missing_file_is_reported_and_updating_it_changes_nothing() { - let dir = TempDir::new("missing"); - let file = dir.file("gone.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("gone.png"); write_png(&file, 4, RED); let mut s = session(); let name = import_as_fill(&mut s, &file); @@ -145,8 +174,8 @@ fn a_missing_file_is_reported_and_updating_it_changes_nothing() { #[test] fn an_unreadable_file_fails_alone_while_the_others_update() { - let dir = TempDir::new("partial"); - let (kept, gone) = (dir.file("kept.png"), dir.file("gone.png")); + let dir = tempfile::tempdir().unwrap(); + let (kept, gone) = (dir.path().join("kept.png"), dir.path().join("gone.png")); write_png(&kept, 4, RED); write_png(&gone, 4, RED); let mut s = session(); @@ -164,8 +193,8 @@ fn an_unreadable_file_fails_alone_while_the_others_update() { #[test] fn relink_reads_another_file_and_follows_it_from_then_on() { - let dir = TempDir::new("relink"); - let (first, second) = (dir.file("first.png"), dir.file("second.png")); + let dir = tempfile::tempdir().unwrap(); + let (first, second) = (dir.path().join("first.png"), dir.path().join("second.png")); write_png(&first, 4, RED); write_png(&second, 8, GREEN); let mut s = session(); @@ -183,45 +212,132 @@ fn relink_reads_another_file_and_follows_it_from_then_on() { // The old file no longer matters, the new one does write_png(&first, 16, GREEN); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); write_png(&second, 16, RED); - assert_eq!(status_of(&s, &name), ResourceStatus::Outdated); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated); execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link"); } +#[test] +fn relink_refuses_resources_that_are_not_images() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("picture.png"); + write_png(&file, 4, RED); + let mut s = session(); + s.doc.resources.insert("material.mcmat".to_string(), Arc::new(vec![1, 2, 3])); + let steps = s.history_labels().len(); + + let error = execute(&mut s, "resource.relink", &json!({"name": "material.mcmat", "path": text(&file)})).unwrap_err(); + + assert!(error.to_string().contains("no image resource"), "{error}"); + assert_eq!(*s.doc.resources["material.mcmat"], vec![1, 2, 3]); + assert_eq!(s.history_labels().len(), steps); +} + #[test] fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() { - let dir = TempDir::new("reopen"); - let file = dir.file("kept.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("kept.png"); write_png(&file, 4, RED); let mut s = session(); let linked = import_as_fill(&mut s, &file); let png = std::fs::read(&file).unwrap(); let unlinked = s.import_resource_bytes("made.png", png).unwrap(); - assert_eq!(status_of(&s, &unlinked), ResourceStatus::NoSource); + assert_eq!(status_of(&mut s, &unlinked), ResourceStatus::NoSource); assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err()); - let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); write_png(&file, 8, GREEN); - assert_eq!(status_of(&reopened, &linked), ResourceStatus::Outdated); + assert_eq!(status_of(&mut reopened, &linked), ResourceStatus::Outdated); } #[test] fn a_removed_resource_forgets_its_file() { - let dir = TempDir::new("remove"); - let file = dir.file("old.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("old.png"); write_png(&file, 4, RED); let mut s = session(); - let name = execute(&mut s, "resource.import", &json!({"path": text(&file)})).unwrap()["name"].as_str().unwrap().to_string(); + let name = import(&mut s, &file); execute(&mut s, "resource.remove", &json!({"name": name})).unwrap(); let png = std::fs::read(&file).unwrap(); let reused = s.import_resource_bytes("old.png", png).unwrap(); assert_eq!(reused, name, "the name is free again"); - assert_eq!(status_of(&s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); + assert_eq!(status_of(&mut s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); +} + +/// The material ball: texture sets "Ball" and "Base" +fn ball() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +fn ambient_occlusion(s: &Session) -> Vec { + s.doc.baked[&0].maps[&BakedMap::AmbientOcclusion].as_ref().clone() +} + +#[test] +fn an_imported_mesh_map_follows_its_changed_file_until_something_else_replaces_it() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_ao.png"); + write_png(&file, 4, [60, 60, 60, 255]); + let mut s = ball(); + execute(&mut s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + let name = s.doc.project.resource_sources.keys().next().expect("the file is remembered").clone(); + let imported = ambient_occlusion(&s); + + write_png(&file, 8, [200, 200, 200, 255]); + execute(&mut s, "resource.update", &json!({})).unwrap(); + let updated = ambient_occlusion(&s); + + assert_ne!(updated, imported, "the mesh map is resampled from the new file"); + + // Another image in the slot is not overwritten by a later change of the file + let other = dir.path().join("other.png"); + write_png(&other, 4, [10, 10, 10, 255]); + let other_name = import(&mut s, &other); + execute(&mut s, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": other_name})).unwrap(); + let replaced = ambient_occlusion(&s); + write_png(&file, 16, [120, 120, 120, 255]); + let result = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap(); + + assert_eq!(result["updated"], json!([name]), "the resource itself still updates"); + assert_eq!(ambient_occlusion(&s), replaced, "the mesh map keeps the image set over it"); +} + +#[test] +fn pbr_folder_and_materialx_imports_remember_their_image_files() { + let dir = tempfile::tempdir().unwrap(); + let color = dir.path().join("moss_col.png"); + write_png(&color, 4, RED); + std::fs::create_dir(dir.path().join("tex")).unwrap(); + let base = dir.path().join("tex").join("base.png"); + write_png(&base, 4, GREEN); + let mtlx = dir.path().join("m.mtlx"); + let document = r#" + + + + +"#; + std::fs::write(&mtlx, document).unwrap(); + let mut s = session(); + + let pbr = execute(&mut s, "file.importPbrFolder", &json!({"files": [text(&color)]})).unwrap(); + let materialx = execute(&mut s, "file.importMaterialX", &json!({"path": text(&mtlx)})).unwrap(); + let pbr_name = pbr["resources"][0].as_str().unwrap().to_string(); + let materialx_name = materialx["resources"][0].as_str().unwrap().to_string(); + + assert!(s.doc.project.resource_sources[&pbr_name].path.ends_with("moss_col.png")); + assert!(s.doc.project.resource_sources[&materialx_name].path.ends_with("base.png")); + + write_png(&color, 8, GREEN); + write_png(&base, 8, RED); + + assert_eq!(status_of(&mut s, &pbr_name), ResourceStatus::Outdated); + assert_eq!(status_of(&mut s, &materialx_name), ResourceStatus::Outdated); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9abb472c..50481899 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -82,3 +82,5 @@ egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } pollster = "0.4" image = { workspace = true } craft-image-codecs = { workspace = true } +# Test folders removed when the test ends +tempfile = "3" diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 235ebc5e..435aac1c 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -237,6 +237,9 @@ mod tests { keys.extend(BlendMode::all().map(|mode| mode.label())); keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label())); keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label())); + keys.extend(texturecraft_engine::ResourceStatus::ALL.iter().map(|status| status.label())); + let notice = crate::toast_action::ToastAction::UpdateResources { project: 0 }; + keys.extend([notice.label(), notice.accessible_name()]); keys.extend(texturecraft_engine::HISTORY_TEMPLATES); keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label())); keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 100d07a5..b10af608 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -325,6 +325,9 @@ pub struct TextureCraftApp { /// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again #[cfg(not(target_arch = "wasm32"))] pub(crate) resources_notified: std::collections::BTreeSet, + /// The project the Resources Updater last checked on opening (see `resources_updater::follow_project`) + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resources_project: Option, /// The update check and prompt (desktop only). #[cfg(not(target_arch = "wasm32"))] pub(crate) updates_rt: updates_ui::Runtime, @@ -449,6 +452,8 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] resources_notified: std::collections::BTreeSet::new(), #[cfg(not(target_arch = "wasm32"))] + resources_project: None, + #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), @@ -1130,9 +1135,11 @@ impl eframe::App for TextureCraftApp { // Files may have been edited in another app meanwhile #[cfg(not(target_arch = "wasm32"))] - resources_updater::check_on_focus(self); + resources_updater::check_files(self); } self.focused = focused; + #[cfg(not(target_arch = "wasm32"))] + resources_updater::follow_project(self); let scale = self.ui.prefs.ui_scale.clamp(*UI_SCALE_APPLIED.start(), *UI_SCALE_APPLIED.end()); if (ctx.zoom_factor() - scale).abs() > SAME_ZOOM_TOLERANCE { @@ -1335,11 +1342,13 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { show_log = true; dismissed = Some(i); } - if let Some(action) = t.action - && ui.button(i18n::tr(action.label())).clicked() - { - clicked_action = Some(action); - dismissed = Some(i); + if let Some(action) = t.action { + let button = ui.button(i18n::tr(action.label())); + button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, i18n::tr(action.accessible_name()))); + if button.clicked() { + clicked_action = Some(action); + dismissed = Some(i); + } } }); if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a0fd80de..1d4588ea 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,9 +526,6 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); - } else if app.ui.windows.resources_updater.is_some() && !popup_open && input.key_pressed(Key::Escape) { - #[cfg(not(target_arch = "wasm32"))] - crate::resources_updater::keys_in(app, input); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 4bb9ce60..c0de777d 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -7,7 +7,6 @@ mod row_request; use std::collections::BTreeSet; -use egui::{Key, Modifiers}; use serde_json::json; use texturecraft_engine::{ResourceState, ResourceStatus}; @@ -25,7 +24,7 @@ use row_request::RowRequest; const WINDOW_WIDTH_POINTS: f32 = 640.0; /// Height of the resource list const LIST_HEIGHT_POINTS: f32 = 360.0; -// Initial space for the header, tabs, filters and footer +/// Initial space for the header, tabs, filters and footer const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0; /// Side of a row's thumbnail const THUMBNAIL_POINTS: f32 = 40.0; @@ -39,6 +38,8 @@ const ROW_MARGIN: egui::Margin = egui::Margin::same(4); const OUTDATED_TINT: f32 = 0.18; /// How long the "changed on disk" notice stays, in seconds: long enough to reach its button const NOTICE_SECONDS: f64 = 12.0; +/// Shortest time between two checks after document changes, in seconds (each check looks at every file) +const RECHECK_SECONDS: f64 = 0.5; /// Opens the window, or closes it when it is open (the shelf button) pub(crate) fn toggle(app: &mut TextureCraftApp) { @@ -54,13 +55,26 @@ pub(crate) fn open(app: &mut TextureCraftApp) { rows: app.session.resource_states(), project: app.session.project_id, checked_revision: app.session.revision, + checked_at: app.last_time, ..window }); } -/// The app has the focus back: check the files again and, when other resources than last time -/// are outdated, show a notice whose button updates them -pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { +/// Check once when another project is open (files may have changed while it was closed), and +/// forget what was announced for the last one +pub(crate) fn follow_project(app: &mut TextureCraftApp) { + if !app.session.project_open || app.resources_project == Some(app.session.project_id) { + return; + } + + app.resources_project = Some(app.session.project_id); + app.resources_notified.clear(); + check_files(app); +} + +/// Check the files again (the app has the focus back, or a project opened) and, when other +/// resources than last time are outdated, show a notice whose button updates them +pub(crate) fn check_files(app: &mut TextureCraftApp) { if !app.session.project_open { return; } @@ -70,6 +84,7 @@ pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { if let Some(window) = app.ui.windows.resources_updater.as_mut() { window.rows = rows; window.checked_revision = app.session.revision; + window.checked_at = app.last_time; } if !outdated.is_empty() && outdated != app.resources_notified { @@ -81,7 +96,7 @@ pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { app.toast(text, false); if let Some(toast) = app.toasts.last_mut() { toast.until = app.last_time + NOTICE_SECONDS; - toast.action = Some(ToastAction::UpdateResources); + toast.action = Some(ToastAction::UpdateResources { project: app.session.project_id }); } } app.resources_notified = outdated; @@ -137,13 +152,6 @@ fn show_in_folder(app: &mut TextureCraftApp, path: &str) { } } -/// The keys of the open window: Escape closes it (an open dropdown takes it first, see `menus`) -pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { - if input.consume_key(Modifiers::NONE, Key::Escape) { - app.ui.windows.resources_updater = None; - } -} - /// Whether `row` passes the window's status and name filters fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool { let name_filter = window.name_filter.trim().to_lowercase(); @@ -164,18 +172,31 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // Every change (an update, undo, redo, a removed resource) is checked again + // Every change (an update, undo, redo, a removed resource) is checked again, at most twice a second if window.checked_revision != app.session.revision { - window.rows = app.session.resource_states(); - window.checked_revision = app.session.revision; + let wait = window.checked_at + RECHECK_SECONDS - app.last_time; + if wait <= 0.0 { + window.rows = app.session.resource_states(); + window.checked_revision = app.session.revision; + window.checked_at = app.last_time; + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } + } + + // Escape closes the window only while one of its controls had the keyboard (egui takes the focus away on it); otherwise it cancels a stroke as usual + // egui consumes that Escape to take the focus away, so the raw events are read + let escape = ctx.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if window.had_keyboard && escape && !egui::Popup::is_any_open(ctx) { + return; } let tokens = Tokens::get(ctx); - let mut open = true; + let mut window_open = true; let (mut refresh, mut update_all) = (false, false); let mut request = None; - crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut open) + let shown = crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut window_open) .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS)) .show(ctx, |ui| { ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name)); @@ -216,7 +237,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { ui.horizontal(|ui| { - refresh = ui.button(tr("Refresh")).clicked(); + let refresh_button = ui.button(tr("Refresh")); + refresh_button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Refresh resources"))); + refresh = refresh_button.clicked(); ui.label(summary(&window.rows)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated); @@ -252,15 +275,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); - if !open { + let focused = ctx.memory(|memory| memory.focused()).and_then(|id| ctx.read_response(id)); + window.had_keyboard = shown.as_ref().zip(focused.as_ref()).is_some_and(|(shown, focused)| focused.layer_id == shown.response.layer_id); + if !window_open { return; } app.ui.windows.resources_updater = Some(window); - if refresh { - open(app); - } + // Its own changes and Refresh show at once + let check_now = refresh || update_all || matches!(request, Some(RowRequest::Update(_))); if update_all { update(app, None); } @@ -270,6 +294,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path), None => {} } + + if check_now { + open(app); + } } /// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are @@ -297,8 +325,7 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: } ui.label(number.to_string()); - // Buttons take their room on the right first, so the texts truncate in what is left - // Each button's accessible name says which resource it acts on + // Buttons go first, so the texts truncate in what is left; each accessible name names its resource ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let update = ui.add_enabled(outdated, egui::Button::new(tr("Update"))); let update_name = format!("{} {}", tr("Update"), row.name); @@ -325,6 +352,7 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: ui.vertical(|ui| { ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate()); + ui.label(format!("{} {}", tr("Shelf :"), tr("project"))); let file = row.path.as_deref().unwrap_or(tr("No source file")); ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file); let status = ui.label(tr(row.status.label())); @@ -352,30 +380,35 @@ mod tests { image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap(); } - fn notices(app: &TextureCraftApp) -> usize { - app.toasts.iter().filter(|toast| toast.action == Some(ToastAction::UpdateResources)).count() + fn notices(app: &TextureCraftApp) -> Vec { + app.toasts.iter().filter_map(|toast| toast.action).collect() } #[test] fn a_changed_file_is_announced_once_and_the_notice_updates_it() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner); - let path = std::env::temp_dir().join(format!("texturecraft-resources-notice-{}.png", std::process::id())); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("notice.png"); write_png(&path, 4); let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); let app = harness.state_mut(); let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); - check_on_focus(app); - assert_eq!(notices(app), 0, "nothing changed yet"); + check_files(app); + assert!(notices(app).is_empty(), "nothing changed yet"); write_png(&path, 8); - check_on_focus(app); - check_on_focus(app); - assert_eq!(notices(app), 1, "the same change is announced once"); + check_files(app); + check_files(app); + let announced = notices(app); + assert_eq!(announced, [ToastAction::UpdateResources { project: app.session.project_id }], "the same change is announced once"); - ToastAction::UpdateResources.run(app); - std::fs::remove_file(&path).ok(); + // A notice about another project does nothing + ToastAction::UpdateResources { project: app.session.project_id + 1 }.run(app); + assert_eq!(app.session.images[&name].width, 4); + + announced[0].run(app); assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource"); assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources")); diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs index 46fb9d12..805ef0b8 100644 --- a/crates/ui-egui/src/state/resources_updater.rs +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -16,4 +16,8 @@ pub struct ResourcesUpdater { pub project: u64, /// The session revision the rows were checked at pub(crate) checked_revision: u64, + /// When the rows were checked, in app seconds + pub(crate) checked_at: f64, + /// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it) + pub(crate) had_keyboard: bool, } diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs index d360fd7b..e7d05308 100644 --- a/crates/ui-egui/src/toast_action.rs +++ b/crates/ui-egui/src/toast_action.rs @@ -5,30 +5,37 @@ use crate::TextureCraftApp; /// What a toast's button does #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ToastAction { - /// "Update": read every outdated resource file again (the "changed on disk" notice) - #[cfg(not(target_arch = "wasm32"))] - UpdateResources, + /// "Update": read every outdated resource file of `project` again (the desktop's "changed on disk" notice) + UpdateResources { + /// The project the notice is about; the button does nothing once another one is open + project: u64, + }, } impl ToastAction { /// The button's text (English; translated where it is drawn) pub fn label(self) -> &'static str { match self { - #[cfg(not(target_arch = "wasm32"))] - ToastAction::UpdateResources => "Update", + ToastAction::UpdateResources { .. } => "Update", + } + } + + /// The button's accessible name, which says what it acts on (English; translated where it is drawn) + pub fn accessible_name(self) -> &'static str { + match self { + ToastAction::UpdateResources { .. } => "Update resources", } } - #[cfg(not(target_arch = "wasm32"))] pub(crate) fn run(self, app: &mut TextureCraftApp) { match self { - ToastAction::UpdateResources => crate::resources_updater::update(app, None), + // Another project's notice is stale + ToastAction::UpdateResources { project } if project != app.session.project_id => {} + #[cfg(not(target_arch = "wasm32"))] + ToastAction::UpdateResources { .. } => crate::resources_updater::update(app, None), + // The browser has no files to read again + #[cfg(target_arch = "wasm32")] + ToastAction::UpdateResources { .. } => {} } } - - /// The browser's toasts carry no action yet - #[cfg(target_arch = "wasm32")] - pub(crate) fn run(self, _: &mut TextureCraftApp) { - match self {} - } } diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 298c1130..534bd7b1 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -4,13 +4,14 @@ use std::path::{Path, PathBuf}; -use egui::{Key, Role}; +use egui::{Key, Role, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; +use texturecraft_ui_egui::state::ViewLayout; use super::temp_dir::TempDir; @@ -59,40 +60,44 @@ fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 { #[test] fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() { let dir = TempDir::new("resources-updater-update"); - let (kept, changed) = (png(&dir, "kept.png", 4), png(&dir, "changed.png", 4)); + let (kept, changed) = (png(&dir, "aa_kept.png", 4), png(&dir, "zz_changed.png", 4)); let mut h = app(); import(&mut h, &kept); import(&mut h, &changed); - png(&dir, "changed.png", 8); + png(&dir, "zz_changed.png", 8); activate(&mut h, "Resources Updater"); let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows; - assert_eq!(rows[0].name, "changed.png", "outdated resources come first"); + assert_eq!(rows[0].name, "zz_changed.png", "outdated resources come first, before names that sort earlier"); assert!(shows(&h, "Project : Test")); + assert_eq!(h.get_all_by_label("Shelf : project").count(), 2, "the reference's shelf line, one per row"); assert!(shows(&h, "(2 resources, 1 outdated)")); assert!(shows(&h, "Outdated"), "the status is written out, not only coloured"); - assert!(h.get_by_role_and_label(Role::Button, "Update kept.png").accesskit_node().is_disabled(), "only outdated resources update"); + assert!(h.get_by_role_and_label(Role::Button, "Update aa_kept.png").accesskit_node().is_disabled(), "only outdated resources update"); let steps = h.state().session.history_labels().len(); - activate(&mut h, "Update changed.png"); + activate(&mut h, "Update zz_changed.png"); - assert_eq!(width_of(&h, "changed.png"), 8, "the new file's pixels are in the project"); + assert_eq!(width_of(&h, "zz_changed.png"), 8, "the new file's pixels are in the project"); assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step"); assert!(shows(&h, "(2 resources, 0 outdated)")); - // Undo brings the old pixels back, so the list shows the file as changed again + // Undo brings the old pixels back, so Refresh shows the file as changed again h.state_mut().run("edit.undo", json!({})).unwrap(); - h.run_steps(3); + activate(&mut h, "Refresh resources"); - assert_eq!(width_of(&h, "changed.png"), 4); + assert_eq!(width_of(&h, "zz_changed.png"), 4); assert!(shows(&h, "(2 resources, 1 outdated)")); activate(&mut h, "Update All"); - assert_eq!(width_of(&h, "changed.png"), 8); + assert_eq!(width_of(&h, "zz_changed.png"), 8); + // Update All went grey with nothing left to update; the keyboard moves on to another button of the window + h.get_by_role_and_label(Role::Button, "Select new resource aa_kept.png").focus(); + h.run_steps(2); press(&mut h, Key::Escape); - assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window"); + assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window while it has the keyboard"); } #[test] @@ -135,3 +140,31 @@ fn show_in_folder_shows_the_folder_of_the_resource_file() { assert_eq!(shown.len(), 1); assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); } + +#[test] +fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() { + const FRAMES_PER_DRAG_EVENT: usize = 2; + + let mut h = app(); + h.state_mut().run("layer.add.paint", json!({})).unwrap(); + h.state_mut().ui.layout = ViewLayout::Only3D; + h.run_steps(3); + let center = h.state().viewport_rect.center(); + h.drag_at(center); + h.run_steps(FRAMES_PER_DRAG_EVENT); + h.hover_at(center + vec2(20.0, 0.0)); + h.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(h.state().session.stroke_active()); + + // Opened from the shelf mid-stroke, the keyboard stays on the shelf button + activate(&mut h, "Resources Updater"); + assert!(h.state().ui.windows.resources_updater.is_some()); + assert!(h.state().session.stroke_active()); + + press(&mut h, Key::Escape); + + assert!(!h.state().session.stroke_active(), "Escape cancels the stroke"); + assert!(h.state().ui.windows.resources_updater.is_some(), "the window keeps open: its controls do not have the keyboard"); + h.drop_at(center + vec2(30.0, 0.0)); + h.run_steps(3); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0cf55589..ce32a426 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -468,17 +468,22 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para ## Resources Updater -An image resource imported with `resource.import {path}` remembers that file (its absolute path and -modification time, saved with the project). The shelf's Resources Updater window lists the project's -image resources through these commands and checks them again when it opens, on Refresh, after every -change and when the app gets the focus back; then a notice ("N resources changed on disk", with an -Update button) appears when the set of outdated resources changed since the last notice. +An image resource read from a file remembers that file (its absolute path and modification time, +saved with the project): `resource.import {path}`, the images `file.importPbrFolder` stores unchanged +(not ORM channels split out, not archive entries), the images of `file.importMaterialX` and the files of +`textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the +old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater +window lists the project's image resources through these commands and checks them when it opens, on +Refresh, after changes (at most twice a second), once after a project opens and when the app gets the +focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of +outdated resources differs from the last notice. A file whose size matches but whose time changed is +read once; its verdict is kept until its size or time changes again. | Command | Params and result | |---|---| | `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | | `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | -| `resource.relink` | `{name, path}` → `{name, path}`: the resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | +| `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | These commands read host paths stored in the project, so MCP and `serve` refuse them through `command_run`; the desktop app's control channel and the trusted local CLI run them. diff --git a/docs/features.md b/docs/features.md index a3692d83..8a25b66a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -98,13 +98,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and alpha images become the brush alpha. Filter by role or remove selected rows before importing. Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are unavailable. The browser imports images straight from its file picker. -- **Resources Updater:** the shelf button under the tools lists the project's image resources with - their files, outdated ones first. An imported image remembers its file; when that file changes on - disk, *Update* (or *Update All*) reads it again and every layer using it recomposites, as one undo - step. *Select new resource* points a resource at another file, *Show in folder* opens its folder, - and the list filters by status and name. When the app gets the focus back after files changed, a - notice offers *Update*. Desktop only; there is no Shaders tab, since TextureCraft has no shader - resources. +- **Resources Updater:** the shelf button under the tools lists the project's image resources, + outdated ones first: name, *Shelf : project* as in the reference, and an extra *File :* line with + the file it came from. An image read from a file (Import resources, PBR folders, MaterialX, imported + mesh maps) remembers it; when the file changes on disk, *Update* (or *Update All*) reads it again + and every layer and imported mesh map using it follows, as one undo step. *Select new resource* + points a resource at another file, *Show in folder* opens its folder, and the list filters by status + and name. After a project opens and when the app gets the focus back after files changed, a notice + offers *Update*. Desktop only; there is no Shaders tab (TextureCraft has no shader resources), no + Pin window and no × to clear a link. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. *Create smart mask* in the same menu saves just the layer's mask (all its effects, painted pixels and images); it appears under From 95fac86e4e4b6d1962b79526305c0ae66692965c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 13:43:31 +0100 Subject: [PATCH 034/190] Resources Updater: recheck files while the window stays open; a mesh map follows its latest imported file --- crates/engine/src/meshmap_import_cmds.rs | 8 ++++- crates/engine/tests/it/resource_updater.rs | 21 +++++++++++++ crates/ui-egui/src/resources_updater.rs | 30 +++++++------------ crates/ui-egui/src/state/resources_updater.rs | 4 +-- crates/ui-egui/tests/it/resources_updater.rs | 18 +++++++++++ docs/control-protocol.md | 2 +- 6 files changed, 59 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 2c9f9b56..0f69659e 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -85,12 +85,18 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result() as u64; let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + + // The slot follows only its latest file: an earlier import into it no longer feeds it + for earlier in s.doc.project.resource_sources.values_mut().filter(|earlier| earlier.mesh_map == Some(slot)) { + earlier.mesh_map = None; + } s.doc.project.resource_sources.insert(name.clone(), source); let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?; reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?; diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index 93b26908..43a9120b 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -341,3 +341,24 @@ fn pbr_folder_and_materialx_imports_remember_their_image_files() { assert_eq!(status_of(&mut s, &pbr_name), ResourceStatus::Outdated); assert_eq!(status_of(&mut s, &materialx_name), ResourceStatus::Outdated); } + +#[test] +fn a_mesh_map_imported_twice_follows_the_latest_file() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_ao.png"); + let import_file = |s: &mut Session| execute(s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + let mut s = ball(); + write_png(&file, 4, [60, 60, 60, 255]); + import_file(&mut s); + let first = s.doc.project.resource_sources.keys().next().unwrap().clone(); + write_png(&file, 8, [200, 200, 200, 255]); + import_file(&mut s); + let latest = s.doc.project.resource_sources.keys().find(|name| **name != first).expect("a second resource").clone(); + let imported = ambient_occlusion(&s); + + write_png(&file, 16, [10, 10, 10, 255]); + execute(&mut s, "resource.update", &json!({"names": [latest]})).unwrap(); + + assert_ne!(ambient_occlusion(&s), imported, "the mesh map follows the file imported last"); + assert!(s.doc.project.resource_sources[&first].mesh_map.is_none(), "the earlier import no longer feeds the slot"); +} diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index c0de777d..95840c26 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -38,7 +38,7 @@ const ROW_MARGIN: egui::Margin = egui::Margin::same(4); const OUTDATED_TINT: f32 = 0.18; /// How long the "changed on disk" notice stays, in seconds: long enough to reach its button const NOTICE_SECONDS: f64 = 12.0; -/// Shortest time between two checks after document changes, in seconds (each check looks at every file) +/// Time between two checks while the window is open, in seconds (each check looks at every file; an unchanged one is not read) const RECHECK_SECONDS: f64 = 0.5; /// Opens the window, or closes it when it is open (the shelf button) @@ -51,13 +51,8 @@ pub(crate) fn toggle(app: &mut TextureCraftApp) { /// Opens the window with the resources checked now (an open window is checked again) pub(crate) fn open(app: &mut TextureCraftApp) { let window = app.ui.windows.resources_updater.take().unwrap_or_default(); - app.ui.windows.resources_updater = Some(ResourcesUpdater { - rows: app.session.resource_states(), - project: app.session.project_id, - checked_revision: app.session.revision, - checked_at: app.last_time, - ..window - }); + app.ui.windows.resources_updater = + Some(ResourcesUpdater { rows: app.session.resource_states(), project: app.session.project_id, checked_at: app.last_time, ..window }); } /// Check once when another project is open (files may have changed while it was closed), and @@ -83,7 +78,6 @@ pub(crate) fn check_files(app: &mut TextureCraftApp) { let outdated: BTreeSet = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect(); if let Some(window) = app.ui.windows.resources_updater.as_mut() { window.rows = rows; - window.checked_revision = app.session.revision; window.checked_at = app.last_time; } @@ -172,16 +166,14 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // Every change (an update, undo, redo, a removed resource) is checked again, at most twice a second - if window.checked_revision != app.session.revision { - let wait = window.checked_at + RECHECK_SECONDS - app.last_time; - if wait <= 0.0 { - window.rows = app.session.resource_states(); - window.checked_revision = app.session.revision; - window.checked_at = app.last_time; - } else { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); - } + // Files changed on disk and document changes (undo, a removed resource) show while the window stays open + let wait = window.checked_at + RECHECK_SECONDS - app.last_time; + if wait <= 0.0 { + window.rows = app.session.resource_states(); + window.checked_at = app.last_time; + ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK_SECONDS)); + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } // Escape closes the window only while one of its controls had the keyboard (egui takes the focus away on it); otherwise it cancels a stroke as usual diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs index 805ef0b8..3b515d32 100644 --- a/crates/ui-egui/src/state/resources_updater.rs +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -4,7 +4,7 @@ use texturecraft_engine::{ResourceState, ResourceStatus}; #[derive(Clone, Debug, PartialEq, Default)] pub struct ResourcesUpdater { /// The resources and how they compare with their files, outdated first (checked on opening, - /// Refresh, every change and when the app gets the focus back) + /// Refresh, twice a second while open and when the app gets the focus back) pub rows: Vec, /// The status the list is narrowed to (None: all) pub status_filter: Option, @@ -14,8 +14,6 @@ pub struct ResourcesUpdater { pub jump: Option, /// The project that was open when this window opened pub project: u64, - /// The session revision the rows were checked at - pub(crate) checked_revision: u64, /// When the rows were checked, in app seconds pub(crate) checked_at: f64, /// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it) diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 534bd7b1..980102a9 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -168,3 +168,21 @@ fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() { h.drop_at(center + vec2(30.0, 0.0)); h.run_steps(3); } + +#[test] +fn a_file_changed_while_the_window_stays_open_shows_without_refresh() { + /// Steps of the harness's quarter second: over the window's half-second check + const FRAMES: usize = 4; + + let dir = TempDir::new("resources-updater-idle"); + let file = png(&dir, "bricks.png", 4); + let mut h = app(); + import(&mut h, &file); + activate(&mut h, "Resources Updater"); + assert!(shows(&h, "(1 resources, 0 outdated)")); + + png(&dir, "bricks.png", 8); + h.run_steps(FRAMES); + + assert!(shows(&h, "(1 resources, 1 outdated)"), "no document change, no focus change and no Refresh"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ce32a426..50825541 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -474,7 +474,7 @@ saved with the project): `resource.import {path}`, the images `file.importPbrFol `textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater window lists the project's image resources through these commands and checks them when it opens, on -Refresh, after changes (at most twice a second), once after a project opens and when the app gets the +Refresh, twice a second while it stays open, once after a project opens and when the app gets the focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of outdated resources differs from the last notice. A file whose size matches but whose time changed is read once; its verdict is kept until its size or time changes again. From e26002d230ed7be816860a36bccbb39ea14b8ef2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 16:49:07 +0100 Subject: [PATCH 035/190] Open the window through Xwayland for a pen on Wayland winit 0.30 doesn't bind the Wayland tablet protocol, so on compositors that don't emulate a pointer for the pen (KWin) the pen did nothing in the window. With a pen attached on a Wayland desktop, and Xwayland able to run the window, the app now opens on X11, where the pen works as the pointer. TEXTURECRAFT_NATIVE_WAYLAND=1 keeps native Wayland. Adapted from PhotoCraft. Fixes #816. --- ATTRIBUTION.md | 1 + apps/texturecraft/Cargo.toml | 5 + apps/texturecraft/src/main.rs | 10 ++ apps/texturecraft/src/xwayland_pen.rs | 150 ++++++++++++++++++++++++++ docs/features.md | 3 + 5 files changed, 169 insertions(+) create mode 100644 apps/texturecraft/src/xwayland_pen.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a136498a..1cf696d9 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -26,6 +26,7 @@ licensed and keep their license file next to them. | `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | +| `apps/texturecraft/src/xwayland_pen.rs` | Pen on Wayland opens the window through Xwayland: pen detection, the Xwayland decision and the X11 library check (adapted, reduced to the pen decision) | PhotoCraft contributors | storytold/photocraft `830316b775f1f6734498ac6e39fd1298955ff93f`: [`apps/photocraft/src/tablet.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/tablet.rs), [`apps/photocraft/src/linux_libs.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/linux_libs.rs) | MIT OR Apache-2.0 | ## Third-party assets compiled into the binary diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 7f5ee538..39fb3c7c 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -35,6 +35,11 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user", "s # The update helper is a copy of this program (`main`). craft-update = { workspace = true } +# Opening the window through Xwayland for a pen on Wayland (src/xwayland_pen.rs): winit's +# `EventLoopBuilderExtX11`. Already in Cargo.lock through eframe. +[target.'cfg(target_os = "linux")'.dependencies] +winit = { version = "0.30", default-features = false, features = ["x11"] } + # Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not. [target.'cfg(target_os = "macos")'.dependencies] craft-menu = { workspace = true } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 349b9275..e7bf7a7b 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -15,6 +15,8 @@ mod nightly_session; mod process_identity; mod profile_root; mod window_frame; +#[cfg(target_os = "linux")] +mod xwayland_pen; use std::ffi::OsString; @@ -398,6 +400,14 @@ fn main() { } let viewport = title_bar.viewport(viewport); let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; + // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; a pen works only through Xwayland there + #[cfg(target_os = "linux")] + if xwayland_pen::opens_through_xwayland() { + use winit::platform::x11::EventLoopBuilderExtX11 as _; + options.event_loop_builder = Some(Box::new(|builder| { + builder.with_x11(); + })); + } if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) { fatal(&e.to_string(), true); std::process::exit(2); diff --git a/apps/texturecraft/src/xwayland_pen.rs b/apps/texturecraft/src/xwayland_pen.rs new file mode 100644 index 00000000..6c3f7d3a --- /dev/null +++ b/apps/texturecraft/src/xwayland_pen.rs @@ -0,0 +1,150 @@ +//! A pen on a Wayland desktop opens the window through Xwayland (#816). +//! +//! Wayland compositors give a pen only to clients that bind the tablet protocol (`zwp_tablet_v2`), +//! which winit 0.30 doesn't (and binding it on winit's connection needs `unsafe`, which this app +//! forbids). Some compositors (KWin) then send the window nothing from the pen: no cursor, no +//! painting. Xwayland binds the protocol and serves the pen as an X11 pointer, so with a pen +//! attached the window opens there. `TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland. +//! +//! Adapted from PhotoCraft (storytold/photocraft `830316b7`, MIT OR Apache-2.0): +//! `apps/photocraft/src/tablet.rs` (`display_session`, `pen_needs_xwayland`, `has_pen`, `bit_set`) +//! and `apps/photocraft/src/linux_libs.rs` (`session_from_env`, `ldconfig_has`, the library +//! search), reduced to the pen decision. Replace it with a shared craft-libs crate once one exists +//! (AGENTS.md rule 9). + +use std::path::{Path, PathBuf}; + +/// Set (and not `0`) to keep native Wayland with a pen attached +const NATIVE_WAYLAND_VARIABLE: &str = "TEXTURECRAFT_NATIVE_WAYLAND"; + +/// `BTN_TOOL_PEN` (linux/input-event-codes.h): the key a tablet's stylus, a pen display's or a +/// pen-enabled touchscreen's pen reports +const BTN_TOOL_PEN: u32 = 0x140; + +/// `ABS_X` and `ABS_Y` (linux/input-event-codes.h): the absolute axes every pen reports +const ABS_X: u32 = 0x00; +const ABS_Y: u32 = 0x01; + +/// What winit 0.30 loads at run time for an X11 window: Xlib, Xlib-xcb, xcb, Xcursor, XInput2 and +/// xkbcommon with its X11 part +const X11_LIBRARIES: &[&str] = + &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; + +/// Whether the window opens through Xwayland: a pen is attached on a Wayland desktop and Xwayland +/// can run the window. Says so on stderr when it does. +pub fn opens_through_xwayland() -> bool { + let var = |name: &str| std::env::var(name).ok(); + let pen = || std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)); + if !pen_needs_xwayland(var, pen, x11_libraries_available) { + return false; + } + + eprintln!("texturecraft: opening the window through Xwayland for the pen ({NATIVE_WAYLAND_VARIABLE}=1 keeps Wayland)"); + true +} + +/// [`opens_through_xwayland`]'s decision. winit picks Wayland when `WAYLAND_DISPLAY` or +/// `WAYLAND_SOCKET` is set; Xwayland needs `DISPLAY`. The system probes run only on Wayland. +fn pen_needs_xwayland(var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool, x11_libraries: impl FnOnce() -> bool) -> bool { + let set = |name: &str| var(name).is_some_and(|value| !value.is_empty()); + let wayland = set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET"); + let keeps_wayland = var(NATIVE_WAYLAND_VARIABLE).is_some_and(|value| !value.is_empty() && value != "0"); + wayland && !keeps_wayland && set("DISPLAY") && pen() && x11_libraries() +} + +/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen's `B: KEY=` bitmap has +/// `BTN_TOOL_PEN` and its `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as libinput asks of a tablet +/// tool. The key alone isn't enough: a virtual keyboard made with uinput claims every key code. +fn has_pen(devices: &str) -> bool { + devices.split("\n\n").any(|device| { + let bitmap = |name: &str| device.lines().find_map(|line| line.strip_prefix(name)); + bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)) + }) +} + +/// Bit `bit` of a `/proc/bus/input/devices` bitmap: hex words of the kernel's `long`, most +/// significant first. Short or malformed bitmaps have no bits set. +fn bit_set(bitmap: &str, bit: u32) -> bool { + let word_bits = usize::BITS; + let word = usize::try_from(bit / word_bits).unwrap_or(usize::MAX); + bitmap.split_whitespace().rev().nth(word).and_then(|hex| u64::from_str_radix(hex, 16).ok()).is_some_and(|value| (value >> (bit % word_bits)) & 1 == 1) +} + +/// Are the libraries an X11 window needs installed? The linker cache (`ldconfig -p`) or the usual +/// library directories must list each; one that can't be found counts as missing. +fn x11_libraries_available() -> bool { + let cache = linker_cache(); + let dirs = library_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref()); + X11_LIBRARIES.iter().all(|soname| cache.as_deref().is_some_and(|cache| ldconfig_has(cache, soname)) || dirs.iter().any(|dir| dir.join(soname).exists())) +} + +/// `ldconfig -p` in English (it is parsed), from where distributions put it +fn linker_cache() -> Option { + ["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"].into_iter().find_map(|command| { + let output = std::process::Command::new(command).arg("-p").env("LC_ALL", "C").output().ok()?; + output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned()) + }) +} + +/// Does an `ldconfig -p` listing have `soname` for this build's architecture? Lines look like +/// `\tlibXi.so.6 (libc6,x86-64) => /lib/x86_64-linux-gnu/libXi.so.6`. +fn ldconfig_has(cache: &str, soname: &str) -> bool { + let architecture = if cfg!(target_arch = "x86_64") { + Some("x86-64") + } else if cfg!(target_arch = "aarch64") { + Some("AArch64") + } else { + None + }; + + cache.lines().any(|line| { + let Some((name, rest)) = line.trim_start().split_once(' ') else { return false }; + let flags = rest.split_once('(').and_then(|(_, after)| after.split_once(')')).map_or("", |(flags, _)| flags); + name == soname && architecture.is_none_or(|tag| flags.split(',').any(|flag| flag.trim() == tag)) + }) +} + +/// `LD_LIBRARY_PATH`, then the usual system and Flatpak library directories +fn library_dirs(ld_library_path: Option<&str>) -> Vec { + let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else { "x86_64-linux-gnu" }; + let mut dirs: Vec = ld_library_path.into_iter().flat_map(|value| value.split(':')).filter(|dir| !dir.is_empty()).map(PathBuf::from).collect(); + dirs.extend(["/app/lib", "/usr/local/lib", "/usr/lib64", "/lib64", "/usr/lib", "/lib"].map(PathBuf::from)); + dirs.extend([Path::new("/usr/lib").join(triplet), Path::new("/lib").join(triplet)]); + dirs +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A touchpad (`BTN_TOOL_FINGER`, no pen) and a Wacom pen, from `/proc/bus/input/devices` + const TOUCHPAD: &str = "N: Name=\"SYNA2B33:00 06CB:CE26 Touchpad\"\nB: KEY=e520 10000 0 0 0 0\nB: ABS=2e0800000000003\n"; + const PEN: &str = "N: Name=\"Wacom Intuos Pro M Pen\"\nB: KEY=1c03 0 0 0 0 0\nB: ABS=1000f000003\n"; + + /// A uinput keyboard (RustDesk's) claims every key, `BTN_TOOL_PEN` included, with no axes + const VIRTUAL_KEYBOARD: &str = "N: Name=\"RustDesk UInput Keyboard\"\nB: EV=20013\nB: KEY=ffffffffff 0 7ffffff000301ff 1000f7fffffff 7fe001fffff000f 7ffffffffffffff ffffffff0003fdff 7fff8fff00ff03ff 1ffffffffffff07 ffffffffffffffff ffffffffffefffff fffffffffffffffe\n"; + + #[test] + fn a_pen_is_a_device_with_the_pen_key_and_absolute_axes() { + assert!(has_pen(&format!("{TOUCHPAD}\n{PEN}"))); + assert!(!has_pen(TOUCHPAD), "a touchpad is no pen"); + assert!(!has_pen(&format!("{VIRTUAL_KEYBOARD}\n{TOUCHPAD}")), "a keyboard claiming the pen key has no pen axes"); + assert!(!has_pen("B: KEY=zz 0 0 0 0 0\nB: ABS=3\n"), "a malformed bitmap is no pen"); + } + + #[test] + fn a_pen_on_wayland_opens_the_window_through_xwayland() { + fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string()) + } + const WAYLAND: &[(&str, &str)] = &[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]; + + assert!(pen_needs_xwayland(env(WAYLAND), || true, || true)); + assert!(!pen_needs_xwayland(env(WAYLAND), || false, || true), "no pen"); + assert!(!pen_needs_xwayland(env(WAYLAND), || true, || false), "no X11 libraries"); + assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0")]), || true, || true), "no Xwayland"); + assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "1")]), || true, || true), "kept"); + assert!(pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "0")]), || true, || true)); + assert!(!pen_needs_xwayland(env(&[("DISPLAY", ":0")]), || panic!("probed off Wayland"), || panic!("probed off Wayland")), "X11 already has the pen"); + } +} diff --git a/docs/features.md b/docs/features.md index 42ea07a6..e08582dc 100644 --- a/docs/features.md +++ b/docs/features.md @@ -255,6 +255,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same strip, and Settings › General › Appearance › System title bar for the system's frame instead. +- **A pen on a Linux Wayland desktop** opens the window through Xwayland, where the pen moves the + cursor and paints (some compositors send a pen nothing in a native Wayland window); + `TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland. - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed them. The right bar's panels (Export, Log, Display Settings, Shader Settings, History) pop out beside it; *Undock* makes one a floating window, and its *Dock* button puts it back on the bar. From fbff8906f4a1f3ea442304138998e780712dbd3b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 18:40:24 +0100 Subject: [PATCH 036/190] Resources Updater: row ids follow the resource name, so the keyboard focus stays with its row --- crates/ui-egui/src/resources_updater.rs | 5 +++- crates/ui-egui/tests/it/resources_updater.rs | 24 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 95840c26..21cf648b 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -254,7 +254,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(tr("No resources match the filters")); } for (index, row) in visible.into_iter().enumerate() { - if let Some(asked) = row_ui(app, ui, &tokens, index + 1, row) { + // Ids from the name alone, so the keyboard focus stays with its resource when a check reorders the rows + let row_scope = egui::UiBuilder::new().scope_id(ui.scope_id().with(("resources_updater_row", &row.name))); + let asked = ui.scope_builder(row_scope, |ui| row_ui(app, ui, &tokens, index + 1, row)).inner; + if let Some(asked) = asked { request = Some(asked); } } diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 980102a9..20609aec 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -186,3 +186,27 @@ fn a_file_changed_while_the_window_stays_open_shows_without_refresh() { assert!(shows(&h, "(1 resources, 1 outdated)"), "no document change, no focus change and no Refresh"); } + +#[test] +fn the_keyboard_focus_stays_with_its_resource_when_the_rows_reorder() { + /// Steps of the harness's quarter second: over the window's half-second check + const FRAMES: usize = 4; + const SELECT_LATER: &str = "Select new resource zz_later.png"; + + let dir = TempDir::new("resources-updater-focus"); + let (earlier, later) = (png(&dir, "aa_earlier.png", 4), png(&dir, "zz_later.png", 4)); + let mut h = app(); + import(&mut h, &earlier); + import(&mut h, &later); + activate(&mut h, "Resources Updater"); + h.get_by_role_and_label(Role::Button, SELECT_LATER).focus(); + h.run_steps(2); + + // The changed file moves to the top of the list + png(&dir, "zz_later.png", 8); + h.run_steps(FRAMES); + + let rows = &h.state().ui.windows.resources_updater.as_ref().unwrap().rows; + assert_eq!(rows[0].name, "zz_later.png", "the outdated resource moved up"); + assert!(h.get_by_role_and_label(Role::Button, SELECT_LATER).accesskit_node().is_focused(), "the focus moved with it"); +} From 26c28febfef7bb25361f0fedfb8e129009146f56 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:45:34 +0000 Subject: [PATCH 037/190] Assets: right-click menu with the asset's info and Export resource Every tile's menu starts with what the asset is: Name, Usages, Path and, where it has one, Category; a long path is cut in the middle. Export resource writes an image resource's file as it was imported (new resource.export command); built-ins have no file and show it greyed. Add as decal and Remove resource stay for project images. Close closes. Part of #411 --- crates/engine/src/resource_cmds.rs | 32 +++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 15 +-- crates/ui-egui/src/shelf_entry.rs | 17 ++- crates/ui-egui/src/shelf_menu.rs | 173 ++++++++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_menu.rs | 67 ++++++++++ 7 files changed, 292 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/src/shelf_menu.rs create mode 100644 crates/ui-egui/tests/it/shelf_menu.rs diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 39d9fb6c..d81263d5 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -24,6 +24,7 @@ pub fn specs() -> Vec { ), cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), + cmd!("resource.export", "Export resource", [], None, "{name, path} — the resource's file as it was imported", always, export), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), cmd!( "layer.add.image", @@ -261,6 +262,24 @@ fn remove(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Writes resource `name`'s bytes, as imported, to `path` +#[cfg(not(target_arch = "wasm32"))] +fn export(s: &mut Session, p: &Value) -> Result { + let command = "resource.export"; + let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?; + let path = strp(p, "path").ok_or_else(|| bad(command, "`path` is required"))?; + let bytes = s.doc.resources.get(name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?; + + std::fs::write(path, bytes.as_slice()).map_err(|error| bad(command, format!("cannot write {path}: {error}")))?; + + Ok(json!({ "path": path })) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.export", "file paths are not available in the browser")) +} + /// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) fn remove_unused(s: &mut Session, _: &Value) -> Result { let mut used = Vec::new(); @@ -331,6 +350,19 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + #[test] + fn export_writes_the_imported_bytes() { + let mut session = crate::sample_session(128, 32).unwrap(); + let bytes = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let name = session.import_resource_bytes("icon.png", bytes.clone()).unwrap(); + let path = std::env::temp_dir().join(format!("texturecraft-export-resource-{}.png", std::process::id())); + + crate::commands::execute(&mut session, "resource.export", &json!({"name": name, "path": path.to_str().unwrap()})).unwrap(); + + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is the resource as imported"); + std::fs::remove_file(path).unwrap(); + } + #[test] fn file_reads_obey_the_remaining_byte_budget() { let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9bc2866a..ab8d1b99 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -139,6 +139,7 @@ pub mod shader_settings; pub mod shelf; mod shelf_entry; mod shelf_folders; +mod shelf_menu; pub mod shelf_panes; pub mod shelf_preview; mod shelf_tabs; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 3416a106..9099a2f9 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -514,7 +514,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str, _: bool) {} -/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu +/// The tile of `entry`, outlined when `selected`: a click applies it, a right-click opens its menu fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) { // An image removed this frame has nothing to show if let ShelfEntry::Image(name) = entry @@ -557,18 +557,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry entry.activate(app); } - if let ShelfEntry::Image(name) = entry { - response.context_menu(|ui| { - if ui.button(tr("Add as decal (view center)")).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); - } - if ui.button(tr("Remove resource")).clicked() { - app.run("resource.remove", json!({"name": name})); - ui.close(); - } - }); - } + crate::shelf_menu::show(app, &response, entry); } /// Asset tile with optional dragging and a larger hover preview, at the medium size diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 66774efc..32669e7f 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -13,7 +13,7 @@ use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask}; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{n_, tr}; use crate::shelf::{Asset, Tab, apply}; use crate::shelf_preview::ShelfPreview; @@ -124,6 +124,21 @@ impl ShelfEntry { path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have) } + /// What the asset is used as, lowercase (English, shown through `tr`): the menu's Usages row + pub(crate) fn usage(&self) -> &'static str { + match self { + ShelfEntry::Material(material) if material.smart => n_("smart material"), + ShelfEntry::Material(_) => n_("material"), + ShelfEntry::SmartMask(_) => n_("smart mask"), + ShelfEntry::Filter(_) => n_("filter"), + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush { .. } => n_("brush"), + ShelfEntry::Alpha(_) => n_("alpha"), + ShelfEntry::Procedural(_) => n_("procedural"), + ShelfEntry::Environment(_) => n_("environment"), + ShelfEntry::Image(_) => n_("texture"), + } + } + /// The name under the tile, translated where the asset's name is pub(crate) fn label(&self) -> &str { match self { diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs new file mode 100644 index 00000000..22d2af95 --- /dev/null +++ b/crates/ui-egui/src/shelf_menu.rs @@ -0,0 +1,173 @@ +//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it + +use egui::{Align2, Color32, CornerRadius, FontId, Response, Sense, Ui, pos2, vec2}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf_entry::{LIBRARIES, ShelfEntry}; +use crate::theme::Tokens; + +/// A menu row's height and the inset of its hover face from the menu's sides, in points +const ROW_HEIGHT: f32 = 24.0; +const HOVER_INSET: f32 = 3.0; +const HOVER_ROUNDING: u8 = 3; +/// Where a row's text starts, from the menu's left edge, in points +const TEXT_X: f32 = 10.0; +/// The space after the text of the widest row, in points +const RIGHT_PADDING: f32 = 24.0; +/// The air between the info block's label column and its values, in points +const LABEL_GAP: f32 = 12.0; +/// The widest the info block's values get before the path is cut in the middle, in points +const MAX_VALUE_WIDTH: f32 = 220.0; +/// The menu's text size, in points +const TEXT_SIZE: f32 = 12.0; +/// The air above and below the separators, in points +const SEPARATOR_SPACE: f32 = 3.0; + +/// The right-click menu on the tile whose response is `response` +pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) { + response.context_menu(|ui| { + let tokens = Tokens::get(ui.ctx()); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let info = info_rows(entry); + let width = menu_width(ui, &info, &row_labels(entry)); + ui.set_width(width); + info_block(ui, width, &info, &tokens); + separator(ui, &tokens); + + if let ShelfEntry::Image(name) = entry { + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_image(app, name); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } + if row(ui, width, tr("Remove resource"), true, &tokens).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); + } + } else { + row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); + } + + separator(ui, &tokens); + if row(ui, width, tr("Close"), true, &tokens).clicked() { + ui.close(); + } + }); +} + +/// The info block's label and value rows: rows only where the asset has the data +fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { + let path = entry.path(); + let shown_path: Vec<&str> = path.iter().map(|part| LIBRARIES.iter().find(|(id, _)| id == part).map_or_else(|| tr(part), |(_, name)| tr(name))).collect(); + let mut rows = + vec![(tr("Name"), entry.label().to_string()), (tr("Usages"), tr(entry.usage()).to_string()), (tr("Path"), format!("/{}/", shown_path.join("/")))]; + if let Some(category) = path.get(2) { + rows.push((tr("Category"), tr(category).to_string())); + } + rows +} + +/// The labels of the rows under the info block, for the menu's width +fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { + let mut labels = vec![tr("Export resource..."), tr("Close")]; + if matches!(entry, ShelfEntry::Image(_)) { + labels.extend([tr("Add as decal (view center)"), tr("Remove resource")]); + } + labels +} + +fn text_width(ui: &Ui, text: &str) -> f32 { + ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x) +} + +/// The label column's width: the longest label and its gap +fn label_column(ui: &Ui, info: &[(&str, String)]) -> f32 { + info.iter().map(|(label, _)| text_width(ui, label)).fold(0.0, f32::max) + LABEL_GAP +} + +/// The widest row, the info block's values capped at [`MAX_VALUE_WIDTH`] +fn menu_width(ui: &Ui, info: &[(&str, String)], labels: &[&str]) -> f32 { + let widest_value = info.iter().map(|(_, value)| text_width(ui, value)).fold(0.0, f32::max).min(MAX_VALUE_WIDTH); + let widest_row = labels.iter().map(|label| text_width(ui, label)).fold(0.0, f32::max); + TEXT_X + (label_column(ui, info) + widest_value).max(widest_row) + RIGHT_PADDING +} + +/// The label (dim) and value rows; a value too wide is cut in the middle with "…" +fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) { + let column = label_column(ui, info); + let value_width = width - TEXT_X - column - RIGHT_PADDING; + for (label, value) in info { + let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); + let shown = cut_middle(ui, value, value_width); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label} {value}"))); + let painter = ui.painter(); + painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, *label, FontId::proportional(TEXT_SIZE), tokens.text_dim); + painter.text(pos2(rect.left() + TEXT_X + column, rect.center().y), Align2::LEFT_CENTER, shown, FontId::proportional(TEXT_SIZE), tokens.text); + } +} + +/// `text`, or its start and end around "…" so it fits `width` points +fn cut_middle(ui: &Ui, text: &str, width: f32) -> String { + if text_width(ui, text) <= width { + return text.to_owned(); + } + + let chars: Vec = text.chars().collect(); + let mut kept = chars.len(); + loop { + let head = kept.div_ceil(2); + let tail = kept / 2; + let cut: String = chars[..head].iter().chain(['…'].iter()).chain(chars[chars.len() - tail..].iter()).collect(); + if kept == 0 || text_width(ui, &cut) <= width { + return cut; + } + + kept -= 1; + } +} + +/// A hairline across the menu between groups of rows +fn separator(ui: &mut Ui, tokens: &Tokens) { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), SEPARATOR_SPACE * 2.0 + 1.0), Sense::hover()); + ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, tokens.separator)); +} + +/// One menu row: a hover face inset from the sides, its text dim and unclickable when not `enabled` +fn row(ui: &mut Ui, width: f32, label: &str, enabled: bool, tokens: &Tokens) -> Response { + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); + let painter = ui.painter(); + if enabled && (response.hovered() || response.has_focus()) { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button); + } + let color = if enabled { tokens.text } else { tokens.text_dim }; + painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), color); + if enabled { response } else { response.on_hover_cursor(egui::CursorIcon::NotAllowed) } +} + +/// Asks where to save image resource `name`, then writes it there as imported +#[cfg(not(target_arch = "wasm32"))] +fn export_image(app: &mut TextureCraftApp, name: &str) { + use crate::file_dialogs::{Bound, FileDialog}; + + let extension = std::path::Path::new(name).extension().and_then(|extension| extension.to_str()).unwrap_or_default().to_owned(); + let name = name.to_owned(); + let dialog = FileDialog::save().filter(tr("Image"), &[extension.as_str()]).file_name(&name); + app.ask_file(dialog, Bound::Project, move |app, paths| { + if let Some(path) = paths.first() { + app.run("resource.export", json!({"name": name, "path": path.to_string_lossy()})); + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn export_image(app: &mut TextureCraftApp, _: &str) { + app.toast(tr("Exporting resources needs the desktop app"), true); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c8d7f0f3..fd55514b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -81,6 +81,7 @@ mod settings_window; mod shelf_click; mod shelf_drop; mod shelf_hover_preview; +mod shelf_menu; mod shelf_panel; mod shift_lines_2d; mod shift_lines_3d; diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs new file mode 100644 index 00000000..1acc99ae --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -0,0 +1,67 @@ +//! An asset tile's right-click menu: the info block says what the asset is, and its rows act on it + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::materials::MATERIALS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; + +/// The types' positions in the shelf's type row (its table is crate-private) +const MATERIALS_TYPE: usize = 0; +const TEXTURES_TYPE: usize = 6; + +/// The sample project with the shelf on type `tab` +fn shelf(tab: usize) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = tab; + harness.run_steps(4); + harness +} + +fn right_click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no tile {label}")).click_secondary(); + harness.run_steps(3); +} + +#[test] +fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() { + // The grid's first plain material (by name), so its tile is in view + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = shelf(MATERIALS_TYPE); + + right_click(&mut harness, material.label); + + for row in [ + format!("Name {}", material.label), + "Usages material".to_string(), + format!("Path /Starter assets/Materials/{}/", material.category), + format!("Category {}", material.category), + ] { + assert!(harness.query_by_label(&row).is_some(), "the menu has the info row {row:?}"); + } + assert!(harness.get_by_label("Export resource...").accesskit_node().is_disabled(), "a built-in has no file to export"); + + harness.get_by_label("Close").click(); + harness.run_steps(3); + assert!(harness.query_by_label("Usages material").is_none(), "Close closes the menu"); +} + +#[test] +fn export_resource_writes_the_image_as_imported() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes.clone()).unwrap(); + harness.run_steps(3); + let dir = super::temp_dir::TempDir::new("shelf-export-resource"); + let target = dir.join("exported.png"); + let answer = target.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + + right_click(&mut harness, &name); + harness.get_by_label("Export resource...").click(); + harness.run_steps(4); + + assert_eq!(std::fs::read(&target).unwrap(), bytes, "the exported file is the resource's own bytes"); +} From 2bc7f69dcad33ad8b8a298e167bcbcf23369c051 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:03:25 +0000 Subject: [PATCH 038/190] Assets: rename, replace, delete and export saved brushes from their menu A saved brush's right-click menu has its Name as a field: Enter or a click elsewhere renames the brush, Escape keeps the name. Below the info block: Replace with the current brush and Delete, then Export resource, which writes the preset as a .tcbrush file (new brush.preset.export command). For project images, Delete takes the place of Remove resource and moves up beside the other actions on the image itself. Part of #411 --- crates/engine/src/brush_preset_cmds.rs | 54 ++++++++++ crates/ui-egui/src/shelf_menu.rs | 139 +++++++++++++++++++++---- crates/ui-egui/tests/it/shelf_menu.rs | 62 +++++++++++ 3 files changed, 234 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 28d96d7b..f2f23a67 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -146,6 +146,15 @@ pub fn specs() -> Vec { cmd!("brush.preset.delete", "Delete a brush preset", [], None, "{name} — one of the user's presets (built-ins are read-only)", always, delete), cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save), cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load), + cmd!( + "brush.preset.export", + "Export brush preset", + [], + None, + "{name, path} — one of the user's presets as a .tcbrush file, as its library folder holds it", + always, + export + ), ] } @@ -325,6 +334,26 @@ fn load(_: &mut Session, _: &Value) -> Result { Err(bad("brush.preset.load", "file paths are not available in the browser")) } +/// Writes user preset `name` to `path` as the library folder holds it +#[cfg(not(target_arch = "wasm32"))] +fn export(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "brush.preset.export"; + let name = name_param(params, "name", CMD)?; + let path = strp(params, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; + let preset = session.brush_presets.find(&name).and_then(|index| session.brush_presets.list.get(index)); + let preset = preset.ok_or_else(|| bad(CMD, format!("no user brush preset `{name}`")))?; + let bytes = serde_json::to_vec_pretty(preset).map_err(|error| bad(CMD, error.to_string()))?; + + std::fs::write(path, bytes).map_err(|error| bad(CMD, format!("cannot write {path}: {error}")))?; + + Ok(json!({ "path": path })) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &Value) -> Result { + Err(bad("brush.preset.export", "file paths are not available in the browser")) +} + #[cfg(test)] mod tests { use super::*; @@ -406,6 +435,31 @@ mod tests { assert_eq!(names(&test_session), ["a/b"]); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_exported_preset_loads_as_the_same_brush() { + let dir = std::env::temp_dir().join(format!("tc-brush-export-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut test_session = session(); + run(&mut test_session, "tool.brush", json!({"size": 41, "hardness": 70})).unwrap(); + run(&mut test_session, "brush.preset.store", json!({"name": "Ink pen"})).unwrap(); + run(&mut test_session, "tool.brush", json!({"size": 5})).unwrap(); + + let path = dir.join("shared.tcbrush"); + run(&mut test_session, "brush.preset.export", json!({"name": "ink pen", "path": path.to_str().unwrap()})).unwrap(); + + let mut fresh = session(); + assert!(fresh.load_brush_presets(dir.clone()).is_empty()); + assert_eq!(names(&fresh), ["Ink pen"], "the file carries the preset's name"); + assert_eq!(fresh.brush_presets.list[0].brush, test_session.brush_presets.list[0].brush, "the stored brush, not the current one"); + assert!( + run(&mut test_session, "brush.preset.export", json!({"name": "Airbrush", "path": path.to_str().unwrap()})).is_err(), + "built-ins are not exported" + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn presets_persist_in_the_folder() { diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index 22d2af95..35a7ba49 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -1,4 +1,4 @@ -//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it +//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it; the Name of an asset the user owns is a field that renames it use egui::{Align2, Color32, CornerRadius, FontId, Response, Sense, Ui, pos2, vec2}; use serde_json::json; @@ -22,36 +22,74 @@ const LABEL_GAP: f32 = 12.0; const MAX_VALUE_WIDTH: f32 = 220.0; /// The menu's text size, in points const TEXT_SIZE: f32 = 12.0; +/// The Name field's row and field heights, and the air before its text, in points +const FIELD_ROW_HEIGHT: f32 = 28.0; +const FIELD_HEIGHT: f32 = 24.0; +const FIELD_TEXT_INSET: f32 = 8.0; /// The air above and below the separators, in points const SEPARATOR_SPACE: f32 = 3.0; /// The right-click menu on the tile whose response is `response` pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) { - response.context_menu(|ui| { + // Clicks inside keep the menu open, so the Name field can be typed in; its rows close it themselves + let menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + menu.show(|ui| { let tokens = Tokens::get(ui.ctx()); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let info = info_rows(entry); let width = menu_width(ui, &info, &row_labels(entry)); ui.set_width(width); - info_block(ui, width, &info, &tokens); + let column = label_column(ui, &info); + + // A saved brush is the user's own: its Name row is a field that renames it + let mut shown_info = info.as_slice(); + if let ShelfEntry::SavedBrush { name, .. } = entry + && let Some((_, rest)) = info.split_first() + { + shown_info = rest; + let field_id = ui.make_persistent_id(("asset_name", entry.identity())); + if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) { + app.run("brush.preset.rename", json!({"name": name, "to": renamed})); + } + } + info_block(ui, width, column, shown_info, &tokens); separator(ui, &tokens); - if let ShelfEntry::Image(name) = entry { - if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { - export_image(app, name); - ui.close(); + match entry { + ShelfEntry::Image(name) => { + if row(ui, width, tr("Delete"), true, &tokens).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_image(app, name); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } } - separator(ui, &tokens); - if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); + ShelfEntry::SavedBrush { name, .. } => { + if row(ui, width, tr("Replace with the current brush"), true, &tokens).clicked() { + app.run("brush.preset.store", json!({"name": name, "overwrite": true})); + ui.close(); + } + if row(ui, width, tr("Delete"), true, &tokens).clicked() { + app.run("brush.preset.delete", json!({"name": name})); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_brush(app, name); + ui.close(); + } } - if row(ui, width, tr("Remove resource"), true, &tokens).clicked() { - app.run("resource.remove", json!({"name": name})); - ui.close(); + _ => { + row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } - } else { - row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } separator(ui, &tokens); @@ -76,8 +114,10 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { let mut labels = vec![tr("Export resource..."), tr("Close")]; - if matches!(entry, ShelfEntry::Image(_)) { - labels.extend([tr("Add as decal (view center)"), tr("Remove resource")]); + match entry { + ShelfEntry::Image(_) => labels.extend([tr("Delete"), tr("Add as decal (view center)")]), + ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), + _ => {} } labels } @@ -98,9 +138,8 @@ fn menu_width(ui: &Ui, info: &[(&str, String)], labels: &[&str]) -> f32 { TEXT_X + (label_column(ui, info) + widest_value).max(widest_row) + RIGHT_PADDING } -/// The label (dim) and value rows; a value too wide is cut in the middle with "…" -fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) { - let column = label_column(ui, info); +/// The label (dim) and value rows, values `column` points after the labels; a value too wide is cut in the middle with "…" +fn info_block(ui: &mut Ui, width: f32, column: f32, info: &[(&str, String)], tokens: &Tokens) { let value_width = width - TEXT_X - column - RIGHT_PADDING; for (label, value) in info { let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); @@ -112,6 +151,44 @@ fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) } } +/// The Name row of an asset the user owns: a field in the value column that returns the new name once typing ends (Enter or a click elsewhere) with a changed, non-blank name. Escape keeps the old one +fn name_field(ui: &mut Ui, width: f32, column: f32, field_id: egui::Id, name: &str, tokens: &Tokens) -> Option { + let (rect, _) = ui.allocate_exact_size(vec2(width, FIELD_ROW_HEIGHT), Sense::hover()); + let label = tr("Name"); + ui.painter().text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), tokens.text_dim); + + // Check raw Escape even if the menu consumed it + let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if escaped { + ui.data_mut(|data| data.remove::(field_id)); + } + let mut text = ui.data(|data| data.get_temp::(field_id)).unwrap_or_else(|| name.to_owned()); + + // The field's text lines up with the values below it + let field = egui::Rect::from_min_max( + pos2(rect.left() + TEXT_X + column - FIELD_TEXT_INSET, rect.center().y - FIELD_HEIGHT / 2.0), + pos2(rect.right() - TEXT_X, rect.center().y + FIELD_HEIGHT / 2.0), + ); + ui.painter().rect(field, CornerRadius::same(HOVER_ROUNDING), tokens.field, egui::Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let edit = egui::TextEdit::singleline(&mut text) + .id(field_id) + .font(FontId::proportional(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(FIELD_TEXT_INSET as i8, 0))) + .align(Align2::LEFT_CENTER); + let response = ui.new_child(egui::UiBuilder::new().max_rect(field.shrink(1.0))).add_sized(field.shrink(1.0).size(), edit); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, label)); + + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(field_id, text)); + return None; + } + + ui.data_mut(|data| data.remove::(field_id)); + let typed = text.trim(); + (response.lost_focus() && !escaped && !typed.is_empty() && typed != name).then(|| typed.to_owned()) +} + /// `text`, or its start and end around "…" so it fits `width` points fn cut_middle(ui: &Ui, text: &str, width: f32) -> String { if text_width(ui, text) <= width { @@ -171,3 +248,23 @@ fn export_image(app: &mut TextureCraftApp, name: &str) { fn export_image(app: &mut TextureCraftApp, _: &str) { app.toast(tr("Exporting resources needs the desktop app"), true); } + +/// Asks where to save saved brush `name`, then writes it there as a brush preset file +#[cfg(not(target_arch = "wasm32"))] +fn export_brush(app: &mut TextureCraftApp, name: &str) { + use crate::file_dialogs::{Bound, FileDialog}; + use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + + let name = name.to_owned(); + let dialog = FileDialog::save().filter(tr("Brush preset"), &[BRUSH_EXT]).file_name(format!("{name}.{BRUSH_EXT}")); + app.ask_file(dialog, Bound::App, move |app, paths| { + if let Some(path) = paths.first() { + app.run("brush.preset.export", json!({"name": name, "path": path.to_string_lossy()})); + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn export_brush(app: &mut TextureCraftApp, _: &str) { + app.toast(tr("Exporting resources needs the desktop app"), true); +} diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 1acc99ae..51b7bdae 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -1,13 +1,16 @@ //! An asset tile's right-click menu: the info block says what the asset is, and its rows act on it +use egui::{Key, Modifiers}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; use texturecraft_engine::materials::MATERIALS; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::Answer; /// The types' positions in the shelf's type row (its table is crate-private) const MATERIALS_TYPE: usize = 0; +const BRUSHES_TYPE: usize = 4; const TEXTURES_TYPE: usize = 6; /// The sample project with the shelf on type `tab` @@ -65,3 +68,62 @@ fn export_resource_writes_the_image_as_imported() { assert_eq!(std::fs::read(&target).unwrap(), bytes, "the exported file is the resource's own bytes"); } + +fn preset_names(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.brush_presets.list.iter().map(|preset| preset.name.clone()).collect() +} + +/// Selects the menu's Name field text and types `text` +fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + harness.get_by_role_and_label(egui::Role::TextInput, "Name").click(); + harness.run_steps(3); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(3); +} + +#[test] +fn a_saved_brush_menu_renames_replaces_and_deletes_it() { + // A name that sorts before every built-in brush, so its tile is in view + let mut harness = shelf(BRUSHES_TYPE); + texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, "Aa ink"); + type_name(&mut harness, "Never applied"); + harness.key_press(Key::Escape); + harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa ink"], "Escape keeps the name"); + + right_click(&mut harness, "Aa ink"); + type_name(&mut harness, "Aa pen"); + harness.key_press(Key::Enter); + harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa pen"], "Enter renames the brush"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({"size": 77})).unwrap(); + right_click(&mut harness, "Aa pen"); + harness.get_by_label("Replace with the current brush").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.brush_presets.list[0].brush, harness.state().session.tool.brush, "the preset holds the current brush"); + + right_click(&mut harness, "Aa pen"); + harness.get_by_label("Delete").click(); + harness.run_steps(3); + assert!(preset_names(&harness).is_empty(), "Delete removes the brush"); +} + +#[test] +fn delete_removes_a_project_image() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, &name); + harness.get_by_label("Delete").click(); + harness.run_steps(3); + + assert!(!harness.state().session.doc.resources.contains_key(&name)); +} From 8abd6ead2613a39fe0f3afcde0c28147fe87329a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:24:41 +0000 Subject: [PATCH 039/190] Assets: rename and reload project images from their menu The Name row of a project image's menu is a field: resource.rename moves the image and every layer, effect, stored path, environment and tool reference to it in one undo step, and refuses rather than leave a reference behind. Reload (resource.reload) reads the image again from the file it was imported from in this session; it is greyed, with the reason, for images imported before. Undo and redo decode a resource again when the step changed its bytes. --- crates/core/src/layer.rs | 31 ++++ crates/core/src/layer/tile_generator.rs | 5 + crates/engine/src/path_tool.rs | 15 ++ crates/engine/src/resource_cmds.rs | 226 +++++++++++++++++++++++- crates/engine/src/session.rs | 46 +++++ crates/ui-egui/src/shelf_menu.rs | 22 ++- crates/ui-egui/tests/it/shelf_menu.rs | 18 ++ 7 files changed, 352 insertions(+), 11 deletions(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index e352bbc0..56a5147f 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -703,6 +703,15 @@ impl Source { } } + /// [`Source::images`], to rename them + pub fn images_mut(&mut self) -> Vec<&mut String> { + match self { + Source::Image { name, .. } => vec![name], + Source::Procedural { pattern, .. } => pattern.tile.iter_mut().flat_map(|tile| tile.images_mut()).collect(), + Source::Uniform(_) | Source::Anchor { .. } => Vec::new(), + } + } + /// The gradient map stops of a procedural or anchor source (empty: none). pub fn ramp(&self) -> &[[f32; 3]] { match self { @@ -808,6 +817,12 @@ pub struct LinkPreset { } impl Fill { + /// The image resource names the fill holds, to rename them: its sources' and, when linked, its package and cooked outputs + pub fn images_mut(&mut self) -> impl Iterator { + let link = self.link.iter_mut().map(|link| &mut **link).flat_map(|link| std::iter::once(&mut link.package).chain(link.outputs.values_mut())); + self.sources.values_mut().flat_map(Source::images_mut).chain(link) + } + /// Value used for `c` when the fill has no source for it: the channel default. pub fn source(&self, c: Channel) -> Source { self.sources.get(&c).cloned().unwrap_or_else(|| Source::uniform_of(c)) @@ -2053,6 +2068,17 @@ impl EffectKind { sources.into_iter().flat_map(Source::images).chain(id_map) } + /// [`EffectKind::images_read`], to rename them + pub fn images_mut(&mut self) -> Vec<&mut String> { + match self { + EffectKind::Fill { source, .. } => source.images_mut(), + EffectKind::Material(fill) => fill.sources.values_mut().flat_map(Source::images_mut).collect(), + EffectKind::Generator(generator) => generator.inputs.values_mut().flat_map(Source::images_mut).collect(), + EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(), + _ => Vec::new(), + } + } + /// Reads a channel of the layer or of the stack below it (a compare mask's layer sides) pub fn reads_stack(&self) -> bool { matches!(self, EffectKind::Compare { left, right, .. } if left.reads_stack() || right.reads_stack()) @@ -2115,6 +2141,11 @@ impl Effect { self.kind.images_read().chain(self.inputs.values().flat_map(Source::images)) } + /// [`Effect::images_read`], to rename them + pub fn images_mut(&mut self) -> impl Iterator { + self.kind.images_mut().into_iter().chain(self.inputs.values_mut().flat_map(Source::images_mut)) + } + /// Whether a source of the effect, or one of its image inputs, reads anchor point `anchor` (any anchor point when None) pub fn reads(&self, anchor: Option) -> bool { self.kind.reads(anchor) || self.inputs.values().any(|source| source.reads_anchor(anchor)) diff --git a/crates/core/src/layer/tile_generator.rs b/crates/core/src/layer/tile_generator.rs index 6836fcd9..94e25752 100644 --- a/crates/core/src/layer/tile_generator.rs +++ b/crates/core/src/layer/tile_generator.rs @@ -202,6 +202,11 @@ impl TileGenerator { pub fn images(&self) -> impl Iterator { self.inputs.iter().chain(&self.background_image).map(String::as_str) } + + /// [`TileGenerator::images`], to rename them + pub fn images_mut(&mut self) -> impl Iterator { + self.inputs.iter_mut().chain(&mut self.background_image) + } } impl Default for TileGenerator { diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 94b9d930..65c10a71 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -385,6 +385,21 @@ pub(crate) fn path_images(kind: &EffectKind) -> Vec { shapes.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image).collect() } +/// Points the stored paths of `kind` that paint with image resource `from` (as mask image or brush alpha) at `to` +pub(crate) fn rename_path_images(kind: &mut EffectKind, from: &str, to: &str) { + let EffectKind::Path(shapes) = kind else { return }; + + for shape in shapes { + for pointer in ["/mask_image", "/brush/alpha_image"] { + if let Some(image) = shape.paint.pointer_mut(pointer) + && image.as_str() == Some(from) + { + *image = serde_json::Value::String(to.to_string()); + } + } + } +} + /// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]) fn state_of(shape: &PathShape) -> PathState { let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect(); diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index d81263d5..da51b8ea 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -25,6 +25,24 @@ pub fn specs() -> Vec { cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), cmd!("resource.export", "Export resource", [], None, "{name, path} — the resource's file as it was imported", always, export), + cmd!( + "resource.rename", + "Rename resource", + [], + None, + "{name, to} — everything that uses the image follows it; `to` keeps the old extension when it has none", + always, + rename + ), + cmd!( + "resource.reload", + "Reload resource", + [], + None, + "{name} — read the image again from the file it was imported from in this session", + always, + reload + ), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), cmd!( "layer.add.image", @@ -97,9 +115,17 @@ impl Session { self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); + // A new resource under a removed one's name has no file of its own until an import says so + self.resource_sources.remove(&name); + Ok(name) } + /// Whether image resource `name` was imported from a file in this session, so `resource.reload` can read it again + pub fn reloadable(&self, name: &str) -> bool { + self.resource_sources.contains_key(name) + } + /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). pub fn sync_images(&mut self) { self.images.retain(|name, _| self.doc.resources.contains_key(name)); @@ -175,6 +201,7 @@ fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; + s.resource_sources.insert(name.clone(), path.into()); Ok(json!({ "name": name })) } @@ -280,18 +307,143 @@ fn export(_: &mut Session, _: &Value) -> Result { Err(bad("resource.export", "file paths are not available in the browser")) } -/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) -fn remove_unused(s: &mut Session, _: &Value) -> Result { - let mut used = Vec::new(); - for set in &s.doc.project.texture_sets { - for root in &set.stack { - crate::material_lib::images_used(&s.doc.project, *root, &mut used, 0); +/// Renames image resource `name` to `to` and every reference to it, in one undo step +fn rename(s: &mut Session, p: &Value) -> Result { + let command = "resource.rename"; + let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?.to_string(); + let to = strp(p, "to").ok_or_else(|| bad(command, "`to` is required"))?.trim(); + if !s.doc.resources.contains_key(&name) { + return Err(bad(command, format!("no resource `{name}`"))); + } + + let mut to = sanitize_resource_name(to); + if std::path::Path::new(&to).extension().is_none() + && let Some(extension) = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()) + { + // The stem gives way, so a long name keeps its extension + let stem_room = MAX_RESOURCE_NAME_LEN.saturating_sub(extension.len() + 1); + to.truncate(stem_room); + to = format!("{to}.{extension}"); + } + if to == name { + return Ok(json!({ "name": name })); + } + if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() { + return Err(bad(command, format!("a resource named `{to}` exists already"))); + } + + s.edit("Rename resource", |s| { + let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?; + s.doc.resources.insert(to.clone(), bytes); + rename_references(&mut s.doc.project, &name, &to); + + // Refuse rather than leave a reference this rename does not know about pointing at nothing + if project_images(&s.doc.project).contains(&name) { + return Err(bad(command, format!("`{name}` is used somewhere it can't be renamed"))); + } + + Ok(()) + })?; + + for tool_image in s.tool_images_mut().filter(|tool_image| **tool_image == name) { + tool_image.clone_from(&to); + } + + // The decoded pixels are the same: they move instead of decoding again + if let Some(image) = s.images.remove(&name) { + s.images.insert(to.clone(), image); + } + if s.library_alphas.remove(&name) { + s.library_alphas.insert(to.clone()); + } + if let Some(source) = s.resource_sources.remove(&name) { + s.resource_sources.insert(to.clone(), source); + } + s.path_cache = None; + s.sync_images(); + Ok(json!({ "name": to })) +} + +/// Points every layer, effect, stored path and the environment that read image resource `from` at `to` +fn rename_references(project: &mut texturecraft_core::Project, from: &str, to: &str) { + for layer in project.layers.values_mut() { + let fill_images: Vec<&mut String> = match &mut layer.kind { + LayerKind::Fill(fill) => fill.images_mut().collect(), + _ => Vec::new(), + }; + let effects = layer.mask.iter_mut().flat_map(|mask| mask.effects.iter_mut()).chain(&mut layer.content_effects); + let mut images = fill_images; + for effect in effects { + crate::path_tool::rename_path_images(&mut effect.kind, from, to); + images.extend(effect.images_mut()); + } + + for image in images.into_iter().filter(|image| *image == from) { + *image = to.to_string(); } } + + if project.display.environment_resource() == Some(from) { + project.display.environment = format!("{}{to}", texturecraft_core::project::ENV_RESOURCE_PREFIX); + } +} + +/// Reads image resource `name` again from the file this session imported it from (one undo step) +#[cfg(not(target_arch = "wasm32"))] +fn reload(s: &mut Session, p: &Value) -> Result { + let command = "resource.reload"; + let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?.to_string(); + if !s.doc.resources.contains_key(&name) { + return Err(bad(command, format!("no resource `{name}`"))); + } + + let path = + s.resource_sources.get(&name).cloned().ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?; + let bytes = read_resource_file(command, &path, MAX_BYTES as u64)?; + let image = texturecraft_formats::decode_image_within(&bytes, texturecraft_formats::MAX_RESOURCE_TEXELS) + .map_err(|error| bad(command, format!("{}: {error}", path.display())))?; + s.edit("Reload resource", |s| { + s.doc.resources.insert(name.clone(), Arc::new(bytes)); + Ok(()) + })?; + + s.library_alphas.remove(&name); + if crate::fill_alpha::matches_saved_picture(&name, &image) { + s.library_alphas.insert(name.clone()); + } + s.images.insert(name.clone(), decoded(image)); + Ok(json!({ "name": name })) +} + +#[cfg(target_arch = "wasm32")] +fn reload(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.reload", "file paths are not available in the browser")) +} + +/// Every image resource a layer, mask effect, stored path or the environment of `project` uses +fn project_images(project: &texturecraft_core::Project) -> Vec { + let mut used = Vec::new(); + for set in &project.texture_sets { + for root in &set.stack { + crate::material_lib::images_used(project, *root, &mut used, 0); + } + } + used.extend(project.display.environment_resource().map(str::to_string)); + used +} + +/// [`project_images`] and the images the brush alpha, the projection stencil and the mask brush use +fn images_in_use(s: &Session) -> Vec { + let mut used = project_images(&s.doc.project); used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone())); used.extend(s.tool.brush.alpha_image.clone()); used.extend(s.tool.mask_image.clone()); - used.extend(s.doc.project.display.environment_resource().map(str::to_string)); + used +} + +/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) +fn remove_unused(s: &mut Session, _: &Value) -> Result { + let used = images_in_use(s); let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); if !unused.is_empty() { s.edit("Remove unused resources", |s| { @@ -363,6 +515,66 @@ mod tests { std::fs::remove_file(path).unwrap(); } + #[test] + fn a_renamed_image_stays_in_use_everywhere_it_was() { + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let name = session.import_resource_bytes("photo.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap(); + session.tool.brush.alpha_image = Some(name.clone()); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); + + assert_ne!(renamed, name); + assert!(renamed.ends_with(".png"), "the extension stays: {renamed}"); + let used = images_in_use(&session); + assert!(used.contains(&renamed) && !used.contains(&name), "every use follows the rename: {used:?}"); + assert!(session.images.contains_key(&renamed) && !session.images.contains_key(&name)); + + session.undo().unwrap(); + + assert!(project_images(&session.doc.project).contains(&name), "undo brings the old name back"); + assert!(session.images.contains_key(&name)); + assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&name), "the brush alpha follows the undo"); + + session.redo().unwrap(); + + assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&renamed), "the brush alpha follows the redo"); + } + + #[test] + fn reloading_reads_the_file_again_and_undo_restores_the_pixels() { + let mut session = crate::sample_session(128, 32).unwrap(); + let path = std::env::temp_dir().join(format!("texturecraft-reload-resource-{}.png", std::process::id())); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.2].into_iter()).unwrap()).unwrap(); + let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let before = session.images[&name].rgba.clone(); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.8].into_iter()).unwrap()).unwrap(); + + crate::execute(&mut session, "resource.reload", &json!({"name": name})).unwrap(); + let reloaded = session.images[&name].rgba.clone(); + session.undo().unwrap(); + + assert_ne!(reloaded, before, "reload decodes the file's new pixels"); + assert_eq!(session.images[&name].rgba, before, "undo shows the old pixels again"); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn a_new_image_under_a_removed_ones_name_does_not_reload_its_file() { + let mut session = crate::sample_session(128, 32).unwrap(); + let path = std::env::temp_dir().join(format!("texturecraft-reused-name-{}.png", std::process::id())); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.2].into_iter()).unwrap()).unwrap(); + let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + crate::execute(&mut session, "resource.remove", &json!({"name": name})).unwrap(); + + let reused = session.import_resource_bytes(&name, texturecraft_formats::gray16_png(1, 1, [0.6].into_iter()).unwrap()).unwrap(); + std::fs::remove_file(path).unwrap(); + + assert_eq!(reused, name, "the name is free again"); + assert!(session.resource_source(&reused).is_none(), "the new image has no file to reload from"); + } + #[test] fn file_reads_obey_the_remaining_byte_budget() { let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..66b58d6f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -462,6 +462,8 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Resource names whose decoded pixels match a library alpha. pub(crate) library_alphas: BTreeSet, + /// The file each image resource imported in this session came from, for Reload (not saved) + pub(crate) resource_sources: BTreeMap, /// Temporary texel mask limiting paint strokes (not saved, not in the history). pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). @@ -547,6 +549,7 @@ impl Session { blending_clipboard: None, images: Default::default(), library_alphas: BTreeSet::new(), + resource_sources: BTreeMap::new(), quick_mask: Default::default(), painting_paths: false, path_cache: None, @@ -983,6 +986,13 @@ impl Session { } fn after_history(&mut self, other: &Document) { + // A resource whose bytes the step changed (a reload) decodes again + self.images.retain(|name, _| match (other.resources.get(name), self.doc.resources.get(name)) { + (Some(left), Some(right)) => Arc::ptr_eq(left, right), + _ => true, + }); + self.follow_renamed_resources(other); + // Pending operations may still hold layer IDs from the discarded snapshot self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id); self.modified = true; @@ -1006,6 +1016,42 @@ impl Session { } } + /// The image names the tools and the 2D view read, which a resource rename follows + pub(crate) fn tool_images_mut(&mut self) -> impl Iterator { + [ + self.tool.stencil.as_mut().map(|stencil| &mut stencil.image), + self.tool.brush.alpha_image.as_mut(), + self.tool.mask_image.as_mut(), + self.view_image.as_mut(), + ] + .into_iter() + .flatten() + } + + /// Points tool images and reload sources at a resource's name on this side of an undone or redone rename + fn follow_renamed_resources(&mut self, other: &Document) { + let mut names: Vec = self.tool_images_mut().map(|name| name.clone()).collect(); + names.extend(self.resource_sources.keys().cloned()); + let renames: Vec<(String, String)> = names + .into_iter() + .filter(|name| !self.doc.resources.contains_key(name)) + .filter_map(|name| { + let bytes = other.resources.get(&name)?; + let to = self.doc.resources.iter().find(|(_, here)| Arc::ptr_eq(here, bytes)).map(|(here, _)| here.clone())?; + Some((name, to)) + }) + .collect(); + + for (name, to) in renames { + for tool_image in self.tool_images_mut().filter(|tool_image| **tool_image == name) { + tool_image.clone_from(&to); + } + if let Some(source) = self.resource_sources.remove(&name) { + self.resource_sources.insert(to, source); + } + } + } + // ----------------------------------------------------------------------------------------- // Compositing diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index 35a7ba49..cd3d8e8e 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -41,15 +41,20 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf ui.set_width(width); let column = label_column(ui, &info); - // A saved brush is the user's own: its Name row is a field that renames it + // A saved brush or a project image is the user's own: its Name row is a field that renames it let mut shown_info = info.as_slice(); - if let ShelfEntry::SavedBrush { name, .. } = entry + let rename = match entry { + ShelfEntry::SavedBrush { name, .. } => Some((name.as_str(), "brush.preset.rename")), + ShelfEntry::Image(name) => Some((name.as_str(), "resource.rename")), + _ => None, + }; + if let Some((name, command)) = rename && let Some((_, rest)) = info.split_first() { shown_info = rest; let field_id = ui.make_persistent_id(("asset_name", entry.identity())); if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) { - app.run("brush.preset.rename", json!({"name": name, "to": renamed})); + app.run(command, json!({"name": name, "to": renamed})); } } info_block(ui, width, column, shown_info, &tokens); @@ -57,6 +62,15 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf match entry { ShelfEntry::Image(name) => { + let reloadable = app.session.reloadable(name); + let reload = row(ui, width, tr("Reload"), reloadable, &tokens); + if reload.clicked() { + app.run("resource.reload", json!({"name": name})); + ui.close(); + } + if !reloadable { + reload.on_hover_text(tr("Imported before this session: no file to reload from")); + } if row(ui, width, tr("Delete"), true, &tokens).clicked() { app.run("resource.remove", json!({"name": name})); ui.close(); @@ -115,7 +129,7 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { let mut labels = vec![tr("Export resource..."), tr("Close")]; match entry { - ShelfEntry::Image(_) => labels.extend([tr("Delete"), tr("Add as decal (view center)")]), + ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), _ => {} } diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 51b7bdae..b1db8921 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -127,3 +127,21 @@ fn delete_removes_a_project_image() { assert!(!harness.state().session.doc.resources.contains_key(&name)); } + +#[test] +fn a_project_image_menu_renames_it_and_reloads_only_a_file_from_this_session() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, &name); + assert!(harness.get_by_label("Reload").accesskit_node().is_disabled(), "an image without a file from this session can't reload"); + type_name(&mut harness, "stone"); + harness.key_press(Key::Enter); + harness.run_steps(3); + + let resources = &harness.state().session.doc.resources; + assert!(resources.contains_key("stone.png") && !resources.contains_key(&name), "Enter renames the image, keeping its extension"); +} From fffe60a08608e4d2a84a0c396e9035c0e2de094a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:45:53 +0000 Subject: [PATCH 040/190] Assets: Show in submenu and keyboard opening for the asset menu Show in opens a submenu with the file manager's own item (Explorer, Finder, file manager), which shows the folder of a saved brush's file or of the file a project image was imported from in this session. The row is greyed, with the reason, for built-in assets and images with no file. Shift+F10 or the Menu key opens the menu on the focused tile, and Escape gives the focus back to it. --- .../src/brush_preset_cmds/user_brushes.rs | 6 + crates/engine/src/resource_cmds.rs | 6 +- crates/ui-egui/src/shelf_menu.rs | 125 ++++++++++++++++-- crates/ui-egui/tests/it/shelf_menu.rs | 48 +++++++ 4 files changed, 172 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/brush_preset_cmds/user_brushes.rs b/crates/engine/src/brush_preset_cmds/user_brushes.rs index 921df2d5..3acb6712 100644 --- a/crates/engine/src/brush_preset_cmds/user_brushes.rs +++ b/crates/engine/src/brush_preset_cmds/user_brushes.rs @@ -45,6 +45,12 @@ impl UserBrushes { self.dir.as_ref().map(|directory| directory.join(format!("{}.{BRUSH_EXT}", sanitize_file_stem(name.trim())))) } + /// The file user preset `name` is mirrored to (None: no such preset, or the presets live in memory only) + pub fn file_for(&self, name: &str) -> Option { + let preset = self.list.get(self.find(name)?)?; + preset.file.clone().or_else(|| self.file_of(&preset.name)) + } + /// The file a preset named `name` that was never written would have. #[cfg(not(target_arch = "wasm32"))] pub(super) fn file_of(&self, name: &str) -> Option { diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index da51b8ea..df7d16ff 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -121,9 +121,9 @@ impl Session { Ok(name) } - /// Whether image resource `name` was imported from a file in this session, so `resource.reload` can read it again - pub fn reloadable(&self, name: &str) -> bool { - self.resource_sources.contains_key(name) + /// The file image resource `name` was imported from in this session (what `resource.reload` reads again) + pub fn resource_source(&self, name: &str) -> Option<&std::path::Path> { + self.resource_sources.get(name).map(std::path::PathBuf::as_path) } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index cd3d8e8e..3c5cb160 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -1,10 +1,10 @@ //! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it; the Name of an asset the user owns is a field that renames it -use egui::{Align2, Color32, CornerRadius, FontId, Response, Sense, Ui, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Response, Sense, Ui, pos2, vec2}; use serde_json::json; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{n_, tr}; use crate::shelf_entry::{LIBRARIES, ShelfEntry}; use crate::theme::Tokens; @@ -29,10 +29,36 @@ const FIELD_TEXT_INSET: f32 = 8.0; /// The air above and below the separators, in points const SEPARATOR_SPACE: f32 = 3.0; +/// A menu just opened from the keyboard gives the focus to its first row that can be picked (ctx temp data) +const FOCUS_FIRST_ROW: &str = "shelf_menu_focus_first_row"; + /// The right-click menu on the tile whose response is `response` pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) { // Clicks inside keep the menu open, so the Name field can be typed in; its rows close it themselves - let menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + let mut menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + response.ctx.accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu)); + + // The keyboard opens it on the focused tile, and Escape gives the focus back to the tile + let keyboard_id = response.id.with("menu_from_keyboard"); + let return_focus = menu.is_open() && response.ctx.input(|input| input.key_pressed(egui::Key::Escape)); + if response.has_focus() + && response + .ctx + .input_mut(|input| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu)) + { + menu = menu.open_memory(Some(egui::SetOpenCommand::Bool(true))); + response.ctx.data_mut(|data| { + data.insert_temp(keyboard_id, true); + data.insert_temp(Id::unique(FOCUS_FIRST_ROW), true); + }); + } else if response.secondary_clicked() { + response.ctx.data_mut(|data| data.remove::(keyboard_id)); + } + + // A menu opened from the keyboard has no pointer position to open at: it opens at the tile + if response.ctx.data(|data| data.get_temp::(keyboard_id)).unwrap_or_default() { + menu = menu.anchor(response); + } menu.show(|ui| { let tokens = Tokens::get(ui.ctx()); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); @@ -62,7 +88,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf match entry { ShelfEntry::Image(name) => { - let reloadable = app.session.reloadable(name); + let reloadable = app.session.resource_source(name).is_some(); let reload = row(ui, width, tr("Reload"), reloadable, &tokens); if reload.clicked() { app.run("resource.reload", json!({"name": name})); @@ -80,11 +106,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf export_image(app, name); ui.close(); } - separator(ui, &tokens); - if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); - } } ShelfEntry::SavedBrush { name, .. } => { if row(ui, width, tr("Replace with the current brush"), true, &tokens).clicked() { @@ -105,12 +126,23 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } } + show_in(app, ui, width, entry, &tokens); + if let ShelfEntry::Image(name) = entry { + separator(ui, &tokens); + if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } + } separator(ui, &tokens); if row(ui, width, tr("Close"), true, &tokens).clicked() { ui.close(); } }); + if return_focus { + response.request_focus(); + } } /// The info block's label and value rows: rows only where the asset has the data @@ -127,7 +159,7 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { - let mut labels = vec![tr("Export resource..."), tr("Close")]; + let mut labels = vec![tr("Export resource..."), tr("Show in"), tr("Close")]; match entry { ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), @@ -229,11 +261,84 @@ fn separator(ui: &mut Ui, tokens: &Tokens) { ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, tokens.separator)); } +/// The file manager's own name for showing a file in it +fn show_in_folder_label() -> &'static str { + if cfg!(target_os = "windows") { + tr("Show in Explorer...") + } else if cfg!(target_os = "macos") { + tr("Show in Finder...") + } else { + tr("Show in file manager...") + } +} + +/// The Show in row: a submenu that opens the folder of the asset's file, greyed for an asset with no file on this computer +fn show_in(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry: &ShelfEntry, tokens: &Tokens) { + let file = match entry { + ShelfEntry::SavedBrush { name, .. } => app.session.brush_presets.file_for(name), + ShelfEntry::Image(name) => app.session.resource_source(name).map(std::path::Path::to_path_buf), + _ => None, + }; + let folder = file.as_deref().and_then(std::path::Path::parent).filter(|folder| folder.is_dir()).map(std::path::Path::to_path_buf); + + // Reserved under the row, so the row stays highlighted while its submenu is open + let open_highlight = ui.painter().add(egui::Shape::Noop); + let response = row(ui, width, tr("Show in"), folder.is_some(), tokens); + let caret_color = if folder.is_some() { tokens.text } else { tokens.text_dim }; + ui.painter().text( + pos2(response.rect.right() - TEXT_X, response.rect.center().y), + Align2::RIGHT_CENTER, + egui_phosphor::regular::CARET_RIGHT, + FontId::proportional(TEXT_SIZE), + caret_color, + ); + let Some(folder) = folder else { + let reason = match (file.is_some(), entry) { + (true, _) => n_("The folder of this asset's file is gone"), + (false, ShelfEntry::Image(_)) => n_("Imported before this session: no file to show"), + (false, ShelfEntry::SavedBrush { .. }) => n_("This brush isn't saved to a file"), + (false, _) => n_("Built-in assets have no file to show"), + }; + + response.on_hover_text(tr(reason)); + return; + }; + + let submenu = egui::containers::menu::SubMenu::new().show(ui, &response, |ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let label = show_in_folder_label(); + let submenu_width = text_width(ui, label) + TEXT_X + RIGHT_PADDING; + if row(ui, submenu_width, label, true, tokens).clicked() { + open_folder(app, &folder); + ui.close(); + } + }); + if submenu.is_some() { + let highlight = egui::Shape::rect_filled(response.rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button); + ui.painter().set(open_highlight, highlight); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn open_folder(app: &mut TextureCraftApp, folder: &std::path::Path) { + if let Err(error) = app.file_dialogs.show_folder(folder) { + app.toast(crate::i18n::trf("Could not open the folder: {error}", &[("error", &error)]), true); + } +} + +#[cfg(target_arch = "wasm32")] +fn open_folder(app: &mut TextureCraftApp, _: &std::path::Path) { + app.toast(tr("Showing files needs the desktop app"), true); +} + /// One menu row: a hover face inset from the sides, its text dim and unclickable when not `enabled` fn row(ui: &mut Ui, width: f32, label: &str, enabled: bool, tokens: &Tokens) -> Response { let sense = if enabled { Sense::click() } else { Sense::hover() }; let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); + if enabled && ui.data_mut(|data| data.remove_temp::(Id::unique(FOCUS_FIRST_ROW))).unwrap_or_default() { + response.request_focus(); + } let painter = ui.painter(); if enabled && (response.hovered() || response.has_focus()) { painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button); diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index b1db8921..242acb0c 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -44,6 +44,7 @@ fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() { assert!(harness.query_by_label(&row).is_some(), "the menu has the info row {row:?}"); } assert!(harness.get_by_label("Export resource...").accesskit_node().is_disabled(), "a built-in has no file to export"); + assert!(harness.get_by_label("Show in").accesskit_node().is_disabled(), "a built-in has no file to show"); harness.get_by_label("Close").click(); harness.run_steps(3); @@ -145,3 +146,50 @@ fn a_project_image_menu_renames_it_and_reloads_only_a_file_from_this_session() { let resources = &harness.state().session.doc.resources; assert!(resources.contains_key("stone.png") && !resources.contains_key(&name), "Enter renames the image, keeping its extension"); } + +#[test] +fn show_in_opens_the_folder_of_a_saved_brush() { + let dir = super::temp_dir::TempDir::new("shelf-show-in"); + let mut harness = shelf(BRUSHES_TYPE); + harness.state_mut().session.brush_presets.dir = Some(dir.to_path_buf()); + texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, "Aa ink"); + harness.get_by_label("Show in").click(); + harness.run_steps(3); + let item = if cfg!(target_os = "windows") { + "Show in Explorer..." + } else if cfg!(target_os = "macos") { + "Show in Finder..." + } else { + "Show in file manager..." + }; + harness.get_by_label(item).click(); + harness.run_steps(3); + + let shown = harness.state().file_dialogs.shown_folders().to_vec(); + assert!(shown.iter().any(|folder| folder.canonicalize().ok() == dir.canonicalize().ok()), "the brush's folder is shown: {shown:?}"); +} + +#[test] +fn shift_f10_opens_the_menu_of_the_focused_tile_on_its_first_row_and_escape_returns_to_it() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + harness.get_all_by_label(&name).next().unwrap().focus(); + harness.run_steps(2); + assert!(harness.get_all_by_label(&name).next().unwrap().is_focused(), "the tile takes the focus"); + harness.key_press_modifiers(Modifiers::SHIFT, Key::F10); + harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_some(), "Shift+F10 opens the menu"); + assert!(harness.get_by_label("Delete").is_focused(), "the first row that can be picked takes the focus (Reload can't: no file)"); + + harness.key_press(Key::Escape); + harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_none(), "Escape closes it"); + assert!(harness.get_all_by_label(&name).next().unwrap().accesskit_node().is_focused(), "the focus is back on the tile"); +} From 6015c6691c10f6280fa7fe50ad32c7803ad9419f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:49:38 +0000 Subject: [PATCH 041/190] Assets: favorites with a star, first in their type, and the Favorites saved search Add to favorites / Remove from favorites in the asset menu. Favorites show a star at the thumbnail's top-right, come first in their type (the newest first), are kept in the UI settings, and the Favorites saved search shows only them. --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 20 +++++-- crates/ui-egui/src/shelf_favorite.rs | 78 ++++++++++++++++++++++++++ crates/ui-egui/src/shelf_menu.rs | 11 +++- crates/ui-egui/src/shelf_panes.rs | 33 ++++++++--- crates/ui-egui/src/shelf_toolbar.rs | 1 + crates/ui-egui/src/state.rs | 20 ++++++- crates/ui-egui/tests/it/shelf_menu.rs | 35 ++++++++++++ crates/ui-egui/tests/it/shelf_panel.rs | 30 +++++++++- 9 files changed, 212 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/src/shelf_favorite.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ab8d1b99..f9b379a3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -138,6 +138,7 @@ pub mod settings_window; pub mod shader_settings; pub mod shelf; mod shelf_entry; +pub mod shelf_favorite; mod shelf_folders; mod shelf_menu; pub mod shelf_panes; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9099a2f9..2c32f595 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -273,6 +273,10 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { Vec::new() }; + if app.ui.shelf_favorites_only { + matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); + } + // All libraries includes every result without constructing an asset path if !folder.is_empty() { matching.retain(|entry| entry.in_folder(&folder)); @@ -280,8 +284,9 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); - // Saved smart materials and masks count toward their tabs even without tiles - let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + // Saved smart materials and masks count toward their tabs even without tiles; they can't be favorites yet + let favorites_only = app.ui.shelf_favorites_only; + let in_user_library = !favorites_only && folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); let saved_materials_matching = saved_matching(app, &filter, false); let saved_masks_matching = saved_matching(app, &filter, true); for (tab, saved) in [(Tab::Smart, saved_materials_matching), (Tab::Masks, saved_masks_matching)] { @@ -300,11 +305,14 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tab = app.ui.shelf_tab; let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); - let show_user_brushes = crate::shelf_tabs::shows(tab, Tab::Brushes) + let show_user_brushes = !favorites_only + && crate::shelf_tabs::shows(tab, Tab::Brushes) && folder.len() <= 2 && folder.iter().zip([crate::shelf_entry::USER, "Brushes"]).all(|(selected, part)| selected == part); let mut entries: Vec = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect(); - entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); + // Favorites first, the most recently added first, then by name + let favorites = &app.ui.shelf_favorites; + entries.sort_by_cached_key(|entry| (crate::shelf_favorite::rank(favorites, entry).unwrap_or(usize::MAX), entry.label().to_lowercase())); // The toolbar has its own strip at the panel's bottom, so nothing above it can push it out let area = ui.available_rect_before_wrap(); @@ -548,6 +556,10 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry if entry.includes_randomness() { randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); } + if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { + crate::shelf_favorite::star(ui.painter(), view.thumbnail_rect(response.rect), Tokens::get(ctx).warning); + ctx.accesskit_node_builder(response.id, |node| node.set_description(tr("Favorite"))); + } if response.clicked() || response.secondary_clicked() { let (kind, id) = entry.identity(); diff --git a/crates/ui-egui/src/shelf_favorite.rs b/crates/ui-egui/src/shelf_favorite.rs new file mode 100644 index 00000000..c3ef0674 --- /dev/null +++ b/crates/ui-egui/src/shelf_favorite.rs @@ -0,0 +1,78 @@ +//! An asset the user marked as a favorite in the Assets panel: it shows a star and comes first in its type + +use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, epaint::Mesh, vec2}; +use serde::{Deserialize, Serialize}; + +use crate::shelf_entry::ShelfEntry; + +/// The star's outer and inner radius and its centre's inset from the thumbnail's top-right corner, in points +const STAR_OUTER_RADIUS: f32 = 5.5; +const STAR_INNER_RADIUS: f32 = 2.4; +const STAR_INSET: f32 = 4.0; +/// The offset and colour of the star's shadow, which keeps it readable on light thumbnails +const STAR_SHADOW_OFFSET: f32 = 1.0; +const STAR_SHADOW: Color32 = Color32::from_black_alpha(170); +const STAR_POINTS: usize = 5; +/// The width of the outline that smooths the star's edges (a mesh has no anti-aliasing), in points +const STAR_EDGE_WIDTH: f32 = 0.6; + +/// A favorite asset by its [`ShelfEntry::identity`] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfFavorite { + pub kind: String, + pub id: String, +} + +impl ShelfFavorite { + fn is(&self, entry: &ShelfEntry) -> bool { + let (kind, id) = entry.identity(); + self.kind == kind && self.id == id + } +} + +/// Where `entry` is in `favorites` (most recently added first), or None if it isn't one +pub(crate) fn rank(favorites: &[ShelfFavorite], entry: &ShelfEntry) -> Option { + favorites.iter().position(|favorite| favorite.is(entry)) +} + +/// Adds `entry` in front of `favorites`, or removes it if it is one +pub(crate) fn toggle(favorites: &mut Vec, entry: &ShelfEntry) { + if let Some(index) = rank(favorites, entry) { + favorites.remove(index); + return; + } + + let (kind, id) = entry.identity(); + favorites.insert(0, ShelfFavorite { kind: kind.to_owned(), id: id.to_owned() }); +} + +/// A filled star in `color` at the thumbnail's top-right corner, over a dark shadow +pub(crate) fn star(painter: &Painter, thumbnail: Rect, color: Color32) { + let center = thumbnail.right_top() + vec2(-STAR_INSET, STAR_INSET); + star_shape(painter, center + vec2(STAR_SHADOW_OFFSET, STAR_SHADOW_OFFSET), STAR_SHADOW); + star_shape(painter, center, color); +} + +/// A five-pointed star around `center`, point up: a triangle fan from the centre, outlined in its colour +fn star_shape(painter: &Painter, center: Pos2, color: Color32) { + let corner_count = STAR_POINTS * 2; + let corners: Vec = (0..corner_count) + .map(|corner| { + let radius = if corner % 2 == 0 { STAR_OUTER_RADIUS } else { STAR_INNER_RADIUS }; + let angle = corner as f32 * std::f32::consts::TAU / corner_count as f32 - std::f32::consts::FRAC_PI_2; + center + radius * vec2(angle.cos(), angle.sin()) + }) + .collect(); + + let mut mesh = Mesh::default(); + mesh.colored_vertex(center, color); + for corner in &corners { + mesh.colored_vertex(*corner, color); + } + let last = corner_count as u32; + for corner in 1..=last { + mesh.add_triangle(0, corner, corner % last + 1); + } + painter.add(Shape::mesh(mesh)); + painter.add(Shape::closed_line(corners, Stroke::new(STAR_EDGE_WIDTH, color))); +} diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index 3c5cb160..c486a0df 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -127,6 +127,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf } } show_in(app, ui, width, entry, &tokens); + if row(ui, width, favorite_label(app, entry), true, &tokens).clicked() { + crate::shelf_favorite::toggle(&mut app.ui.shelf_favorites, entry); + ui.close(); + } if let ShelfEntry::Image(name) = entry { separator(ui, &tokens); if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { @@ -159,7 +163,7 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { - let mut labels = vec![tr("Export resource..."), tr("Show in"), tr("Close")]; + let mut labels = vec![tr("Export resource..."), tr("Show in"), tr("Add to favorites"), tr("Remove from favorites"), tr("Close")]; match entry { ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), @@ -168,6 +172,11 @@ fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { labels } +/// The row that adds the asset to the favorites, or takes a favorite out +fn favorite_label(app: &TextureCraftApp, entry: &ShelfEntry) -> &'static str { + if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { tr("Remove from favorites") } else { tr("Add to favorites") } +} + fn text_width(ui: &Ui, text: &str) -> f32 { ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x) } diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index 96f5c25f..118d9bc4 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -17,8 +17,10 @@ const COLUMN_FRACTION: f32 = 0.45; const COLUMN_MIN_WIDTH_POINTS: f32 = 110.0; const SPLITTER_HEIGHT_POINTS: f32 = 6.0; const PANE_MIN_HEIGHT_POINTS: f32 = 40.0; -/// The reference's built-in saved searches after "All", shown greyed until they work -const BUILT_IN_SEARCHES: [&str; 3] = [n_("Favorites"), n_("3D Assets"), n_("Flattened layers")]; +/// The built-in saved search after "All" that shows only the favorite assets +const FAVORITES: &str = n_("Favorites"); +/// The reference's other built-in saved searches, shown greyed until they work +const UNAVAILABLE_SEARCHES: [&str; 2] = [n_("3D Assets"), n_("Flattened layers")]; /// The reference's font libraries after the asset libraries, shown greyed until they work const FONT_LIBRARIES: [&str; 2] = [n_("System fonts"), n_("User fonts")]; /// The pane header's caption size in points @@ -191,7 +193,12 @@ fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { }); } -/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one +/// Saved searches' first rows: "All", then Favorites, then the searches that aren't available +const ALL_ROW: usize = 0; +const FAVORITES_ROW: usize = 1; +const FIXED_SEARCH_ROWS: usize = 2; + +/// "All", Favorites, then the saved queries; the header's button saves the current one, a right-click deletes one fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { let size = ui.spacing().interact_size.y; header(ui, tr("Saved searches"), |ui| { @@ -203,8 +210,9 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - let all_selected = app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE; - let first_saved_row = 1 + BUILT_IN_SEARCHES.len(); + let favorites_only = app.ui.shelf_favorites_only; + let all_selected = !favorites_only && app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE; + let first_saved_row = FIXED_SEARCH_ROWS + UNAVAILABLE_SEARCHES.len(); let row_height = ui.spacing().interact_size.y; let total_rows = first_saved_row + app.ui.shelf_saved_searches.len(); let mut deleted_index = None; @@ -216,14 +224,22 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { total_rows, |ui, visible_rows| { for row in visible_rows { - if row == 0 { + if row == ALL_ROW { if ui.selectable_label(all_selected, tr("All")).clicked() { crate::shelf_toolbar::reset_query(app); } continue; } - if let Some(name) = BUILT_IN_SEARCHES.get(row - 1) { + if row == FAVORITES_ROW { + if ui.selectable_label(favorites_only, tr(FAVORITES)).clicked() { + crate::shelf_toolbar::reset_query(app); + app.ui.shelf_favorites_only = true; + } + continue; + } + + if let Some(name) = UNAVAILABLE_SEARCHES.get(row - FIXED_SEARCH_ROWS) { ui.add_enabled(false, egui::Button::selectable(false, tr(name))).on_disabled_hover_text(tr(NOT_AVAILABLE)); continue; } @@ -231,10 +247,11 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { let saved_index = row - first_saved_row; let Some(saved) = app.ui.shelf_saved_searches.get(saved_index) else { continue }; - let selected = saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path; + let selected = !favorites_only && saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path; let response = ui.selectable_label(selected, &saved.name); if response.clicked() { (app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone()); + app.ui.shelf_favorites_only = false; } response.context_menu(|ui| { diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index a8708685..c7c00b81 100644 --- a/crates/ui-egui/src/shelf_toolbar.rs +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -40,6 +40,7 @@ pub(crate) fn reset_query(app: &mut TextureCraftApp) { app.ui.shelf_filter.clear(); app.ui.shelf_tab = crate::shelf_tabs::NO_TYPE; app.ui.shelf_path.clear(); + app.ui.shelf_favorites_only = false; } /// Read the user's saved assets from disk again and redraw their thumbnails diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..d51db221 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -6,6 +6,7 @@ use texturecraft_engine::core::{BakedMap, Channel, ChannelBlend, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; use crate::saved_search::SavedSearch; +use crate::shelf_favorite::ShelfFavorite; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; @@ -585,6 +586,12 @@ pub struct UiState { /// The asset shelf's saved queries, in the order they were saved #[serde(default)] pub shelf_saved_searches: Vec, + /// The asset shelf's favorite assets, most recently added first + #[serde(default)] + pub shelf_favorites: Vec, + /// The asset shelf shows only favorites (the Favorites saved search) + #[serde(default)] + pub shelf_favorites_only: bool, /// Saved searches' share of the pane column above Filter by path, set by the splitter between them #[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")] pub shelf_panes_split: f32, @@ -741,6 +748,8 @@ impl UiState { self.shelf_tab = keep.shelf_tab; self.shelf_path = keep.shelf_path; self.shelf_saved_searches = keep.shelf_saved_searches; + self.shelf_favorites = keep.shelf_favorites; + self.shelf_favorites_only = keep.shelf_favorites_only; } } @@ -775,6 +784,8 @@ impl Default for UiState { shelf_view: ShelfView::default(), shelf_panes: ShelfPanes::default(), shelf_saved_searches: Vec::new(), + shelf_favorites: Vec::new(), + shelf_favorites_only: false, shelf_panes_split: default_shelf_panes_split(), props_tab: PropsTab::Brush, text: TextUi::default(), @@ -902,15 +913,20 @@ mod tests { } #[test] - fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() { + fn adopting_a_layout_keeps_the_shelf_query_saved_searches_and_favorites() { let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; - let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], ..UiState::default() }; + let favorite = crate::shelf_favorite::ShelfFavorite { kind: "material".into(), id: "gold".into() }; + let mut ui = + UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], shelf_favorites_only: true, ..UiState::default() }; ui.shelf_saved_searches.push(saved.clone()); + ui.shelf_favorites.push(favorite.clone()); ui.adopt_layout(UiState::default()); assert_eq!((ui.shelf_filter.as_str(), ui.shelf_tab, ui.shelf_path.as_slice()), ("rust", 2, ["starter".to_string()].as_slice())); assert_eq!(ui.shelf_saved_searches, [saved]); + assert_eq!(ui.shelf_favorites, [favorite], "favorites are the user's own too"); + assert!(ui.shelf_favorites_only, "the Favorites search is part of the query"); } #[test] diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 242acb0c..4cd920d6 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -193,3 +193,38 @@ fn shift_f10_opens_the_menu_of_the_focused_tile_on_its_first_row_and_escape_retu assert!(harness.query_by_label("Usages texture").is_none(), "Escape closes it"); assert!(harness.get_all_by_label(&name).next().unwrap().accesskit_node().is_focused(), "the focus is back on the tile"); } + +/// Whether the tile `first` comes before the tile `second` in the grid (rows top to bottom, each left to right) +fn comes_before(harness: &Harness<'_, TextureCraftApp>, first: &str, second: &str) -> bool { + let place = |label: &str| { + let rect = harness.get_by_label(label).rect(); + (rect.top(), rect.left()) + }; + place(first) < place(second) +} + +fn pick_from_menu(harness: &mut Harness<'_, TextureCraftApp>, tile: &str, row: &str) { + right_click(harness, tile); + harness.get_by_label(row).click(); + harness.run_steps(3); +} + +#[test] +fn favorites_come_first_newest_first_with_a_star_until_removed() { + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + let (first, second, third) = (plain[0].label, plain[1].label, plain[2].label); + let mut harness = shelf(MATERIALS_TYPE); + + pick_from_menu(&mut harness, third, "Add to favorites"); + pick_from_menu(&mut harness, second, "Add to favorites"); + + assert!(comes_before(&harness, second, third) && comes_before(&harness, third, first), "favorites first, the newest first"); + assert_eq!(harness.get_by_label(second).accesskit_node().description().as_deref(), Some("Favorite"), "the star is announced"); + assert_eq!(harness.get_by_label(first).accesskit_node().description(), None); + + pick_from_menu(&mut harness, second, "Remove from favorites"); + + assert!(comes_before(&harness, first, second), "a removed favorite goes back to its place by name"); + assert!(comes_before(&harness, third, first), "the other favorite stays first"); +} diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index cbfdf687..7dcd12a4 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -385,10 +385,10 @@ fn the_panes_list_the_reference_rows_and_grey_the_missing_ones() { let tops: Vec = rows.iter().map(|label| latest_node_with_label(&harness, label).rect().top()).collect(); assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "{rows:?} run top to bottom: {tops:?}"); } - for label in ["Favorites", "3D Assets", "Flattened layers", "System fonts", "User fonts"] { + for label in ["3D Assets", "Flattened layers", "System fonts", "User fonts"] { assert!(latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} is greyed"); } - for label in ["All", "All libraries", "Project", "Starter assets", "Your assets"] { + for label in ["All", "Favorites", "All libraries", "Project", "Starter assets", "Your assets"] { assert!(!latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} works"); } assert!(shows_not_available(&mut harness, "Flattened layers"), "a greyed saved search explains itself"); @@ -516,3 +516,29 @@ fn the_splitter_is_exposed_as_a_resizable_control() { assert!(harness.state().ui.shelf_panes_split > before); } + +#[test] +fn the_favorites_search_shows_only_favorites_until_all_is_picked() { + let plain = plain_materials(); + let (favorite, other) = (plain[1].label, plain[0].label); + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + button(&harness, favorite).click_secondary(); + harness.run_steps(3); + button(&harness, "Add to favorites").click(); + harness.run_steps(3); + + button(&harness, "Favorites").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(favorite).is_some(), "the favorite shows"); + assert!(harness.query_by_label(other).is_none(), "an asset that is no favorite is hidden"); + assert!(harness.query_by_label("My brushes").is_none(), "the saved brushes list is no favorite either"); + + button(&harness, "All").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(other).is_some(), "All shows every asset again"); + assert!(harness.query_by_label("My brushes").is_some(), "All shows the saved brushes list again"); +} From 10e04cacb3d657529b81b124510683d0518a3ad9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:52:40 +0000 Subject: [PATCH 042/190] Assets: Set custom preview... shows a picked picture on an asset's tile The asset menu's Set custom preview... asks for a picture; the tile shows its centred square instead of the rendered thumbnail until Remove custom preview. The pick is kept in the UI settings; a file that isn't a picture is refused with a message. --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 4 +- crates/ui-egui/src/shelf_custom_preview.rs | 66 +++++++++++++++++ crates/ui-egui/src/shelf_menu.rs | 85 +++++++++++++++++++++- crates/ui-egui/src/state.rs | 11 ++- crates/ui-egui/src/thumbs.rs | 21 ++++++ crates/ui-egui/tests/it/shelf_menu.rs | 37 +++++++++- 7 files changed, 218 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/shelf_custom_preview.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f9b379a3..2441b1d1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -137,6 +137,7 @@ mod session_log_file; pub mod settings_window; pub mod shader_settings; pub mod shelf; +pub mod shelf_custom_preview; mod shelf_entry; pub mod shelf_favorite; mod shelf_folders; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 2c32f595..3431f405 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -531,7 +531,9 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry return; } - let texture = entry.thumbnail(app, ctx); + // A picture the user picked replaces the thumbnail, unless its file is gone + let custom = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry).and_then(|file| app.thumbs.custom_preview(ctx, file)); + let texture = custom.or_else(|| entry.thumbnail(app, ctx)); let asset = entry.asset(); let session = &app.session; let response = tile_in_view( diff --git a/crates/ui-egui/src/shelf_custom_preview.rs b/crates/ui-egui/src/shelf_custom_preview.rs new file mode 100644 index 00000000..8717b314 --- /dev/null +++ b/crates/ui-egui/src/shelf_custom_preview.rs @@ -0,0 +1,66 @@ +//! A picture the user picked to show on an asset's tile instead of its rendered thumbnail ("Set custom preview..." in the asset menu) + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::shelf_entry::ShelfEntry; + +/// The custom preview's size in pixels: the largest tile's thumbnail on a high-density screen +pub(crate) const CUSTOM_PREVIEW_PX: u32 = 164; + +/// The image file shown on the tile of the asset with [`ShelfEntry::identity`] `kind` and `id` +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfCustomPreview { + pub kind: String, + pub id: String, + pub file: PathBuf, +} + +impl ShelfCustomPreview { + fn is(&self, entry: &ShelfEntry) -> bool { + let (kind, id) = entry.identity(); + self.kind == kind && self.id == id + } +} + +/// The image file `entry` shows instead of its thumbnail, if the user picked one +pub(crate) fn file_for<'a>(previews: &'a [ShelfCustomPreview], entry: &ShelfEntry) -> Option<&'a Path> { + previews.iter().find(|preview| preview.is(entry)).map(|preview| preview.file.as_path()) +} + +/// Shows `file` on the tile of the asset with identity `kind` and `id`, replacing an earlier pick +pub(crate) fn set(previews: &mut Vec, kind: String, id: String, file: PathBuf) { + previews.retain(|preview| preview.kind != kind || preview.id != id); + previews.push(ShelfCustomPreview { kind, id, file }); +} + +/// Shows `entry`'s own thumbnail again +pub(crate) fn remove(previews: &mut Vec, entry: &ShelfEntry) { + previews.retain(|preview| !preview.is(entry)); +} + +/// The largest centred square of `image`, scaled to [`CUSTOM_PREVIEW_PX`] (smaller images keep their size) +pub(crate) fn square(image: &image::DynamicImage) -> image::RgbaImage { + let side = image.width().min(image.height()); + let cropped = image.crop_imm((image.width() - side) / 2, (image.height() - side) / 2, side, side); + let size = side.min(CUSTOM_PREVIEW_PX); + cropped.resize_exact(size, size, image::imageops::FilterType::Triangle).to_rgba8() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_wide_picture_keeps_its_middle() { + let red = image::Rgba([255, 0, 0, 255]); + let blue = image::Rgba([0, 0, 255, 255]); + let wide = image::RgbaImage::from_fn(6, 2, |x, _| if (2..4).contains(&x) { blue } else { red }); + + let square = square(&image::DynamicImage::ImageRgba8(wide)); + + assert_eq!(square.width(), square.height(), "the preview is square"); + assert!(square.pixels().all(|pixel| *pixel == blue), "only the middle of a wide picture shows"); + } +} diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index c486a0df..e7546ecf 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -29,6 +29,9 @@ const FIELD_TEXT_INSET: f32 = 8.0; /// The air above and below the separators, in points const SEPARATOR_SPACE: f32 = 3.0; +/// The category's place in an asset's path: after the library and the type's folder +const CATEGORY_PART: usize = 2; + /// A menu just opened from the keyboard gives the focus to its first row that can be picked (ctx temp data) const FOCUS_FIRST_ROW: &str = "shelf_menu_focus_first_row"; @@ -79,8 +82,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf { shown_info = rest; let field_id = ui.make_persistent_id(("asset_name", entry.identity())); - if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) { - app.run(command, json!({"name": name, "to": renamed})); + if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) + && let Some(result) = app.run(command, json!({"name": name, "to": renamed})) + && let Some(new_name) = result["name"].as_str() + { + keep_star_and_preview(app, entry, new_name); } } info_block(ui, width, column, shown_info, &tokens); @@ -126,6 +132,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } } + custom_preview_rows(app, ui, width, entry, &tokens); show_in(app, ui, width, entry, &tokens); if row(ui, width, favorite_label(app, entry), true, &tokens).clicked() { crate::shelf_favorite::toggle(&mut app.ui.shelf_favorites, entry); @@ -149,13 +156,36 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf } } +/// Moves the favorite star and custom preview of `entry`, just renamed to `new_name`, to its new identity +fn keep_star_and_preview(app: &mut TextureCraftApp, entry: &ShelfEntry, new_name: &str) { + let (kind, old_id) = entry.identity(); + let new_id = match entry { + ShelfEntry::SavedBrush { .. } => app + .session + .brush_presets + .list + .iter() + .find(|preset| preset.name == new_name) + .map(|preset| preset.file.as_ref().and_then(|file| file.to_str()).unwrap_or(&preset.name).to_owned()), + _ => Some(new_name.to_owned()), + }; + let Some(new_id) = new_id else { return }; + + let ui = &mut app.ui; + let favorites = ui.shelf_favorites.iter_mut().map(|favorite| (&favorite.kind, &mut favorite.id)); + let previews = ui.shelf_custom_previews.iter_mut().map(|preview| (&preview.kind, &mut preview.id)); + for (_, id) in favorites.chain(previews).filter(|(stored_kind, id)| *stored_kind == kind && *id == old_id) { + id.clone_from(&new_id); + } +} + /// The info block's label and value rows: rows only where the asset has the data fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { let path = entry.path(); let shown_path: Vec<&str> = path.iter().map(|part| LIBRARIES.iter().find(|(id, _)| id == part).map_or_else(|| tr(part), |(_, name)| tr(name))).collect(); let mut rows = vec![(tr("Name"), entry.label().to_string()), (tr("Usages"), tr(entry.usage()).to_string()), (tr("Path"), format!("/{}/", shown_path.join("/")))]; - if let Some(category) = path.get(2) { + if let Some(category) = path.get(CATEGORY_PART) { rows.push((tr("Category"), tr(category).to_string())); } rows @@ -163,7 +193,15 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { - let mut labels = vec![tr("Export resource..."), tr("Show in"), tr("Add to favorites"), tr("Remove from favorites"), tr("Close")]; + let mut labels = vec![ + tr("Export resource..."), + tr("Set custom preview..."), + tr("Remove custom preview"), + tr("Show in"), + tr("Add to favorites"), + tr("Remove from favorites"), + tr("Close"), + ]; match entry { ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), @@ -172,6 +210,45 @@ fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { labels } +/// Set custom preview... picks a picture to show on the tile; Remove custom preview, once one is set, shows the asset's own thumbnail again +fn custom_preview_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry: &ShelfEntry, tokens: &Tokens) { + if row(ui, width, tr("Set custom preview..."), true, tokens).clicked() { + pick_custom_preview(app, entry); + ui.close(); + } + if crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry).is_some() + && row(ui, width, tr("Remove custom preview"), true, tokens).clicked() + { + crate::shelf_custom_preview::remove(&mut app.ui.shelf_custom_previews, entry); + ui.close(); + } +} + +/// Asks for a picture, then shows it on `entry`'s tile +#[cfg(not(target_arch = "wasm32"))] +fn pick_custom_preview(app: &mut TextureCraftApp, entry: &ShelfEntry) { + use crate::file_dialogs::{Bound, FileDialog}; + + let (kind, id) = entry.identity(); + let (kind, id) = (kind.to_owned(), id.to_owned()); + let dialog = FileDialog::open().filter(tr("Images"), crate::web_files::IMAGE_EXTS); + app.ask_file(dialog, Bound::App, move |app, paths| { + let Some(file) = paths.into_iter().next() else { return }; + if image::image_dimensions(&file).is_err() { + app.toast(crate::i18n::trf("Could not read {file} as a picture", &[("file", &file.display())]), true); + return; + } + + app.thumbs.forget_custom_preview(&file); + crate::shelf_custom_preview::set(&mut app.ui.shelf_custom_previews, kind, id, file); + }); +} + +#[cfg(target_arch = "wasm32")] +fn pick_custom_preview(app: &mut TextureCraftApp, _: &ShelfEntry) { + app.toast(tr("Custom previews need the desktop app"), true); +} + /// The row that adds the asset to the favorites, or takes a favorite out fn favorite_label(app: &TextureCraftApp, entry: &ShelfEntry) -> &'static str { if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { tr("Remove from favorites") } else { tr("Add to favorites") } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d51db221..debef955 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -6,6 +6,7 @@ use texturecraft_engine::core::{BakedMap, Channel, ChannelBlend, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; use crate::saved_search::SavedSearch; +use crate::shelf_custom_preview::ShelfCustomPreview; use crate::shelf_favorite::ShelfFavorite; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; @@ -592,6 +593,9 @@ pub struct UiState { /// The asset shelf shows only favorites (the Favorites saved search) #[serde(default)] pub shelf_favorites_only: bool, + /// Pictures the user picked to show on asset tiles instead of their thumbnails + #[serde(default)] + pub shelf_custom_previews: Vec, /// Saved searches' share of the pane column above Filter by path, set by the splitter between them #[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")] pub shelf_panes_split: f32, @@ -750,6 +754,7 @@ impl UiState { self.shelf_saved_searches = keep.shelf_saved_searches; self.shelf_favorites = keep.shelf_favorites; self.shelf_favorites_only = keep.shelf_favorites_only; + self.shelf_custom_previews = keep.shelf_custom_previews; } } @@ -786,6 +791,7 @@ impl Default for UiState { shelf_saved_searches: Vec::new(), shelf_favorites: Vec::new(), shelf_favorites_only: false, + shelf_custom_previews: Vec::new(), shelf_panes_split: default_shelf_panes_split(), props_tab: PropsTab::Brush, text: TextUi::default(), @@ -913,13 +919,15 @@ mod tests { } #[test] - fn adopting_a_layout_keeps_the_shelf_query_saved_searches_and_favorites() { + fn adopting_a_layout_keeps_the_shelf_query_saved_searches_favorites_and_custom_previews() { let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; let favorite = crate::shelf_favorite::ShelfFavorite { kind: "material".into(), id: "gold".into() }; let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], shelf_favorites_only: true, ..UiState::default() }; ui.shelf_saved_searches.push(saved.clone()); ui.shelf_favorites.push(favorite.clone()); + let preview = crate::shelf_custom_preview::ShelfCustomPreview { kind: "material".into(), id: "gold".into(), file: "gold.png".into() }; + ui.shelf_custom_previews.push(preview.clone()); ui.adopt_layout(UiState::default()); @@ -927,6 +935,7 @@ mod tests { assert_eq!(ui.shelf_saved_searches, [saved]); assert_eq!(ui.shelf_favorites, [favorite], "favorites are the user's own too"); assert!(ui.shelf_favorites_only, "the Favorites search is part of the query"); + assert_eq!(ui.shelf_custom_previews, [preview], "custom previews are the user's own"); } #[test] diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 875ac6ae..0a711ae2 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -64,6 +64,8 @@ pub struct Thumbs { big_shown: VecDeque, /// The frame that last took in the worker's results received_in_pass: u64, + /// Pictures the user picked as asset previews, by file; None for a file that doesn't load + custom_previews: HashMap>, } impl Thumbs { @@ -288,6 +290,25 @@ impl Thumbs { self.rendered.retain(|key, _| current(key)); self.big_shown.retain(current); self.saved_brush_previews.clear(); + self.custom_previews.clear(); + } + + /// Load the picture at `file` again next time: the user picked it anew, maybe after changing it + pub(crate) fn forget_custom_preview(&mut self, file: &Path) { + self.custom_previews.remove(file); + } + + /// The picture at `file` as an asset's custom preview (its centred square), loaded once; None if it doesn't load + pub(crate) fn custom_preview(&mut self, ctx: &egui::Context, file: &Path) -> Option { + self.custom_previews + .entry(file.to_path_buf()) + .or_insert_with(|| { + let image = crate::shelf_custom_preview::square(&image::open(file).ok()?); + let size = [image.width() as usize, image.height() as usize]; + let pixels = ColorImage::from_rgba_unmultiplied(size, image.as_raw()); + Some(ctx.load_texture(format!("custom_preview_{}", file.display()), pixels, TextureOptions::LINEAR)) + }) + .clone() } /// Smart mask thumbnail; None until the worker returns it diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 4cd920d6..3ebea8ef 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -130,12 +130,13 @@ fn delete_removes_a_project_image() { } #[test] -fn a_project_image_menu_renames_it_and_reloads_only_a_file_from_this_session() { +fn a_project_image_menu_renames_it_keeping_its_star_and_greys_reload_without_a_file() { let mut harness = shelf(TEXTURES_TYPE); let mut bytes = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); harness.run_steps(3); + pick_from_menu(&mut harness, &name, "Add to favorites"); right_click(&mut harness, &name); assert!(harness.get_by_label("Reload").accesskit_node().is_disabled(), "an image without a file from this session can't reload"); @@ -145,6 +146,8 @@ fn a_project_image_menu_renames_it_and_reloads_only_a_file_from_this_session() { let resources = &harness.state().session.doc.resources; assert!(resources.contains_key("stone.png") && !resources.contains_key(&name), "Enter renames the image, keeping its extension"); + let favorites: Vec<&str> = harness.state().ui.shelf_favorites.iter().map(|favorite| favorite.id.as_str()).collect(); + assert_eq!(favorites, ["stone.png"], "the star follows the rename"); } #[test] @@ -228,3 +231,35 @@ fn favorites_come_first_newest_first_with_a_star_until_removed() { assert!(comes_before(&harness, first, second), "a removed favorite goes back to its place by name"); assert!(comes_before(&harness, third, first), "the other favorite stays first"); } + +#[test] +fn set_custom_preview_shows_a_picked_picture_until_removed() { + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = shelf(MATERIALS_TYPE); + let dir = super::temp_dir::TempDir::new("shelf-custom-preview"); + let picture = dir.join("preview.png"); + image::RgbaImage::from_pixel(8, 4, image::Rgba([40, 160, 90, 255])).save(&picture).unwrap(); + let not_a_picture = dir.join("notes.png"); + std::fs::write(¬_a_picture, b"not a picture").unwrap(); + let answers = std::sync::Arc::new(std::sync::Mutex::new(vec![picture.clone(), not_a_picture])); + let pick = answers.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![pick.lock().unwrap().remove(0)])))); + let picked = + |harness: &Harness<'_, TextureCraftApp>| harness.state().ui.shelf_custom_previews.iter().map(|preview| preview.file.clone()).collect::>(); + + pick_from_menu(&mut harness, material.label, "Set custom preview..."); + harness.run_steps(2); + + assert_eq!(picked(&harness), std::slice::from_ref(&picture), "the tile shows the picked picture"); + + pick_from_menu(&mut harness, material.label, "Set custom preview..."); + harness.run_steps(2); + + assert_eq!(picked(&harness), [picture], "a file that isn't a picture leaves the preview as it was"); + + pick_from_menu(&mut harness, material.label, "Remove custom preview"); + + assert!(picked(&harness).is_empty(), "the tile shows its own thumbnail again"); + right_click(&mut harness, material.label); + assert!(harness.query_by_label("Remove custom preview").is_none(), "only a tile with a custom preview offers to remove it"); +} From 4f73e0c54117b684cf5567db816ff27b8be5f0bf Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:10:57 +0000 Subject: [PATCH 043/190] Assets: refresh popup with automatic updates of the panel and the project's images The refresh button opens a popup above the toolbar: automatic updates of the Assets panel and of the images used in the project every few minutes, the two updates by hand, and a greyed parameter-mismatch switch whose i says TextureCraft has no assets with parameters to update yet. New command resource.update reads again, in one undo step, every image imported this session whose file changed. --- crates/engine/src/resource_cmds.rs | 115 +++++++++- crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/property_sheet/info_icon.rs | 54 ++++- crates/ui-egui/src/property_sheet/mod.rs | 3 +- .../section_tabs/section_scope.rs | 2 + .../src/property_sheet/switch_control.rs | 26 ++- crates/ui-egui/src/shelf_toolbar.rs | 19 +- crates/ui-egui/src/shelf_updates.rs | 211 ++++++++++++++++++ crates/ui-egui/src/state.rs | 7 + crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_panel.rs | 2 + crates/ui-egui/tests/it/shelf_updates.rs | 91 ++++++++ 12 files changed, 498 insertions(+), 35 deletions(-) create mode 100644 crates/ui-egui/src/shelf_updates.rs create mode 100644 crates/ui-egui/tests/it/shelf_updates.rs diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index df7d16ff..1d93ccb9 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -43,6 +43,15 @@ pub fn specs() -> Vec { always, reload ), + cmd!( + "resource.update", + "Update resources used in project", + [], + None, + "{} — read again every image imported from a file in this session whose file changed (one undo step); returns {updated: [names], failed: [{name, error}]}", + always, + update + ), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), cmd!( "layer.add.image", @@ -399,27 +408,87 @@ fn reload(s: &mut Session, p: &Value) -> Result { let path = s.resource_sources.get(&name).cloned().ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?; - let bytes = read_resource_file(command, &path, MAX_BYTES as u64)?; - let image = texturecraft_formats::decode_image_within(&bytes, texturecraft_formats::MAX_RESOURCE_TEXELS) - .map_err(|error| bad(command, format!("{}: {error}", path.display())))?; + let (bytes, image) = read_source(command, &path)?; s.edit("Reload resource", |s| { s.doc.resources.insert(name.clone(), Arc::new(bytes)); Ok(()) })?; - s.library_alphas.remove(&name); - if crate::fill_alpha::matches_saved_picture(&name, &image) { - s.library_alphas.insert(name.clone()); - } - s.images.insert(name.clone(), decoded(image)); + s.show_reloaded(name.clone(), image); Ok(json!({ "name": name })) } +/// Reads again, in one undo step, every image whose source file no longer holds the bytes the project has; nothing changed adds no step +#[cfg(not(target_arch = "wasm32"))] +fn update(s: &mut Session, _: &Value) -> Result { + let command = "resource.update"; + let mut changed = Vec::new(); + let mut failed = Vec::new(); + for (name, path) in &s.resource_sources { + let Some(held) = s.doc.resources.get(name) else { continue }; + // Only a file whose bytes changed is decoded + let read = read_resource_file(command, path, MAX_BYTES as u64) + .and_then(|bytes| if bytes == **held { Ok(None) } else { decode_source(command, path, &bytes).map(|image| Some((bytes, image))) }); + match read { + Ok(None) => {} + Ok(Some((bytes, image))) => changed.push((name.clone(), bytes, image)), + Err(error) => failed.push(json!({ "name": name, "error": error.to_string() })), + } + } + + if !changed.is_empty() { + s.edit("Update resources", |s| { + for (name, bytes, _) in &mut changed { + s.doc.resources.insert(name.clone(), Arc::new(std::mem::take(bytes))); + } + Ok(()) + })?; + } + + let updated: Vec = changed.iter().map(|(name, _, _)| name.clone()).collect(); + for (name, _, image) in changed { + s.show_reloaded(name, image); + } + Ok(json!({ "updated": updated, "failed": failed })) +} + +/// The bytes of the image file at `path` and its decoded pixels +#[cfg(not(target_arch = "wasm32"))] +fn read_source(command: &str, path: &std::path::Path) -> Result<(Vec, texturecraft_formats::DecodedImage)> { + let bytes = read_resource_file(command, path, MAX_BYTES as u64)?; + let image = decode_source(command, path, &bytes)?; + Ok((bytes, image)) +} + +/// The pixels of `bytes` read from the image file at `path` +#[cfg(not(target_arch = "wasm32"))] +fn decode_source(command: &str, path: &std::path::Path, bytes: &[u8]) -> Result { + texturecraft_formats::decode_image_within(bytes, texturecraft_formats::MAX_RESOURCE_TEXELS) + .map_err(|error| bad(command, format!("{}: {error}", path.display()))) +} + +#[cfg(not(target_arch = "wasm32"))] +impl Session { + /// Shows the pixels of image `name` read again from its file, still a saved brush picture when it matches one + fn show_reloaded(&mut self, name: String, image: texturecraft_formats::DecodedImage) { + self.library_alphas.remove(&name); + if crate::fill_alpha::matches_saved_picture(&name, &image) { + self.library_alphas.insert(name.clone()); + } + self.images.insert(name, decoded(image)); + } +} + #[cfg(target_arch = "wasm32")] fn reload(_: &mut Session, _: &Value) -> Result { Err(bad("resource.reload", "file paths are not available in the browser")) } +#[cfg(target_arch = "wasm32")] +fn update(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.update", "file paths are not available in the browser")) +} + /// Every image resource a layer, mask effect, stored path or the environment of `project` uses fn project_images(project: &texturecraft_core::Project) -> Vec { let mut used = Vec::new(); @@ -575,6 +644,36 @@ mod tests { assert!(session.resource_source(&reused).is_none(), "the new image has no file to reload from"); } + #[test] + fn updating_reads_only_changed_files_in_one_undo_step() { + let mut session = crate::sample_session(128, 32).unwrap(); + let import = |session: &mut Session, label: &str, value: f32| { + let path = std::env::temp_dir().join(format!("texturecraft-update-{label}-{}.png", std::process::id())); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [value].into_iter()).unwrap()).unwrap(); + let name = crate::execute(session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + (path, name) + }; + let (edited_path, edited) = import(&mut session, "edited", 0.2); + let (kept_path, kept) = import(&mut session, "kept", 0.4); + let unchanged = crate::execute(&mut session, "resource.update", &json!({})).unwrap(); + let steps = session.history_labels().len(); + let before = session.images[&edited].rgba.clone(); + std::fs::write(&edited_path, texturecraft_formats::gray16_png(1, 1, [0.8].into_iter()).unwrap()).unwrap(); + + let result = crate::execute(&mut session, "resource.update", &json!({})).unwrap(); + let updated = session.images[&edited].rgba.clone(); + let steps_after = session.history_labels().len(); + session.undo().unwrap(); + + assert_eq!(unchanged["updated"], json!([]), "files that didn't change aren't read in again"); + assert_eq!(result["updated"], json!([edited]), "only the changed file is read again, not `{kept}`"); + assert_ne!(updated, before, "the changed file's new pixels show"); + assert_eq!(steps_after, steps + 1, "one undo step for the update"); + assert_eq!(session.images[&edited].rgba, before, "undo shows the old pixels again"); + std::fs::remove_file(edited_path).unwrap(); + std::fs::remove_file(kept_path).unwrap(); + } + #[test] fn file_reads_obey_the_remaining_byte_budget() { let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2441b1d1..f49d4d4e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -146,6 +146,7 @@ pub mod shelf_panes; pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; +pub mod shelf_updates; pub mod shelf_view; mod slot_thumbnail; #[cfg(not(target_arch = "wasm32"))] @@ -1090,6 +1091,7 @@ impl eframe::App for TextureCraftApp { self.ui.prefs.apply_resource_limits(); control::poll(self, ctx); + shelf_updates::tick(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.run_file_dialog_answers(); web_files::poll(self); diff --git a/crates/ui-egui/src/property_sheet/info_icon.rs b/crates/ui-egui/src/property_sheet/info_icon.rs index a8cbee52..dc866982 100644 --- a/crates/ui-egui/src/property_sheet/info_icon.rs +++ b/crates/ui-egui/src/property_sheet/info_icon.rs @@ -1,7 +1,7 @@ use egui::{Align2, CornerRadius, FontId, Frame, Margin, Rect, RectAlign, RichText, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; -use super::{PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE}; +use super::{PropertySheet, ROW_HEIGHT, SIDE_PADDING_POINTS, SMALL_TEXT_SIZE}; use crate::theme::HARD_SHADOW; /// The i's slot at the panel edge; a row with an i at its left starts this much further right @@ -16,6 +16,9 @@ const INFO_ICON_SIZE: f32 = 13.0; /// Room the tooltip leaves at the panel's right edge, so it covers no number, dial or switch const TIP_VALUE_ROOM: f32 = 70.0; +/// Width of a tooltip beside its window +const BESIDE_TIP_WIDTH: f32 = 320.0; + /// How far the tooltip reaches up into its row const TIP_OVERLAP: f32 = 2.0; @@ -47,6 +50,48 @@ impl<'u> PropertySheet<'u> { self.paint_info_in(self.right - INFO_SLOT, self.right - INFO_ICON_SIZE / 2.0, center_y); } + /// Paints an i for the row just laid out in the `column` right of the sheet, its tooltip beside the window the sheet is in + pub(crate) fn beside_info(&mut self, column: f32, tip: &str) { + let center_y = self.cursor_y() - ROW_HEIGHT / 2.0; + let row_top = center_y - ROW_HEIGHT / 2.0; + let edge = self.right + SIDE_PADDING_POINTS + column; + let slot = Rect::from_min_max(pos2(edge - SIDE_PADDING_POINTS - INFO_SLOT, row_top), pos2(edge - SIDE_PADDING_POINTS, row_top + ROW_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(slot, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tip)); + + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + self.ui.painter().text(slot.center(), Align2::CENTER_CENTER, ic::INFO, FontId::proportional(INFO_ICON_SIZE), color); + + // Beside the window, from this row down, so it covers none of the rows under it + let layer = self.ui.layer_id().id; + let window = self.ui.ctx().memory(|memory| memory.area_rect(layer)).unwrap_or(self.ui.clip_rect()); + let anchor = Rect::from_min_max(pos2(window.left(), row_top), pos2(window.right(), row_top + ROW_HEIGHT)); + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip + .popup + .anchor(anchor) + .align(RectAlign::RIGHT_START) + .align_alternatives(&[RectAlign::LEFT_START]) + .frame(self.tip_frame()) + .width(BESIDE_TIP_WIDTH); + tooltip.show(|ui| { + ui.set_width(BESIDE_TIP_WIDTH); + ui.label(RichText::new(tip).size(SMALL_TEXT_SIZE).color(tokens.text).line_height(Some(TIP_LINE_HEIGHT))); + }); + } + + /// The tooltips' box: the chrome, a hairline, rounded, with a hard shadow + fn tip_frame(&self) -> Frame { + Frame::NONE + .fill(self.tokens.chrome) + .stroke(Stroke::new(1.0, self.tokens.field_border)) + .corner_radius(CornerRadius::same(TIP_ROUNDING)) + .inner_margin(TIP_MARGIN) + .shadow(TIP_SHADOW) + } + /// Paints the pending i at `glyph_x` in its slot from `slot_left` fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) { let Some(tip) = self.info.take() else { return }; @@ -63,12 +108,7 @@ impl<'u> PropertySheet<'u> { // Under the row from the i, ending before the value column; above it where the window ends first let anchor = Rect::from_min_max(pos2(self.left, row_top), pos2(self.right - TIP_VALUE_ROOM, row_top + ROW_HEIGHT)); - let frame = Frame::NONE - .fill(tokens.chrome) - .stroke(Stroke::new(1.0, tokens.field_border)) - .corner_radius(CornerRadius::same(TIP_ROUNDING)) - .inner_margin(TIP_MARGIN) - .shadow(TIP_SHADOW); + let frame = self.tip_frame(); let text_width = anchor.width() - TIP_MARGIN.sum().x; let mut tooltip = egui::Tooltip::for_enabled(&response); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 62c81046..78fb2e4d 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -68,6 +68,7 @@ pub(crate) use section_tabs::{ pub(crate) use sheet::PropertySheet; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; +pub(crate) use switch_control::TOGGLE_ROOM; /// Side padding: every row starts and ends this far inside the panel pub(crate) const SIDE_PADDING_POINTS: f32 = 12.0; @@ -103,7 +104,7 @@ const VALUE_MIN_WIDTH: f32 = 26.0; const TRACK_TO_VALUE: f32 = 14.0; /// Size of regular labels and SemiBold values -const TEXT_SIZE: f32 = 12.0; +pub(crate) const TEXT_SIZE: f32 = 12.0; /// Size of captions, pill names and the switch's words const SMALL_TEXT_SIZE: f32 = 11.0; diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs index 5fe48e1f..bc17fa4f 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs @@ -5,4 +5,6 @@ pub(crate) enum SectionScope { Docked, /// The right-click Properties popup over a view Popup, + /// The Assets panel's refresh popup, which has no strip + Shelf, } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 7443f9f4..85e007be 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -38,6 +38,9 @@ const TOGGLE_LABEL_AIR: f32 = 10.0; /// From that column to the pill's centre: the pill starts on the column const TOGGLE_CENTER_OFFSET: f32 = PILL_SIZE.x / 2.0; +/// Room a toggle takes right of its label: the air and the switch +pub(crate) const TOGGLE_ROOM: f32 = TOGGLE_LABEL_AIR + PILL_SIZE.x; + /// From one of a pair's toggles to the next, and from its name to its pill's centre const PAIR_PITCH: f32 = 76.0; const PAIR_NAME_TO_PILL: f32 = 32.0; @@ -191,6 +194,15 @@ impl PropertySheet<'_> { /// An on/off beside its label; every toggle in a panel lines up past the longest toggle label pub(crate) fn toggle(&mut self, label: &str, on: &mut bool) -> bool { + self.toggle_in(label, on, true) + } + + /// A [`Self::toggle`] greyed out and off: a setting this app can't act on yet, said in its row's i + pub(crate) fn unavailable_toggle(&mut self, label: &str) { + self.toggle_in(label, &mut false, false); + } + + fn toggle_in(&mut self, label: &str, on: &mut bool, enabled: bool) -> bool { let rect = self.take(ROW_HEIGHT); let center_y = rect.center().y; let label_x = self.left + self.lead_shift(); @@ -201,11 +213,19 @@ impl PropertySheet<'_> { let column = (self.column() - self.left).max(self.used.toggle_label_end).max(label_end); let pill = Rect::from_center_size(pos2(self.left + column + TOGGLE_CENTER_OFFSET, center_y), PILL_SIZE); - let clicked = self.toggle_hit(Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())), label, on); + let hit = Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())); + let clicked = if enabled { + self.toggle_hit(hit, label, on) + } else { + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::hover()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, false, false, label)); + false + }; - let text = self.tokens.text; + let text = if enabled { self.tokens.text } else { self.tokens.text_dim }; self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, label, font, text); - self.pill(pill.center(), *on, true); + self.pill(pill.center(), *on, enabled); self.drawn(center_y + PILL_SIZE.y / 2.0); clicked } diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index c7c00b81..99a80cb6 100644 --- a/crates/ui-egui/src/shelf_toolbar.rs +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -1,4 +1,4 @@ -//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh with its update settings, reset query and import on the right use egui::Ui; use egui_phosphor::regular as ic; @@ -18,6 +18,7 @@ pub(crate) fn height(ui: &Ui) -> f32 { /// The toolbar pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let size = ui.spacing().interact_size.y; + let panel = ui.max_rect(); ui.add_space(GAP_ABOVE); ui.horizontal(|ui| { crate::shelf_panes::toggles(app, ui, size); @@ -28,9 +29,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() { reset_query(app); } - if icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Refresh"), false, size).clicked() { - refresh(app); - } + crate::shelf_updates::button(app, ui, size, panel); }); }); } @@ -42,15 +41,3 @@ pub(crate) fn reset_query(app: &mut TextureCraftApp) { app.ui.shelf_path.clear(); app.ui.shelf_favorites_only = false; } - -/// Read the user's saved assets from disk again and redraw their thumbnails -fn refresh(app: &mut TextureCraftApp) { - app.library = None; - - #[cfg(not(target_arch = "wasm32"))] - for warning in app.session.load_brush_presets(crate::user_dir("brushes")) { - app.toast(warning, true); - } - - app.thumbs.forget_saved_files(); -} diff --git a/crates/ui-egui/src/shelf_updates.rs b/crates/ui-egui/src/shelf_updates.rs new file mode 100644 index 00000000..8300357d --- /dev/null +++ b/crates/ui-egui/src/shelf_updates.rs @@ -0,0 +1,211 @@ +//! The shelf's refresh popup: read the Assets panel and the project's images again every few minutes, or now by hand + +use egui::{Context, Id, Ui, vec2}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::i18n::{n_, tr}; +use crate::property_sheet::{NumberField, PropertySheet, SIDE_PADDING_POINTS, SectionScope, in_scope}; +use crate::widgets::icon_dropdown_button; + +/// Least and most minutes between automatic updates +const MIN_MINUTES: u32 = 1; +const MAX_MINUTES: u32 = 24 * 60; + +/// Air between the popup and the toolbar under it +const POPUP_GAP: f32 = 1.0; + +/// Air between the two update buttons and under the last one +const BUTTON_GAP: f32 = 6.0; + +/// Room right of a row's switch for its i +const INFO_COLUMN: f32 = 28.0; + +/// How soon a run that waited for a stroke tries again +const STROKE_RETRY: std::time::Duration = std::time::Duration::from_millis(250); + +/// A drag of 20 points moves the minutes by one +const MINUTES_PER_DRAG_POINT: f32 = 0.05; + +/// How much shorter a manual update button is than a sheet row, so neighbouring buttons don't touch +const BUTTON_INSET: f32 = 4.0; + +const SKIP_MISMATCH: &str = n_("Skip assets when their parameters mismatch"); + +/// Which automatic updates are on and how often they run +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ShelfUpdates { + /// Read the user's saved assets again + pub assets: bool, + /// Read the images the project imported from files in this session again when a file changed + pub resources: bool, + pub minutes: u32, +} + +impl Default for ShelfUpdates { + fn default() -> Self { + ShelfUpdates { assets: false, resources: false, minutes: MIN_MINUTES } + } +} + +/// When the automatic updates last ran, on egui's clock +fn last_run_id() -> Id { + Id::unique("shelf_updates_last_run") +} + +/// Runs the automatic updates once their minutes have passed since the last run, and wakes the app for the next one +pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &Context) { + let updates = app.ui.shelf_updates; + if !updates.assets && !updates.resources { + ctx.data_mut(|data| data.remove::(last_run_id())); + return; + } + + // An update during a stroke would land in the stroke's undo step: it waits for the stroke to end + if app.session.stroke_active() { + ctx.request_repaint_after(STROKE_RETRY); + return; + } + + let now = ctx.input(|input| input.time); + let every = f64::from(updates.minutes.clamp(MIN_MINUTES, MAX_MINUTES)) * 60.0; + let last = ctx.data_mut(|data| *data.get_temp_mut_or(last_run_id(), now)); + if now - last < every { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(every - (now - last))); + return; + } + + ctx.data_mut(|data| data.insert_temp(last_run_id(), now)); + if updates.assets { + refresh_assets(app); + } + if updates.resources { + update_resources(app, ctx); + } + ctx.request_repaint_after(std::time::Duration::from_secs_f64(every)); +} + +/// Read the user's saved assets from disk again and redraw their thumbnails +pub(crate) fn refresh_assets(app: &mut TextureCraftApp) { + app.library = None; + + #[cfg(not(target_arch = "wasm32"))] + for warning in app.session.load_brush_presets(crate::user_dir("brushes")) { + app.toast(warning, true); + } + + app.thumbs.forget_saved_files(); +} + +/// Reads the project's changed image files again; a file that can't be read says why once, until it reads again +fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { + let Some(result) = app.run("resource.update", json!({})) else { return }; + + let failures: Vec<(String, String)> = result["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failure| (failure["name"].as_str().unwrap_or_default().to_owned(), failure["error"].as_str().unwrap_or_default().to_owned())) + .collect(); + let mut reported: Vec = ctx.data(|data| data.get_temp(reported_failures_id())).unwrap_or_default(); + reported.retain(|name| failures.iter().any(|(failed, _)| failed == name)); + for (name, error) in failures { + if !reported.contains(&name) { + app.toast(format!("{name}: {error}"), true); + reported.push(name); + } + } + ctx.data_mut(|data| data.insert_temp(reported_failures_id(), reported)); +} + +/// The files whose failure to read was already shown (ctx temp data) +fn reported_failures_id() -> Id { + Id::unique("shelf_updates_reported_failures") +} + +/// The refresh button with its popup of update settings, opening upward from the toolbar `panel` with its left edge on the panel's +pub(crate) fn button(app: &mut TextureCraftApp, ui: &mut Ui, size: f32, panel: egui::Rect) { + let label = tr("Refresh"); + let response = icon_dropdown_button(ui, ic::ARROWS_CLOCKWISE, label, false, size).on_hover_text(label); + let width = popup_width(ui, panel.width()); + egui::Popup::from_toggle_button_response(&response) + .anchor(panel) + .align(egui::RectAlign::TOP_START) + .gap(POPUP_GAP) + .width(width) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + ui.set_width(width); + popup(app, ui); + }); +} + +/// The panel's width, or wider to fit the longest row +fn popup_width(ui: &Ui, panel_width: f32) -> f32 { + let font = egui::FontId::proportional(crate::property_sheet::TEXT_SIZE); + let longest = ui.painter().layout_no_wrap(tr(SKIP_MISMATCH).to_owned(), font, egui::Color32::WHITE).size().x; + panel_width.max(longest + crate::property_sheet::TOGGLE_ROOM + INFO_COLUMN + 2.0 * SIDE_PADDING_POINTS) +} + +fn popup(app: &mut TextureCraftApp, ui: &mut Ui) { + let updates = &mut app.ui.shelf_updates; + let full = ui.available_rect_before_wrap(); + let rows = full.with_max_x(full.right() - INFO_COLUMN); + in_scope(ui, SectionScope::Shelf, |ui| { + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + PropertySheet::show(ui, "shelf_updates", |sheet| { + sheet.section(tr("Automatic updates"), false); + sheet.toggle(tr("Assets panel"), &mut updates.assets); + sheet.beside_info(INFO_COLUMN, tr("Reads your saved assets from disk again every few minutes, so new and changed ones show here.")); + sheet.toggle(tr("Resources used in project"), &mut updates.resources); + sheet.beside_info( + INFO_COLUMN, + tr("Every few minutes, reads again the images this project imported from files in this session whose files changed. Each update is one undo step."), + ); + + let mut minutes = [NumberField { + tag: "", + tag_color: None, + value: updates.minutes as f32, + speed: MINUTES_PER_DRAG_POINT, + decimals: 0, + suffix: tr(" min"), + }]; + if sheet.number_fields(tr("Update every"), &mut minutes, None, false).is_some() { + updates.minutes = (minutes[0].value.round() as u32).clamp(MIN_MINUTES, MAX_MINUTES); + } + sheet.beside_info(INFO_COLUMN, tr("How often the automatic updates above run.")); + + sheet.section(tr("Advanced settings"), false); + sheet.unavailable_toggle(tr(SKIP_MISMATCH)); + sheet.beside_info( + INFO_COLUMN, + tr("For assets with parameters: an update whose parameters were renamed or removed would change your texturing, so it is skipped. TextureCraft doesn't update assets with parameters from their files yet, so there is nothing to skip."), + ); + + sheet.section(tr("Manual"), false); + }); + }); + }); + + let button_size = vec2(full.width() - 2.0 * SIDE_PADDING_POINTS, crate::property_sheet::ROW_HEIGHT - BUTTON_INSET); + let add_button = |ui: &mut Ui, label: &str| { + let clicked = ui + .horizontal(|ui| { + ui.add_space(SIDE_PADDING_POINTS); + ui.add_sized(button_size, egui::Button::new(label)).clicked() + }) + .inner; + ui.add_space(BUTTON_GAP); + clicked + }; + if add_button(ui, tr("Update Assets panel")) { + refresh_assets(app); + } + if add_button(ui, tr("Update resources used in project")) { + update_resources(app, ui.ctx()); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index debef955..7caf4d29 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -593,6 +593,9 @@ pub struct UiState { /// The asset shelf shows only favorites (the Favorites saved search) #[serde(default)] pub shelf_favorites_only: bool, + /// The asset shelf's automatic updates (its refresh popup) + #[serde(default)] + pub shelf_updates: crate::shelf_updates::ShelfUpdates, /// Pictures the user picked to show on asset tiles instead of their thumbnails #[serde(default)] pub shelf_custom_previews: Vec, @@ -755,6 +758,7 @@ impl UiState { self.shelf_favorites = keep.shelf_favorites; self.shelf_favorites_only = keep.shelf_favorites_only; self.shelf_custom_previews = keep.shelf_custom_previews; + self.shelf_updates = keep.shelf_updates; } } @@ -792,6 +796,7 @@ impl Default for UiState { shelf_favorites: Vec::new(), shelf_favorites_only: false, shelf_custom_previews: Vec::new(), + shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), props_tab: PropsTab::Brush, text: TextUi::default(), @@ -928,6 +933,7 @@ mod tests { ui.shelf_favorites.push(favorite.clone()); let preview = crate::shelf_custom_preview::ShelfCustomPreview { kind: "material".into(), id: "gold".into(), file: "gold.png".into() }; ui.shelf_custom_previews.push(preview.clone()); + ui.shelf_updates.resources = true; ui.adopt_layout(UiState::default()); @@ -936,6 +942,7 @@ mod tests { assert_eq!(ui.shelf_favorites, [favorite], "favorites are the user's own too"); assert!(ui.shelf_favorites_only, "the Favorites search is part of the query"); assert_eq!(ui.shelf_custom_previews, [preview], "custom previews are the user's own"); + assert!(ui.shelf_updates.resources, "automatic updates are a setting, not part of a layout"); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index fd55514b..580812c5 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -83,6 +83,7 @@ mod shelf_drop; mod shelf_hover_preview; mod shelf_menu; mod shelf_panel; +mod shelf_updates; mod shift_lines_2d; mod shift_lines_3d; mod shortcut_keys; diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 7dcd12a4..06856a41 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -152,6 +152,8 @@ fn refresh_reads_the_saved_brushes_again() { harness.run_steps(1); button(&harness, "Refresh").click(); + harness.run_steps(2); + button(&harness, "Update Assets panel").click(); harness.run_steps(3); assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again"); diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs new file mode 100644 index 00000000..0a3e06fd --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -0,0 +1,91 @@ +//! The Assets panel's refresh popup: automatic updates of the panel and of the project's images + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::brush_preset_cmds::UserBrush; +use texturecraft_ui_egui::TextureCraftApp; + +/// A little more than the shortest update interval, in seconds +const PAST_A_MINUTE: f64 = 61.0; + +/// The sample project with the Assets panel open and its refresh popup shown +fn refresh_popup() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1920.0, 1032.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(2); + harness.get_all_by_label("Refresh").next().unwrap().click(); + harness.run_steps(2); + harness +} + +/// Moves the app's clock on by more than a minute in one frame, then lets the frames after it settle +fn pass_a_minute(harness: &mut Harness<'_, TextureCraftApp>) { + let now = harness.ctx.input(|input| input.time); + harness.input_mut().time = Some(now + PAST_A_MINUTE); + harness.run_steps(2); +} + +/// A grey one-pixel PNG of `value` +fn grey_png(value: f32) -> Vec { + texturecraft_engine::formats::gray16_png(1, 1, [value].into_iter()).unwrap() +} + +#[test] +fn turning_on_project_resources_reads_a_changed_image_file_again_every_minute() { + let mut harness = refresh_popup(); + let path = std::env::temp_dir().join(format!("texturecraft-auto-update-{}.png", std::process::id())); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let before = harness.state().session.images[&name].rgba.clone(); + std::fs::write(&path, grey_png(0.8)).unwrap(); + + pass_a_minute(&mut harness); + let while_off = harness.state().session.images[&name].rgba.clone(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + pass_a_minute(&mut harness); + let after = harness.state().session.images[&name].rgba.clone(); + std::fs::remove_file(path).unwrap(); + + assert_eq!(while_off, before, "nothing is read again while automatic updates are off"); + assert!(harness.state().ui.shelf_updates.resources, "the switch turned the update on"); + assert_ne!(after, before, "the changed file was read again within a minute"); +} + +#[test] +fn turning_on_the_assets_panel_reads_the_saved_brushes_again_every_minute() { + let mut harness = refresh_popup(); + let stale = UserBrush { name: "Stale brush marker".into(), brush: Default::default(), channels: None, file: None }; + harness.state_mut().session.brush_presets.list.push(stale); + + harness.get_by_label("Assets panel").click(); + harness.run_steps(2); + pass_a_minute(&mut harness); + + assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again"); +} + +#[test] +fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { + let mut harness = refresh_popup(); + let path = std::env::temp_dir().join(format!("texturecraft-auto-update-stroke-{}.png", std::process::id())); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let before = harness.state().session.images[&name].rgba.clone(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + std::fs::write(&path, grey_png(0.8)).unwrap(); + + harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + pass_a_minute(&mut harness); + let during_stroke = harness.state().session.images[&name].rgba.clone(); + harness.state_mut().session.end_stroke().unwrap(); + harness.run_steps(2); + let after_stroke = harness.state().session.images[&name].rgba.clone(); + std::fs::remove_file(path).unwrap(); + + assert_eq!(during_stroke, before, "nothing is read again while a stroke is under way"); + assert_ne!(after_stroke, before, "the update runs once the stroke ended"); + assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.8).as_slice(), "the stroke's undo state didn't swallow the update"); +} From 9e6aa0f865b0126befde56bed269a2287b101f8a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:29:05 +0000 Subject: [PATCH 044/190] Assets: dragged assets follow the pointer with a badge saying whether the place under it takes them --- crates/ui-egui/src/dock.rs | 13 +- crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/shelf.rs | 32 ++--- crates/ui-egui/src/shelf_drag_ghost.rs | 130 ++++++++++++++++++ crates/ui-egui/src/shelf_drag_verdict.rs | 10 ++ .../ui-egui/tests/it/display_environment.rs | 2 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_drag_ghost.rs | 66 +++++++++ crates/ui-egui/tests/it/shelf_drop.rs | 2 +- crates/ui-egui/tests/it/stencil.rs | 2 +- crates/ui-egui/tests/ui_snapshots.rs | 58 ++++++++ 11 files changed, 297 insertions(+), 24 deletions(-) create mode 100644 crates/ui-egui/src/shelf_drag_ghost.rs create mode 100644 crates/ui-egui/src/shelf_drag_verdict.rs create mode 100644 crates/ui-egui/tests/it/shelf_drag_ghost.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e7efb8b9..e904046d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -174,6 +174,9 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { _ => {} } let material = response.dnd_hover_payload::().is_some_and(|drag| drag.asset.is_material()); + if material { + crate::shelf_drag_ghost::accept(ui.ctx()); + } if response.dnd_hover_payload::().is_some() || material { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(DROP_STROKE, tokens.accent)); } @@ -740,6 +743,11 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let moving = row.dnd_hover_payload::().is_some_and(|dragged| !in_drag(app, *dragged)); let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); let shelf_material = shelf.as_ref().is_some_and(Asset::is_material); + let shelf_mask = matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))); + let shelf_filter = matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group(); + if shelf_material || shelf_mask || shelf_filter { + crate::shelf_drag_ghost::accept(&row.ctx); + } if moving || shelf_material { if inside { painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); @@ -748,9 +756,9 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } else { painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); } - } else if matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))) { + } else if shelf_mask { painter.rect_stroke(mask_rect.expand(HIGHLIGHT_OUTSET), THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Outside); - } else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() { + } else if shelf_filter { painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } if let Some(dragged) = dnd_release::(&row) @@ -1790,6 +1798,7 @@ pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { } ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, Tokens::get(ui.ctx()).accent), egui::StrokeKind::Inside); + crate::shelf_drag_ghost::accept(ui.ctx()); match dnd_release::(resp).map(|d| d.asset.clone()) { Some(Asset::Texture(name)) => Some(name), _ => None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f49d4d4e..df72f333 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -138,6 +138,8 @@ pub mod settings_window; pub mod shader_settings; pub mod shelf; pub mod shelf_custom_preview; +pub mod shelf_drag_ghost; +pub mod shelf_drag_verdict; mod shelf_entry; pub mod shelf_favorite; mod shelf_folders; @@ -1197,6 +1199,9 @@ impl eframe::App for TextureCraftApp { egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); + // After every drop target has said whether it takes the dragged asset + shelf_drag_ghost::show(&ctx); + // Finish after the dock and windows have requested their thumbnails self.layer_panel.end(&ctx, &self.session); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 3431f405..7bed8f3e 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -108,10 +108,12 @@ impl Asset { } /// The drag-and-drop payload of a shelf tile. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct ShelfDrag { pub asset: Asset, pub label: String, + /// The tile's thumbnail, shown at the pointer while dragging (the name when there is none) + pub thumb: Option, } /// Apply `asset` the way a shelf click does: a simple material becomes the brush's material (no @@ -217,8 +219,14 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::SmartMask(_) | Asset::SavedMask(_) | Asset::Filter(_) => false, }; let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.goes_onto_set(); - if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { - ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); + if let Some(drag) = response.dnd_hover_payload::().filter(|drag| accepts(drag)) { + // The 3D view outlines the set under the pointer itself; its background takes nothing + if !onto_set(&drag.asset) { + ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); + crate::shelf_drag_ghost::accept(ui.ctx()); + } else if set_under_pointer(app, ui, response).is_some() { + crate::shelf_drag_ghost::accept(ui.ctx()); + } } let pointer = ui.input(|input| input.pointer.interact_pos()); @@ -252,7 +260,6 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response /// The Assets panel body (a dock tab) pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let ctx = ui.ctx().clone(); let filter = app.ui.shelf_filter.to_lowercase(); scan_library(app); let all_entries = ShelfEntry::all(app); @@ -334,7 +341,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { grid(app, ui, &entries, grid_rect.height(), [saved_materials, saved_masks], show_user_brushes, &filter); }); ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui)); - drag_preview(&ctx); } /// The tiles of `entries` in a scroll area `height` high, then user brushes, saved smart materials and saved smart masks when selected @@ -391,18 +397,6 @@ fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -/// The dragged asset's name next to the pointer. -fn drag_preview(ctx: &egui::Context) { - let tk = Tokens::get(ctx); - let (Some(d), Some(pos)) = (egui::DragAndDrop::payload::(ctx), ctx.input(|i| i.pointer.hover_pos())) else { return }; - let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("shelf_drag"))); - let galley = p.layout_no_wrap(d.label.clone(), egui::FontId::proportional(11.0), tk.text_strong); - let rect = egui::Rect::from_min_size(pos + vec2(14.0, 12.0), galley.size() + vec2(12.0, 6.0)); - p.rect_filled(rect, 3.0, tk.row_selected); - p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong); -} - pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } @@ -501,7 +495,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { let location = path.display().to_string(); let asset = if masks { Asset::SavedMask(location) } else { Asset::Library(location) }; if response.drag_started() { - response.dnd_set_drag_payload(ShelfDrag { asset, label: label.to_owned() }); + response.dnd_set_drag_payload(ShelfDrag { asset, label: label.to_owned(), thumb: None }); } else { selected.push(asset); } @@ -604,7 +598,7 @@ fn tile_in_view( if let Some(asset) = drag && response.drag_started() { - response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string(), thumb: texture.clone() }); } let painter = ui.painter(); diff --git a/crates/ui-egui/src/shelf_drag_ghost.rs b/crates/ui-egui/src/shelf_drag_ghost.rs new file mode 100644 index 00000000..05f311af --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_ghost.rs @@ -0,0 +1,130 @@ +//! The picture that follows the pointer while an asset is dragged from the Assets panel, with a +//! badge on its corner saying whether the place under the pointer takes the asset + +use egui::{Color32, Context, Id, LayerId, Order, Pos2, Rect, Stroke, Vec2, vec2}; + +use crate::shelf::ShelfDrag; +pub use crate::shelf_drag_verdict::Verdict; +use crate::theme::Tokens; + +/// Side of the dragged asset's thumbnail +const GHOST_SIZE: f32 = 48.0; + +/// The thumbnail's top-left corner from the pointer: just under its tip +const GHOST_OFFSET: Vec2 = vec2(4.0, 4.0); + +/// How opaque the thumbnail is, so the target shows through it +const GHOST_OPACITY: f32 = 0.6; + +/// Corner rounding of the name chip +const CHIP_ROUNDING: f32 = 3.0; + +/// Side of the badge +const BADGE_SIZE: f32 = 9.0; + +/// The badge's centre from the pointer: past the pointer arrow's tail, on the thumbnail's corner +const BADGE_OFFSET: Vec2 = vec2(14.0, 22.0); + +/// Size of the badge's icon +const BADGE_ICON_SIZE: f32 = 7.5; + +/// Corner rounding of the square badge +const BADGE_ROUNDING: f32 = 2.0; + +/// Fill of the square badge and colour of the icon on the red one +const BADGE_LIGHT: Color32 = Color32::from_gray(245); + +/// Colour of the icon on the square badge +const BADGE_DARK: Color32 = Color32::from_gray(35); + +/// Opacity of the thin dark outline that keeps the badge apart from whatever is under it +const BADGE_OUTLINE_ALPHA: u8 = 140; + +/// Padding of the name chip shown when the asset has no thumbnail +const CHIP_PADDING: Vec2 = vec2(6.0, 3.0); + +/// Text size of the name chip +const CHIP_TEXT_SIZE: f32 = 11.0; + +/// Pass number of the last drop target that took the dragged asset (ctx temp data) +const ACCEPTED: &str = "shelf_drag_accepted"; + +/// What the last pass painted (ctx temp data) +const SHOWN: &str = "shelf_drag_shown"; + +/// The ghost as the last pass painted it +#[derive(Clone, Copy, Debug)] +pub struct Shown { + /// What the badge says + pub verdict: Verdict, + /// Where the thumbnail (or the name chip) is + pub ghost: Rect, + /// Where the badge is + pub badge: Rect, +} + +/// Note that the drop target being drawn takes the dragged asset, where it paints its drop highlight +pub(crate) fn accept(ctx: &Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| data.insert_temp(Id::unique(ACCEPTED), pass)); +} + +/// The ghost painted this pass, if an asset is being dragged +pub fn shown(ctx: &Context) -> Option { + ctx.data(|data| data.get_temp(Id::unique(SHOWN))) +} + +/// Paint the dragged asset and its badge at the pointer, once a pass after every drop target +pub(crate) fn show(ctx: &Context) { + let (Some(drag), Some(pointer)) = (egui::DragAndDrop::payload::(ctx), ctx.input(|input| input.pointer.hover_pos())) else { + ctx.data_mut(|data| data.remove::(Id::unique(SHOWN))); + return; + }; + + let pass = ctx.cumulative_pass_nr(); + let accepted = ctx.data(|data| data.get_temp::(Id::unique(ACCEPTED))) == Some(pass); + let verdict = if accepted { Verdict::Valid } else { Verdict::NotValid }; + let painter = ctx.layer_painter(LayerId::new(Order::Tooltip, Id::unique("shelf_drag_ghost"))); + let tokens = Tokens::get(ctx); + + let ghost = match &drag.thumb { + Some(thumb) => { + let rect = Rect::from_min_size(pointer + GHOST_OFFSET, Vec2::splat(GHOST_SIZE)); + let uv = Rect::from_min_max(Pos2::ZERO, egui::pos2(1.0, 1.0)); + painter.image(thumb.id(), rect, uv, Color32::WHITE.gamma_multiply(GHOST_OPACITY)); + rect + } + None => name_chip(&painter, &tokens, pointer + GHOST_OFFSET, &drag.label), + }; + let badge = badge(&painter, &tokens, pointer + BADGE_OFFSET, verdict); + ctx.data_mut(|data| data.insert_temp(Id::unique(SHOWN), Shown { verdict, ghost, badge })); +} + +/// The asset's name in a chip at `top_left`, for assets without a thumbnail (saved smart materials) +fn name_chip(painter: &egui::Painter, tokens: &Tokens, top_left: Pos2, label: &str) -> Rect { + let galley = painter.layout_no_wrap(label.to_owned(), egui::FontId::proportional(CHIP_TEXT_SIZE), tokens.text_strong); + let rect = Rect::from_min_size(top_left, galley.size() + CHIP_PADDING * 2.0); + painter.rect_filled(rect, CHIP_ROUNDING, tokens.row_selected); + painter.rect_stroke(rect, CHIP_ROUNDING, Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + painter.galley(rect.min + CHIP_PADDING, galley, tokens.text_strong); + rect +} + +/// The badge at `centre`: a crosshair on a light square where a drop works, else a no-entry sign +fn badge(painter: &egui::Painter, tokens: &Tokens, centre: Pos2, verdict: Verdict) -> Rect { + let rect = Rect::from_center_size(centre, Vec2::splat(BADGE_SIZE)); + let outline = Stroke::new(1.0, Color32::from_black_alpha(BADGE_OUTLINE_ALPHA)); + let (icon, color) = match verdict { + Verdict::Valid => { + painter.rect(rect, BADGE_ROUNDING, BADGE_LIGHT, outline, egui::StrokeKind::Outside); + (egui_phosphor::regular::CROSSHAIR_SIMPLE, BADGE_DARK) + } + Verdict::NotValid => { + painter.circle(centre, BADGE_SIZE / 2.0, tokens.danger, outline); + (egui_phosphor::regular::PROHIBIT, BADGE_LIGHT) + } + }; + let glyph = painter.layout_no_wrap(icon.to_owned(), egui::FontId::proportional(BADGE_ICON_SIZE), color); + painter.galley(centre - glyph.mesh_bounds.center().to_vec2(), glyph, color); + rect.expand(outline.width) +} diff --git a/crates/ui-egui/src/shelf_drag_verdict.rs b/crates/ui-egui/src/shelf_drag_verdict.rs new file mode 100644 index 00000000..b6713b95 --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_verdict.rs @@ -0,0 +1,10 @@ +//! What the drag badge says about the place under the pointer + +/// Whether the place under the pointer takes the dragged asset +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + /// A drop here does something: a crosshair on a light square + Valid, + /// A drop here does nothing: a no-entry sign on red + NotValid, +} diff --git a/crates/ui-egui/tests/it/display_environment.rs b/crates/ui-egui/tests/it/display_environment.rs index 66cfff9f..46a785ca 100644 --- a/crates/ui-egui/tests/it/display_environment.rs +++ b/crates/ui-egui/tests/it/display_environment.rs @@ -107,7 +107,7 @@ fn an_image_dropped_on_the_slot_becomes_the_environment() { h.run_steps(SETTLE); let slot = h.get_by_role_and_label(Role::Button, "Studio Soft").rect().center(); - egui::DragAndDrop::set_payload(&h.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() }); + egui::DragAndDrop::set_payload(&h.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None }); h.hover_at(slot); h.run_steps(2); h.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 580812c5..7354a597 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -79,6 +79,7 @@ mod rename_anchor; mod reset_ui; mod settings_window; mod shelf_click; +mod shelf_drag_ghost; mod shelf_drop; mod shelf_hover_preview; mod shelf_menu; diff --git a/crates/ui-egui/tests/it/shelf_drag_ghost.rs b/crates/ui-egui/tests/it/shelf_drag_ghost.rs new file mode 100644 index 00000000..8311846f --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_drag_ghost.rs @@ -0,0 +1,66 @@ +//! Dragging an asset from the Assets panel shows it at the pointer with a badge on its corner that says +//! whether the place under the pointer takes it + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::materials::MATERIALS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_drag_ghost::{Verdict, shown}; + +/// Distance between the view points searched for a set or the background +const SEARCH_STEP: f32 = 8.0; + +/// How far the pointer moves off the tile before it counts as a drag +const DRAG_START: f32 = 12.0; + +/// The sample project at 1600 x 960, the shelf on Materials +fn sample_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// The first point of the 3D view showing texture set `set`, or the background when `None` +fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let steps = |length: f32| (1..(length / SEARCH_STEP) as usize).map(|step| step as f32 * SEARCH_STEP); + + steps(rect.height()) + .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) + .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) + .map(|(x, y)| rect.min + egui::vec2(x, y)) + .unwrap() +} + +#[test] +fn the_badge_says_whether_the_place_under_the_pointer_takes_the_asset_without_covering_the_pointer() { + // The grid's first plain material (by name), so its tile is in view + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = sample_app(); + let (set, background) = (point_over(&harness, Some(0)), point_over(&harness, None)); + let tile = harness.get_all_by_label(material.label).next().unwrap().rect().center(); + assert!(shown(&harness.ctx).is_none(), "nothing follows the pointer before a drag"); + + harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(tile + vec2(DRAG_START, DRAG_START)); + harness.run_steps(2); + + let mut seen = Vec::new(); + for target in [set, background] { + harness.hover_at(target); + harness.run_steps(2); + let ghost = shown(&harness.ctx).expect("the dragged asset follows the pointer"); + assert!(ghost.badge.min.x > target.x && ghost.badge.min.y > target.y, "the badge leaves the pointer's tip clear"); + seen.push(ghost.verdict); + } + assert_eq!(seen, [Verdict::Valid, Verdict::NotValid], "a texture set takes a material, the background doesn't"); + + harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); +} diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index d1c732fd..a6c999b0 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -45,7 +45,7 @@ fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { /// Drop shelf `asset` at `position`, as a drag from the shelf ends there fn drop_asset(harness: &mut Harness<'_, TextureCraftApp>, asset: Asset, position: Pos2) { - egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into() }); + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into(), thumb: None }); harness.hover_at(position); harness.run_steps(2); diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index c746d213..178d1ab3 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -85,7 +85,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { assert!(harness.state().session.tool.stencil.is_none()); let slot = harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).unwrap().rect().center(); - egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() }); + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None }); harness.hover_at(slot); harness.run_steps(2); harness.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..bffa737b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -686,6 +686,64 @@ fn smart_material_shelf_snapshot() { save(&mut harness, &output_dir, "smart-material-hover"); } +/// A smart material dragged from the Assets panel over a texture set, then over the background +#[test] +#[ignore] +fn shelf_drag_ghost_snapshots() { + use egui::{Event, Modifiers, PointerButton, vec2}; + use texturecraft_engine::geom::glam::Vec2; + use texturecraft_engine::materials::MATERIALS; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + // The system draws the pointer, not the app + .with_render_cursor(false) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.shelf_tab = 1; + let material = MATERIALS.iter().find(|material| material.id == "steel_painted_worn").unwrap(); + let context = harness.ctx.clone(); + let started = std::time::Instant::now(); + while harness.state_mut().thumbs.material(&context, material.id).is_none() { + assert!(started.elapsed() < std::time::Duration::from_secs(120), "the material's thumbnail did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + harness.run_steps(1); + } + harness.run_steps(2); + + // The first view points showing a texture set and the background + let point_over = |harness: &Harness<'_, TextureCraftApp>, set: Option| { + let app = harness.state(); + let rect = app.viewport_rect; + let steps = |length: f32| (1..(length / 8.0) as usize).map(|step| step as f32 * 8.0); + steps(rect.height()) + .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) + .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) + .map(|(x, y)| rect.min + vec2(x, y)) + .unwrap() + }; + let (on_set, background) = (point_over(&harness, Some(0)), point_over(&harness, None)); + let on_set = on_set + vec2(40.0, 40.0); + + let tile = harness.get_by_role_and_label(egui::Role::Button, material.label).rect().center(); + harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(tile + vec2(12.0, 12.0)); + harness.run_steps(2); + for (target, name) in [(on_set, "drag-ghost-valid"), (background, "drag-ghost-not-valid")] { + harness.hover_at(target); + harness.run_steps(2); + save(&mut harness, &output_dir, name); + if let Some(shown) = texturecraft_ui_egui::shelf_drag_ghost::shown(&harness.ctx) { + std::fs::write(output_dir.join(format!("{name}.pointer.txt")), format!("{} {} {:?}", target.x, target.y, shown.verdict)).unwrap(); + } + } +} + /// Compact nested rows must keep their content, mask and effect controls in the panel. #[test] #[ignore] From f7fde16e58e60d91463bc0db44fec2697c2a839f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:44:05 +0000 Subject: [PATCH 045/190] Assets: the folder button opens a second Assets panel with its own search, type and folder --- crates/ui-egui/src/docking.rs | 19 +++++++---- crates/ui-egui/src/lib.rs | 2 ++ crates/ui-egui/src/shelf_query.rs | 24 ++++++++++++++ crates/ui-egui/src/shelf_second.rs | 23 +++++++++++++ crates/ui-egui/src/shelf_toolbar.rs | 5 ++- crates/ui-egui/src/state.rs | 5 +++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_second.rs | 44 +++++++++++++++++++++++++ 8 files changed, 116 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/shelf_query.rs create mode 100644 crates/ui-egui/src/shelf_second.rs create mode 100644 crates/ui-egui/tests/it/shelf_second.rs diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 761928ec..fd2cc368 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -29,6 +29,8 @@ pub(crate) use shown_group_tab::HEADER_TITLE_LEFT; pub enum Panel { Viewport, Assets, + /// A second Assets panel with its own search, type and folder (the Assets panel's folder button) + AssetsSecond, // Saved layouts name the bake panels by their earlier names #[serde(rename = "BakeMaps")] MeshMapSettings, @@ -82,7 +84,7 @@ impl Panel { use crate::state::Mode; match self { Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers | Self::BakingLog => mode == Mode::Baking, - Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting, + Self::Assets | Self::AssetsSecond | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting, Self::History => mode != Mode::Rendering, Self::Shader => mode != Mode::Baking, Self::Renderer => mode == Mode::Rendering, @@ -90,9 +92,10 @@ impl Panel { } } - pub const ALL: [Panel; 16] = [ + pub const ALL: [Panel; 17] = [ Panel::Viewport, Panel::Assets, + Panel::AssetsSecond, Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, @@ -113,6 +116,8 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", + // The second panel shows every type at first, so it's named for that, as the reference names it + Panel::AssetsSecond => "All", Panel::MeshMapSettings => "Mesh Map Settings", Panel::CommonSettings => "Common Settings", Panel::MeshMapBakers => "Mesh Map Bakers", @@ -194,12 +199,12 @@ pub fn default_workspace() -> Workspace { } } - for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { + for (panel, anchor) in [(MeshMapSettings, TextureSetList), (CommonSettings, TextureSetList), (MeshMapBakers, TextureSetList), (AssetsSecond, Assets)] { workspace.hidden.push(( panel, Location { floating: None, - anchor: Some(TextureSetList), + anchor: Some(anchor), placement: Placement::Tab { before: None }, size: None, stack: None, @@ -328,7 +333,7 @@ impl Dock { /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport pub(crate) fn for_baking() -> Self { let mut workspace = default_workspace(); - for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { + for panel in [Panel::Assets, Panel::AssetsSecond, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { if let Ok(location) = workspace.layout.location(&panel) { workspace.hidden.push((panel, location)); } @@ -558,7 +563,8 @@ fn min_size(panel: Panel) -> Vec2 { /// The body of every panel except the viewport, in the dock or on the rail pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { // No project open: the library and the log work, the other panels about a project stay empty - let works_empty = matches!(panel, Panel::Assets | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export); + let works_empty = + matches!(panel, Panel::Assets | Panel::AssetsSecond | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export); if !app.session.project_open && !works_empty { return; } @@ -568,6 +574,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel { Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), + Panel::AssetsSecond => crate::shelf_second::body(app, ui), Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index df72f333..77ec52f8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -146,6 +146,8 @@ mod shelf_folders; mod shelf_menu; pub mod shelf_panes; pub mod shelf_preview; +pub mod shelf_query; +pub mod shelf_second; mod shelf_tabs; mod shelf_toolbar; pub mod shelf_updates; diff --git a/crates/ui-egui/src/shelf_query.rs b/crates/ui-egui/src/shelf_query.rs new file mode 100644 index 00000000..9e9d4b67 --- /dev/null +++ b/crates/ui-egui/src/shelf_query.rs @@ -0,0 +1,24 @@ +//! One Assets panel's query: search, type, folder and favorites only + +use serde::{Deserialize, Serialize}; + +/// One Assets panel's search, type and folder, and whether it shows only favorites +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ShelfQuery { + /// The search text + pub filter: String, + /// The picked type: an index into the shelf's types, or past them for every type + pub tab: usize, + /// The library folder: a library id, then folder names (empty: all libraries) + pub path: Vec, + /// Only favorites (the Favorites saved search) + pub favorites_only: bool, +} + +impl Default for ShelfQuery { + /// Every asset of every type + fn default() -> Self { + Self { filter: String::new(), tab: crate::shelf_tabs::NO_TYPE, path: Vec::new(), favorites_only: false } + } +} diff --git a/crates/ui-egui/src/shelf_second.rs b/crates/ui-egui/src/shelf_second.rs new file mode 100644 index 00000000..4c129816 --- /dev/null +++ b/crates/ui-egui/src/shelf_second.rs @@ -0,0 +1,23 @@ +//! The second Assets panel, opened by the folder button: the same panel with its own query + +use egui::Ui; + +use crate::TextureCraftApp; +use crate::shelf_query::ShelfQuery; + +/// Swap `query` with the first Assets panel's query in `ui` +fn swap_query(ui: &mut crate::state::UiState, query: &mut ShelfQuery) { + std::mem::swap(&mut ui.shelf_filter, &mut query.filter); + std::mem::swap(&mut ui.shelf_tab, &mut query.tab); + std::mem::swap(&mut ui.shelf_path, &mut query.path); + std::mem::swap(&mut ui.shelf_favorites_only, &mut query.favorites_only); +} + +/// The second Assets panel's body: the Assets panel drawn with its own query +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + let mut query = std::mem::take(&mut app.ui.shelf_second); + swap_query(&mut app.ui, &mut query); + ui.push_id("assets_second", |ui| crate::shelf::body(app, ui)); + swap_query(&mut app.ui, &mut query); + app.ui.shelf_second = query; +} diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index 99a80cb6..c61d37bc 100644 --- a/crates/ui-egui/src/shelf_toolbar.rs +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -1,4 +1,4 @@ -//! The shelf's bottom toolbar: the side pane toggles on the left; refresh with its update settings, reset query and import on the right +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query, new panel and import on the right use egui::Ui; use egui_phosphor::regular as ic; @@ -26,6 +26,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), "resource.import"); } + if icon_button(ui, ic::FOLDER, tr("New Assets panel"), false, size).clicked() { + app.ui.dock.focus(crate::docking::Panel::AssetsSecond); + } if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() { reset_query(app); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 7caf4d29..3cdf54db 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -593,6 +593,9 @@ pub struct UiState { /// The asset shelf shows only favorites (the Favorites saved search) #[serde(default)] pub shelf_favorites_only: bool, + /// The second Assets panel's search, type and folder, swapped in while it draws + #[serde(default)] + pub shelf_second: crate::shelf_query::ShelfQuery, /// The asset shelf's automatic updates (its refresh popup) #[serde(default)] pub shelf_updates: crate::shelf_updates::ShelfUpdates, @@ -757,6 +760,7 @@ impl UiState { self.shelf_saved_searches = keep.shelf_saved_searches; self.shelf_favorites = keep.shelf_favorites; self.shelf_favorites_only = keep.shelf_favorites_only; + self.shelf_second = keep.shelf_second; self.shelf_custom_previews = keep.shelf_custom_previews; self.shelf_updates = keep.shelf_updates; } @@ -795,6 +799,7 @@ impl Default for UiState { shelf_saved_searches: Vec::new(), shelf_favorites: Vec::new(), shelf_favorites_only: false, + shelf_second: crate::shelf_query::ShelfQuery::default(), shelf_custom_previews: Vec::new(), shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 7354a597..85bf32ed 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -84,6 +84,7 @@ mod shelf_drop; mod shelf_hover_preview; mod shelf_menu; mod shelf_panel; +mod shelf_second; mod shelf_updates; mod shift_lines_2d; mod shift_lines_3d; diff --git a/crates/ui-egui/tests/it/shelf_second.rs b/crates/ui-egui/tests/it/shelf_second.rs new file mode 100644 index 00000000..7095f6bc --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_second.rs @@ -0,0 +1,44 @@ +//! The Assets panel's folder button opens a second Assets panel with its own search + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +/// The sample project at 1600 x 960 +fn sample_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// Type `text` into the search field of the Assets panel shown left of the 3D view +fn search_shown_panel(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + let left_of_view = harness.state().viewport_rect.min.x; + harness.get_all_by_role(Role::TextInput).find(|field| field.rect().max.x < left_of_view).expect("the shown Assets panel has a search field").click(); + harness.run_steps(2); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(2); +} + +#[test] +fn the_folder_button_opens_a_second_assets_panel_that_searches_on_its_own() { + let mut harness = sample_app(); + assert!(!harness.state().ui.dock.is_open(Panel::AssetsSecond), "one Assets panel at first"); + + harness.get_by_label("New Assets panel").click(); + harness.run_steps(3); + assert!(harness.state().ui.dock.is_visible(Panel::AssetsSecond), "the folder button shows a second Assets panel"); + + search_shown_panel(&mut harness, "brick"); + let ui = &harness.state().ui; + assert_eq!((ui.shelf_second.filter.as_str(), ui.shelf_filter.as_str()), ("brick", ""), "the second panel's search leaves the first panel's alone"); + + harness.state_mut().ui.dock.focus(Panel::Assets); + harness.run_steps(3); + search_shown_panel(&mut harness, "rust"); + let ui = &harness.state().ui; + assert_eq!((ui.shelf_second.filter.as_str(), ui.shelf_filter.as_str()), ("brick", "rust"), "the first panel's search leaves the second panel's alone"); +} From d42bccb2366a60b48cd71a6e6c2b3f94e1d27a37 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:00:45 +0000 Subject: [PATCH 046/190] Assets: snapshots of every pass 2 screen mid-interaction in the three themes --- crates/ui-egui/tests/ui_snapshots.rs | 274 ++++++++++++++++++++++----- 1 file changed, 227 insertions(+), 47 deletions(-) diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index bffa737b..8f8c6718 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -686,62 +686,242 @@ fn smart_material_shelf_snapshot() { save(&mut harness, &output_dir, "smart-material-hover"); } -/// A smart material dragged from the Assets panel over a texture set, then over the background +/// Writes `name` and, beside it, where the pointer is (`.pointer.txt`: x y), so a picture can draw the system's pointer +fn save_with_pointer(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { + save(harness, dir, name); + if let Some(pointer) = harness.ctx.input(|input| input.pointer.hover_pos()) { + std::fs::write(dir.join(format!("{name}.pointer.txt")), format!("{} {}", pointer.x, pointer.y)).unwrap(); + } +} + +/// Assets types the pass 2 snapshots show, as indexes into the Assets panel's type row +const SMART_MATERIALS_TYPE: usize = 1; +const BRUSHES_TYPE: usize = 4; +const TEXTURES_TYPE: usize = 6; + +/// A move from a pressed tile or row long enough to start a drag +const DRAG_START: egui::Vec2 = egui::vec2(12.0, 12.0); + +/// A point in the window's top bar, so no tile shows its hover outline +const AWAY_FROM_TILES: egui::Pos2 = egui::pos2(800.0, 40.0); + +/// How far down the window a point is inside Properties +const PROPERTIES_HEIGHT_SHARE: f32 = 0.75; + +/// The panes' edge drag: steps and points per step +const EDGE_DRAG_STEPS: usize = 4; +const EDGE_DRAG_STEP: f32 = 15.0; + +/// Assets pass 2, every screen mid-interaction (menus, submenu, favorites, custom preview, drag ghost, refresh popup, second panel); `TC_UI_THEMES` adds dark and light #[test] #[ignore] -fn shelf_drag_ghost_snapshots() { - use egui::{Event, Modifiers, PointerButton, vec2}; - use texturecraft_engine::geom::glam::Vec2; +fn assets_pass_two_snapshots() { + use egui::{Event, Modifiers, PointerButton, Role, vec2}; use texturecraft_engine::materials::MATERIALS; + use texturecraft_ui_egui::file_dialogs::Answer; let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; std::fs::create_dir_all(&output_dir).unwrap(); - let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder() - .with_size(egui::vec2(1600.0, 960.0)) - .with_pixels_per_point(1.0) - // The system draws the pointer, not the app - .with_render_cursor(false) - .wgpu() - .build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.shelf_tab = 1; - let material = MATERIALS.iter().find(|material| material.id == "steel_painted_worn").unwrap(); - let context = harness.ctx.clone(); - let started = std::time::Instant::now(); - while harness.state_mut().thumbs.material(&context, material.id).is_none() { - assert!(started.elapsed() < std::time::Duration::from_secs(120), "the material's thumbnail did not arrive"); - std::thread::sleep(std::time::Duration::from_millis(20)); - harness.run_steps(1); - } - harness.run_steps(2); - - // The first view points showing a texture set and the background - let point_over = |harness: &Harness<'_, TextureCraftApp>, set: Option| { - let app = harness.state(); - let rect = app.viewport_rect; - let steps = |length: f32| (1..(length / 8.0) as usize).map(|step| step as f32 * 8.0); - steps(rect.height()) - .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) - .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) - .map(|(x, y)| rect.min + vec2(x, y)) - .unwrap() + let files = std::env::temp_dir().join(format!("texturecraft-assets-pass-two-{}", std::process::id())); + std::fs::create_dir_all(&files).unwrap(); + let brushes = files.join("brushes"); + let plate = files.join("rust_plate.png"); + image::RgbaImage::from_fn(128, 128, |x, y| { + let grain = ((x * 7 + y * 13) % 23) as u8 * 3; + image::Rgba([120 + grain, 66 + grain / 2, 38, 255]) + }) + .save(&plate) + .unwrap(); + let preview = files.join("brushed_preview.png"); + image::RgbaImage::from_fn(160, 120, |x, y| { + let line = 140 + ((y * 37 + x / 9) % 41) as u8; + image::Rgba([line, line, line + 8, 255]) + }) + .save(&preview) + .unwrap(); + let show_in = if cfg!(target_os = "windows") { + "Show in Explorer..." + } else if cfg!(target_os = "macos") { + "Show in Finder..." + } else { + "Show in file manager..." }; - let (on_set, background) = (point_over(&harness, Some(0)), point_over(&harness, None)); - let on_set = on_set + vec2(40.0, 40.0); - let tile = harness.get_by_role_and_label(egui::Role::Button, material.label).rect().center(); - harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - harness.run_steps(2); - harness.hover_at(tile + vec2(12.0, 12.0)); - harness.run_steps(2); - for (target, name) in [(on_set, "drag-ghost-valid"), (background, "drag-ghost-not-valid")] { - harness.hover_at(target); - harness.run_steps(2); - save(&mut harness, &output_dir, name); - if let Some(shown) = texturecraft_ui_egui::shelf_drag_ghost::shown(&harness.ctx) { - std::fs::write(output_dir.join(format!("{name}.pointer.txt")), format!("{} {} {:?}", target.x, target.y, shown.verdict)).unwrap(); - } + let mut themes = vec![(Brightness::MediumDark, "medium")]; + if std::env::var_os("TC_UI_THEMES").is_some() { + themes.extend([(Brightness::Dark, "dark"), (Brightness::Light, "light")]); } + for (brightness, theme) in themes { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + // The system draws the pointer, not the app + .with_render_cursor(false) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.ui.prefs.brightness = brightness; + app.ui.prefs.language = "en".into(); + let theme_brushes = brushes.join(theme); + std::fs::create_dir_all(&theme_brushes).unwrap(); + app.session.brush_presets.dir = Some(theme_brushes); + app.run("brush.preset.store", serde_json::json!({"name": "Ink soft"})).unwrap(); + let image = app.run("resource.import", serde_json::json!({"path": plate.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let answer = preview.clone(); + app.file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + app.ui.shelf_tab = SMART_MATERIALS_TYPE; + let context = harness.ctx.clone(); + let started = std::time::Instant::now(); + loop { + harness.run_steps(1); + let thumbnails = &mut harness.state_mut().thumbs; + if MATERIALS.iter().filter(|material| material.smart).all(|material| thumbnails.material(&context, material.id).is_some()) { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(120), "smart material thumbnails did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let shot = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| save_with_pointer(harness, &output_dir, &format!("assets-{name}-{theme}")); + let right_click = |harness: &mut Harness<'_, TextureCraftApp>, tile: &str| { + harness.get_all_by_label(tile).next().unwrap_or_else(|| panic!("no tile {tile}")).click_secondary(); + harness.run_steps(3); + }; + let close_menu = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + }; + + // 01: a built-in smart material, a row hovered; 03: its greyed Show in + right_click(&mut harness, "Brass Tarnished"); + harness.get_by_label("Export resource...").hover(); + shot(&mut harness, "01-menu-built-in"); + harness.get_by_label("Show in").hover(); + harness.run_steps(30); + shot(&mut harness, "03-show-in-built-in"); + close_menu(&mut harness); + + // 04: two favorites, the newest first, then a favorite's menu; 08: a custom preview on a third tile + for tile in ["Gold Dirty", "Bronze Statue"] { + right_click(&mut harness, tile); + harness.get_by_label("Add to favorites").click(); + harness.run_steps(3); + } + right_click(&mut harness, "Brass Tarnished"); + harness.get_by_label("Set custom preview...").click(); + harness.run_steps(3); + settle_thumbnails(&mut harness); + harness.hover_at(AWAY_FROM_TILES); + shot(&mut harness, "04-favorites-and-custom-preview"); + right_click(&mut harness, "Bronze Statue"); + harness.get_by_label("Remove from favorites").hover(); + shot(&mut harness, "04-menu-favorite"); + close_menu(&mut harness); + + // 05: the drag ghost over the layer stack (takes a material) and over Properties (doesn't) + let viewport_right = harness.state().viewport_rect.max.x; + let layer = harness.get_all_by_role(Role::ListItem).find(|row| row.rect().min.x > viewport_right).expect("a layer row").rect().center(); + // Properties fills the right column under the layer stack, in the window's lower part + let properties = egui::pos2(layer.x, harness.ctx.content_rect().height() * PROPERTIES_HEIGHT_SHARE); + let tile = harness.get_all_by_label("Gold Dirty").next().unwrap().rect().center(); + harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(tile + DRAG_START); + harness.run_steps(2); + for (target, name) in [(layer, "05-drag-valid-layer-stack"), (properties, "05-drag-not-valid-properties")] { + harness.hover_at(target); + harness.run_steps(2); + shot(&mut harness, name); + } + harness.event(Event::PointerButton { pos: properties, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + // 09: a layer dragged in the layer stack over another row (takes it) and over Properties (doesn't) + harness.state_mut().run("layer.add.paint", serde_json::json!({"name": "Dragged layer"})).unwrap(); + harness.run_steps(3); + let dragged = harness.get_by_role_and_label(Role::ListItem, "Dragged layer").rect().center(); + let rows: Vec<_> = harness.get_all_by_role(Role::ListItem).filter(|row| row.rect().min.x > viewport_right).map(|row| row.rect().center()).collect(); + let other = *rows.iter().find(|at| at.y > dragged.y).expect("a row below it"); + harness.event(Event::PointerButton { pos: dragged, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(dragged + DRAG_START); + harness.run_steps(2); + for (target, name) in [(other, "09-layer-drag-valid-row"), (properties, "09-layer-drag-not-valid-properties")] { + harness.hover_at(target); + harness.run_steps(2); + shot(&mut harness, name); + } + harness.event(Event::PointerButton { pos: properties, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + // 02: a project image and a saved brush; 03: Show in open on the image + harness.state_mut().ui.shelf_tab = TEXTURES_TYPE; + settle_thumbnails(&mut harness); + right_click(&mut harness, &image); + harness.get_by_label("Reload").hover(); + shot(&mut harness, "02-menu-project-image"); + harness.get_by_label("Show in").click(); + harness.run_steps(3); + harness.get_by_label(show_in).hover(); + shot(&mut harness, "03-show-in-image"); + close_menu(&mut harness); + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + settle_thumbnails(&mut harness); + right_click(&mut harness, "Ink soft"); + harness.get_by_label("Replace with the current brush").hover(); + shot(&mut harness, "02-menu-saved-brush"); + close_menu(&mut harness); + + // 06: the refresh popup, then with an i hovered + harness.state_mut().ui.shelf_tab = SMART_MATERIALS_TYPE; + harness.run_steps(3); + harness.get_all_by_label("Refresh").next().unwrap().click(); + harness.run_steps(3); + harness.get_by_label("Update Assets panel").hover(); + shot(&mut harness, "06-refresh-popup"); + harness.get_by_label("Reads your saved assets from disk again every few minutes, so new and changed ones show here.").hover(); + harness.run_steps(30); + shot(&mut harness, "06-refresh-info"); + close_menu(&mut harness); + + // 10: both filter panes open, their edge with the grid dragged wider + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.run_steps(3); + let edge = harness.get_by_label("Resize Assets filter panes and grid").rect().center(); + harness.hover_at(edge); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: edge, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=EDGE_DRAG_STEPS { + harness.hover_at(edge + vec2(EDGE_DRAG_STEP * step as f32, 0.0)); + harness.run_steps(1); + } + shot(&mut harness, "10-panes-edge-drag"); + harness.event(Event::PointerButton { + pos: edge + vec2(EDGE_DRAG_STEP * EDGE_DRAG_STEPS as f32, 0.0), + button: PointerButton::Primary, + pressed: false, + modifiers: Modifiers::NONE, + }); + harness.state_mut().ui.shelf_panes.saved_searches = false; + harness.state_mut().ui.shelf_panes.filter_by_path = false; + harness.run_steps(3); + + // 07: the folder button hovered, then the second panel searching "brick" + harness.get_by_label("New Assets panel").hover(); + harness.run_steps(30); + shot(&mut harness, "07-folder-button"); + harness.get_all_by_label("New Assets panel").next().unwrap().click(); + harness.run_steps(3); + let left_of_view = harness.state().viewport_rect.min.x; + harness.get_all_by_role(Role::TextInput).find(|field| field.rect().max.x < left_of_view).expect("the second panel's search").click(); + harness.run_steps(2); + harness.event(Event::Text("brick".into())); + settle_thumbnails(&mut harness); + shot(&mut harness, "07-second-panel"); + } + std::fs::remove_dir_all(files).unwrap(); } /// Compact nested rows must keep their content, mask and effect controls in the panel. From e61d99944182cdbb64a622862822bc04f03c57a7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:37:14 +0000 Subject: [PATCH 047/190] Layers: a layer dragged in the layer stack follows the pointer as a chip with its name and the same badge as dragged assets --- crates/ui-egui/src/dock.rs | 10 +-- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 4 +- crates/ui-egui/src/shelf_drag_ghost.rs | 80 +++++++++++++------- crates/ui-egui/src/shelf_drag_ghost_shown.rs | 16 ++++ crates/ui-egui/src/shelf_drag_verdict.rs | 2 +- crates/ui-egui/tests/it/shelf_drag_ghost.rs | 36 ++++++++- 7 files changed, 107 insertions(+), 42 deletions(-) create mode 100644 crates/ui-egui/src/shelf_drag_ghost_shown.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e904046d..aaa7a3f4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -174,11 +174,9 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { _ => {} } let material = response.dnd_hover_payload::().is_some_and(|drag| drag.asset.is_material()); - if material { - crate::shelf_drag_ghost::accept(ui.ctx()); - } if response.dnd_hover_payload::().is_some() || material { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(DROP_STROKE, tokens.accent)); + crate::shelf_drag_ghost::accept(ui.ctx()); } }); select_all_layers(app, ui); @@ -729,6 +727,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } if row.drag_started() && !renaming { row.dnd_set_drag_payload(layer.id.0); + crate::shelf_drag_ghost::start_layer(ui.ctx(), &layer.name); } // A folder midpoint accepts child drops; a smart mask replaces the current mask @@ -745,7 +744,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let shelf_material = shelf.as_ref().is_some_and(Asset::is_material); let shelf_mask = matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))); let shelf_filter = matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group(); - if shelf_material || shelf_mask || shelf_filter { + if moving || shelf_material || shelf_mask || shelf_filter { crate::shelf_drag_ghost::accept(&row.ctx); } if moving || shelf_material { @@ -1797,8 +1796,7 @@ pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { return None; } - ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, Tokens::get(ui.ctx()).accent), egui::StrokeKind::Inside); - crate::shelf_drag_ghost::accept(ui.ctx()); + crate::shelf_drag_ghost::outline_target(ui, resp.rect); match dnd_release::(resp).map(|d| d.asset.clone()) { Some(Asset::Texture(name)) => Some(name), _ => None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 77ec52f8..a16934e2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -139,6 +139,7 @@ pub mod shader_settings; pub mod shelf; pub mod shelf_custom_preview; pub mod shelf_drag_ghost; +pub mod shelf_drag_ghost_shown; pub mod shelf_drag_verdict; mod shelf_entry; pub mod shelf_favorite; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 7bed8f3e..7285787d 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -211,7 +211,6 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response DecalDrop::show_menu(app, ui, response); } - let tokens = Tokens::get(ui.ctx()); let accepts = |drag: &ShelfDrag| match drag.asset { Asset::Alpha(_) => true, Asset::Material(_) | Asset::Library(_) => zone != DropZone::Brush, @@ -222,8 +221,7 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response if let Some(drag) = response.dnd_hover_payload::().filter(|drag| accepts(drag)) { // The 3D view outlines the set under the pointer itself; its background takes nothing if !onto_set(&drag.asset) { - ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); - crate::shelf_drag_ghost::accept(ui.ctx()); + crate::shelf_drag_ghost::outline_target(ui, response.rect); } else if set_under_pointer(app, ui, response).is_some() { crate::shelf_drag_ghost::accept(ui.ctx()); } diff --git a/crates/ui-egui/src/shelf_drag_ghost.rs b/crates/ui-egui/src/shelf_drag_ghost.rs index 05f311af..2c11a2a1 100644 --- a/crates/ui-egui/src/shelf_drag_ghost.rs +++ b/crates/ui-egui/src/shelf_drag_ghost.rs @@ -1,10 +1,10 @@ -//! The picture that follows the pointer while an asset is dragged from the Assets panel, with a -//! badge on its corner saying whether the place under the pointer takes the asset +//! The picture that follows a dragged asset or layer, with a badge saying whether the place under it takes it -use egui::{Color32, Context, Id, LayerId, Order, Pos2, Rect, Stroke, Vec2, vec2}; +use egui::{Color32, Context, Id, LayerId, Order, Pos2, Rect, Stroke, TextureId, Vec2, vec2}; use crate::shelf::ShelfDrag; -pub use crate::shelf_drag_verdict::Verdict; +pub use crate::shelf_drag_ghost_shown::ShelfDragGhostShown; +pub use crate::shelf_drag_verdict::ShelfDragVerdict; use crate::theme::Tokens; /// Side of the dragged asset's thumbnail @@ -46,61 +46,85 @@ const CHIP_PADDING: Vec2 = vec2(6.0, 3.0); /// Text size of the name chip const CHIP_TEXT_SIZE: f32 = 11.0; +/// Width of the outline around a drop target that takes the dragged asset +const TARGET_OUTLINE_WIDTH: f32 = 2.0; + +/// How far the outline sits inside the target's edge, so a neighbouring panel doesn't cut it +const TARGET_OUTLINE_INSET: f32 = 1.0; + +/// Corner rounding of the outline +const TARGET_OUTLINE_ROUNDING: f32 = 3.0; + /// Pass number of the last drop target that took the dragged asset (ctx temp data) const ACCEPTED: &str = "shelf_drag_accepted"; /// What the last pass painted (ctx temp data) const SHOWN: &str = "shelf_drag_shown"; -/// The ghost as the last pass painted it -#[derive(Clone, Copy, Debug)] -pub struct Shown { - /// What the badge says - pub verdict: Verdict, - /// Where the thumbnail (or the name chip) is - pub ghost: Rect, - /// Where the badge is - pub badge: Rect, -} +/// The name of the layer being dragged in the layer stack, whose payload is only its id (ctx temp data) +const LAYER: &str = "shelf_drag_layer"; -/// Note that the drop target being drawn takes the dragged asset, where it paints its drop highlight +/// Note that the drop target being drawn takes the dragged asset or layer, where it paints its drop highlight pub(crate) fn accept(ctx: &Context) { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|data| data.insert_temp(Id::unique(ACCEPTED), pass)); } -/// The ghost painted this pass, if an asset is being dragged -pub fn shown(ctx: &Context) -> Option { +/// Outlines drop target `rect` while the dragged asset hovers it, and notes that it takes the asset +pub(crate) fn outline_target(ui: &egui::Ui, rect: Rect) { + let stroke = Stroke::new(TARGET_OUTLINE_WIDTH, Tokens::get(ui.ctx()).accent); + ui.painter().rect_stroke(rect.shrink(TARGET_OUTLINE_INSET), TARGET_OUTLINE_ROUNDING, stroke, egui::StrokeKind::Inside); + accept(ui.ctx()); +} + +/// Note the name of the layer whose drag starts: a chip with it follows the pointer, since an empty layer's thumbnail shows nothing +pub(crate) fn start_layer(ctx: &Context, label: &str) { + ctx.data_mut(|data| data.insert_temp(Id::unique(LAYER), label.to_owned())); +} + +/// The picture and name of what is being dragged: an asset, or a layer (its name only) +fn dragged(ctx: &Context) -> Option<(Option, String)> { + if let Some(drag) = egui::DragAndDrop::payload::(ctx) { + return Some((drag.thumb.as_ref().map(egui::TextureHandle::id), drag.label.clone())); + } + if !egui::DragAndDrop::has_payload_of_type::(ctx) { + return None; + } + ctx.data(|data| data.get_temp::(Id::unique(LAYER))).map(|label| (None, label)) +} + +/// The ghost painted this pass, if an asset or a layer is being dragged +pub fn shown(ctx: &Context) -> Option { ctx.data(|data| data.get_temp(Id::unique(SHOWN))) } /// Paint the dragged asset and its badge at the pointer, once a pass after every drop target pub(crate) fn show(ctx: &Context) { - let (Some(drag), Some(pointer)) = (egui::DragAndDrop::payload::(ctx), ctx.input(|input| input.pointer.hover_pos())) else { - ctx.data_mut(|data| data.remove::(Id::unique(SHOWN))); + let (Some((thumb, label)), Some(pointer)) = (dragged(ctx), ctx.input(|input| input.pointer.hover_pos())) else { + ctx.data_mut(|data| data.remove::(Id::unique(SHOWN))); return; }; let pass = ctx.cumulative_pass_nr(); let accepted = ctx.data(|data| data.get_temp::(Id::unique(ACCEPTED))) == Some(pass); - let verdict = if accepted { Verdict::Valid } else { Verdict::NotValid }; + let verdict = if accepted { ShelfDragVerdict::Valid } else { ShelfDragVerdict::NotValid }; let painter = ctx.layer_painter(LayerId::new(Order::Tooltip, Id::unique("shelf_drag_ghost"))); let tokens = Tokens::get(ctx); - let ghost = match &drag.thumb { + let ghost = match thumb { Some(thumb) => { let rect = Rect::from_min_size(pointer + GHOST_OFFSET, Vec2::splat(GHOST_SIZE)); let uv = Rect::from_min_max(Pos2::ZERO, egui::pos2(1.0, 1.0)); - painter.image(thumb.id(), rect, uv, Color32::WHITE.gamma_multiply(GHOST_OPACITY)); + painter.image(thumb, rect, uv, Color32::WHITE.gamma_multiply(GHOST_OPACITY)); rect } - None => name_chip(&painter, &tokens, pointer + GHOST_OFFSET, &drag.label), + None => name_chip(&painter, &tokens, pointer + GHOST_OFFSET, &label), }; let badge = badge(&painter, &tokens, pointer + BADGE_OFFSET, verdict); - ctx.data_mut(|data| data.insert_temp(Id::unique(SHOWN), Shown { verdict, ghost, badge })); + ctx.data_mut(|data| data.insert_temp(Id::unique(SHOWN), ShelfDragGhostShown { verdict, ghost, badge })); } -/// The asset's name in a chip at `top_left`, for assets without a thumbnail (saved smart materials) +/// The name in a chip at `top_left`, for what has no thumbnail (saved smart materials and masks, layers) fn name_chip(painter: &egui::Painter, tokens: &Tokens, top_left: Pos2, label: &str) -> Rect { let galley = painter.layout_no_wrap(label.to_owned(), egui::FontId::proportional(CHIP_TEXT_SIZE), tokens.text_strong); let rect = Rect::from_min_size(top_left, galley.size() + CHIP_PADDING * 2.0); @@ -111,15 +135,15 @@ fn name_chip(painter: &egui::Painter, tokens: &Tokens, top_left: Pos2, label: &s } /// The badge at `centre`: a crosshair on a light square where a drop works, else a no-entry sign -fn badge(painter: &egui::Painter, tokens: &Tokens, centre: Pos2, verdict: Verdict) -> Rect { +fn badge(painter: &egui::Painter, tokens: &Tokens, centre: Pos2, verdict: ShelfDragVerdict) -> Rect { let rect = Rect::from_center_size(centre, Vec2::splat(BADGE_SIZE)); let outline = Stroke::new(1.0, Color32::from_black_alpha(BADGE_OUTLINE_ALPHA)); let (icon, color) = match verdict { - Verdict::Valid => { + ShelfDragVerdict::Valid => { painter.rect(rect, BADGE_ROUNDING, BADGE_LIGHT, outline, egui::StrokeKind::Outside); (egui_phosphor::regular::CROSSHAIR_SIMPLE, BADGE_DARK) } - Verdict::NotValid => { + ShelfDragVerdict::NotValid => { painter.circle(centre, BADGE_SIZE / 2.0, tokens.danger, outline); (egui_phosphor::regular::PROHIBIT, BADGE_LIGHT) } diff --git a/crates/ui-egui/src/shelf_drag_ghost_shown.rs b/crates/ui-egui/src/shelf_drag_ghost_shown.rs new file mode 100644 index 00000000..2e961053 --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_ghost_shown.rs @@ -0,0 +1,16 @@ +//! Where the drag ghost and its badge were painted, and what the badge said + +use egui::Rect; + +use crate::shelf_drag_verdict::ShelfDragVerdict; + +/// The ghost as the last pass painted it +#[derive(Clone, Copy, Debug)] +pub struct ShelfDragGhostShown { + /// What the badge says + pub verdict: ShelfDragVerdict, + /// Where the thumbnail (or the name chip) is + pub ghost: Rect, + /// Where the badge is + pub badge: Rect, +} diff --git a/crates/ui-egui/src/shelf_drag_verdict.rs b/crates/ui-egui/src/shelf_drag_verdict.rs index b6713b95..2af311da 100644 --- a/crates/ui-egui/src/shelf_drag_verdict.rs +++ b/crates/ui-egui/src/shelf_drag_verdict.rs @@ -2,7 +2,7 @@ /// Whether the place under the pointer takes the dragged asset #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Verdict { +pub enum ShelfDragVerdict { /// A drop here does something: a crosshair on a light square Valid, /// A drop here does nothing: a no-entry sign on red diff --git a/crates/ui-egui/tests/it/shelf_drag_ghost.rs b/crates/ui-egui/tests/it/shelf_drag_ghost.rs index 8311846f..8a006eab 100644 --- a/crates/ui-egui/tests/it/shelf_drag_ghost.rs +++ b/crates/ui-egui/tests/it/shelf_drag_ghost.rs @@ -1,5 +1,4 @@ -//! Dragging an asset from the Assets panel shows it at the pointer with a badge on its corner that says -//! whether the place under the pointer takes it +//! A dragged asset or layer shows at the pointer with a badge saying whether the place under it takes it use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::Harness; @@ -7,7 +6,7 @@ use egui_kittest::kittest::Queryable; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::materials::MATERIALS; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::shelf_drag_ghost::{Verdict, shown}; +use texturecraft_ui_egui::shelf_drag_ghost::{ShelfDragVerdict, shown}; /// Distance between the view points searched for a set or the background const SEARCH_STEP: f32 = 8.0; @@ -58,7 +57,36 @@ fn the_badge_says_whether_the_place_under_the_pointer_takes_the_asset_without_co assert!(ghost.badge.min.x > target.x && ghost.badge.min.y > target.y, "the badge leaves the pointer's tip clear"); seen.push(ghost.verdict); } - assert_eq!(seen, [Verdict::Valid, Verdict::NotValid], "a texture set takes a material, the background doesn't"); + assert_eq!(seen, [ShelfDragVerdict::Valid, ShelfDragVerdict::NotValid], "a texture set takes a material, the background doesn't"); + + harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); +} + +#[test] +fn a_layer_dragged_in_the_layer_stack_gets_the_same_ghost_and_badge() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for name in ["Ghost low", "Ghost high"] { + texturecraft_engine::execute(&mut session, "layer.add.paint", &serde_json::json!({ "name": name })).unwrap(); + } + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + let background = point_over(&harness, None); + let (high, low) = (harness.get_by_label("Ghost high").rect().center(), harness.get_by_label("Ghost low").rect().center()); + + harness.event(Event::PointerButton { pos: high, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(high + vec2(DRAG_START, DRAG_START)); + harness.run_steps(2); + + let mut seen = Vec::new(); + for target in [low, background] { + harness.hover_at(target); + harness.run_steps(2); + seen.push(shown(&harness.ctx).expect("the dragged layer follows the pointer").verdict); + } + assert_eq!(seen, [ShelfDragVerdict::Valid, ShelfDragVerdict::NotValid], "another row takes the layer, the 3D view doesn't"); harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); From 4b95153430d49a86ba44eea5b8dccf62768d4455 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:37:14 +0000 Subject: [PATCH 048/190] Assets: the edge between the filter panes and the grid drags to share the panel's width --- crates/ui-egui/src/shelf.rs | 2 +- crates/ui-egui/src/shelf_panes.rs | 29 +++++++++++++++++++++++-- crates/ui-egui/src/state.rs | 16 ++++++++++++++ crates/ui-egui/tests/it/shelf_panel.rs | 30 ++++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 7285787d..18d61227 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -330,7 +330,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.set_min_size(vec2(width, grid_rect.height())); crate::shelf_panes::column(app, ui, &paths, &applicable); }); - ui.separator(); + crate::shelf_panes::edge(app, ui, width, grid_rect.width()); } // Saved smart materials are files in the user's library, without folders of their own diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index 118d9bc4..f2a6d42f 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -13,8 +13,11 @@ use crate::theme::Tokens; use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; -const COLUMN_FRACTION: f32 = 0.45; const COLUMN_MIN_WIDTH_POINTS: f32 = 110.0; +/// Width of the draggable edge between the panes and the grid +const EDGE_WIDTH_POINTS: f32 = 6.0; +/// The grid keeps at least this much width when the edge is dragged right +const GRID_MIN_WIDTH_POINTS: f32 = 80.0; const SPLITTER_HEIGHT_POINTS: f32 = 6.0; const PANE_MIN_HEIGHT_POINTS: f32 = 40.0; /// The built-in saved search after "All" that shows only the favorite assets @@ -49,7 +52,29 @@ pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { /// The width of the panes' column in a panel `width` wide, or None while no pane is open pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option { let panes = &app.ui.shelf_panes; - (panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH_POINTS).min(width)) + let share = app.ui.shelf_panes_share; + (panes.saved_searches || panes.filter_by_path) + .then(|| (width * share).min(width - EDGE_WIDTH_POINTS - GRID_MIN_WIDTH_POINTS).max(COLUMN_MIN_WIDTH_POINTS).min(width)) +} + +/// The draggable edge between the panes' column (`column` wide) and the grid in a panel `width` wide +pub(crate) fn edge(app: &mut TextureCraftApp, ui: &mut Ui, column: f32, width: f32) { + let (rect, _) = ui.allocate_exact_size(egui::vec2(EDGE_WIDTH_POINTS, ui.available_height()), egui::Sense::hover()); + let visuals = ui.visuals(); + let line_stroke = visuals.widgets.noninteractive.bg_stroke; + let widest = (width - EDGE_WIDTH_POINTS - GRID_MIN_WIDTH_POINTS).max(COLUMN_MIN_WIDTH_POINTS); + if width > 0.0 && widest > COLUMN_MIN_WIDTH_POINTS { + let colors = + ResizeHandleStyle { hovered: visuals.widgets.hovered.bg_fill, dragged: visuals.widgets.active.bg_fill, focused: visuals.selection.bg_fill }; + let resize = ResizeHandle::new(ui.scope_id().with("shelf_panes_edge"), SplitAxis::Horizontal, rect, tr("Resize Assets filter panes and grid"), colors) + .hit_margin(0.0) + .value(column.clamp(COLUMN_MIN_WIDTH_POINTS, widest), COLUMN_MIN_WIDTH_POINTS..=widest) + .show(ui); + if resize.delta != 0.0 { + app.ui.shelf_panes_share = (column + resize.delta).clamp(COLUMN_MIN_WIDTH_POINTS, widest) / width; + } + } + ui.painter().vline(rect.center().x, rect.y_range(), line_stroke); } /// Draws the open panes and a divider when both are visible. diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3cdf54db..34748b34 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -493,6 +493,18 @@ pub(crate) fn default_shelf_panes_split() -> f32 { 0.45 } +/// The share of the Assets panel's width the filter panes take until their edge is dragged +fn default_shelf_panes_share() -> f32 { + 0.45 +} + +fn deserialize_shelf_panes_share<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + let share = f32::deserialize(deserializer)?; + + // A finite JSON number can overflow f32 and prevent the next settings save + Ok(if share.is_finite() { share } else { default_shelf_panes_share() }) +} + fn deserialize_shelf_panes_split<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { let share = f32::deserialize(deserializer)?; @@ -605,6 +617,9 @@ pub struct UiState { /// Saved searches' share of the pane column above Filter by path, set by the splitter between them #[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")] pub shelf_panes_split: f32, + /// The share of the Assets panel's width the filter panes take + #[serde(default = "default_shelf_panes_share", deserialize_with = "deserialize_shelf_panes_share")] + pub shelf_panes_share: f32, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -803,6 +818,7 @@ impl Default for UiState { shelf_custom_previews: Vec::new(), shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), + shelf_panes_share: default_shelf_panes_share(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 06856a41..23686275 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -544,3 +544,33 @@ fn the_favorites_search_shows_only_favorites_until_all_is_picked() { assert!(harness.query_by_label(other).is_some(), "All shows every asset again"); assert!(harness.query_by_label("My brushes").is_some(), "All shows the saved brushes list again"); } + +#[test] +fn the_edge_between_the_panes_and_the_grid_drags_and_the_width_is_saved() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + + const DRAG_DISTANCE_POINTS: f32 = 40.0; + let (initial_share, edge) = (harness.state().ui.shelf_panes_share, harness.get_by_label("Resize Assets filter panes and grid").rect()); + let from = edge.center(); + let to = from + egui::vec2(DRAG_DISTANCE_POINTS, 0.0); + harness.hover_at(from); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(3); + + let moved = harness.get_by_label("Resize Assets filter panes and grid").rect(); + assert!(moved.center().x > edge.center().x, "the edge follows the drag: {edge:?} to {moved:?}"); + assert!(harness.state().ui.shelf_panes_share > initial_share, "the panes take a larger share"); + + let saved = serde_json::to_value(&harness.state().ui).unwrap(); + let restored: texturecraft_ui_egui::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(restored.shelf_panes_share, harness.state().ui.shelf_panes_share, "the width is saved"); +} From 7d59a82e1b699cbf8d4a9801c49d7836c5292cbe Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 25 Nov 2026 22:35:31 +0000 Subject: [PATCH 049/190] Auto: Fix PSD batch exports and preserve template settings Bound retained PSD output and preserve document names, layer names, and preview channels. Keep saved presets and draft map overrides usable, report explicit grayscale J2K colour spaces, and let active picks handle Escape first. Validated with local export regressions, Clippy, layering, and WebAssembly compilation. --- crates/engine/src/file_cmds.rs | 39 ++++-- crates/engine/src/preset_cmds.rs | 109 ++++++++++++++--- crates/formats/README.md | 2 +- crates/formats/src/export/layered_psd.rs | 6 +- crates/formats/src/export/map_preview.rs | 14 ++- crates/formats/src/export/map_renderer.rs | 4 +- crates/formats/src/export/mod.rs | 97 +++++++++++++-- crates/formats/src/export/tests.rs | 126 ++++++++++++++++++++ crates/formats/src/lib.rs | 2 +- crates/formats/src/presets.rs | 9 ++ crates/ui-egui/src/export_templates.rs | 74 +++++++++--- crates/ui-egui/src/export_window.rs | 52 ++++---- crates/ui-egui/src/menus.rs | 30 +++-- crates/ui-egui/src/web_files.rs | 14 +-- crates/ui-egui/tests/it/export_settings.rs | 21 ++++ crates/ui-egui/tests/it/output_templates.rs | 19 +++ 16 files changed, 516 insertions(+), 102 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 8818c010..6b47fa94 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -288,30 +288,51 @@ impl Session { /// named like one an earlier set exports is left out, with a warning (see /// [`texturecraft_formats::skip_repeated_names`]). pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result> { - let mut files = self.render_export_files(sets, opts, |_, plans| plans)?; + self.export_file_jobs(sets.iter().map(|&set| (set, opts))) + } + + /// Render one in-memory batch, using each set's own export settings when supplied. + pub fn export_file_jobs<'a>(&mut self, jobs: impl IntoIterator) -> Result> { + let mut files = self.render_export_jobs(jobs, |_, plans| plans)?; texturecraft_formats::skip_repeated_names(&mut files); Ok(files) } + #[cfg(not(target_arch = "wasm32"))] fn render_export_files( &mut self, sets: &[usize], options: &ExportOptions, + select: impl FnMut(usize, Vec) -> Vec, + ) -> Result> { + self.render_export_jobs(sets.iter().map(|&set| (set, options)), select) + } + + fn render_export_jobs<'a>( + &mut self, + jobs: impl IntoIterator, mut select: impl FnMut(usize, Vec) -> Vec, ) -> Result> { + let project = &self.doc.project; + let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); + let mut psd_bytes = 0; + let mut pending = Vec::new(); + for (set_index, options) in jobs { + let plans = texturecraft_formats::list_outputs(project, set_index, &mesh_name, options).map_err(fe)?; + let plans = select(set_index, plans); + if !plans.is_empty() { + let set = project.texture_set(set_index).map_err(|error| EngineError::Other(error.to_string()))?; + texturecraft_formats::export::check_psd_batch(set, options, &plans, &mut psd_bytes).map_err(fe)?; + pending.push((set_index, options, plans)); + } + } + if self.solo.is_none() { self.update(); } - let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); - for &set_index in sets { - let plans = texturecraft_formats::list_outputs(&self.doc.project, set_index, &mesh_name, options).map_err(fe)?; - let plans = select(set_index, plans); - if plans.is_empty() { - continue; - } - + for (set_index, options, plans) in pending { let files = self.with_export_input( set_index, &mesh_name, diff --git a/crates/engine/src/preset_cmds.rs b/crates/engine/src/preset_cmds.rs index 8bae78b3..eeaea8bd 100644 --- a/crates/engine/src/preset_cmds.rs +++ b/crates/engine/src/preset_cmds.rs @@ -2,15 +2,18 @@ //! dialog's Output templates tab list, read, save and remove. On the desktop the user presets //! are mirrored as `.json` files in a library folder (see [`Session::load_export_presets`]). +use std::borrow::Cow; + use serde_json::{Value, json}; use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem}; -use texturecraft_formats::{ExportPreset, builtin_preset, builtin_preset_catalog, preset_from_json}; +use texturecraft_formats::{ExportPreset, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, preset_from_json}; use crate::commands::{CommandSpec, always, bad, boolp, strp}; use crate::{Result, Session, cmd}; /// Most user presets kept (and read from the library folder). const MAX_USER_PRESETS: usize = 512; +const BUILTIN_PRESET_PREFIX: &str = "builtin:"; /// The user's export presets. #[derive(Clone, Debug, Default)] @@ -49,6 +52,16 @@ fn same_name(a: &str, b: &str) -> bool { a.trim().eq_ignore_ascii_case(b.trim()) } +/// A qualified selector names a built-in independently of a saved library entry. +pub fn unqualified_preset_name(name: &str) -> &str { + let mut name = name.trim(); + while name.get(..BUILTIN_PRESET_PREFIX.len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(BUILTIN_PRESET_PREFIX)) { + name = &name[BUILTIN_PRESET_PREFIX.len()..]; + } + + name +} + /// Library file stem: two names with the same stem would share a file. fn file_key(name: &str) -> String { sanitize_file_stem(name.trim()).to_ascii_lowercase() @@ -61,8 +74,25 @@ impl UserPresets { /// `name` belongs to a built-in or to a user preset other than `skip` (or shares its file). fn taken(&self, name: &str, skip: Option) -> bool { - builtin_preset(name).is_some() - || self.list.iter().enumerate().any(|(i, p)| Some(i) != skip && (same_name(&p.name, name) || file_key(&p.name) == file_key(name))) + let keeps_name = skip.and_then(|index| self.list.get(index)).is_some_and(|preset| same_name(&preset.name, name)); + (!keeps_name && builtin_preset(unqualified_preset_name(name)).is_some()) || self.user_name_taken(name, skip) + } + + fn user_name_taken(&self, name: &str, skip: Option) -> bool { + let key = file_key(name); + self.list.iter().enumerate().any(|(i, preset)| Some(i) != skip && (same_name(&preset.name, name) || file_key(&preset.name) == key)) + } + + /// Restore a saved preset under the name existing settings use. + pub fn restore(&mut self, preset: ExportPreset) -> std::result::Result<(), String> { + preset.validate().map_err(|error| error.to_string())?; + let reserved = builtin_preset(&preset.name).is_some_and(|builtin| !NEW_BUILTIN_PRESET_NAMES.contains(&builtin.name.as_str())); + if reserved || self.user_name_taken(&preset.name, None) || self.list.len() >= MAX_USER_PRESETS { + return Err(format!("preset \"{}\" exists already or the library is full", preset.name)); + } + + self.list.push(preset); + Ok(()) } /// `name`, or `name 2`, `name 3`… (shortened to fit) when taken. @@ -115,7 +145,21 @@ impl UserPresets { impl Session { /// A built-in or user export preset by name (case-insensitive). pub fn export_preset(&self, name: &str) -> Option { - builtin_preset(name).or_else(|| self.export_presets.find(name).and_then(|i| self.export_presets.list.get(i).cloned())) + self.export_presets.find(name).and_then(|index| self.export_presets.list.get(index).cloned()).or_else(|| builtin_preset(unqualified_preset_name(name))) + } + + pub fn has_user_export_preset(&self, name: &str) -> bool { + self.export_presets.find(name).is_some() + } + + /// Use the familiar built-in name unless the user's library already owns that selector. + pub fn builtin_export_preset_id<'a>(&self, name: &'a str) -> Cow<'a, str> { + let mut id = Cow::Borrowed(name); + while self.has_user_export_preset(&id) { + id = Cow::Owned(format!("{BUILTIN_PRESET_PREFIX}{id}")); + } + + id } /// Use `dir` as the user preset library: read its `*.json` presets (replacing the list) and @@ -129,10 +173,8 @@ impl Session { files.sort(); let mut lib = UserPresets { list: Vec::new(), dir: Some(dir) }; for path in files.into_iter().take(MAX_USER_PRESETS) { - match texturecraft_formats::load_preset(&path).map_err(|e| e.to_string()) { - Ok(p) if lib.taken(&p.name, None) => warnings.push(format!("{}: preset \"{}\" exists already", path.display(), p.name)), - Ok(p) => lib.list.push(p), - Err(e) => warnings.push(format!("{}: {e}", path.display())), + if let Err(error) = texturecraft_formats::load_preset(&path).map_err(|error| error.to_string()).and_then(|preset| lib.restore(preset)) { + warnings.push(format!("{}: {error}", path.display())); } } self.export_presets = lib; @@ -141,9 +183,9 @@ impl Session { } fn list(session: &mut Session, _: &Value) -> Result { - let entry = |preset: &ExportPreset, builtin: bool| json!({"name": preset.name, "maps": preset.maps.len(), "builtin": builtin}); - let builtins = builtin_preset_catalog().iter().map(|preset| entry(preset, true)); - let custom = session.export_presets.list.iter().map(|preset| entry(preset, false)); + let entry = |name: &str, maps: usize, builtin: bool| json!({"name": name, "maps": maps, "builtin": builtin}); + let builtins = builtin_preset_catalog().iter().map(|preset| entry(&session.builtin_export_preset_id(&preset.name), preset.maps.len(), true)); + let custom = session.export_presets.list.iter().map(|preset| entry(&preset.name, preset.maps.len(), false)); Ok(json!(builtins.chain(custom).collect::>())) } @@ -196,11 +238,16 @@ fn save(s: &mut Session, p: &Value) -> Result { fn remove(s: &mut Session, p: &Value) -> Result { const CMD: &str = "export.preset.remove"; let name = name_param(p, CMD)?; - if builtin_preset(name).is_some() { - return Err(bad(CMD, format!("\"{name}\" is a built-in preset and can't be removed"))); - } - let i = s.export_presets.find(name).ok_or_else(|| bad(CMD, format!("no user export preset `{name}`")))?; - let removed = s.export_presets.list.remove(i); + let Some(index) = s.export_presets.find(name) else { + let message = if builtin_preset(unqualified_preset_name(name)).is_some() { + format!("\"{name}\" is a built-in preset and can't be removed") + } else { + format!("no user export preset `{name}`") + }; + return Err(bad(CMD, message)); + }; + + let removed = s.export_presets.list.remove(index); s.export_presets.delete(&removed.name); Ok(Value::Null) } @@ -316,6 +363,36 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn feedback_existing_preset_keeps_its_name_and_export_maps() { + let dir = tempfile::tempdir().unwrap(); + let name = "Roblox SurfaceAppearance (separate maps)"; + let custom = preset(name); + std::fs::write(dir.path().join(format!("{}.json", sanitize_file_stem(name))), custom.to_string()).unwrap(); + let mut s = session(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); + + let warnings = s.load_export_presets(dir.path().to_path_buf()); + + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom); + let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), 1); + assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png")); + + let listed = run(&mut s, "export.presets", json!({})).unwrap(); + let names = listed.as_array().unwrap(); + assert!(names.iter().any(|entry| entry["name"] == name && entry["builtin"] == false)); + let builtin = format!("builtin:{name}"); + assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true)); + let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap(); + assert!(builtin_plan.as_array().unwrap().len() > 1); + run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap(); + run(&mut s, "export.preset.remove", json!({"name": name})).unwrap(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn the_library_folder_mirrors_saves_renames_and_removals() { diff --git a/crates/formats/README.md b/crates/formats/README.md index 6c876997..4be58133 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -142,7 +142,7 @@ Built-in presets (each one lists the public specification its packing follows in | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | | Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | | glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | -| Redshift Standard Material (separate maps) | one map per Standard Material input the set has: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | +| Redshift Standard Material (separate maps) | separate maps for the listed inputs when the set supplies their sources: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | | Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` | | Sketchfab Metalness (separate maps) | `BaseColor` (no alpha), `Metalness`, `Roughness`, `Normal` (DirectX), `AmbientOcclusion`, `Emission` | | Separate maps | one file per channel, gray where scalar, height 16-bit | diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index a55b3d5d..f8982036 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -18,14 +18,14 @@ const ALPHA_INDEX: usize = 3; /// Budget for the pixel buffers of one PSD export, including the renderer's padding and encoder const MAX_PSD_WORKING_BYTES: u64 = 2 * 1024 * 1024 * 1024; -/// Check file limits and pixel-buffer working memory before constructing the renderer. +/// Check file and working memory limits, returning the canvas size and estimated encoded bytes. pub(super) fn preflight<'a>( set: &TextureSet, options: &ExportOptions, tile: Option, depth: u8, layers: impl Iterator + Clone, -) -> Result<(u32, u32)> { +) -> Result<((u32, u32), u64)> { let texels = |(width, height)| u64::from(width) * u64::from(height); let folder_count = layers.clone().map(|layer| layer.name.matches('/').count()).sum(); let sizes = layers.map(|layer| psd_size(set, tile, options.map_size(layer.map))); @@ -63,7 +63,7 @@ pub(super) fn preflight<'a>( ))); } - Ok(canvas) + Ok((canvas, file_bytes)) } /// Render each layer at its requested size, aligned to the upper-left corner of the PSD canvas. diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs index eace759c..81063de3 100644 --- a/crates/formats/src/export/map_preview.rs +++ b/crates/formats/src/export/map_preview.rs @@ -63,10 +63,13 @@ impl MapPreview { } let gray_source = channel_layout.first().filter(|(dest, _)| *dest == Dest::L); - let rgb_from_gray = - gray_source.filter(|_| file.format == FileFormat::Hdr || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2))); + let psd = file.format == FileFormat::Psd; + let rgb_from_gray = gray_source + .filter(|_| psd || file.format == FileFormat::Hdr || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2))); let channels = if grayscale { vec![Dest::L] + } else if psd { + vec![Dest::R, Dest::G, Dest::B, Dest::A] } else if rgb_from_gray.is_some() { [Dest::R, Dest::G, Dest::B].into_iter().chain(channel_layout.iter().skip(1).map(|(dest, _)| *dest)).collect() } else { @@ -108,13 +111,16 @@ impl MapPreview { } else if let (Some(gray), [red, green, blue, alpha @ ..]) = (rgb_from_gray, &mut *pixel) { let value = preview_sample(sample(gray), Dest::L); (*red, *green, *blue) = (value, value, value); - if let ([alpha], Some(source)) = (alpha, channel_layout.get(1)) { - *alpha = preview_sample(sample(source), Dest::A); + if let [alpha] = alpha { + *alpha = channel_layout.get(1).map_or(u8::MAX, |source| preview_sample(sample(source), Dest::A)); } } else { for (output, channel) in pixel.iter_mut().zip(&channel_layout) { *output = preview_sample(sample(channel), channel.0); } + if psd && channel_layout.len() < component_count { + pixel[component_count - 1] = u8::MAX; + } } } }); diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs index 3b493ab4..ebfd2e29 100644 --- a/crates/formats/src/export/map_renderer.rs +++ b/crates/formats/src/export/map_renderer.rs @@ -126,8 +126,8 @@ impl<'a> MapRenderer<'a> { } let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); - // A colour space the user chose is written into the colour maps (data maps have none) - let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space); + // Raw J2K reports the missing tag even for a grayscale colour map + let embed = (options.color_space.is_some() && map.is_color() && (component_count >= 3 || format == FileFormat::J2k)).then_some(space); Ok(RenderedMap { data, size, component_count, srgb, embed }) } } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 93c8329a..41522520 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -45,6 +45,8 @@ const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// Bound retained PSD payloads before rendering, with headroom for a document's working buffers and ZIP packaging +const MAX_PSD_BATCH_BYTES: u64 = 1024 * 1024 * 1024; /// Planes of a PSD image or layer: red, green, blue and alpha const PSD_RGBA_PLANES: usize = 4; /// Preset limits (user presets are untrusted JSON). @@ -651,6 +653,44 @@ fn psd_stem(mesh_name: &str, set_name: &str, set_index: usize, max_len: usize) - format!("{mesh}_{set}_{set_index}") } +/// Keep tiled names stable even when the export window plans each texture set separately. +fn untiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, atlas: bool) -> String { + let stem = psd_stem(mesh_name, &set.name, set_index, MAX_STEM); + if atlas { + return stem; + } + + let Some((base, tile)) = stem.rsplit_once('.') else { return stem }; + let Ok(number) = tile.parse::() else { return stem }; + + let suffix_len = tile.len() + 1; + let collides = number.to_string() == tile + && project.texture_sets.iter().enumerate().any(|(index, other)| { + other.uv_tiles.contains(&number) && base.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM - suffix_len)) + }); + if !collides { + return stem; + } + + // Reserve the ordinary untiled names, including names that already end in an index + let untiled_names: BTreeSet<_> = project + .texture_sets + .iter() + .enumerate() + .filter(|(_, other)| other.uv_tiles.is_empty()) + .map(|(index, other)| psd_stem(mesh_name, &other.name, index, MAX_STEM).to_ascii_lowercase()) + .collect(); + let mut attempt = 0usize; + loop { + let suffix = if attempt == 0 { format!("_{set_index}") } else { format!("-{attempt}_{set_index}") }; + let name = format!("{}{suffix}", &stem[..stem.len().min(MAX_STEM - suffix.len())]); + if !untiled_names.contains(&name.to_ascii_lowercase()) { + return name; + } + attempt += 1; + } +} + /// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. pub fn sanitize_file_path(s: &str) -> String { s.split('/').map(sanitize_file_stem).collect::>().join("/") @@ -697,8 +737,12 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export // Integer files clamp wide-gamut linear color to 0–1 let clamps = color_map && !format.holds_float(bit_depth) && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065); - // Append `$udim` to names for separate UV tiles - let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; + // A PSD layer needs only explicit tile tokens because its document name already holds the tile number + let template = if format != FileFormat::Psd && tiles[0].is_some() && !map.file.contains("$udim") { + std::borrow::Cow::Owned(format!("{}.$udim", map.file)) + } else { + std::borrow::Cow::Borrowed(map.file.as_str()) + }; let expand_stem = |udim: &str| { let expanded = template .replace("$udim", udim) @@ -737,16 +781,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export .then(|| format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())) }; - // The PSD's own name holds the tile number, so its layers are named without the one appended if format == FileFormat::Psd { if enabled { - let appended = tile.filter(|_| template != map.file).map(|number| format!(".{number}")); - let name = appended.as_deref().and_then(|suffix| stem.strip_suffix(suffix)).unwrap_or(&stem).to_string(); - warnings.extend(packs_colour(&name)); + warnings.extend(packs_colour(&stem)); if psd_layers.is_empty() { psd_layers.resize_with(tiles.len(), Vec::new); } - psd_layers[tile_index].push((PlannedLayer { map: map_index, name, dither }, bit_depth, warnings)); + psd_layers[tile_index].push((PlannedLayer { map: map_index, name: stem, dither }, bit_depth, warnings)); } continue; } @@ -800,7 +841,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let base = psd_stem(mesh_name, &set.name, ts, MAX_STEM - suffix.len()); (format!("{base}{suffix}"), Some(format!("{base}."))) } else { - (psd_stem(mesh_name, &set.name, ts, MAX_STEM), None) + (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) }; let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); claim_path(&mut active_files, &mut active_dirs, &name)?; @@ -870,9 +911,12 @@ fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u /// Plan a selection in export order, keeping only the first case-insensitive use of a name. pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { + let mut psd_bytes = 0; let mut files = Vec::new(); - for &set in sets { - files.extend(list_outputs(project, set, mesh_name, opts)?.into_iter().map(|file| (set, file))); + for &index in sets { + let planned = list_outputs(project, index, mesh_name, opts)?; + check_psd_batch(project.texture_set(index)?, opts, &planned, &mut psd_bytes)?; + files.extend(planned.into_iter().map(|file| (index, file))); } Ok(keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings)) @@ -1048,6 +1092,28 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result Result<()> { + let mut estimate = *total_bytes; + for file in planned.iter().filter(|file| file.format == FileFormat::Psd) { + let (_, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())?; + add_psd_batch_bytes(&mut estimate, file_bytes)?; + } + + *total_bytes = estimate; + Ok(()) +} + +fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64) -> Result<()> { + let estimate = total_bytes.saturating_add(file_bytes); + if estimate > MAX_PSD_BATCH_BYTES { + return Err(FormatError::TooLarge("total PSD output would exceed 1 GiB; use a smaller export size, fewer PSD maps or separate exports".into())); + } + + *total_bytes = estimate; + Ok(()) +} + /// Render the retained plans from `list_outputs` for this input and these options. pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned: Vec) -> Result> { if planned.is_empty() { @@ -1066,10 +1132,15 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned ))); } + let mut psd_bytes = 0; for file in &planned { - let size = - (file.format == FileFormat::Psd).then(|| layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())).transpose()?; - psd_sizes.push(size); + if file.format == FileFormat::Psd { + let (size, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())?; + add_psd_batch_bytes(&mut psd_bytes, file_bytes)?; + psd_sizes.push(Some(size)); + } else { + psd_sizes.push(None); + } } } diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 437fcf1e..b5d18af0 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -2191,3 +2191,129 @@ fn the_sketchfab_template_writes_directx_normals_and_one_map_per_channel() { assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); } + +#[test] +fn feedback_psd_preview_matches_layer_rgba() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + + for channels in [roughness(), gray_alpha, rgba_half_alpha()] { + let options = one_map(FileFormat::Psd, 8, channels); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let files = fx.render(&options); + let psd = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap().rgba8().unwrap(); + + assert_eq!(preview.channels, [Dest::R, Dest::G, Dest::B, Dest::A]); + assert!(preview.pixels == layer.data, "the preview shows the layer's stored channels"); + } +} + +#[test] +fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001]; + let mut options = one_map(FileFormat::Psd, 8, roughness()); + let literal = format!("{}.1001", "a".repeat(MAX_STEM - ".1001".len())); + options.preset.maps[0].file = literal.clone(); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert_eq!(plan[0].layers[0].name, literal); + + options.preset.maps[0].file = "Group/Map.$udim".into(); + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].layers[0].name, "Group/Map.1001"); + + options.preset.maps[0].file = "Map".into(); + options.format_override = Some(FileFormat::Png); + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].name, "Map.1001.png"); +} + +#[test] +fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].name = "Body".into(); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + for name in ["body.1001", "Body.1001_1", "Trim"] { + let mut untiled = fx.project.texture_sets[0].clone(); + untiled.name = name.into(); + untiled.uv_tiles.clear(); + fx.project.texture_sets.push(untiled); + } + let options = one_map(FileFormat::Psd, 8, roughness()); + + let plans = list_set_outputs(&fx.project, &[1, 0, 2, 3], "sphere", &options).unwrap(); + + assert_eq!(plans.len(), 5); + assert_eq!(plans[1].1.name, "sphere_Body.1001.psd"); + assert_eq!(plans[2].1.name, "sphere_Body.1002.psd"); + assert_eq!(plans[3].1.name, "sphere_Body.1001_1.psd"); + assert_eq!(plans[4].1.name, "sphere_Trim.psd"); + let separate = list_outputs(&fx.project, 1, "sphere", &options).unwrap(); + assert_eq!(plans[0].1.name, separate[0].name, "individual desktop jobs agree with selection planning"); +} + +#[test] +fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { + let mut fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.padding = Padding::None; + options.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1008).collect(); + + let smaller = list_set_outputs(&fx.project, &[0], "sphere", &options).unwrap(); + assert_eq!(smaller.len(), 7, "seven 128 MiB payloads fit with record overhead"); + fx.project.texture_sets[0].uv_tiles.extend(1008..1034); + + let oversized = list_set_outputs(&fx.project, &[0], "sphere", &options); + assert!(matches!(&oversized, Err(error) if error.to_string().contains("total PSD")), "the 33 individually valid tiles must be rejected as a batch"); + + let set = &fx.project.texture_sets[0]; + let (width, height) = set.size(); + fx.comp = Composite::with_size(&default_channels(), width, height); + fx.coverage.resize((width * height) as usize, true); + let error = render_maps(&fx.input(), &options).unwrap_err(); + assert!(error.to_string().contains("total PSD"), "{error}"); + + let (_, estimated_bytes) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); + println!("PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {MAX_PSD_BATCH_BYTES}", estimated_bytes * 33); + + let mut small = fx.project.texture_sets[0].clone(); + small.uv_tiles = (1001..1006).collect(); + fx.project.texture_sets[0] = small.clone(); + small.name = "Other".into(); + fx.project.texture_sets.push(small); + assert!(list_set_outputs(&fx.project, &[0], "sphere", &options).is_ok()); + assert!(list_set_outputs(&fx.project, &[1], "sphere", &options).is_ok()); + assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_err(), "the budget includes all selected sets"); +} + +#[test] +fn feedback_j2k_warns_for_explicit_gray_and_rgb_colour_spaces() { + let fx = Fx::new(&default_channels()); + let base = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; + let gray = vec![(Dest::L, base(0))]; + let rgb = vec![(Dest::R, base(0)), (Dest::G, base(1)), (Dest::B, base(2))]; + + for (channels, selected, expected) in [ + (gray.clone(), Some(ColorSpace::LinearRec709), Some(ColorSpace::LinearRec709)), + (gray, Some(ColorSpace::AcesCg), Some(ColorSpace::LinearRec709)), + (rgb, Some(ColorSpace::Srgb), Some(ColorSpace::Srgb)), + (roughness(), None, None), + ] { + let mut options = one_map(FileFormat::J2k, 8, channels); + options.color_space = selected; + + let files = fx.render(&options); + let warnings: Vec<_> = files[0].warnings.iter().filter(|warning| warning.contains("J2K export does not embed")).collect(); + + assert_eq!(warnings.len(), usize::from(expected.is_some()), "warnings: {:?}", files[0].warnings); + if let Some(space) = expected { + assert!(warnings[0].ends_with(space.name())); + } + } +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 5baa1a7a..85356dce 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -53,7 +53,7 @@ pub use mesh_export::{ 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::{DEFAULT_PRESET, builtin_preset, builtin_preset_catalog, builtin_presets, preset_from_json, preset_to_json}; +pub use presets::{DEFAULT_PRESET, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, builtin_presets, preset_from_json, preset_to_json}; pub use project_file::{ BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, RamReservation, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes, set_project_open_limit_gib, diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 8ef1fc79..0b34ceb5 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -311,6 +311,15 @@ pub const DEFAULT_PRESET: &str = "Document channels + Normal + AO (No Alpha)"; /// scripts still use it). const OLD_DEFAULT_PRESET: &str = "Document channels + Normal + AO"; +/// Names introduced with the export update, which could previously belong to saved user presets. +pub const NEW_BUILTIN_PRESET_NAMES: [&str; 5] = [ + "Unreal Engine Subsurface Profile (Packed)", + "glTF Specular Glossiness (archived extension)", + "Redshift Standard Material (separate maps)", + "Roblox SurfaceAppearance (separate maps)", + "Sketchfab Metalness (separate maps)", +]; + /// The immutable built-in templates shared by menu and command lookups. pub fn builtin_preset_catalog() -> &'static [ExportPreset] { static CATALOG: std::sync::LazyLock> = std::sync::LazyLock::new(builtin_presets); diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index a0e0802e..3832919c 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -584,7 +584,8 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32, n } } None => { - let response = preset_row(ui, rect, name, *name == selected_name, is_user).on_hover_text(name); + let label = template_label(&app.session, name); + let response = preset_row(ui, rect, name, label, *name == selected_name, is_user).on_hover_text(name); if response.double_clicked() && is_user { act = Some(ListAction::StartRename(name.clone())); } else if response.clicked() { @@ -633,11 +634,10 @@ fn template_file_items(ui: &mut Ui, act: &mut Option, with_export: b } /// A Presets row: a locked file glyph for a built-in template, the name cut with "…", the selected one in bold -fn preset_row(ui: &mut Ui, rect: Rect, name: &str, selected: bool, is_user: bool) -> egui::Response { +fn preset_row(ui: &mut Ui, rect: Rect, name: &str, label: &str, selected: bool, is_user: bool) -> egui::Response { let look = ExportLook::get(ui.ctx()); let response = ui.interact(rect, ui.scope_id().with(("exp_preset_row", name)), egui::Sense::click()); - let name = template_label(name); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, label)); let painter = ui.painter(); if selected { painter.rect_filled(rect, 0.0, look.chrome); @@ -646,7 +646,7 @@ fn preset_row(ui: &mut Ui, rect: Rect, name: &str, selected: bool, is_user: bool } let icon = if is_user { ic::FILE_TEXT } else { ic::FILE_LOCK }; drawn::glyph(ui, pos2(rect.left() + PRESET_ICON_X, rect.center().y), icon, PRESET_ROW_ICON_SIZE, look.text_dim); - let shown = drawn::fitted(ui, name, rect.width() - PRESET_NAME_LEFT, false, selected); + let shown = drawn::fitted(ui, label, rect.width() - PRESET_NAME_LEFT, false, selected); let color = if selected { look.text } else { look.list_text }; drawn::text_at(ui, rect.left() + PRESET_NAME_LEFT, rect.center().y, &shown, color, selected); drawn::paint_focus(ui, &response); @@ -683,7 +683,7 @@ fn perform(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) { } ListAction::Duplicate(name) => { if let Some(p) = app.session.export_preset(&name) { - let name = format!("{}_copy", template_label(&p.name)).chars().take(MAX_PRESET_NAME).collect(); + let name = format!("{}_copy", template_label(&app.session, &name)).chars().take(MAX_PRESET_NAME).collect(); save_new(app, &ExportPreset { name, ..p }); } } @@ -867,9 +867,9 @@ pub fn load_library(app: &mut TextureCraftApp, storage: Option<&dyn eframe::Stor app.session.log.warnings(texturecraft_engine::log::LIBRARY_SOURCE, skipped.into_iter().map(|w| format!("Export template skipped: {w}"))); } #[cfg(target_arch = "wasm32")] - for p in storage.and_then(|s| eframe::get_value::>(s, STORAGE_KEY)).unwrap_or_default() { - if let Ok(v) = serde_json::to_value(&p) { - app.run("export.preset.save", json!({ "preset": v, "unique": true })); + for preset in storage.and_then(|s| eframe::get_value::>(s, STORAGE_KEY)).unwrap_or_default() { + if let Err(error) = app.session.export_presets.restore(preset) { + app.session.log.warnings(texturecraft_engine::log::LIBRARY_SOURCE, [format!("Export template skipped: {error}")]); } } } @@ -913,7 +913,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { let title = tr("Current preset:"); let name_left = column.left() + drawn::text_width(ui, title, true) + NAME_GAP; drawn::label_at(ui, column.left(), y, title, look.text, true); - let name = drawn::label_at(ui, name_left, y, template_label(&preset.name), look.text, false); + let name = drawn::label_at(ui, name_left, y, template_label(&app.session, &app.ui.export.preset), look.text, false); if !editable { let lock_at = pos2(name.rect.right() + LOCK_GAP, y); drawn::glyph(ui, lock_at, ic::LOCK_SIMPLE, CARD_ICON_SIZE, look.text_dim); @@ -1069,12 +1069,23 @@ fn commit(app: &mut TextureCraftApp, preset: ExportPreset, mut origin: Vec Result { let mut params = crate::export_window::set_params(app, app.session.ts()); - params["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?; + let export = &app.ui.export; + let same_template = params.get("preset").and_then(Value::as_str) == Some(export.preset.as_str()); - // The set's map overrides apply only to its own template - if let Some(params) = params.as_object_mut() { + if !same_template && let Some(params) = params.as_object_mut() { params.remove("maps"); + } else if let (Some(_), Some(maps)) = (&export.draft, params.get_mut("maps").and_then(Value::as_array_mut)) { + // Draft positions have no override until they map to a saved output + maps.retain_mut(|settings| { + let Some(saved_index) = settings["map"].as_u64().and_then(|index| usize::try_from(index).ok()) else { return false }; + let Some(draft_index) = export.draft_maps.iter().position(|origin| *origin == Some(saved_index)) else { return false }; + + settings["map"] = json!(draft_index); + true + }); } + + params["preset"] = serde_json::to_value(preset).map_err(|error| error.to_string())?; Ok(params) } @@ -1503,7 +1514,8 @@ fn preview_pictures(ui: &mut Ui, map: &MapSpec, pictures: &MapPreviewPictures) { Dest::R | Dest::G | Dest::B if source_of(map, gray).is_some() => gray, _ => target, }; - let source = source_of(map, source_target).unwrap_or(&SourceRef::Constant(CLEARED_VALUE)); + let fallback = SourceRef::Constant(if *dest == Dest::A { CLEARED_ALPHA } else { CLEARED_VALUE }); + let source = source_of(map, source_target).unwrap_or(&fallback); let inverted = source_target.dests().iter().any(|dest| map.inverted.contains(dest)); ui.horizontal(|ui| { @@ -1855,6 +1867,40 @@ mod tests { SourceRef::Channel { channel, component } } + #[test] + fn feedback_preview_follows_draft_maps_to_their_saved_overrides() { + use crate::state::{MapExport, SetExport}; + use egui_kittest::Harness; + + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let ts = app.session.ts(); + let saved = app.session.export_preset("Unreal Engine (Packed)").unwrap(); + let mut draft = saved.clone(); + draft.maps = vec![saved.maps[1].clone(), new_map(Layout::Gray, "New"), saved.maps[0].clone()]; + let resized = MapExport { size: Some(128), ..MapExport::default() }; + let disabled = MapExport { enabled: false, ..MapExport::default() }; + app.ui.export.preset = saved.name.clone(); + app.ui.export.sets.insert( + ts, + SetExport { + maps_template: saved.name, + maps: [(0, resized), (1, disabled), (2, MapExport { size: Some(512), ..MapExport::default() })].into(), + ..SetExport::default() + }, + ); + app.ui.export.draft = Some(draft.clone()); + app.ui.export.draft_maps = vec![Some(1), None, Some(0)]; + + let params = plan_params(app, &draft).unwrap(); + let outputs = planned_outputs(app, ¶ms).unwrap(); + + assert!(outputs[0].is_none(), "the disabled map stays disabled in its new position"); + assert_eq!(outputs[2].as_ref().unwrap().size, 128); + assert_eq!(params["maps"].as_array().unwrap().len(), 2, "the new map and the removed map get no override"); + } + #[test] fn layouts_keep_sources_and_drops_fill_rgb() { let mut map = new_map(Layout::Rgb, "t"); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 9a93edad..fd2fea9a 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -335,31 +335,47 @@ fn file_type_name(format: &str) -> String { } /// The label shown for a stored template name. Custom template names pass through unchanged. -pub(super) fn template_label(name: &str) -> &str { - match name { +pub(super) fn template_label<'a>(session: &texturecraft_engine::Session, name: &'a str) -> &'a str { + use texturecraft_engine::preset_cmds::unqualified_preset_name; + + let label = match unqualified_preset_name(name) { "Unreal Engine Subsurface Profile (Packed)" => tr("Packed maps with a scattering mask"), "Redshift Standard Material (separate maps)" => tr("Separate coat, sheen and scattering maps"), "Roblox SurfaceAppearance (separate maps)" => tr("Four maps with opacity in color"), "Sketchfab Metalness (separate maps)" => tr("Six maps with a negative-Y normal"), - _ => name, - } + _ => return name, + }; + + if session.has_user_export_preset(name) { name } else { label } } /// The template list: the first group (name, whether TextureCraft has it), then the others /// (built-in and user templates) sorted by name. pub(crate) fn template_groups(app: &TextureCraftApp, builtins: &[ExportPreset]) -> (Vec<(&'static str, bool)>, Vec) { let first = FIRST_GROUP.iter().map(|name| (*name, builtins.iter().any(|p| p.name == *name))).collect(); - let mut rest: Vec = builtins.iter().map(|p| p.name.clone()).filter(|n| !FIRST_GROUP.contains(&n.as_str())).collect(); + let mut rest: Vec = builtins + .iter() + .filter(|preset| !FIRST_GROUP.contains(&preset.name.as_str())) + .map(|preset| app.session.builtin_export_preset_id(&preset.name).into_owned()) + .collect(); rest.extend(app.session.export_presets.list.iter().map(|p| p.name.clone())); - rest.sort_by(|left, right| template_label(left).cmp(template_label(right)).then_with(|| left.cmp(right))); + rest.sort_by(|left, right| template_label(&app.session, left).cmp(template_label(&app.session, right)).then_with(|| left.cmp(right))); rest.dedup(); (first, rest) } /// A template dropdown in `rect` over `first` and `rest`; true when `current` changed -fn template_combo(ui: &mut Ui, rect: egui::Rect, id: &str, current: &mut String, first: &[(&str, bool)], rest: &[String]) -> bool { +fn template_combo( + session: &texturecraft_engine::Session, + ui: &mut Ui, + rect: egui::Rect, + id: &str, + current: &mut String, + first: &[(&str, bool)], + rest: &[String], +) -> bool { let mut changed = false; - drawn::combo(ui, rect, id, template_label(current).to_owned(), |ui| { + drawn::combo(ui, rect, id, template_label(session, current).to_owned(), |ui| { for (name, have) in first { if *have { changed |= ui.selectable_value(current, (*name).to_string(), *name).on_hover_text(*name).changed(); @@ -369,7 +385,7 @@ fn template_combo(ui: &mut Ui, rect: egui::Rect, id: &str, current: &mut String, } ui.separator().on_hover_text(tr("Some templates in this list are unavailable")); for name in rest { - changed |= ui.selectable_value(current, name.clone(), template_label(name)).on_hover_text(name).changed(); + changed |= ui.selectable_value(current, name.clone(), template_label(session, name)).on_hover_text(name).changed(); } }); changed @@ -1013,7 +1029,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, builtin row_label(ui, place, y, tr("Output template")); let (first, rest) = template_groups(app, builtins); let mut picked = app.ui.export.preset.clone(); - if template_combo(ui, drawn::control_rect(left, right, y), "exp_preset", &mut picked, &first, &rest) { + if template_combo(&app.session, ui, drawn::control_rect(left, right, y), "exp_preset", &mut picked, &first, &rest) { crate::export_templates::select(app, picked); } @@ -1237,9 +1253,9 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, let row_y = |row: usize| place.y(SET_FIRST_ROW_Y + row as f32 * SET_ROW_PITCH); let mut toggled = None; - if override_row(ui, place, row_y(0), tr("Output template"), overrides.preset.is_some(), template_label(&from.preset), |ui, rect| { + if override_row(ui, place, row_y(0), tr("Output template"), overrides.preset.is_some(), template_label(&app.session, &from.preset), |ui, rect| { if let Some(preset) = &mut overrides.preset { - template_combo(ui, rect, "exp_set_preset", preset, &first, &rest); + template_combo(&app.session, ui, rect, "exp_set_preset", preset, &first, &rest); } }) { toggled = Some(0); @@ -1687,13 +1703,8 @@ fn cancel(app: &mut TextureCraftApp) { app.ui.windows.export = false; } -/// Escape closes the window as Cancel does, read in `menus::shortcuts`; an open dropdown, channel question, template rename or text field takes it first -pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, popup_open: bool) { - let export = &app.ui.export; - if popup_open || export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some() { - return; - } - +/// Escape closes the window as Cancel does after shortcut routing checks higher-priority inputs. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { app.ui.export.job = None; cancel(app); @@ -1804,7 +1815,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } // Settings saved under the default template's old name - if let Some(b) = texturecraft_engine::formats::builtin_preset(&app.ui.export.preset) + if !app.session.has_user_export_preset(&app.ui.export.preset) + && let Some(b) = texturecraft_engine::formats::builtin_preset(&app.ui.export.preset) && b.name != app.ui.export.preset { app.ui.export.preset = b.name; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9a497ce9..53547d2f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -514,11 +514,14 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - // The open list or the picker window closes on this Escape itself + let export = &app.ui.export; let escape_is_free = !popup_open && !picker_open; + + // Local export inputs handle Escape during drawing + let export_input_active = app.ui.windows.export && (export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some()); if confirming_reset { // Its keys were handled before the shortcuts ran - } else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { // The Output templates question: Escape answers it with the safe choice app.ui.export.ask = None; } else if app.ui.windows.project_config.is_some() { @@ -528,22 +531,25 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); - } else if app.ui.windows.export { - // Escape is the window's Cancel; nothing behind the window reads it - crate::export_window::keys_in(app, input, !escape_is_free); - } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if popup_open || export_input_active { + // The open list or export input handles the key + } else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; - } else if !popup_open && point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { cancel_point_pick = true; - } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if !escape_is_free { + // The picker window handles the key + } else if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; - } else if escape_is_free && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { crate::id_color_pick::IdColorPick::end(app); - } else if escape_is_free && app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_symmetry_plane = false; - } else if escape_is_free && app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.ui.windows.export { + crate::export_window::keys_in(app, input); + } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.cancel_path(); } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 41caad25..72227984 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -360,14 +360,14 @@ mod web { } fn export(app: &mut TextureCraftApp, jobs: &[(usize, Value)]) -> Result { - let mut files = Vec::new(); - for (set_index, params) in jobs { - let options = texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures").map_err(|e| e.to_string())?; - files.extend(app.session.export_files(&[*set_index], &options).map_err(|e| e.to_string())?); - } + let options = jobs + .iter() + .map(|(_, params)| texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures")) + .collect::, _>>() + .map_err(|error| error.to_string())?; + let jobs_with_options = jobs.iter().zip(&options).map(|((set_index, _), options)| (*set_index, options)); + let mut files = app.session.export_file_jobs(jobs_with_options).map_err(|error| error.to_string())?; - // Keep one file for each case-insensitive name in the download - texturecraft_engine::formats::skip_repeated_names(&mut files); if app.ui.export.shader_parameters { let sets: Vec = jobs.iter().map(|(set_index, _)| *set_index).collect(); match shader_parameters_sidecar(&app.session.doc.project, &sets, &files) { diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index c379b0f8..2c79474b 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -216,3 +216,24 @@ fn the_page_reset_puts_the_parameters_back() { assert_eq!((e.size, e.padding.as_str()), (0, "infinite")); assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page"); } + +#[test] +fn feedback_escape_clears_a_pick_before_cancelling_export() { + let mut h = harness(); + let pick = egui::Id::unique("export_escape_screen_color_pick"); + h.state_mut().picking_color = Some(pick); + h.state_mut().ui.export.size = 512; + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.state().picking_color.is_none(), "the armed pick receives Escape first"); + assert!(h.query_by_role_and_label(egui::Role::Button, "Save settings").is_some()); + assert_eq!(h.state().ui.export.size, 512); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(h.state().ui.export.size, 0); +} diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 12a40ace..c40deb73 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -763,3 +763,22 @@ fn leaving_output_templates_releases_pictures_from_each_hovered_map() { assert!(!h.state().ui.windows.export); assert_eq!(previews(&h), 0); } + +#[test] +fn feedback_template_preview_counts_overrides_only_for_its_own_maps() { + let library = TemplateLibrary::new("preview-map-overrides"); + let mut h = harness(&library); + let ts = h.state().session.ts(); + let plan = h.state_mut().run("export.plan", json!({"ts": ts, "preset": "Mine"})).unwrap(); + let initial = plan.as_array().unwrap().len(); + assert!(initial > 0); + let disabled = MapExport { enabled: false, ..MapExport::default() }; + h.state_mut().ui.export.sets.insert(ts, SetExport { maps_template: "Mine".into(), maps: [(0, disabled)].into(), ..SetExport::default() }); + + h.run_steps(4); + + assert!(h.query_by_label(&format!("{} output maps will be exported", initial - 1)).is_some()); + h.state_mut().ui.export.sets.get_mut(&ts).unwrap().preset = Some("Separate maps".into()); + h.run_steps(4); + assert!(h.query_by_label(&format!("{initial} output maps will be exported")).is_some()); +} From b965b750f7707c075f71a17cfa3084ee9cc8c352 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 25 Nov 2026 23:10:17 +0000 Subject: [PATCH 050/190] Auto: Fix export planning, previews, and file-list scrolling Disambiguate colliding PSD filenames and budget only the documents retained for export. Match grayscale WebP previews to the encoded channels and make wide export details reachable by scrolling. Document built-in preset selection and verify declared JPEG 2000 component precision. Focused Linux tests, affected-package Clippy, and WebAssembly checks passed. --- crates/engine/src/file_cmds.rs | 23 +++-- crates/engine/tests/it/export_file_types.rs | 22 +++++ crates/formats/README.md | 10 ++- crates/formats/src/export/map_preview.rs | 6 +- crates/formats/src/export/mod.rs | 95 +++++++++++++++------ crates/formats/src/export/tests.rs | 91 ++++++++++++++++++++ crates/ui-egui/src/export_window.rs | 20 ++++- crates/ui-egui/tests/it/export_progress.rs | 30 +++++++ 8 files changed, 255 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 6b47fa94..9940b372 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -285,17 +285,14 @@ impl Session { } /// Render every export file for texture sets `sets` (in memory; works on the web). A file - /// named like one an earlier set exports is left out, with a warning (see - /// [`texturecraft_formats::skip_repeated_names`]). + /// named like one an earlier set exports is left out, with a warning. pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result> { self.export_file_jobs(sets.iter().map(|&set| (set, opts))) } /// Render one in-memory batch, using each set's own export settings when supplied. pub fn export_file_jobs<'a>(&mut self, jobs: impl IntoIterator) -> Result> { - let mut files = self.render_export_jobs(jobs, |_, plans| plans)?; - texturecraft_formats::skip_repeated_names(&mut files); - Ok(files) + self.render_export_jobs(jobs, |_, plans| plans) } #[cfg(not(target_arch = "wasm32"))] @@ -315,18 +312,28 @@ impl Session { ) -> Result> { let project = &self.doc.project; let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); - let mut psd_bytes = 0; let mut pending = Vec::new(); for (set_index, options) in jobs { let plans = texturecraft_formats::list_outputs(project, set_index, &mesh_name, options).map_err(fe)?; let plans = select(set_index, plans); if !plans.is_empty() { - let set = project.texture_set(set_index).map_err(|error| EngineError::Other(error.to_string()))?; - texturecraft_formats::export::check_psd_batch(set, options, &plans, &mut psd_bytes).map_err(fe)?; pending.push((set_index, options, plans)); } } + // Keep each winning plan with the options of the job that produced it + let plans = pending.iter_mut().enumerate().flat_map(|(job, (_, _, plans))| plans.drain(..).map(move |plan| (job, plan))); + for (job, plan) in texturecraft_formats::export::keep_first_planned_names(plans) { + pending[job].2.push(plan); + } + pending.retain(|(_, _, plans)| !plans.is_empty()); + + let mut psd_bytes = 0; + for (set_index, options, plans) in &pending { + let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?; + texturecraft_formats::export::check_psd_batch(set, options, plans, &mut psd_bytes).map_err(fe)?; + } + if self.solo.is_none() { self.update(); } diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index e8bbe2c3..40e4816f 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -28,6 +28,28 @@ fn the_new_file_types_dithering_and_diffusion_export() { assert!(execute(&mut s, "export.plan", &json!({"padding": "smudge"})).is_err()); } +#[test] +fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() { + const SMALL_SIDE: u32 = 128; + let mesh = texturecraft_engine::geom::primitives::udim_plane(); + let mut session = texturecraft_engine::Session::new_project("test", mesh, "builtin:udim_plane", None, SMALL_SIDE).unwrap(); + let preset = + json!({"name": "Roughness", "maps": [{"file": "rough", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]}); + let options = |size| texturecraft_engine::file_cmds::export_options(&session, &json!({"preset": preset, "size": size, "padding": "none"}), "test").unwrap(); + let small = options(SMALL_SIDE); + let large = options(4096); + let first = session.export_files(&[0], &small).unwrap(); + assert!(first.len() > 1, "the mesh supplies multiple PSD tiles"); + + let jobs = std::iter::once((0, &small)).chain(std::iter::repeat_n((0, &large), 4)); + let batch = session.export_file_jobs(jobs).unwrap(); + + assert_eq!(batch.len(), first.len()); + assert!(batch.iter().zip(&first).all(|(kept, original)| kept.name == original.name && kept.bytes == original.bytes)); + assert!(batch.iter().zip(&first).all(|(kept, original)| kept.warnings.len() > original.warnings.len())); + println!("Kept {} PSDs totaling {} encoded bytes", batch.len(), batch.iter().map(|file| file.bytes.len()).sum::()); +} + #[test] fn a_map_size_wins_over_the_export_size_in_the_plan() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); diff --git a/crates/formats/README.md b/crates/formats/README.md index 4be58133..eb04b8bf 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -148,9 +148,13 @@ Built-in presets (each one lists the public specification its packing follows in | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | -The preset column gives the stable automation and saved-setting names. The export window describes -four templates by their output. **Packed maps with a scattering mask** targets Unreal Engine's -subsurface input. **Separate coat, sheen and scattering maps** targets Redshift. +The preset column gives the stable automation and saved-setting names. When a user preset shares +a table name, that name selects the user preset so saved settings keep working. To select the +built-in through automation, pass the exact `name` from its `builtin: true` entry in +`export.presets`. + +The export window describes four templates by their output. **Packed maps with a scattering mask** +targets Unreal Engine's subsurface input. **Separate coat, sheen and scattering maps** targets Redshift. **Four maps with opacity in color** targets Roblox, and **Six maps with a negative-Y normal** targets Sketchfab. diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs index 81063de3..282ec063 100644 --- a/crates/formats/src/export/map_preview.rs +++ b/crates/formats/src/export/map_preview.rs @@ -64,8 +64,10 @@ impl MapPreview { let gray_source = channel_layout.first().filter(|(dest, _)| *dest == Dest::L); let psd = file.format == FileFormat::Psd; - let rgb_from_gray = gray_source - .filter(|_| psd || file.format == FileFormat::Hdr || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2))); + let rgb_from_gray = gray_source.filter(|_| { + matches!(file.format, FileFormat::Psd | FileFormat::Hdr | FileFormat::Webp) + || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2)) + }); let channels = if grayscale { vec![Dest::L] } else if psd { diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 41522520..7e0afcb3 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -653,40 +653,67 @@ fn psd_stem(mesh_name: &str, set_name: &str, set_index: usize, max_len: usize) - format!("{mesh}_{set}_{set_index}") } -/// Keep tiled names stable even when the export window plans each texture set separately. +/// Compare against the whole project so a separate export and a batch agree on names. fn untiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, atlas: bool) -> String { let stem = psd_stem(mesh_name, &set.name, set_index, MAX_STEM); - if atlas { - return stem; - } + let taken = |candidate: &str| { + let tile = psd_tile_suffix(candidate); + project.texture_sets.iter().enumerate().filter(|(index, _)| *index != set_index).any(|(index, other)| { + if atlas || other.uv_tiles.is_empty() { + candidate.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM)) + } else { + tile.is_some_and(|(base, number)| { + other.uv_tiles.contains(&number) + && base.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM - (candidate.len() - base.len()))) + }) + } + }) + }; + if taken(&stem) { disambiguated_psd_stem(&stem, set_index, MAX_STEM, taken) } else { stem } +} - let Some((base, tile)) = stem.rsplit_once('.') else { return stem }; - let Ok(number) = tile.parse::() else { return stem }; +/// Only a canonical tile number can collide with a generated UDIM suffix. +fn psd_tile_suffix(stem: &str) -> Option<(&str, u32)> { + let (base, suffix) = stem.rsplit_once('.')?; + let number: u32 = suffix.parse().ok()?; + (number.to_string() == suffix).then_some((base, number)) +} - let suffix_len = tile.len() + 1; - let collides = number.to_string() == tile - && project.texture_sets.iter().enumerate().any(|(index, other)| { - other.uv_tiles.contains(&number) && base.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM - suffix_len)) - }); +/// Keep one UDIM base for all tiles of a set when any tile's ordinary name collides. +fn tiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, limit: usize) -> String { + let stem = psd_stem(mesh_name, &set.name, set_index, limit); + let other_sets = || project.texture_sets.iter().enumerate().filter(|(index, _)| *index != set_index); + let collides = other_sets().any(|(index, other)| { + !other.uv_tiles.is_empty() + && stem.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, limit)) + && other.uv_tiles.iter().any(|tile| set.uv_tiles.contains(tile)) + }); if !collides { return stem; } - // Reserve the ordinary untiled names, including names that already end in an index - let untiled_names: BTreeSet<_> = project - .texture_sets - .iter() - .enumerate() - .filter(|(_, other)| other.uv_tiles.is_empty()) - .map(|(index, other)| psd_stem(mesh_name, &other.name, index, MAX_STEM).to_ascii_lowercase()) - .collect(); + // Reserve ordinary names so a generated suffix cannot take another document's name + disambiguated_psd_stem(&stem, set_index, limit, |candidate| { + other_sets().any(|(index, other)| { + if other.uv_tiles.is_empty() { + let untiled = psd_stem(mesh_name, &other.name, index, MAX_STEM); + psd_tile_suffix(&untiled).is_some_and(|(base, tile)| candidate.eq_ignore_ascii_case(base) && set.uv_tiles.contains(&tile)) + } else { + candidate.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, limit)) + } + }) + }) +} + +fn disambiguated_psd_stem(stem: &str, set_index: usize, limit: usize, taken: impl Fn(&str) -> bool) -> String { let mut attempt = 0usize; loop { let suffix = if attempt == 0 { format!("_{set_index}") } else { format!("-{attempt}_{set_index}") }; - let name = format!("{}{suffix}", &stem[..stem.len().min(MAX_STEM - suffix.len())]); - if !untiled_names.contains(&name.to_ascii_lowercase()) { + let name = format!("{}{suffix}", &stem[..stem.len().min(limit - suffix.len())]); + if !taken(&name) { return name; } + attempt += 1; } } @@ -810,6 +837,9 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export } } + // Reuse the base across tiles with the same suffix width + let mut tiled_bases = HashMap::new(); + // Each tile's PSD maps are the layers of one file named after the texture set for (&tile, in_tile) in tiles.iter().zip(psd_layers) { let Some((first_layer, ..)) = in_tile.first() else { continue }; @@ -838,7 +868,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let ext = FileFormat::Psd.extension(); let (stem, udim_stem) = if let Some(number) = tile { let suffix = format!(".{number}"); - let base = psd_stem(mesh_name, &set.name, ts, MAX_STEM - suffix.len()); + let limit = MAX_STEM - suffix.len(); + let base = tiled_bases.entry(limit).or_insert_with(|| tiled_psd_stem(project, mesh_name, ts, set, limit)); (format!("{base}{suffix}"), Some(format!("{base}."))) } else { (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) @@ -911,15 +942,19 @@ fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u /// Plan a selection in export order, keeping only the first case-insensitive use of a name. pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { - let mut psd_bytes = 0; let mut files = Vec::new(); for &index in sets { let planned = list_outputs(project, index, mesh_name, opts)?; - check_psd_batch(project.texture_set(index)?, opts, &planned, &mut psd_bytes)?; files.extend(planned.into_iter().map(|file| (index, file))); } - Ok(keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings)) + let files = keep_first_planned_names(files); + let mut psd_bytes = 0; + for (index, file) in files.iter().filter(|(_, file)| file.format == FileFormat::Psd) { + check_psd_batch(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes)?; + } + + Ok(files) } // --------------------------------------------------------------------------------------------- @@ -1703,9 +1738,15 @@ pub fn skip_repeated_names(files: &mut Vec) { *files = keep_first_names(std::mem::take(files), |file| &file.name, |file| &mut file.warnings); } -fn keep_first_names(files: Vec, name: impl Fn(&T) -> &str, warnings: impl Fn(&mut T) -> &mut Vec) -> Vec { +/// Keep the first case-insensitive use of each filename and attach duplicate warnings to its plan. +pub fn keep_first_planned_names(files: impl IntoIterator) -> Vec<(T, PlannedFile)> { + keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings) +} + +fn keep_first_names(files: impl IntoIterator, name: impl Fn(&T) -> &str, warnings: impl Fn(&mut T) -> &mut Vec) -> Vec { + let files = files.into_iter(); let mut first = HashMap::new(); - let mut kept = Vec::with_capacity(files.len()); + let mut kept = Vec::with_capacity(files.size_hint().0); for file in files { let filename = name(&file); match first.entry(filename.to_ascii_lowercase()) { diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index b5d18af0..a7e6fcb0 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1498,7 +1498,12 @@ fn jpeg2000_is_lossless_at_8_and_16_bits() { let components = usize::from(image.color().channel_count()); let expected = image.to_rgba16(); let planes = jpeg2000_planes(&file.bytes); + let info = j2k::J2kDecoder::inspect_support(&file.bytes).unwrap(); + assert_eq!(info.components.len(), components, "{}", file.name); + for (component, declared) in info.components.iter().enumerate() { + assert_eq!(declared.bit_depth, depth, "{} component {component} precision", file.name); + } assert_eq!(planes.len(), components, "{}", file.name); for (component, plane) in planes.iter().enumerate() { assert_eq!(plane.len(), expected.pixels().len(), "{} component {component}", file.name); @@ -1993,6 +1998,28 @@ fn feedback_jpeg_previews_omit_the_alpha_channel() { } } +#[test] +fn webp_preview_matches_the_exported_channels_and_samples() { + let fx = Fx::new(&default_channels()); + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.retain(|(dest, _)| *dest != Dest::A); + + for (layout, expected) in + [(roughness(), &[Dest::R, Dest::G, Dest::B][..]), (gray_alpha, &[Dest::R, Dest::G, Dest::B, Dest::A][..]), (rgb, &[Dest::R, Dest::G, Dest::B][..])] + { + let options = one_map(FileFormat::Webp, 8, layout); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let image = decode(&fx.render(&options)[0]); + + assert_eq!(preview.channels, expected); + assert_eq!(preview.channels.len(), usize::from(image.color().channel_count())); + assert_eq!(preview.pixels, image.as_bytes()); + } +} + #[test] fn pgm_preview_shows_exported_luminance_without_alpha() { let fx = Fx::new(&default_channels()); @@ -2257,6 +2284,70 @@ fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() { assert_eq!(plans[0].1.name, separate[0].name, "individual desktop jobs agree with selection planning"); } +#[test] +fn psd_document_names_survive_sanitization_and_case_collisions() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].name = "Body Coat".into(); + for (name, tiles) in [ + ("body_coat", vec![]), + ("Body_Coat_0", vec![]), + ("Body Coat", vec![1001, 1002]), + ("BODY_COAT", vec![1001]), + ("Trim", vec![]), + ("body_coat", vec![1011]), + ] { + let mut set = fx.project.texture_sets[0].clone(); + set.name = name.into(); + set.uv_tiles = tiles; + fx.project.texture_sets.push(set); + } + let options = one_map(FileFormat::Psd, 8, roughness()); + let indices = [6, 5, 4, 3, 2, 1, 0]; + + let batch = list_set_outputs(&fx.project, &indices, "sphere", &options).unwrap(); + let separate: Vec<_> = indices + .into_iter() + .flat_map(|index| list_outputs(&fx.project, index, "sphere", &options).unwrap().into_iter().map(move |file| (index, file.name))) + .collect(); + + assert_eq!(batch.into_iter().map(|(index, file)| (index, file.name)).collect::>(), separate); + for (index, unchanged) in [(2, "sphere_Body_Coat_0.psd"), (5, "sphere_Trim.psd"), (6, "sphere_body_coat.1011.psd")] { + assert!(separate.iter().any(|(set, name)| *set == index && name == unchanged)); + } + let tiled = list_outputs(&fx.project, 3, "sphere", &options).unwrap(); + assert!(tiled[0].udim_name.is_some()); + assert_eq!(tiled[0].udim_name, tiled[1].udim_name, "tiles of one set keep the same pattern"); + + let atlas_options = ExportOptions { atlas: true, ..options }; + let atlas = list_set_outputs(&fx.project, &indices, "sphere", &atlas_options).unwrap(); + assert_eq!(atlas.len(), indices.len(), "atlas documents also need distinct names"); +} + +#[test] +fn psd_batch_budget_counts_only_retained_documents() { + let mut fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1006).collect(); + let mut other = fx.project.texture_sets[0].clone(); + other.name = "Other".into(); + fx.project.texture_sets.push(other); + + let once = list_set_outputs(&fx.project, &[0], "sphere", &options).unwrap(); + let repeated = list_set_outputs(&fx.project, &[0, 0], "sphere", &options).unwrap(); + let distinct = list_set_outputs(&fx.project, &[0, 1], "sphere", &options); + let (_, bytes_per_tile) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); + + assert_eq!(once.len(), repeated.len()); + assert!(once.iter().zip(&repeated).all(|((_, first), (_, kept))| first.name == kept.name && kept.warnings.len() > first.warnings.len())); + assert!(matches!(distinct, Err(FormatError::TooLarge(message)) if message.contains("total PSD"))); + println!( + "PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {MAX_PSD_BATCH_BYTES}", + bytes_per_tile * once.len() as u64, + bytes_per_tile * (once.len() + repeated.len()) as u64 + ); +} + #[test] fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { let mut fx = Fx::new(&default_channels()); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index fd2fea9a..9cc30594 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1350,7 +1350,7 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { let tree = egui::Rect::from_min_max(egui::pos2(body.left(), body.top() + 1.0), egui::pos2(strip.left() - STRIP_GAP, body.bottom())); ui.painter().rect_filled(tree, 0.0, look.chrome); ui.scope_builder(egui::UiBuilder::new().max_rect(tree), |ui| { - egui::ScrollArea::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); + egui::ScrollArea::both().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); // The strip at the console's left edge: a click hides or shows the console, a drag resizes it @@ -1441,7 +1441,10 @@ fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { .zip(&open) .map(|(((_, set), files), open)| 1 + 1 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) .sum(); - let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT), egui::Sense::hover()); + let width = ui.available_width().max(columns[2] + longest(|file| &file.bits) + TREE_BITS_GAP); + let height = TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT; + let (area, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); + let mut y = area.top() + TREE_TOP_PADDING; for (((index, set), files), open) in sets.iter().zip(&rows).zip(open) { let header = egui::Rect::from_min_max(egui::pos2(area.left(), y), egui::pos2(area.right(), y + TREE_ROW_HEIGHT)); @@ -1514,6 +1517,19 @@ fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui:: drawn::glyph(ui, egui::pos2(rect.left() + TREE_CHEVRON_X, y), chevron, drawn::CHEVRON_SIZE, look.text); drawn::text_at(ui, rect.left() + TREE_NAME_INDENT, y, name, look.text, true); drawn::paint_focus(ui, &response); + + if response.has_focus() && rect.width() > ui.clip_rect().width() { + let direction = ui.input_mut(|input| { + let start = input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft); + let end = input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowRight); + i8::from(start) - i8::from(end) + }); + if direction != 0 { + ui.memory_mut(|memory| memory.move_focus(egui::FocusDirection::None)); + ui.scroll_with_delta(vec2(f32::from(direction) * ui.clip_rect().width() / 2.0, 0.0)); + } + } + response.clicked() } diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index de7e577b..f264b092 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -154,6 +154,36 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { assert!(!h.state().ui.export.console_hidden); } +#[test] +fn long_filenames_leave_the_export_details_reachable_by_scrolling() { + let (mut h, _) = harness("wide-tree"); + let name = "Wide".repeat(44); + h.state_mut().session.doc.project.texture_sets[0].name.clone_from(&name); + h.state_mut().ui.export.tab = 2; + h.run_steps(4); + let bits_label = "16 bits"; + let bits_fit = |h: &Harness<'_, TextureCraftApp>| { + h.output().shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == bits_label => clipped.clip_rect.contains_rect(text.visual_bounding_rect()), + _ => false, + }) + }; + assert!(!bits_fit(&h), "the bit-depth column starts beyond the viewport"); + h.get_by_role_and_label(egui::Role::Button, &name).focus(); + h.run_steps(3); + assert!(h.get_by_role_and_label(egui::Role::Button, &name).is_focused()); + + for _ in 0..12 { + h.key_press(egui::Key::ArrowRight); + h.run_steps(2); + } + h.run_steps(10); + + assert!(bits_fit(&h), "horizontal keyboard scrolling brings bit depth into the viewport"); + assert!(h.query_all_by_label(bits_label).next().is_some(), "bit depth has an accessibility label"); + assert!(h.query_by_label("Console").is_some()); +} + #[test] fn open_output_directory_asks_the_system_to_show_the_folder() { let (mut h, dir) = harness("open"); From f67270d6ae765ac56ad97f03298e394f7e9d8f7f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:10:02 +0000 Subject: [PATCH 051/190] Export: JPEG 2000 back to greyed; its writer moves to craft-libs The j2k/jp2 writer is a codec, so it goes to craft-image-codecs first (review on #827); the export wires it in again once craft-libs ships it. --- ATTRIBUTION.md | 8 - Cargo.lock | 69 +------ Cargo.toml | 3 - NOTICE | 5 - README.md | 2 +- crates/engine/src/file_cmds.rs | 4 +- crates/engine/tests/it/materialx.rs | 2 +- crates/engine/tests/it/usd_asset.rs | 16 -- crates/formats/Cargo.toml | 2 - crates/formats/README.md | 2 +- crates/formats/src/export/jpeg2000.rs | 67 ------- crates/formats/src/export/linear_gray.icc | Bin 460 -> 0 bytes crates/formats/src/export/map_renderer.rs | 4 +- crates/formats/src/export/mod.rs | 31 +--- crates/formats/src/export/tests.rs | 181 +------------------ crates/formats/src/mesh_export/usd.rs | 4 +- crates/ui-egui/src/export_window.rs | 4 +- crates/ui-egui/tests/it/export_file_types.rs | 23 ++- docs/control-protocol.md | 6 +- docs/features.md | 2 +- 20 files changed, 35 insertions(+), 400 deletions(-) delete mode 100644 crates/formats/src/export/jpeg2000.rs delete mode 100644 crates/formats/src/export/linear_gray.icc diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8ec51fb8..a895078e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -27,7 +27,6 @@ licensed and keep their license file next to them. | `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | -| `crates/formats/src/export/linear_gray.icc` | TextureCraft Linear Gray (D50) | TextureCraft contributors | Original ICC v2.1 monochrome display profile generated with Little CMS 2.14 from D50 and gamma 1.0, with a fixed creation date of 2026-01-01 | MIT OR Apache-2.0 | ## Third-party assets compiled into the binary @@ -54,13 +53,6 @@ time (nothing is bundled); see [docs/localization-parity.md](docs/localization-p | `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 | | `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT | -## JPEG 2000 export dependencies - -| Crate | Use | Upstream | License | -|---|---|---|---| -| `j2k`, `j2k-core`, `j2k-native`, `j2k-types`, `j2k-profile`, `j2k-codec-math` 0.11.3 | JPEG 2000 codestream and JP2 export | [frames-sg contributors](https://github.com/frames-sg/j2k/tree/c708d2fda9f2672472b9e06aa2e66bf1f191dc3d) | MIT OR Apache-2.0 | -| `fearless_simd` 1.3.0 | SIMD support used by `j2k-native` | [Raph Levien and contributors](https://github.com/linebender/fearless_simd/tree/2ac6acdd13efb7689a6e80049a4933516a57ec20) | Apache-2.0 OR MIT | - ## Procedural content (no asset files) Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedurals diff --git a/Cargo.lock b/Cargo.lock index be50cc5f..7da98739 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1832,12 +1832,6 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" -[[package]] -name = "fearless_simd" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599" - [[package]] name = "filetime" version = "0.2.29" @@ -2400,7 +2394,7 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" dependencies = [ - "fearless_simd 0.4.1", + "fearless_simd", ] [[package]] @@ -2766,63 +2760,6 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" -[[package]] -name = "j2k" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5dcb93d62c580930297896f25933b034bf665534568626787dbf0f03027e7b0" -dependencies = [ - "j2k-core", - "j2k-native", - "j2k-types", - "moxcms", - "thiserror 2.0.21", -] - -[[package]] -name = "j2k-codec-math" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a38b1ddbaa04c07213dba6180ed1168f0e96bfa35890542c414d872cea0c7d58" -dependencies = [ - "j2k-types", -] - -[[package]] -name = "j2k-core" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae969eb19e9b3a8d65c4342f9921717be407571cc0fbc44e4379daa0b588d01c" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "j2k-native" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "971da314ca1501363f686b6796d309ebbda7d2f88d34671c38d79132f7cb59ff" -dependencies = [ - "fearless_simd 1.3.0", - "j2k-codec-math", - "j2k-profile", - "j2k-types", - "libm", - "rayon", -] - -[[package]] -name = "j2k-profile" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c1c0cc7e85f2ab1cc85c9a6d2bad3680319c0cdf558f3be14b4ccdbd6917fca" - -[[package]] -name = "j2k-types" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "716edd556741a415294d955121f76d41b7d8d650554fb09f30d0654b15127ac9" - [[package]] name = "jni" version = "0.22.4" @@ -5282,8 +5219,6 @@ dependencies = [ "gltf", "half", "image", - "j2k", - "j2k-core", "png", "rayon", "serde", @@ -5822,7 +5757,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd" dependencies = [ "bytemuck", - "fearless_simd 0.4.1", + "fearless_simd", "guillotiere", "log", "peniko", diff --git a/Cargo.toml b/Cargo.toml index 2f7b4610..656c9522 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,9 +44,6 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } half = "2" exr = { version = "1.73", default-features = false } -# JPEG 2000 writing (craft-image-codecs only reads it); j2k 0.13 needs Rust 1.99 -j2k = "0.11.3" -j2k-core = "0.11.3" eframe = { version = "0.37", default-features = false } egui = "0.37" wgpu = "30" diff --git a/NOTICE b/NOTICE index 2e3666df..25d962ff 100644 --- a/NOTICE +++ b/NOTICE @@ -24,11 +24,6 @@ Native eyedropper components: - x11rb — MIT OR Apache-2.0. Copyright 2019 x11rb contributors. - zbus — MIT. Copyright (c) 2024 Zeeshan Ali Khan and zbus contributors. -JPEG 2000 export components: -- j2k, j2k-core, j2k-native, j2k-types, j2k-profile and j2k-codec-math — MIT OR Apache-2.0. - Copyright (c) 2026 frames-sg contributors. -- fearless_simd — Apache-2.0 OR MIT. Copyright (c) 2018 Raph Levien. - Phosphor Icons (compiled in through the egui-phosphor crate) — MIT. egui default fonts (compiled in through the epaint_default_fonts crate): Ubuntu-Light — Ubuntu Font Licence 1.0; Hack — MIT and Bitstream Vera License; Noto Emoji — SIL Open Font License 1.1; diff --git a/README.md b/README.md index 29b1daea..345c32c1 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.96 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). +You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). **File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none. Japanese, Chinese, Korean and Arabic interface text uses the fonts of diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 9940b372..aa390ad0 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write _shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write _shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -1079,7 +1079,7 @@ fn material_map_options(options: &ExportOptions, project_normal: NormalFormat) - #[cfg(not(target_arch = "wasm32"))] fn material_format(format: FileFormat) -> bool { - !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp | FileFormat::J2k | FileFormat::Jp2) + !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 504ed162..c6ee8dfe 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -187,7 +187,7 @@ fn per_map_overrides_of_the_template_do_not_reach_the_openpbr_maps() { #[test] fn a_file_type_a_material_cannot_use_falls_back_to_png() { let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); - for (format, bit_depth, ext) in [("psd", 16, "psd"), ("pgm", 8, "pgm"), ("jng", 8, "jng"), ("j2k", 8, "j2k"), ("jp2", 8, "jp2"), ("tiff", 16, "tif")] { + for (format, bit_depth, ext) in [("psd", 16, "psd"), ("pgm", 8, "pgm"), ("jng", 8, "jng"), ("tiff", 16, "tif")] { let dir = temp(format); let result = execute( diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index 1abbb0e9..a130f813 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -421,19 +421,3 @@ fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() { assert!(materials[material_of(&s, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&s, 0)]); assert!(r["warnings"].to_string().contains("doesn't read PSD files"), "{r}"); } - -#[test] -fn jpeg2000_maps_export_beside_usd_without_creating_texture_bindings() { - let mut s = ball(); - for format in ["j2k", "jp2"] { - let dir = temp(format); - - let result = export(&mut s, &dir, json!({"ts": 0, "format": format, "usdAsset": true})); - - assert!(files(&result).iter().any(|file| file.ends_with(&format!(".{format}"))), "{result}"); - let materials = read_back(&s, &dir); - - assert!(materials[material_of(&s, 0)].0.is_empty(), "{materials:?}"); - assert!(result["warnings"].to_string().contains(&format!("doesn't read {} files", format.to_uppercase())), "{result}"); - } -} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 43775bb6..dff3f94d 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -31,8 +31,6 @@ flate2 = { workspace = true } half = { workspace = true } zip = { workspace = true } exr = { workspace = true } -j2k = { workspace = true } -j2k-core = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/formats/README.md b/crates/formats/README.md index eb04b8bf..b92e715f 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -106,7 +106,7 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result; collisions get `_2`, `_3`, … plus a warning. - A map is written only when one of its sources has data in the texture set (channel present, map baked, …); alpha from a missing channel is dropped. -- Formats: PNG 8/16, JPEG 8 (q 95), J2K and JP2 8/16 (lossless), JNG 8 (JPEG colour, +- Formats: PNG 8/16, JPEG 8 (q 95), JNG 8 (JPEG colour, deflate alpha), PGM 8/16 (gray; colour becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, WebP 8 (lossless), PSD 8/16, EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. PSD writes one file per texture set or UV tile, with each output map stored as a layer. diff --git a/crates/formats/src/export/jpeg2000.rs b/crates/formats/src/export/jpeg2000.rs deleted file mode 100644 index d2142c25..00000000 --- a/crates/formats/src/export/jpeg2000.rs +++ /dev/null @@ -1,67 +0,0 @@ -//! JPEG 2000, lossless (reversible 5/3 wavelet): a raw codestream (.j2k) or one in a JP2 file (.jp2) - -use j2k::{ - J2kChannelAssociation, J2kChannelDefinition, J2kChannelType, J2kFileBoxMetadata, J2kFileColorSpec, J2kFileWrapOptions, J2kLosslessEncodeOptions, - J2kLosslessSamples, encode_j2k_lossless, wrap_j2k_codestream, -}; -use j2k_core::Colorspace; - -/// Original ICC v2 profile with a D50 white point and gamma 1.0 (ITU-T T.800, I.5.3.3) -pub(super) const LINEAR_GRAY_PROFILE: &[u8] = include_bytes!("linear_gray.icc"); - -/// Encode `bytes` (8-bit or native-endian 16-bit L, LA, RGB or RGBA samples) of a `width`×`height` image; `jp2` wraps it in a JP2 file that records `icc` -pub(super) fn write_jpeg2000( - bytes: Vec, - (width, height): (u32, u32), - component_count: usize, - depth: u8, - jp2: bool, - icc: Option<&[u8]>, -) -> Result, String> { - // Only big-endian hosts need to reverse the native 16-bit samples - #[cfg(target_endian = "big")] - let bytes = { - let mut bytes = bytes; - if depth == 16 { - for sample in bytes.as_chunks_mut::<2>().0 { - sample.swap(0, 1); - } - } - bytes - }; - - let components = u16::try_from(component_count).map_err(|_| format!("{component_count} components"))?; - let input = J2kLosslessSamples { data: &bytes, width, height, components, bit_depth: depth, signed: false }; - let codestream = encode_j2k_lossless(input, &J2kLosslessEncodeOptions::default()).map_err(|error| error.to_string())?.codestream; - drop(bytes); - if !jp2 { - return Ok(codestream); - } - - // The last component of LA and RGBA is opacity, for the whole image - let color_count = if component_count >= 3 { 3 } else { 1 }; - let definitions: Vec = (0..components) - .map(|channel_index| { - if channel_index < color_count { - J2kChannelDefinition { - channel_index, - channel_type: J2kChannelType::Color, - association: J2kChannelAssociation::Color { index: channel_index + 1 }, - } - } else { - J2kChannelDefinition { channel_index, channel_type: J2kChannelType::Opacity, association: J2kChannelAssociation::WholeImage } - } - }) - .collect(); - let mut options = J2kFileWrapOptions::jp2(); - options.color = match icc { - Some(profile) => J2kFileColorSpec::IccProfile(profile), - None if color_count == 3 => J2kFileColorSpec::Enumerated(Colorspace::SRgb), - None => J2kFileColorSpec::Enumerated(Colorspace::Grayscale), - }; - if component_count.is_multiple_of(2) { - options.metadata = J2kFileBoxMetadata { palette: None, component_mappings: &[], channel_definitions: &definitions }; - } - - wrap_j2k_codestream(&codestream, options).map_err(|error| error.to_string()) -} diff --git a/crates/formats/src/export/linear_gray.icc b/crates/formats/src/export/linear_gray.icc deleted file mode 100644 index 1b338b34097128d0de61b17293e7031fc2859e4f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 460 zcmZQzU_6tPoLkH!z`&53S5o92_s-M{+??2?GOT4v=kCUQz&JuK=<|vO|KLf$Tj%HXl?ykjWq) zl3GzxT9oQsl$chc;FFn`npmXZUX)m=py6U_pb1g}0`d$Y45 MapRenderer<'a> { } let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); - // Raw J2K reports the missing tag even for a grayscale colour map - let embed = (options.color_space.is_some() && map.is_color() && (component_count >= 3 || format == FileFormat::J2k)).then_some(space); + // A colour space the user chose is written into the colour maps (data maps have none) + let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space); Ok(RenderedMap { data, size, component_count, srgb, embed }) } } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 7e0afcb3..03de7767 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -26,7 +26,6 @@ use texturecraft_texel::{ColorSpace, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; mod encoding; -mod jpeg2000; mod layered_psd; mod map_override; mod map_preview; @@ -106,19 +105,15 @@ pub enum FileFormat { Pgm, /// Photoshop document: every output map of a texture set in this format as a layer of one file Psd, - /// JPEG 2000 codestream, lossless - J2k, - /// JPEG 2000 in a JP2 file, lossless - Jp2, } impl FileFormat { /// Whether the texture can be referenced by the USD asset exporter. pub fn usable_by_usd_asset(self) -> bool { - !matches!(self, Self::Psd | Self::J2k | Self::Jp2) + self != Self::Psd } - pub const ALL: [FileFormat; 13] = [ + pub const ALL: [FileFormat; 11] = [ FileFormat::Png, FileFormat::Jpeg, FileFormat::Tga, @@ -130,8 +125,6 @@ impl FileFormat { FileFormat::Jng, FileFormat::Pgm, FileFormat::Psd, - FileFormat::J2k, - FileFormat::Jp2, ]; pub fn extension(self) -> &'static str { @@ -147,8 +140,6 @@ impl FileFormat { FileFormat::Jng => "jng", FileFormat::Pgm => "pgm", FileFormat::Psd => "psd", - FileFormat::J2k => "j2k", - FileFormat::Jp2 => "jp2", } } @@ -176,7 +167,7 @@ impl FileFormat { /// float for TIFF and HDR). pub fn bit_depths(self) -> &'static [u8] { match self { - FileFormat::Png | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2 => &[8, 16], + FileFormat::Png | FileFormat::Pgm | FileFormat::Psd => &[8, 16], FileFormat::Tiff => &[8, 16, 32], FileFormat::Exr => &[16, 32], FileFormat::Hdr => &[32], @@ -1402,7 +1393,7 @@ fn encode( // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed - && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::J2k) + && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng) { warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name())); } @@ -1504,20 +1495,6 @@ fn encode( FileFormat::Webp => CodecFormat::WebP, FileFormat::Pgm => CodecFormat::Pnm, FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)), - FileFormat::J2k | FileFormat::Jp2 => { - let jp2 = format == FileFormat::Jp2; - let gray = component_count <= 2; - let profile = if jp2 && !gray { - let linear_rgb = srgb.iter().take(3).all(|encoded| !encoded); - embed.or(linear_rgb.then_some(ColorSpace::LinearRec709)).and_then(crate::icc::profile) - } else { - None - }; - let linear_gray = jp2 && gray && !srgb.first().copied().unwrap_or(false); - let icc = profile.as_deref().or(linear_gray.then_some(jpeg2000::LINEAR_GRAY_PROFILE)); - - return jpeg2000::write_jpeg2000(bytes, size, component_count, depth, jp2, icc).map_err(|error| encoding_error(&error)); - } FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")), FileFormat::Psd => return Err(encoding_error(&"a PSD holds the layers of several maps (`layered_psd`)")), }; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index a7e6fcb0..355b0ec9 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -366,9 +366,8 @@ fn every_format_encodes_and_decodes() { let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); preset.maps.push(gray_alpha); - // JNG, PGM, PSD and JPEG 2000 have tests of their own (the image crate reads none of them) - let own_tests = |format: &FileFormat| matches!(format, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2); - for format in FileFormat::ALL.into_iter().filter(|format| !own_tests(format)) { + // JNG, PGM and PSD have tests of their own (the image crate reads none of them) + for format in FileFormat::ALL.into_iter().filter(|f| !matches!(f, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd)) { for &depth in format.bit_depths() { let mut opts = ExportOptions::new(preset.clone()); opts.format_override = Some(format); @@ -948,7 +947,7 @@ fn exr_carries_the_chromaticities_of_the_space() { #[test] fn formats_without_a_place_for_a_colour_space_say_so() { let data = vec![0.25f32; 4 * 4 * 3]; - for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr, FileFormat::J2k] { + for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr] { let mut warnings = Vec::new(); encode(Encoding { format, depth: 8, dither: false }, (4, 4), 3, data.clone(), &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap(); assert!(warnings.iter().any(|w| w.contains("colour space") && w.contains("ACEScg")), "{format:?}: {warnings:?}"); @@ -1456,154 +1455,6 @@ fn jng_has_jpeg_colour_and_lossless_alpha() { assert!(!gray.bytes.windows(4).any(|w| w == b"IDAT")); } -/// A JPEG 2000 file's component planes -fn jpeg2000_planes(bytes: &[u8]) -> Vec> { - let mut decoder = j2k::J2kDecoder::new(bytes).unwrap(); - let decoded = decoder.decode_native_components().unwrap(); - decoded - .planes() - .iter() - .map(|plane| match plane.bytes_per_sample() { - 1 => plane.data().iter().map(|byte| u16::from(*byte)).collect(), - _ => plane.data().chunks(2).map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect(), - }) - .collect() -} - -#[test] -fn jpeg2000_is_lossless_at_8_and_16_bits() { - let fx = Fx::new(&[Channel::BaseColor, Channel::Opacity, Channel::Roughness, Channel::Metallic, Channel::Normal]); - let preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); - let jp2_signature = [0, 0, 0, 12, b'j', b'P', b' ', b' ']; - let codestream_signature = [0xFF, 0x4F, 0xFF, 0x51]; - for depth in [8u8, 16] { - let mut png_options = ExportOptions::new(preset.clone()); - png_options.bit_depth_override = Some(depth); - let png = fx.render(&png_options); - for format in [FileFormat::J2k, FileFormat::Jp2] { - let mut options = png_options.clone(); - options.format_override = Some(format); - let files = fx.render(&options); - - assert_eq!(files.len(), png.len()); - - for (file, reference) in files.iter().zip(&png) { - assert!(file.name.ends_with(format.extension()), "{}", file.name); - let signature: &[u8] = if format == FileFormat::Jp2 { &jp2_signature } else { &codestream_signature }; - - assert!(file.bytes.starts_with(signature), "{}", file.name); - - // Every sample is the PNG's, with alpha the last component - let image = decode(reference); - let components = usize::from(image.color().channel_count()); - let expected = image.to_rgba16(); - let planes = jpeg2000_planes(&file.bytes); - let info = j2k::J2kDecoder::inspect_support(&file.bytes).unwrap(); - - assert_eq!(info.components.len(), components, "{}", file.name); - for (component, declared) in info.components.iter().enumerate() { - assert_eq!(declared.bit_depth, depth, "{} component {component} precision", file.name); - } - assert_eq!(planes.len(), components, "{}", file.name); - for (component, plane) in planes.iter().enumerate() { - assert_eq!(plane.len(), expected.pixels().len(), "{} component {component}", file.name); - let source = if components <= 2 && component == 1 { 3 } else { component }; - for (texel, sample) in expected.pixels().zip(plane) { - let want = if depth == 8 { texel[source] / 257 } else { texel[source] }; - - assert_eq!(*sample, want, "{} component {component}", file.name); - } - } - } - } - } -} - -#[test] -fn jp2_declares_linear_storage_for_rgb_data_maps() { - let fx = Fx::new(&default_channels()); - let mut options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); - options.format_override = Some(FileFormat::Jp2); - let linear = crate::icc::profile(ColorSpace::LinearRec709).unwrap(); - - let files = fx.render(&options); - let has_linear_profile = |file: &ExportedFile| file.bytes.windows(linear.len()).any(|bytes| bytes == linear); - - assert!(has_linear_profile(find(&files, "_OcclusionRoughnessMetallic"))); - assert!(has_linear_profile(find(&files, "_Normal"))); - assert!(!has_linear_profile(find(&files, "_BaseColor"))); -} - -#[test] -fn feedback_jp2_grayscale_declares_the_transfer_applied_to_samples() { - use j2k::{J2kChannelAssociation, J2kChannelType, J2kColorSpec}; - - let fx = Fx::new(&default_channels()); - for format in [FileFormat::J2k, FileFormat::Jp2] { - for depth in [8, 16] { - for alpha in [false, true] { - for linear in [true, false] { - let channel = if linear { Channel::Roughness } else { Channel::BaseColor }; - let mut channels = vec![(Dest::L, SourceRef::Channel { channel, component: 0 })]; - if alpha { - channels.push((Dest::A, SourceRef::Constant(0.5))); - } - - let options = one_map(format, depth, channels); - let reference = fx.render(&ExportOptions { format_override: Some(FileFormat::Png), ..options.clone() }); - let samples = decode(&reference[0]).to_rgba16(); - let exported = fx.render(&options); - let planes = jpeg2000_planes(&exported[0].bytes); - - assert_eq!(planes.len(), 1 + usize::from(alpha)); - for (plane, component) in planes.iter().zip([0, 3]) { - let expected: Vec<_> = samples.pixels().map(|pixel| if depth == 8 { pixel[component] / 257 } else { pixel[component] }).collect(); - assert_eq!(plane, &expected); - } - - let info = j2k::J2kDecoder::inspect_support(&exported[0].bytes).unwrap(); - let metadata = info.file_metadata; - if format == FileFormat::J2k { - assert!(metadata.is_none()); - continue; - } - - let metadata = metadata.unwrap(); - match (&metadata.color_specs[..], linear) { - ([J2kColorSpec::IccProfile { profile }], true) => { - assert_eq!(&profile[16..24], b"GRAYXYZ "); - let word = |at| u32::from_be_bytes(profile[at..at + 4].try_into().unwrap()) as usize; - let curve_tag = (132..132 + 12 * word(128)).step_by(12).find(|&at| &profile[at..at + 4] == b"kTRC").unwrap(); - let curve = word(curve_tag + 4); - assert_eq!(&profile[curve..curve + 4], b"curv"); - assert_eq!(word(curve + 8), 1); - assert_eq!(&profile[curve + 12..curve + 14], &0x0100u16.to_be_bytes(), "gamma 1.0"); - } - ([J2kColorSpec::Enumerated { value: 17 }], false) => {} - (spec, _) => panic!("wrong grayscale colour declaration for linear={linear}: {spec:?}"), - } - if alpha { - assert!(metadata.channel_definitions.iter().any(|definition| definition.channel_index == 1 - && definition.channel_type == J2kChannelType::Opacity - && definition.association == J2kChannelAssociation::WholeImage)); - } - } - } - } - } -} - -#[test] -fn jp2_records_a_chosen_colour_space_as_an_icc_profile() { - let data = vec![0.25f32; 8 * 8 * 3]; - let profile = crate::icc::profile(ColorSpace::AcesCg).unwrap(); - let mut warnings = Vec::new(); - let bytes = - encode(Encoding { format: FileFormat::Jp2, depth: 8, dither: false }, (8, 8), 3, data, &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap(); - assert!(bytes.windows(profile.len()).any(|window| window == profile.as_slice()), "the profile is in the file"); - assert!(warnings.is_empty(), "{warnings:?}"); -} - #[test] fn tiff_32f_holds_linear_floats() { let fx = Fx::new(&default_channels()); @@ -2382,29 +2233,3 @@ fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { assert!(list_set_outputs(&fx.project, &[1], "sphere", &options).is_ok()); assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_err(), "the budget includes all selected sets"); } - -#[test] -fn feedback_j2k_warns_for_explicit_gray_and_rgb_colour_spaces() { - let fx = Fx::new(&default_channels()); - let base = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; - let gray = vec![(Dest::L, base(0))]; - let rgb = vec![(Dest::R, base(0)), (Dest::G, base(1)), (Dest::B, base(2))]; - - for (channels, selected, expected) in [ - (gray.clone(), Some(ColorSpace::LinearRec709), Some(ColorSpace::LinearRec709)), - (gray, Some(ColorSpace::AcesCg), Some(ColorSpace::LinearRec709)), - (rgb, Some(ColorSpace::Srgb), Some(ColorSpace::Srgb)), - (roughness(), None, None), - ] { - let mut options = one_map(FileFormat::J2k, 8, channels); - options.color_space = selected; - - let files = fx.render(&options); - let warnings: Vec<_> = files[0].warnings.iter().filter(|warning| warning.contains("J2K export does not embed")).collect(); - - assert_eq!(warnings.len(), usize::from(expected.is_some()), "warnings: {:?}", files[0].warnings); - if let Some(space) = expected { - assert!(warnings[0].ends_with(space.name())); - } - } -} diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 2a03b8f1..1ccbdb67 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -386,12 +386,12 @@ fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: /// opacity, clear coat and clear coat roughness. Maps with none of them (ambient occlusion, /// height, specular/glossiness, baked maps...) bind nothing, and neither do channels the set has /// no data for. `project_normal` is the project's normal convention, used by normal maps that -/// follow it. Layered PSD files and JPEG 2000 files are omitted. +/// follow it. Layered PSD files are omitted. pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec { let mut out: Vec = Vec::new(); let mut seen_maps = Vec::new(); for file in files { - // PSD stores several maps and OpenUSD's default reader has no JPEG 2000 support + // PSD stores several maps in one file if !file.format.usable_by_usd_asset() { continue; } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 9cc30594..6772698d 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -229,8 +229,8 @@ pub(crate) const FILE_TYPES: [(&str, Option); 14] = [ ("tiff", Some(FileFormat::Tiff)), ("hdr", Some(FileFormat::Hdr)), ("exr", Some(FileFormat::Exr)), - ("j2k", Some(FileFormat::J2k)), - ("jp2", Some(FileFormat::Jp2)), + ("j2k", None), + ("jp2", None), ("webp", Some(FileFormat::Webp)), ("psd", Some(FileFormat::Psd)), ("sbsar", None), diff --git a/crates/ui-egui/tests/it/export_file_types.rs b/crates/ui-egui/tests/it/export_file_types.rs index 682f3625..8967fe80 100644 --- a/crates/ui-egui/tests/it/export_file_types.rs +++ b/crates/ui-egui/tests/it/export_file_types.rs @@ -46,23 +46,22 @@ fn entries(h: &Harness<'_, TextureCraftApp>, labels: &[&str]) -> Vec { const TYPES: [&str; 14] = ["bmp", "jpeg", "jng", "pgm", "png", "targa", "tiff", "hdr", "exr", "j2k", "jp2", "webp", "psd", "sbsar"]; #[test] -fn the_file_type_list_is_the_reference_one_with_sbsar_greyed() { +fn the_file_type_list_is_the_reference_one_with_three_greyed() { let mut h = harness(); open_combo(&mut h, "Based on output template"); - assert_eq!(entries(&h, &TYPES), TYPES.map(String::from).to_vec()); - assert!(h.get_all_by_label("sbsar").last().unwrap().accesskit_node().is_disabled(), "sbsar is greyed"); - h.get_all_by_label("sbsar").last().unwrap().scroll_to_me(); - h.run_steps(6); - let at = h.get_all_by_label("sbsar").last().unwrap().rect().center(); - h.hover_at(at); - h.run_steps(30); - - assert!(h.query_by_label("Not available yet").is_some(), "sbsar at {at:?}"); - for name in ["j2k", "jp2", "psd"] { - assert!(!h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} can be picked"); + // Bottom up, so no tooltip covers the next entry + for name in ["sbsar", "jp2", "j2k"] { + assert!(h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} is greyed"); + h.get_all_by_label(name).last().unwrap().scroll_to_me(); + h.run_steps(6); + let at = h.get_all_by_label(name).last().unwrap().rect().center(); + h.hover_at(at); + h.run_steps(30); + assert!(h.query_by_label("Not available yet").is_some(), "{name} at {at:?}"); } + assert!(!h.get_all_by_label("psd").last().unwrap().accesskit_node().is_disabled()); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index faaf80c0..07f933bd 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -80,7 +80,7 @@ and names it in `warnings`. Materials omit any map with incomplete tiles or a UD shared by different sets. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, -`hdr`, `exr`, `j2k`, `jp2`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for +`hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and `export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `export.preview` takes the same parameters plus `map` (an index into the template's maps) and @@ -93,8 +93,8 @@ channel defaults. `padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. -Layered PSD and JPEG 2000 maps are written as requested. MaterialX uses compatible companion -maps for these formats. USD omits their texture bindings and returns a warning. +Layered PSD maps are written as requested. MaterialX uses compatible companion maps for this +format. USD omits their texture bindings and returns a warning. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus diff --git a/docs/features.md b/docs/features.md index edc6c265..a7e2f0b9 100644 --- a/docs/features.md +++ b/docs/features.md @@ -164,7 +164,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, Sketchfab (metalness), separate maps, mesh maps and document channels, in - PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 + PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. - **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion, From 5032edca95685d46b4d7bede889432937f21d8c0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:48:11 +0000 Subject: [PATCH 052/190] Export: PSD memory budgets only in the browser; a desktop PSD renders a layer at a time An 8192 PSD of one map and a 4096 "Separate maps" PSD were refused on desktop by the 2 GiB working budget and the 1 GiB batch budget, which main never had (review on #827). Both budgets are now a browser tab's only (PsdBudget::WEB on wasm32); the 30000 px side and 2 GiB file limits stay everywhere. The merged image is no longer a floating-point canvas: it is built a row at a time from the quantized layers, so only the layer being rendered is in floating point. Peak working bytes by the code's own accounting (default infinite padding): - 8192, one map, 8-bit: 2.75 GiB (2 GiB source and layer, 512 MiB file, 256 MiB padding); before, 3.75 GiB with the 1 GiB float canvas - 4096, "Separate maps" on the default 5-channel set: 2.31 GiB at its 16-bit document depth, 1.19 GiB in 8-bit (the encoder's 3x file bytes dominate) A PSD that cannot be planned no longer stops the set's other files: list_outputs leaves it out with a warning on the set's first file, and is an error only when the PSD was the set's only output. --- crates/formats/src/export/layered_psd.rs | 97 +++++++++++++++++++----- crates/formats/src/export/mod.rs | 59 ++++++++++---- crates/formats/src/export/psd_budget.rs | 17 +++++ crates/formats/src/export/tests.rs | 71 +++++++++++++---- 4 files changed, 195 insertions(+), 49 deletions(-) create mode 100644 crates/formats/src/export/psd_budget.rs diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index f8982036..951a18ef 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -15,17 +15,34 @@ use crate::{FormatError, Result}; /// Where alpha sits in an RGBA texel const ALPHA_INDEX: usize = 3; -/// Budget for the pixel buffers of one PSD export, including the renderer's padding and encoder -const MAX_PSD_WORKING_BYTES: u64 = 2 * 1024 * 1024 * 1024; - -/// Check file and working memory limits, returning the canvas size and estimated encoded bytes. +/// Check the file limits and the working memory against `working_limit` (None: unlimited), returning the canvas size and estimated encoded bytes pub(super) fn preflight<'a>( set: &TextureSet, options: &ExportOptions, tile: Option, depth: u8, layers: impl Iterator + Clone, + working_limit: Option, ) -> Result<((u32, u32), u64)> { + let (canvas, file_bytes, working_bytes) = working_set(set, options, tile, depth, layers)?; + if working_limit.is_some_and(|limit| working_bytes >= limit) { + let (width, height) = canvas; + return Err(FormatError::Invalid(format!( + "a PSD at {width}×{height} would exceed the working memory budget; use a smaller export size, fewer PSD maps or another format" + ))); + } + + Ok((canvas, file_bytes)) +} + +/// The canvas size, estimated encoded bytes and peak working bytes of one PSD, after checking the file limits +fn working_set<'a>( + set: &TextureSet, + options: &ExportOptions, + tile: Option, + depth: u8, + layers: impl Iterator + Clone, +) -> Result<((u32, u32), u64, u64)> { let texels = |(width, height)| u64::from(width) * u64::from(height); let folder_count = layers.clone().map(|layer| layer.name.matches('/').count()).sum(); let sizes = layers.map(|layer| psd_size(set, tile, options.map_size(layer.map))); @@ -33,7 +50,9 @@ pub(super) fn preflight<'a>( let float_bytes_per_texel = (PSD_RGBA_PLANES * size_of::()) as u64; let source_bytes = texels(psd_size(set, tile, None)).saturating_mul(float_bytes_per_texel); let largest_layer_bytes = sizes.map(texels).max().unwrap_or(0) * float_bytes_per_texel; - let composite_bytes = texels(canvas) * float_bytes_per_texel; + + // The merged image is built a row at a time: a canvas row and a layer row in floating point + let merge_bytes = 2 * u64::from(canvas.0) * float_bytes_per_texel; // Resizing overlaps source and destination, and RGBA conversion can overlap two output buffers let mut scratch_bytes = source_bytes.saturating_add(largest_layer_bytes).max(2 * largest_layer_bytes); @@ -52,34 +71,24 @@ pub(super) fn preflight<'a>( padding_peak = padding_bytes.saturating_add(atlas_texels.saturating_mul((4 * size_of::()) as u64)); } - // The encoder can hold staged pixels, planes and the output at once - let rendering = scratch_bytes.saturating_add(composite_bytes).saturating_add(file_bytes); + // The quantized layers kept so far and the merged image are part of the file; the encoder can hold staged pixels, planes and the output at once + let rendering = scratch_bytes.max(merge_bytes).saturating_add(file_bytes); let encoding = 3 * file_bytes; let working_bytes = padding_bytes.saturating_add(rendering.max(encoding)).max(padding_peak); - if working_bytes >= MAX_PSD_WORKING_BYTES { - let (width, height) = canvas; - return Err(FormatError::Invalid(format!( - "a PSD at {width}×{height} would exceed the working memory budget; use a smaller export size, fewer PSD maps or another format" - ))); - } - - Ok((canvas, file_bytes)) + Ok((canvas, file_bytes, working_bytes)) } /// Render each layer at its requested size, aligned to the upper-left corner of the PSD canvas. pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u32, u32)) -> Result { let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned; - // Keep only the current layer in floating point alongside the merged image - let mut composite = vec![0.0f32; size.0 as usize * size.1 as usize * PSD_RGBA_PLANES]; + // Only the current layer is in floating point; the others are kept as the file stores them let mut pixels = Vec::with_capacity(layers.len()); let mut embedded = None; for layer in layers.iter().rev() { let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; embedded = map.embed.or(embedded); let rgba = to_rgba(map.data, map.component_count, &map.srgb); - over(&mut composite, size.0, &rgba, map.size.0); - let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; let layer_pixels = pixel_data(rgba, map.size.0, encoding)?; pixels.push((layer.name.as_str(), map.size, layer_pixels)); @@ -88,8 +97,7 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u3 warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name())); } - let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: false }; - let composite = pixel_data(composite, size.0, encoding)?; + let composite = merged_image(size, bit_depth, &pixels)?; let bytes = write_layers(size, bit_depth, pixels, composite).map_err(|error| FormatError::Invalid(format!("psd encoding failed: {error}")))?; if bytes.len() as u64 >= PSD_MAX_FILE_BYTES { @@ -129,6 +137,53 @@ fn to_rgba(mut data: Vec, component_count: usize, srgb: &[bool]) -> Vec Result { + let row_len = width as usize * PSD_RGBA_PLANES; + let sample_count = row_len * height as usize; + let mut merged_row = vec![0.0f32; row_len]; + let mut layer_row = Vec::with_capacity(row_len); + let reserve_error = |error| FormatError::Invalid(format!("PSD merged image allocation failed: {error}")); + if depth == 16 { + let mut merged = Vec::new(); + merged.try_reserve_exact(sample_count).map_err(reserve_error)?; + for y in 0..height as usize { + merge_row(y, width, layers, &mut merged_row, &mut layer_row); + merged.extend(merged_row.iter().map(|&value| quantize_u16(value))); + } + return Ok(PixelData::Rgba16(merged)); + } + + let mut merged = Vec::new(); + merged.try_reserve_exact(sample_count).map_err(reserve_error)?; + let encoding = Encoding { format: FileFormat::Psd, depth, dither: false }; + for y in 0..height as usize { + merge_row(y, width, layers, &mut merged_row, &mut layer_row); + merged.extend(quantize_integer(encoding, width, PSD_RGBA_PLANES, merged_row.iter().copied())?); + } + Ok(PixelData::Rgba8(merged)) +} + +/// Row `y` of the merged image into `merged_row`, each layer's row decoded into `layer_row` in turn +fn merge_row(y: usize, width: u32, layers: &[(&str, (u32, u32), PixelData)], merged_row: &mut [f32], layer_row: &mut Vec) { + merged_row.fill(0.0); + for (_, (layer_width, layer_height), samples) in layers { + if y >= *layer_height as usize { + continue; + } + + let span = *layer_width as usize * PSD_RGBA_PLANES; + let range = y * span..(y + 1) * span; + layer_row.clear(); + match samples { + PixelData::Rgba8(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u8::MAX))), + PixelData::Rgba16(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u16::MAX))), + _ => continue, + } + over(merged_row, width, layer_row, *layer_width); + } +} + /// Composite a straight-alpha RGBA layer at the top left of the canvas. fn over(canvas: &mut [f32], canvas_width: u32, layer: &[f32], layer_width: u32) { let canvas_rows = canvas.chunks_exact_mut(canvas_width as usize * PSD_RGBA_PLANES); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 03de7767..e7eafd58 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -31,12 +31,14 @@ mod map_override; mod map_preview; mod map_renderer; mod planned_layer; +mod psd_budget; mod rendered_map; use encoding::Encoding; pub use map_override::MapOverride; pub use map_preview::{MAX_PREVIEW_SIDE, MapPreview}; use map_renderer::MapRenderer; pub use planned_layer::PlannedLayer; +use psd_budget::PsdBudget; /// Height-to-normal slope: with strength 1, a height change of 1 across 1/16 of the texture /// width tilts the normal 45°, at any resolution. @@ -44,8 +46,6 @@ const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; -/// Bound retained PSD payloads before rendering, with headroom for a document's working buffers and ZIP packaging -const MAX_PSD_BATCH_BYTES: u64 = 1024 * 1024 * 1024; /// Planes of a PSD image or layer: red, green, blue and alpha const PSD_RGBA_PLANES: usize = 4; /// Preset limits (user presets are untrusted JSON). @@ -716,6 +716,11 @@ pub fn sanitize_file_path(s: &str) -> String { /// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { + plan_outputs(project, ts, mesh_name, opts, PsdBudget::TARGET) +} + +/// [`list_outputs`] with the PSD memory limits of `budget` +fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions, budget: PsdBudget) -> Result> { opts.preset.validate()?; let set = project.texture_set(ts)?; for requested_size in opts.size.iter().chain(opts.maps.values().filter_map(|own| own.size.as_ref())) { @@ -832,13 +837,12 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let mut tiled_bases = HashMap::new(); // Each tile's PSD maps are the layers of one file named after the texture set + let mut psd_failures = Vec::new(); for (&tile, in_tile) in tiles.iter().zip(psd_layers) { let Some((first_layer, ..)) = in_tile.first() else { continue }; let first_map = first_layer.map; let bit_depth = in_tile.iter().map(|(_, depth, _)| *depth).max().unwrap_or(8); - layered_psd::preflight(set, opts, tile, bit_depth, in_tile.iter().map(|(layer, ..)| layer))?; - let mut warnings = Vec::new(); let mut layers = Vec::with_capacity(in_tile.len()); let mut dither_requested = false; @@ -866,11 +870,26 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) }; let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); + if let Err(error) = layered_psd::preflight(set, opts, tile, bit_depth, layers.iter(), budget.working_bytes) { + psd_failures.push((name, error)); + continue; + } + claim_path(&mut active_files, &mut active_dirs, &name)?; let udim_name = udim_stem.map(|stem| format!("{stem}{renamed}.{ext}")); let dither = bit_depth == 8 && dither_requested; out.push(PlannedFile { name, map: first_map, format: FileFormat::Psd, bit_depth, dither, tile, udim_name, warnings, layers }); } + + // A PSD that cannot be written leaves the set's other files to export, its reason a warning on the first of them + for (name, error) in psd_failures { + let Some(first) = out.first_mut() else { return Err(error) }; + let reason = match error { + FormatError::Invalid(reason) | FormatError::TooLarge(reason) => reason, + other => other.to_string(), + }; + first.warnings.push(format!("\"{name}\" was not written: {reason}")); + } Ok(out) } @@ -933,16 +952,21 @@ fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u /// Plan a selection in export order, keeping only the first case-insensitive use of a name. pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { + plan_set_outputs(project, sets, mesh_name, opts, PsdBudget::TARGET) +} + +/// [`list_set_outputs`] with the PSD memory limits of `budget` +fn plan_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions, budget: PsdBudget) -> Result> { let mut files = Vec::new(); for &index in sets { - let planned = list_outputs(project, index, mesh_name, opts)?; + let planned = plan_outputs(project, index, mesh_name, opts, budget)?; files.extend(planned.into_iter().map(|file| (index, file))); } let files = keep_first_planned_names(files); let mut psd_bytes = 0; for (index, file) in files.iter().filter(|(_, file)| file.format == FileFormat::Psd) { - check_psd_batch(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes)?; + check_psd_batch_within(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes, budget)?; } Ok(files) @@ -1118,21 +1142,25 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result Result<()> { + check_psd_batch_within(set, options, planned, total_bytes, PsdBudget::TARGET) +} + +fn check_psd_batch_within(set: &TextureSet, options: &ExportOptions, planned: &[PlannedFile], total_bytes: &mut u64, budget: PsdBudget) -> Result<()> { let mut estimate = *total_bytes; for file in planned.iter().filter(|file| file.format == FileFormat::Psd) { - let (_, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())?; - add_psd_batch_bytes(&mut estimate, file_bytes)?; + let (_, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter(), budget.working_bytes)?; + add_psd_batch_bytes(&mut estimate, file_bytes, budget.batch_bytes)?; } *total_bytes = estimate; Ok(()) } -fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64) -> Result<()> { +fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64, limit: Option) -> Result<()> { let estimate = total_bytes.saturating_add(file_bytes); - if estimate > MAX_PSD_BATCH_BYTES { + if limit.is_some_and(|limit| estimate > limit) { return Err(FormatError::TooLarge("total PSD output would exceed 1 GiB; use a smaller export size, fewer PSD maps or separate exports".into())); } @@ -1142,6 +1170,11 @@ fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64) -> Result<()> { /// Render the retained plans from `list_outputs` for this input and these options. pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned: Vec) -> Result> { + render_planned_maps_within(input, options, planned, PsdBudget::TARGET) +} + +/// [`render_planned_maps`] with the PSD memory limits of `budget` +fn render_planned_maps_within(input: &ExportInput, options: &ExportOptions, planned: Vec, budget: PsdBudget) -> Result> { if planned.is_empty() { return Ok(Vec::new()); } @@ -1161,8 +1194,8 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned let mut psd_bytes = 0; for file in &planned { if file.format == FileFormat::Psd { - let (size, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())?; - add_psd_batch_bytes(&mut psd_bytes, file_bytes)?; + let (size, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter(), budget.working_bytes)?; + add_psd_batch_bytes(&mut psd_bytes, file_bytes, budget.batch_bytes)?; psd_sizes.push(Some(size)); } else { psd_sizes.push(None); diff --git a/crates/formats/src/export/psd_budget.rs b/crates/formats/src/export/psd_budget.rs new file mode 100644 index 00000000..e6300254 --- /dev/null +++ b/crates/formats/src/export/psd_budget.rs @@ -0,0 +1,17 @@ +/// The memory limits PSD planning holds an export to: a browser tab's address space needs them, a native export renders one layer at a time without them +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct PsdBudget { + /// Pixel buffers of one document, including the renderer's padding and encoder + pub(super) working_bytes: Option, + /// Encoded documents one batch holds in memory, with headroom for a document's working buffers and ZIP packaging + pub(super) batch_bytes: Option, +} + +impl PsdBudget { + /// A browser tab's: the export and the app share its 4 GiB address space + pub(super) const WEB: Self = Self { working_bytes: Some(2 * 1024 * 1024 * 1024), batch_bytes: Some(1024 * 1024 * 1024) }; + /// A desktop export's: the machine bounds it, as it does every other file type + pub(super) const NATIVE: Self = Self { working_bytes: None, batch_bytes: None }; + /// The budget of the platform this build runs on + pub(super) const TARGET: Self = if cfg!(target_arch = "wasm32") { Self::WEB } else { Self::NATIVE }; +} diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 355b0ec9..f6035d35 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1350,11 +1350,45 @@ fn feedback_psd_rejects_large_working_set_during_planning() { let mut options = one_map(FileFormat::Psd, 8, rgba_half_alpha()); options.size = Some(8192); - let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); + let error = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err(); assert!(error.to_string().contains("working memory"), "{error}"); options.size = Some(4096); - assert!(list_outputs(&fx.project, 0, "sphere", &options).is_ok()); + assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).is_ok()); +} + +#[test] +fn a_native_export_plans_psds_a_browser_tab_cannot_hold() { + let mut fx = Fx::new(&default_channels()); + let mut one = one_map(FileFormat::Psd, 8, rgba_half_alpha()); + one.size = Some(MAX_IMAGE_SIZE / 2); + let mut separate = ExportOptions::new(builtin_preset("Separate maps").unwrap()); + separate.format_override = Some(FileFormat::Psd); + separate.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1005).collect(); + + let plans = [list_outputs(&fx.project, 0, "sphere", &one), list_outputs(&fx.project, 0, "sphere", &separate)]; + + for plan in plans { + let plan = plan.unwrap(); + assert!(!plan.is_empty() && plan.iter().all(|file| file.format == FileFormat::Psd), "{plan:?}"); + } + assert!(list_set_outputs(&fx.project, &[0], "sphere", &separate).is_ok(), "a desktop batch holds every tile's PSD"); +} + +#[test] +fn a_psd_that_cannot_be_planned_leaves_the_sets_other_maps() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Png, 8, roughness()); + let mut psd = options.preset.maps[0].clone(); + (psd.file, psd.format, psd.bit_depth, psd.channels) = ("layered".into(), FileFormat::Psd, 16, rgba_half_alpha()); + options.preset.maps.push(psd); + options.size = Some(MAX_IMAGE_SIZE); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert!(plan.len() == 1 && plan[0].format == FileFormat::Png, "{plan:?}"); + assert!(plan[0].warnings.iter().any(|warning| warning.contains(".psd") && warning.contains("2 GiB")), "{:?}", plan[0].warnings); } #[test] @@ -1397,7 +1431,7 @@ fn psd_byte_limit_includes_the_merged_image_and_keeps_separate_tiles_valid() { assert!(error.to_string().contains("2 GiB"), "{error}"); options.size = Some(4096); - assert!(list_outputs(&fx.project, 0, "sphere", &options).unwrap_err().to_string().contains("working memory")); + assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err().to_string().contains("working memory")); options.atlas = false; assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 3); } @@ -2184,18 +2218,19 @@ fn psd_batch_budget_counts_only_retained_documents() { other.name = "Other".into(); fx.project.texture_sets.push(other); - let once = list_set_outputs(&fx.project, &[0], "sphere", &options).unwrap(); - let repeated = list_set_outputs(&fx.project, &[0, 0], "sphere", &options).unwrap(); - let distinct = list_set_outputs(&fx.project, &[0, 1], "sphere", &options); + let once = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); + let repeated = plan_set_outputs(&fx.project, &[0, 0], "sphere", &options, PsdBudget::WEB).unwrap(); + let distinct = plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB); let (_, bytes_per_tile) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); assert_eq!(once.len(), repeated.len()); assert!(once.iter().zip(&repeated).all(|((_, first), (_, kept))| first.name == kept.name && kept.warnings.len() > first.warnings.len())); assert!(matches!(distinct, Err(FormatError::TooLarge(message)) if message.contains("total PSD"))); println!( - "PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {MAX_PSD_BATCH_BYTES}", + "PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {:?}", bytes_per_tile * once.len() as u64, - bytes_per_tile * (once.len() + repeated.len()) as u64 + bytes_per_tile * (once.len() + repeated.len()) as u64, + PsdBudget::WEB.batch_bytes ); } @@ -2207,29 +2242,35 @@ fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { options.size = Some(4096); fx.project.texture_sets[0].uv_tiles = (1001..1008).collect(); - let smaller = list_set_outputs(&fx.project, &[0], "sphere", &options).unwrap(); + let smaller = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); assert_eq!(smaller.len(), 7, "seven 128 MiB payloads fit with record overhead"); fx.project.texture_sets[0].uv_tiles.extend(1008..1034); - let oversized = list_set_outputs(&fx.project, &[0], "sphere", &options); + let oversized = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB); assert!(matches!(&oversized, Err(error) if error.to_string().contains("total PSD")), "the 33 individually valid tiles must be rejected as a batch"); let set = &fx.project.texture_sets[0]; let (width, height) = set.size(); fx.comp = Composite::with_size(&default_channels(), width, height); fx.coverage.resize((width * height) as usize, true); - let error = render_maps(&fx.input(), &options).unwrap_err(); + let planned = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap(); + let error = render_planned_maps_within(&fx.input(), &options, planned, PsdBudget::WEB).unwrap_err(); assert!(error.to_string().contains("total PSD"), "{error}"); let (_, estimated_bytes) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); - println!("PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {MAX_PSD_BATCH_BYTES}", estimated_bytes * 33); + println!( + "PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {:?}", + estimated_bytes * 33, + PsdBudget::WEB.batch_bytes + ); let mut small = fx.project.texture_sets[0].clone(); small.uv_tiles = (1001..1006).collect(); fx.project.texture_sets[0] = small.clone(); small.name = "Other".into(); fx.project.texture_sets.push(small); - assert!(list_set_outputs(&fx.project, &[0], "sphere", &options).is_ok()); - assert!(list_set_outputs(&fx.project, &[1], "sphere", &options).is_ok()); - assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_err(), "the budget includes all selected sets"); + assert!(plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).is_ok()); + assert!(plan_set_outputs(&fx.project, &[1], "sphere", &options, PsdBudget::WEB).is_ok()); + assert!(plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB).is_err(), "the budget includes all selected sets"); + assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_ok(), "a desktop batch has no such budget"); } From 67ac6e65e4bacc2107e5c4ed39ae48081415d73e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:32 +0000 Subject: [PATCH 053/190] Export: a glTF specular/glossiness file stays RGBA without a glossiness channel KHR_materials_pbrSpecularGlossiness reads glossiness from the specularGlossinessTexture's alpha, so a set with specular but no glossiness wrote an RGB file the extension can't use (review on #827). A glossiness alpha the set lacks is now written fully glossy, the extension's glossinessFactor default of 1. --- crates/formats/src/export/mod.rs | 9 ++++++++- crates/formats/src/export/tests.rs | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index e7eafd58..5ee5768e 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -44,6 +44,8 @@ use psd_budget::PsdBudget; /// width tilts the normal 45°, at any resolution. const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; +/// Glossiness a set lacks: the KHR_materials_pbrSpecularGlossiness glossinessFactor default +const MISSING_GLOSSINESS: SourceRef = SourceRef::Constant(1.0); const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; /// Planes of a PSD image or layer: red, green, blue and alpha @@ -584,7 +586,12 @@ pub(crate) fn source_present(set: &TextureSet, s: &SourceRef) -> bool { /// does not have is dropped. fn layout<'m>(set: &TextureSet, map: &'m MapSpec) -> Vec<(Dest, &'m SourceRef)> { let get = |d: Dest| map.channels.iter().find(|(x, _)| *x == d).map(|(_, s)| s); - let alpha = get(Dest::A).filter(|s| !matches!(s, SourceRef::Channel { channel, .. } if !set.has_channel(*channel))); + + // A glossiness alpha stays, fully glossy, so a specular/glossiness file is RGBA without the channel too + let alpha = match get(Dest::A) { + Some(SourceRef::Channel { channel: Channel::Glossiness, .. }) if !set.has_channel(Channel::Glossiness) => Some(&MISSING_GLOSSINESS), + alpha => alpha.filter(|s| !matches!(s, SourceRef::Channel { channel, .. } if !set.has_channel(*channel))), + }; let black = &SourceRef::Constant(0.0); let mut out = match get(Dest::L) { Some(l) => vec![(Dest::L, l)], diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index f6035d35..36d120d9 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -2039,6 +2039,18 @@ fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_ch assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); } +#[test] +fn the_gltf_specular_glossiness_file_is_rgba_and_fully_glossy_without_a_glossiness_channel() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Normal]); + fx.set_all(Channel::Specular, |_, _| [0.2, 0.5, 0.8]); + + let files = fx.render_preset("glTF Specular Glossiness (archived extension)"); + + let specular_glossiness = find(&files, "_SpecularGlossiness.png"); + assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8, "the extension reads glossiness from alpha"); + assert_eq!(pixel(specular_glossiness)[3], 255, "glossinessFactor defaults to 1"); +} + #[test] fn the_redshift_template_writes_one_map_per_input_the_set_has() { let mut channels = default_channels(); From 254868413eb7add4724bc3a1c37ed25f6c14293f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:32 +0000 Subject: [PATCH 054/190] Export: the hover preview is no larger than the map's own size MapPreview bounded its side only by the requested side and the composite, so a map with its own size (or a smaller export size) previewed larger than the file it writes (review on #827). The file's longer side, from the map's own size, else the export size, now bounds it too. --- crates/formats/src/export/map_preview.rs | 6 ++++-- crates/formats/src/export/tests.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs index 282ec063..a4401503 100644 --- a/crates/formats/src/export/map_preview.rs +++ b/crates/formats/src/export/map_preview.rs @@ -50,11 +50,13 @@ impl MapPreview { return Err(FormatError::Invalid(format!("composite size {composite_width}×{height} does not match its coverage"))); } + // The file's longer side bounds the preview: the map's own size, else the export size, else the set's + let tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1); + let file_side = |source| super::scale_export_side(source, tile_res, options.map_size(map)); let source_side = composite_width.max(height); - let preview_side = side.clamp(1, MAX_PREVIEW_SIDE).min(source_side); + let preview_side = side.clamp(1, MAX_PREVIEW_SIDE).min(file_side(composite_width).max(file_side(height))).min(source_side); let width = super::scale_export_side(composite_width, source_side, Some(preview_side)); let rows = super::scale_export_side(height, source_side, Some(preview_side)); - let tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1); let sampler = Sampler::new(input, options, set, tile_res, uncovered); let mut channel_layout = layout(set, spec); let grayscale = file.format == FileFormat::Pgm; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 36d120d9..0a252f7f 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1836,6 +1836,24 @@ fn map_preview_bounds_the_longer_side_of_a_tall_atlas() { assert_eq!(preview.pixels.len(), (preview.width * preview.height) as usize); } +#[test] +fn a_map_preview_is_no_larger_than_the_maps_own_size() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Png, 8, roughness()); + let own = RES / 4; + options.maps.insert(0, MapOverride { size: Some(own), ..MapOverride::default() }); + let file = decode(&fx.render(&options)[0]); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + + assert_eq!((preview.width, preview.height), file.dimensions(), "the preview shows the file at its own size"); + options.size = Some(RES / 2); + options.maps.clear(); + let export_sized = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + + assert!(export_sized.width > preview.width && export_sized.width < RES, "the export size bounds a map without its own"); +} + #[test] fn a_map_preview_holds_the_values_its_file_stores() { let mut fx = Fx::new(&default_channels()); From abe73ab18035c8ac497cf003ef76b2cd577d21dd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:32 +0000 Subject: [PATCH 055/190] Export: each greyed bit depth list has its own id disabled_combo took its id from the label alone, so two Output maps rows with a one-depth file type (BMP, JPEG) clashed and shared one accessibility node (review on #827). It is now salted with the row's own id, as the enabled bit depth list is. --- crates/ui-egui/src/export_window.rs | 2 +- crates/ui-egui/src/export_window/drawn.rs | 6 +++--- .../ui-egui/tests/it/export_map_overrides.rs | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 6772698d..3230c7cc 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -298,7 +298,7 @@ fn file_type_lists( let options = parsed.map(depth_options).unwrap_or_default(); let shown = if parsed.is_some() { depth_label(parsed, *bit_depth, *dithering) } else { String::new() }; if options.len() < 2 { - drawn::disabled_combo(ui, rects[1], &shown, tr("Bit depth")); + drawn::disabled_combo(ui, rects[1], ("bits", id), &shown, tr("Bit depth")); return; } diff --git a/crates/ui-egui/src/export_window/drawn.rs b/crates/ui-egui/src/export_window/drawn.rs index ad2604f9..9f92508f 100644 --- a/crates/ui-egui/src/export_window/drawn.rs +++ b/crates/ui-egui/src/export_window/drawn.rs @@ -235,10 +235,10 @@ pub(crate) fn field_button(ui: &mut Ui, rect: Rect, id: Id, text: &str) -> Respo response } -/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim -pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, shown: &str, name: &str) -> Response { +/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim; `id` tells it from the rows' other ones +pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, name: &str) -> Response { let look = ExportLook::get(ui.ctx()); - let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", name)), Sense::hover()); + let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", id)), Sense::hover()); response.widget_info(|| { let mut info = WidgetInfo::labeled(Role::ComboBox, false, name); info.current_text_value = Some(shown.to_owned()); diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 594c2916..2df31472 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -278,3 +278,22 @@ fn a_map_picks_its_own_size_and_the_export_writes_it_at_that_size() { assert_eq!(image::image_dimensions(&path).unwrap(), (side, side), "{}", path.display()); } } + +#[test] +fn rows_with_a_one_depth_file_type_each_have_their_own_bit_depth_list() { + let mut h = harness(); + let rows: Vec = plan(&mut h).iter().take(2).map(|file| file["map"].as_u64().unwrap() as usize).collect(); + let template = h.state().ui.export.preset.clone(); + let mut o = SetExport { maps_template: template, ..SetExport::default() }; + for map in &rows { + o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "bmp".into(), bit_depth: 8, dithering: false }), size: None }); + } + h.state_mut().ui.export.sets.insert(0, o); + h.run_steps(4); + + let greyed: Vec<_> = h.get_all_by_role_and_label(egui::Role::ComboBox, "Bit depth").map(|node| node.accesskit_node().id()).collect(); + + assert_eq!(rows.len(), 2); + assert_eq!(greyed.len(), 2, "each row's greyed bit depth list is its own node"); + assert_ne!(greyed[0], greyed[1]); +} From 2a79b229bbab4c717e2d78adafa0f99c5b35b21b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:33 +0000 Subject: [PATCH 056/190] Export: the desktop shader settings file runs the same name check as the web and headless ones file.exportTextures wrote _shaders.json without checking it against the export's texture paths, which the web download and the headless export do (review on #827). The check is one shared helper, check_shader_parameters_name, run here against this command's files and the earlier commands' reservedNames, so a clash is a warning and the file is not written. --- crates/engine/src/file_cmds.rs | 9 +++++++-- crates/engine/src/shader_parameters.rs | 13 ++++++++++--- crates/engine/tests/it/export_file_types.rs | 20 ++++++++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index aa390ad0..13324de1 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -825,11 +825,16 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { written.extend(write_usd_asset(session, dir, exports, &mut warnings)); } if let Some(shader_sets) = shader_sets { - let path = dir.join(crate::shader_parameters::shader_parameters_file(&session.doc.project.name)); + let name = crate::shader_parameters::shader_parameters_file(&session.doc.project.name); + let path = dir.join(&name); let parameters = crate::shader_parameters::shader_parameters(&session.doc.project, &shader_sets); + // Check the name against this command's files and the earlier commands' `reservedNames`, as the web download and headless export do + let roots = written.iter().filter_map(|written| written.strip_prefix(dir).ok()?.components().next()?.as_os_str().to_str()); + let checked = crate::shader_parameters::check_shader_parameters_name(&name, roots.chain(taken_names.keys().map(String::as_str))); + // The textures are written by now: a shaders file that fails is a warning, as a failed USD asset is - let text = serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string()); + let text = checked.and_then(|()| serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string())); match text.and_then(|text| texturecraft_formats::write_atomic(&path, &text).map_err(|error| error.to_string())) { Ok(()) => written.push(path), Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), diff --git a/crates/engine/src/shader_parameters.rs b/crates/engine/src/shader_parameters.rs index 428615b2..12a04674 100644 --- a/crates/engine/src/shader_parameters.rs +++ b/crates/engine/src/shader_parameters.rs @@ -34,12 +34,19 @@ pub fn shader_parameters_file(name: &str) -> String { format!("{}_shaders.json", texturecraft_formats::export::sanitize_file_stem(name)) } +/// Refuse the file name `name` when one of the export's texture paths (`/`-separated, relative to the export folder) is that file or lies in a folder of that name, ignoring case +pub fn check_shader_parameters_name<'a>(name: &str, texture_paths: impl IntoIterator) -> std::result::Result<(), String> { + if texture_paths.into_iter().any(|path| path.split('/').next().is_some_and(|root| root.eq_ignore_ascii_case(name))) { + return Err(format!("\"{name}\" is already used by a texture file or folder")); + } + + Ok(()) +} + /// Build the download or headless sidecar after checking its name against every texture path. pub fn shader_parameters_sidecar(project: &Project, sets: &[usize], textures: &[ExportedFile]) -> std::result::Result { let name = shader_parameters_file(&project.name); - if textures.iter().any(|texture| texture.name.split('/').next().is_some_and(|root| root.eq_ignore_ascii_case(&name))) { - return Err(format!("\"{name}\" is already used by a texture file or folder")); - } + check_shader_parameters_name(&name, textures.iter().map(|texture| texture.name.as_str()))?; let bytes = serde_json::to_vec_pretty(&shader_parameters(project, sets)).map_err(|error| error.to_string())?; Ok(ExportedFile { name, bytes, width: 0, height: 0, warnings: Vec::new() }) diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index 40e4816f..2240954f 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -96,3 +96,23 @@ fn a_shaders_json_that_cannot_be_written_is_a_warning_after_the_textures() { assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("The shader settings file was not written"))), "{result}"); } + +#[test] +fn a_shaders_json_named_like_an_earlier_commands_folder_is_a_warning() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let name = texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name); + let reserved = format!("{}/Color.png", name.to_uppercase()); + + let result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": dir.path().display().to_string(), "ts": 0, "shaderParameters": true, "reservedNames": [reserved]}), + ) + .unwrap(); + + assert!(!dir.path().join(&name).exists(), "{result}"); + let warnings = result["warnings"].as_array().unwrap(); + + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("already used by a texture file or folder"))), "{result}"); +} From 00238575c878ea5dc1a69dfeeaf497e67aa47495 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:42 +0000 Subject: [PATCH 057/190] Export: document PSD file names, layer names and limits A PSD export writes one _.psd per UV tile, and the template's file names become its layer names instead of file names (review on #827). docs/control-protocol.md says so, with the size limits and the browser-only memory budgets. --- docs/control-protocol.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 07f933bd..31d23fd5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -93,8 +93,13 @@ channel defaults. `padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. -Layered PSD maps are written as requested. MaterialX uses compatible companion maps for this -format. USD omits their texture bindings and returns a warning. +Layered PSD: the maps written as `psd` are the layers of one `_.psd` per +texture set and UV tile (`_..psd` for a tiled set), so the template's file +names don't name the file: they become the layer names, a `/` in one making layer groups. A PSD +that would pass 30000 pixels a side or 2 GiB is left out with a warning on the set's first other +file (an error when it is the set's only file); in the browser a PSD's working memory and a batch's +PSD output are also bounded. MaterialX uses compatible companion maps for this format. USD omits +their texture bindings and returns a warning. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus From 982a17c10f2bb6c3616107666f363bfc2ce7b640 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:21:32 +0000 Subject: [PATCH 058/190] Export: the greyed bit depth test uses a one-depth file type and finds the lists by value BMP and JPEG list 8 bits and 8 bits + dithering, so their bit depth list is enabled; the greyed one is HDR's (32f bits only), whose rows clashed. The greyed lists expose their value, not a label, to the accessibility tree, so the test now counts two HDR rows' "32f bits" lists. --- crates/ui-egui/tests/it/export_map_overrides.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 2df31472..497acf60 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -286,12 +286,13 @@ fn rows_with_a_one_depth_file_type_each_have_their_own_bit_depth_list() { let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; for map in &rows { - o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "bmp".into(), bit_depth: 8, dithering: false }), size: None }); + o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "hdr".into(), bit_depth: 32, dithering: false }), size: None }); } h.state_mut().ui.export.sets.insert(0, o); h.run_steps(4); - let greyed: Vec<_> = h.get_all_by_role_and_label(egui::Role::ComboBox, "Bit depth").map(|node| node.accesskit_node().id()).collect(); + let greyed: Vec<_> = + h.get_all_by_role(egui::Role::ComboBox).filter(|node| node.value().as_deref() == Some("32f bits")).map(|node| node.accesskit_node().id()).collect(); assert_eq!(rows.len(), 2); assert_eq!(greyed.len(), 2, "each row's greyed bit depth list is its own node"); From 61c601e040bbbfe089329c5a035203adff619f82 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:33:55 +0000 Subject: [PATCH 059/190] Export: a PSD planning warning outlives the file that carried it when reserved or repeated names drop that file --- crates/engine/src/file_cmds.rs | 22 +++++++++++++------- crates/engine/tests/it/export_file_types.rs | 23 +++++++++++++++++++++ crates/formats/src/export/mod.rs | 17 ++++++++++++--- 3 files changed, 51 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 13324de1..ae004bcf 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -967,8 +967,20 @@ fn reserve_export_names( let mut blocked_maps = HashSet::new(); plans.retain(|plan| { let name = plan.name.to_ascii_lowercase(); - if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) { - blocked_maps.extend(plan.maps()); + let reserved = reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)); + if !reserved && let Entry::Vacant(entry) = taken_names.entry(name) { + entry.insert(Some(set_index)); + return true; + } + + // A set warning outlives the file that carried it + for warning in plan.warnings.iter().filter(|warning| texturecraft_formats::export::is_set_warning(warning)) { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } + blocked_maps.extend(plan.maps()); + if reserved { warnings.push(format!( "\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names", plan.name @@ -976,12 +988,6 @@ fn reserve_export_names( return false; } - if let Entry::Vacant(entry) = taken_names.entry(name) { - entry.insert(Some(set_index)); - return true; - } - - blocked_maps.extend(plan.maps()); if fallback { warnings.push(format!( "MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names", diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index 2240954f..d4e16341 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -116,3 +116,26 @@ fn a_shaders_json_named_like_an_earlier_commands_folder_is_a_warning() { assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("already used by a texture file or folder"))), "{result}"); } + +#[test] +fn a_psd_warning_outlives_a_reserved_file_that_carried_it() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let roughness = json!([["L", {"Channel": {"channel": "Roughness"}}]]); + let colour = json!([["R", {"Channel": {"channel": "BaseColor"}}], ["G", {"Channel": {"channel": "BaseColor", "component": 1}}], ["B", {"Channel": {"channel": "BaseColor", "component": 2}}], ["A", {"Constant": 0.5}]]); + let preset = json!({"name": "Two and a PSD", "maps": [ + {"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness}, + {"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness}, + {"file": "layered", "format": "Psd", "bit_depth": 16, "channels": colour}, + ]}); + let params = |reserved: Vec| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": [{"map": 2, "size": 16384}], "reservedNames": reserved}); + let plan = execute(&mut session, "export.plan", ¶ms(Vec::new())).unwrap(); + let first = plan[0]["file"].as_str().unwrap().to_owned(); + let second = plan[1]["file"].as_str().unwrap().to_owned(); + + let result = execute(&mut session, "file.exportTextures", ¶ms(vec![first.clone()])).unwrap(); + + let warnings = result["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written"))), "{result}"); + assert!(dir.path().join(&second).exists() && !dir.path().join(&first).exists(), "{result}"); +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 5ee5768e..42328c95 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -895,11 +895,19 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti FormatError::Invalid(reason) | FormatError::TooLarge(reason) => reason, other => other.to_string(), }; - first.warnings.push(format!("\"{name}\" was not written: {reason}")); + first.warnings.push(format!("\"{name}\" {PSD_NOT_WRITTEN}{reason}")); } Ok(out) } +/// What a set's PSD planning failure says after the file name +const PSD_NOT_WRITTEN: &str = "was not written: "; + +/// Whether `warning` is about a PSD of the set that was not planned rather than the file carrying it, so it outlives that file +pub fn is_set_warning(warning: &str) -> bool { + warning.split_once(".psd\" ").is_some_and(|(name, rest)| name.starts_with('"') && rest.starts_with(PSD_NOT_WRITTEN)) +} + /// `stem.ext`, or `stem_2.ext`… when an earlier file has the name ignoring case (as Windows and macOS file systems do): the name and the suffix added fn unique_name(used: &mut BTreeSet, stem: &str, ext: &str, warnings: &mut Vec) -> (String, String) { let mut name = format!("{stem}.{ext}"); @@ -1764,11 +1772,14 @@ fn keep_first_names(files: impl IntoIterator, name: impl Fn(&T) -> let files = files.into_iter(); let mut first = HashMap::new(); let mut kept = Vec::with_capacity(files.size_hint().0); - for file in files { - let filename = name(&file); + for mut file in files { + let filename = name(&file).to_owned(); match first.entry(filename.to_ascii_lowercase()) { Entry::Occupied(previous) => { + // The later file's set warnings stay with the export + let moved: Vec<_> = warnings(&mut file).extract_if(.., |warning| is_set_warning(warning)).collect(); if let Some(winner) = kept.get_mut(*previous.get()) { + warnings(winner).extend(moved); warnings(winner).push(format!( "\"{}\" of a later texture set has the name of a file an earlier texture set exports, so it was not written; add $textureSet to the template's file names or rename a texture set", filename From 7a41c2c03c1aedc1a75ffa2dd0e7bab99309fb30 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:33:55 +0000 Subject: [PATCH 060/190] Export: say PSD names can be sanitized or disambiguated and point clients to export.plan --- docs/control-protocol.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 31d23fd5..48b63c45 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -95,11 +95,13 @@ channel defaults. Layered PSD: the maps written as `psd` are the layers of one `_.psd` per texture set and UV tile (`_..psd` for a tiled set), so the template's file -names don't name the file: they become the layer names, a `/` in one making layer groups. A PSD -that would pass 30000 pixels a side or 2 GiB is left out with a warning on the set's first other -file (an error when it is the set's only file); in the browser a PSD's working memory and a batch's -PSD output are also bounded. MaterialX uses compatible companion maps for this format. USD omits -their texture bindings and returns a warning. +names don't name the file: they become the layer names, a `/` in one making layer groups. The +document name is sanitized like other file names and can be shortened or disambiguated (a +texture-set index suffix when two sets' names give the same stem, as "A B" and "A_B" do), so read +the actual names from `export.plan`. A PSD that would pass 30000 pixels a side or 2 GiB is left +out with a warning on the set's first other file (an error when it is the set's only file); in the +browser a PSD's working memory and a batch's PSD output are also bounded. MaterialX uses +compatible companion maps for this format. USD omits their texture bindings and returns a warning. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus From f304cea242c4485b7ed909b41e74925005362604 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:34:00 +0000 Subject: [PATCH 061/190] Export: describe the browser PSD limits as estimates of PSD buffers and output, not a total memory bound --- docs/control-protocol.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 48b63c45..34f65fec 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -99,9 +99,10 @@ names don't name the file: they become the layer names, a `/` in one making laye document name is sanitized like other file names and can be shortened or disambiguated (a texture-set index suffix when two sets' names give the same stem, as "A B" and "A_B" do), so read the actual names from `export.plan`. A PSD that would pass 30000 pixels a side or 2 GiB is left -out with a warning on the set's first other file (an error when it is the set's only file); in the -browser a PSD's working memory and a batch's PSD output are also bounded. MaterialX uses -compatible companion maps for this format. USD omits their texture bindings and returns a warning. +out with a warning on the set's first other file (an error when it is the set's only file). In the +browser, estimates of a PSD's working buffers and of a batch's encoded PSD output are also bounded; +they don't bound the tab's total memory, as raster outputs and ZIP packaging use memory outside +them. MaterialX uses compatible companion maps for this format. USD omits their texture bindings and returns a warning. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus From 6aa412db625925ea20384f134709ab5bed44dada Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:42:53 +0000 Subject: [PATCH 062/190] Export: the PSD warning test plans a too-large PSD within the export size limit --- crates/engine/tests/it/export_file_types.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index d4e16341..341e196c 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -123,19 +123,25 @@ fn a_psd_warning_outlives_a_reserved_file_that_carried_it() { let dir = tempfile::tempdir().unwrap(); let roughness = json!([["L", {"Channel": {"channel": "Roughness"}}]]); let colour = json!([["R", {"Channel": {"channel": "BaseColor"}}], ["G", {"Channel": {"channel": "BaseColor", "component": 1}}], ["B", {"Channel": {"channel": "BaseColor", "component": 2}}], ["A", {"Constant": 0.5}]]); - let preset = json!({"name": "Two and a PSD", "maps": [ + let mut preset = json!({"name": "Two and a PSD", "maps": [ {"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness}, {"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness}, - {"file": "layered", "format": "Psd", "bit_depth": 16, "channels": colour}, ]}); - let params = |reserved: Vec| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": [{"map": 2, "size": 16384}], "reservedNames": reserved}); + // Four 16-bit RGBA layers at 8192 pixels and the merged image pass the 2 GiB PSD limit + for layer in 0..4 { + preset["maps"].as_array_mut().unwrap().push(json!({"file": format!("layer{layer}"), "format": "Psd", "bit_depth": 16, "channels": colour})); + } + let sizes: Vec<_> = (2..6).map(|map| json!({"map": map, "size": 8192})).collect(); + let params = |reserved: Vec| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": sizes, "reservedNames": reserved}); let plan = execute(&mut session, "export.plan", ¶ms(Vec::new())).unwrap(); let first = plan[0]["file"].as_str().unwrap().to_owned(); let second = plan[1]["file"].as_str().unwrap().to_owned(); + let psd_warning = + |warnings: &serde_json::Value| warnings.as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written"))); + assert!(plan.as_array().unwrap().len() == 2 && psd_warning(&plan[0]["warnings"]), "{plan}"); let result = execute(&mut session, "file.exportTextures", ¶ms(vec![first.clone()])).unwrap(); - let warnings = result["warnings"].as_array().unwrap(); - assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written"))), "{result}"); + assert!(psd_warning(&result["warnings"]), "{result}"); assert!(dir.path().join(&second).exists() && !dir.path().join(&first).exists(), "{result}"); } From 48dc4832155fa4344f2e549ceb2f14db7e0ebcbe Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:50:04 +0000 Subject: [PATCH 063/190] Export: a PSD layer is quantized to RGBA as it widens, without a floating-point RGBA copy --- crates/formats/src/export/layered_psd.rs | 63 ++++++++++-------------- crates/formats/src/export/tests.rs | 36 ++++++++++++++ 2 files changed, 62 insertions(+), 37 deletions(-) diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index 951a18ef..af95e664 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -88,9 +88,8 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u3 for layer in layers.iter().rev() { let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; embedded = map.embed.or(embedded); - let rgba = to_rgba(map.data, map.component_count, &map.srgb); let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; - let layer_pixels = pixel_data(rgba, map.size.0, encoding)?; + let layer_pixels = rgba_pixel_data(map.data, map.component_count, &map.srgb, map.size.0, encoding)?; pixels.push((layer.name.as_str(), map.size, layer_pixels)); } if let Some(space) = embedded { @@ -107,36 +106,6 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u3 Ok(ExportedFile { name, bytes, width: size.0, height: size.1, warnings }) } -/// L, LA, RGB or RGBA samples as RGBA (gray repeated, opaque without alpha), sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 -fn to_rgba(mut data: Vec, component_count: usize, srgb: &[bool]) -> Vec { - let encode = |component: usize, value: f32| if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }; - - if component_count == PSD_RGBA_PLANES { - for texel in data.as_chunks_mut::().0 { - for (component, value) in texel.iter_mut().enumerate() { - *value = encode(component, *value); - } - } - - return data; - } - - data.chunks_exact(component_count.max(1)) - .flat_map(|texel| { - let encoded = |component| encode(component, texel.get(component).copied().unwrap_or(0.0)); - match component_count { - 1 | 2 => { - let gray = encoded(0); - let alpha = if component_count == 2 { encoded(1) } else { 1.0 }; - [gray, gray, gray, alpha] - } - 3 => [encoded(0), encoded(1), encoded(2), 1.0], - _ => [encoded(0), encoded(1), encoded(2), encoded(3)], - } - }) - .collect() -} - /// The merged image of `layers` (bottom first, as the file stores them), one row at a time fn merged_image((width, height): (u32, u32), depth: u8, layers: &[(&str, (u32, u32), PixelData)]) -> Result { let row_len = width as usize * PSD_RGBA_PLANES; @@ -206,16 +175,36 @@ fn over(canvas: &mut [f32], canvas_width: u32, layer: &[f32], layer_width: u32) } } -/// Quantize directly into the sample type the PSD builder accepts. -fn pixel_data(samples: Vec, width: u32, encoding: Encoding) -> Result { +/// L, LA, RGB or RGBA samples quantized as the RGBA the PSD builder accepts: gray repeated, opaque without alpha, sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 +fn rgba_pixel_data(mut data: Vec, component_count: usize, srgb: &[bool], width: u32, encoding: Encoding) -> Result { + let component_count = component_count.max(1); + for texel in data.chunks_exact_mut(component_count) { + for (component, value) in texel.iter_mut().enumerate() { + *value = if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(*value) } else { value.clamp(0.0, 1.0) }; + } + } + + // Widen each texel while quantizing, so no floating-point RGBA copy of the layer is made + let texel_count = data.len() / component_count; + let rgba = (0..texel_count * PSD_RGBA_PLANES).map(|index| { + let (texel, component) = (index / PSD_RGBA_PLANES, index % PSD_RGBA_PLANES); + let source = match component_count { + 1 | 2 if component < ALPHA_INDEX => Some(0), + 1 | 3 if component == ALPHA_INDEX => None, + 2 => Some(1), + _ => Some(component), + }; + source.map_or(1.0, |source| data.get(texel * component_count + source).copied().unwrap_or(0.0)) + }); + if encoding.depth == 16 { let mut pixels = Vec::new(); - pixels.try_reserve_exact(samples.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?; - pixels.extend(samples.into_iter().map(quantize_u16)); + pixels.try_reserve_exact(rgba.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?; + pixels.extend(rgba.map(quantize_u16)); return Ok(PixelData::Rgba16(pixels)); } - quantize_integer(encoding, width, PSD_RGBA_PLANES, samples.into_iter()).map(PixelData::Rgba8) + quantize_integer(encoding, width, PSD_RGBA_PLANES, rgba).map(PixelData::Rgba8) } /// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 0a252f7f..64fd5115 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -2153,6 +2153,42 @@ fn feedback_psd_preview_matches_layer_rgba() { } } +#[test] +fn psd_layers_hold_the_samples_of_the_same_png_at_every_layout_and_depth() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let base_colour = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.pop(); + let layouts = [roughness(), vec![(Dest::L, base_colour(0))], gray_alpha, rgb, rgba_half_alpha()]; + + for channels in layouts { + for (depth, dither) in [(8, false), (8, true), (16, false)] { + let mut png_options = one_map(FileFormat::Png, depth, channels.clone()); + png_options.dither = dither; + let mut psd_options = png_options.clone(); + psd_options.format_override = Some(FileFormat::Psd); + + let png = decode(&fx.render(&png_options)[0]); + let psd = craft_psd::PsdFile::from_bytes(&fx.render(&psd_options)[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap(); + + let context = format!("{channels:?} at {depth} bits, dithering {dither}"); + if depth == 16 { + // Planes of big-endian samples: red, green, blue, then transparency + let planes: Vec> = [0, 1, 2, -1].into_iter().map(|id| layer.channel_bytes(id).unwrap()).collect(); + let texel_count = planes[0].len() / 2; + let samples: Vec = + (0..texel_count).flat_map(|texel| planes.iter().map(move |plane| u16::from_be_bytes([plane[2 * texel], plane[2 * texel + 1]]))).collect(); + assert!(samples == png.to_rgba16().into_raw(), "{context}"); + } else { + assert!(layer.rgba8().unwrap().data == png.to_rgba8().into_raw(), "{context}"); + } + } + } +} + #[test] fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { let mut fx = Fx::new(&default_channels()); From c58fd595471b095e8b5fc92625158df0e633e7cc Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:56:38 +0000 Subject: [PATCH 064/190] Export: a tiled map's UDIM name pattern is expanded once per map, not once per tile --- crates/formats/src/export/mod.rs | 11 +++++++---- crates/formats/src/export/tests.rs | 3 +++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 42328c95..7fe9b6be 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -784,8 +784,11 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti sanitize_file_path(&expanded) }; + // A tiled raster's name with a placeholder for its tile, the same for every tile + let udim_template = (format != FileFormat::Psd && tiles[0].is_some()).then(|| expand_stem("UDIMTOKEN")); for (tile_index, &tile) in tiles.iter().enumerate() { - let stem = expand_stem(&tile.unwrap_or(1001).to_string()); + let tile_number = tile.unwrap_or(1001).to_string(); + let stem = expand_stem(&tile_number); let ext = format.extension(); let mut warnings = Vec::new(); if color_map @@ -832,9 +835,9 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti // Use a UDIM name only when substituting its tile recovers the output name // Truncation or literal placeholder text can make that substitution ambiguous - let udim_name = tile - .map(|_| expand_stem("UDIMTOKEN")) - .filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)) + let udim_name = udim_template + .as_deref() + .filter(|t| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &tile_number) == stem) .map(|t| format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "")); out.push(PlannedFile { name, map: map_index, format, bit_depth, dither, tile, udim_name, warnings, layers: Vec::new() }); } diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 64fd5115..3fe0e174 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -759,6 +759,9 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() { // A folder stays in the placeholder name assert_eq!(udim_names("Base/$textureSet_$udim".into()), [Some("Base/Body_.png".to_string()), Some("Base/Body_.png".to_string())]); + + // A name without the token gets the tile as a suffix, and so does its placeholder + assert_eq!(udim_names("$textureSet".into()), [Some("Body..png".to_string()), Some("Body..png".to_string())]); } #[test] From 468b016da229aadf5dab73e6c5e98b17a4531ba0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:17:22 +0000 Subject: [PATCH 065/190] Resources: a reload keeps each image's own file across undo, and renaming a linked material's package moves a material effect's link too The file an image was imported from is kept by the image's bytes instead of its name, so an undo that brings back a removed image reloads it from its own file, not from a later file that took its name. A rename now also points a material effect's link package and cooked outputs at the new name. --- crates/core/src/layer.rs | 2 +- crates/engine/src/resource_cmds.rs | 105 ++++++++++++++++++++++++----- crates/engine/src/session.rs | 14 ++-- 3 files changed, 94 insertions(+), 27 deletions(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 56a5147f..2aded5ac 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -2072,7 +2072,7 @@ impl EffectKind { pub fn images_mut(&mut self) -> Vec<&mut String> { match self { EffectKind::Fill { source, .. } => source.images_mut(), - EffectKind::Material(fill) => fill.sources.values_mut().flat_map(Source::images_mut).collect(), + EffectKind::Material(fill) => fill.images_mut().collect(), EffectKind::Generator(generator) => generator.inputs.values_mut().flat_map(Source::images_mut).collect(), EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(), _ => Vec::new(), diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 1d93ccb9..83f9d180 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -123,16 +123,22 @@ impl Session { self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); - - // A new resource under a removed one's name has no file of its own until an import says so - self.resource_sources.remove(&name); - Ok(name) } /// The file image resource `name` was imported from in this session (what `resource.reload` reads again) pub fn resource_source(&self, name: &str) -> Option<&std::path::Path> { - self.resource_sources.get(name).map(std::path::PathBuf::as_path) + let bytes = self.doc.resources.get(name)?; + self.resource_sources.iter().rev().find(|(source, _)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(bytes))).map(|(_, path)| path.as_path()) + } + + /// Remembers that image resource `name`, with the bytes it holds now, came from the file at `path` + #[cfg(not(target_arch = "wasm32"))] + fn remember_resource_source(&mut self, name: &str, path: &std::path::Path) { + self.resource_sources.retain(|(source, _)| source.strong_count() > 0); + if let Some(bytes) = self.doc.resources.get(name) { + self.resource_sources.push((Arc::downgrade(bytes), path.to_path_buf())); + } } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). @@ -210,7 +216,7 @@ fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; - s.resource_sources.insert(name.clone(), path.into()); + s.remember_resource_source(&name, std::path::Path::new(path)); Ok(json!({ "name": name })) } @@ -365,9 +371,6 @@ fn rename(s: &mut Session, p: &Value) -> Result { if s.library_alphas.remove(&name) { s.library_alphas.insert(to.clone()); } - if let Some(source) = s.resource_sources.remove(&name) { - s.resource_sources.insert(to.clone(), source); - } s.path_cache = None; s.sync_images(); Ok(json!({ "name": to })) @@ -406,14 +409,17 @@ fn reload(s: &mut Session, p: &Value) -> Result { return Err(bad(command, format!("no resource `{name}`"))); } - let path = - s.resource_sources.get(&name).cloned().ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?; + let path = s + .resource_source(&name) + .map(std::path::Path::to_path_buf) + .ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?; let (bytes, image) = read_source(command, &path)?; s.edit("Reload resource", |s| { s.doc.resources.insert(name.clone(), Arc::new(bytes)); Ok(()) })?; + s.remember_resource_source(&name, &path); s.show_reloaded(name.clone(), image); Ok(json!({ "name": name })) } @@ -424,29 +430,30 @@ fn update(s: &mut Session, _: &Value) -> Result { let command = "resource.update"; let mut changed = Vec::new(); let mut failed = Vec::new(); - for (name, path) in &s.resource_sources { - let Some(held) = s.doc.resources.get(name) else { continue }; + for (name, held) in &s.doc.resources { + let Some(path) = s.resource_source(name) else { continue }; // Only a file whose bytes changed is decoded let read = read_resource_file(command, path, MAX_BYTES as u64) .and_then(|bytes| if bytes == **held { Ok(None) } else { decode_source(command, path, &bytes).map(|image| Some((bytes, image))) }); match read { Ok(None) => {} - Ok(Some((bytes, image))) => changed.push((name.clone(), bytes, image)), + Ok(Some((bytes, image))) => changed.push((name.clone(), path.to_path_buf(), bytes, image)), Err(error) => failed.push(json!({ "name": name, "error": error.to_string() })), } } if !changed.is_empty() { s.edit("Update resources", |s| { - for (name, bytes, _) in &mut changed { + for (name, _, bytes, _) in &mut changed { s.doc.resources.insert(name.clone(), Arc::new(std::mem::take(bytes))); } Ok(()) })?; } - let updated: Vec = changed.iter().map(|(name, _, _)| name.clone()).collect(); - for (name, _, image) in changed { + let updated: Vec = changed.iter().map(|(name, _, _, _)| name.clone()).collect(); + for (name, path, _, image) in changed { + s.remember_resource_source(&name, &path); s.show_reloaded(name, image); } Ok(json!({ "updated": updated, "failed": failed })) @@ -611,6 +618,42 @@ mod tests { assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&renamed), "the brush alpha follows the redo"); } + #[test] + fn renaming_a_linked_materials_package_moves_a_material_effects_link_with_it() { + use std::collections::BTreeMap; + use texturecraft_core::{Effect, EffectKind, MaterialLink}; + + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let package = session.import_resource_bytes("package.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": package})).unwrap(); + let layer_id = session.selected_layer().unwrap(); + let link = MaterialLink { + name: "linked".into(), + package: package.clone(), + graph: String::new(), + params: Vec::new(), + presets: Vec::new(), + inputs: Vec::new(), + size: 1, + resolution: None, + mapping: BTreeMap::new(), + outputs: BTreeMap::from([("basecolor".to_string(), package.clone())]), + }; + let effect_id = session.doc.project.alloc_id(); + let material = Effect::new(effect_id, EffectKind::Material(Fill { link: Some(Box::new(link)), ..Fill::default() })); + session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(material); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": package, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); + + let effect = &session.doc.project.layers[&layer_id].content_effects[0]; + let EffectKind::Material(fill) = &effect.kind else { panic!("the effect stays a material") }; + let link = fill.link.as_ref().unwrap(); + assert_ne!(renamed, package); + assert_eq!(link.package, renamed, "the link's package follows the rename"); + assert_eq!(link.outputs.values().collect::>(), [&renamed], "the link's cooked outputs follow the rename"); + } + #[test] fn reloading_reads_the_file_again_and_undo_restores_the_pixels() { let mut session = crate::sample_session(128, 32).unwrap(); @@ -644,6 +687,34 @@ mod tests { assert!(session.resource_source(&reused).is_none(), "the new image has no file to reload from"); } + #[test] + fn undo_gives_an_image_back_its_own_file_after_another_file_took_its_name() { + let mut session = crate::sample_session(128, 32).unwrap(); + let folder = |side: &str| std::env::temp_dir().join(format!("texturecraft-own-file-{side}-{}", std::process::id())); + let import = |session: &mut Session, side: &str, value: f32| { + std::fs::create_dir_all(folder(side)).unwrap(); + let path = folder(side).join("photo.png"); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [value].into_iter()).unwrap()).unwrap(); + let name = crate::execute(session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + (path, name) + }; + let (first_path, first) = import(&mut session, "first", 0.2); + crate::execute(&mut session, "resource.remove", &json!({"name": first})).unwrap(); + let (second_path, second) = import(&mut session, "second", 0.6); + + // One undo takes back the second import, the next the removal + session.undo().unwrap(); + session.undo().unwrap(); + let source = session.resource_source(&first).map(std::path::Path::to_path_buf); + for side in ["first", "second"] { + std::fs::remove_dir_all(folder(side)).unwrap(); + } + + assert_eq!(second, first, "the second file takes the removed image's name"); + assert_ne!(first_path, second_path); + assert_eq!(source, Some(first_path), "the image the undo brings back reloads from its own file"); + } + #[test] fn updating_reads_only_changed_files_in_one_undo_step() { let mut session = crate::sample_session(128, 32).unwrap(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 66b58d6f..68fd8fd9 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -462,8 +462,8 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Resource names whose decoded pixels match a library alpha. pub(crate) library_alphas: BTreeSet, - /// The file each image resource imported in this session came from, for Reload (not saved) - pub(crate) resource_sources: BTreeMap, + /// The file each image resource imported in this session came from, for Reload (not saved). Kept by the resource's bytes, so undo, redo and renames keep each file with its own image + pub(crate) resource_sources: Vec<(std::sync::Weak>, std::path::PathBuf)>, /// Temporary texel mask limiting paint strokes (not saved, not in the history). pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). @@ -549,7 +549,7 @@ impl Session { blending_clipboard: None, images: Default::default(), library_alphas: BTreeSet::new(), - resource_sources: BTreeMap::new(), + resource_sources: Vec::new(), quick_mask: Default::default(), painting_paths: false, path_cache: None, @@ -1028,10 +1028,9 @@ impl Session { .flatten() } - /// Points tool images and reload sources at a resource's name on this side of an undone or redone rename + /// Points tool images at a resource's name on this side of an undone or redone rename fn follow_renamed_resources(&mut self, other: &Document) { - let mut names: Vec = self.tool_images_mut().map(|name| name.clone()).collect(); - names.extend(self.resource_sources.keys().cloned()); + let names: Vec = self.tool_images_mut().map(|name| name.clone()).collect(); let renames: Vec<(String, String)> = names .into_iter() .filter(|name| !self.doc.resources.contains_key(name)) @@ -1046,9 +1045,6 @@ impl Session { for tool_image in self.tool_images_mut().filter(|tool_image| **tool_image == name) { tool_image.clone_from(&to); } - if let Some(source) = self.resource_sources.remove(&name) { - self.resource_sources.insert(to, source); - } } } From 53d24eac47b4515681bd404531a1b64da5105cf9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:17:22 +0000 Subject: [PATCH 066/190] Assets: review fixes for saved searches under Favorites, folder hiding, read failures per project and custom previews A saved search keeps the Favorites choice it was saved with. Hide non-applicable folders under Favorites only keeps the favorites' folders. A file that fails to read is reported once per project. A custom preview is read only when its tile shows. A rename in the asset menu stops that frame's rows from acting on the old name. The stroke test also checks that undo takes back the update on its own. --- crates/ui-egui/src/saved_search.rs | 5 +- crates/ui-egui/src/shelf.rs | 18 +++---- crates/ui-egui/src/shelf_menu.rs | 2 + crates/ui-egui/src/shelf_panes.rs | 14 +++-- crates/ui-egui/src/shelf_updates.rs | 11 ++-- crates/ui-egui/src/state.rs | 3 +- crates/ui-egui/tests/it/shelf_panel.rs | 69 ++++++++++++++++++++++-- crates/ui-egui/tests/it/shelf_updates.rs | 33 ++++++++++++ 8 files changed, 132 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/saved_search.rs b/crates/ui-egui/src/saved_search.rs index ec6181b8..b4d4c562 100644 --- a/crates/ui-egui/src/saved_search.rs +++ b/crates/ui-egui/src/saved_search.rs @@ -2,11 +2,14 @@ use serde::{Deserialize, Serialize}; -/// The search text, tab and library folder of a saved shelf query, under the name it lists as +/// The search text, tab, library folder and Favorites choice of a saved shelf query, under the name it lists as #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct SavedSearch { pub name: String, pub filter: String, pub tab: usize, pub path: Vec, + /// Only favorites show; searches saved before favorites show everything + #[serde(default)] + pub favorites_only: bool, } diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 18d61227..28f8a898 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -271,6 +271,10 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let folder = app.ui.shelf_path.clone(); let picked_tab = app.ui.shelf_tab; let mut matching: Vec = all_entries.into_iter().filter(|entry| entry.matches(&filter)).collect(); + if app.ui.shelf_favorites_only { + matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); + } + let path_pane_open = app.ui.shelf_panes.filter_by_path; let mut applicable = if path_pane_open { crate::shelf_folders::paths(matching.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))) @@ -278,10 +282,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { Vec::new() }; - if app.ui.shelf_favorites_only { - matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); - } - // All libraries includes every result without constructing an asset path if !folder.is_empty() { matching.retain(|entry| entry.in_folder(&folder)); @@ -298,7 +298,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if in_user_library && let Some(count) = TABS.iter().position(|(shown, _, _)| *shown == tab).and_then(|position| counts.get_mut(position)) { *count += saved; } - if path_pane_open && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) { + if path_pane_open && !favorites_only && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) { applicable.push(vec![crate::shelf_entry::USER.to_string()]); } } @@ -523,15 +523,15 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry return; } - // A picture the user picked replaces the thumbnail, unless its file is gone - let custom = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry).and_then(|file| app.thumbs.custom_preview(ctx, file)); - let texture = custom.or_else(|| entry.thumbnail(app, ctx)); + // A picture the user picked replaces the thumbnail, unless its file is gone; it is read only once its tile shows + let thumbnail = entry.thumbnail(app, ctx); + let custom_file = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry); let asset = entry.asset(); let session = &app.session; let response = tile_in_view( ui, &mut app.thumbs, - |_, _| texture, + |ui, thumbs| custom_file.and_then(|file| thumbs.custom_preview(ui.ctx(), file)).or(thumbnail), |thumbs| match entry { ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)), _ => entry.preview(session), diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index e7546ecf..bd6210c4 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -86,7 +86,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf && let Some(result) = app.run(command, json!({"name": name, "to": renamed})) && let Some(new_name) = result["name"].as_str() { + // The rows below would act on the old name: the menu draws again under the new one next frame keep_star_and_preview(app, entry, new_name); + return; } } info_block(ui, width, column, shown_info, &tokens); diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index f2a6d42f..a642a731 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -272,11 +272,14 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { let saved_index = row - first_saved_row; let Some(saved) = app.ui.shelf_saved_searches.get(saved_index) else { continue }; - let selected = !favorites_only && saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path; + let selected = saved.favorites_only == favorites_only + && saved.filter == app.ui.shelf_filter + && saved.tab == app.ui.shelf_tab + && saved.path == app.ui.shelf_path; let response = ui.selectable_label(selected, &saved.name); if response.clicked() { (app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone()); - app.ui.shelf_favorites_only = false; + app.ui.shelf_favorites_only = saved.favorites_only; } response.context_menu(|ui| { @@ -294,18 +297,21 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// The shelf's query, named after its search text, else its folder, else its tab +/// The shelf's query, named after its search text, else its folder, else Favorites, else its tab fn current_query(app: &TextureCraftApp) -> SavedSearch { let filter = &app.ui.shelf_filter; let tab = app.ui.shelf_tab; let path = &app.ui.shelf_path; + let favorites_only = app.ui.shelf_favorites_only; let name = if !filter.is_empty() { filter.as_str() } else if let Some(folder) = path.last() { crate::shelf_folders::name(path.len() - 1, folder) + } else if favorites_only { + tr(FAVORITES) } else { TABS.get(tab).map_or_else(|| tr("All"), |(_, _, label)| tr(label)) }; - SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone() } + SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone(), favorites_only } } diff --git a/crates/ui-egui/src/shelf_updates.rs b/crates/ui-egui/src/shelf_updates.rs index 8300357d..648bd87a 100644 --- a/crates/ui-egui/src/shelf_updates.rs +++ b/crates/ui-egui/src/shelf_updates.rs @@ -110,7 +110,8 @@ fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { .flatten() .map(|failure| (failure["name"].as_str().unwrap_or_default().to_owned(), failure["error"].as_str().unwrap_or_default().to_owned())) .collect(); - let mut reported: Vec = ctx.data(|data| data.get_temp(reported_failures_id())).unwrap_or_default(); + let reported_id = reported_failures_id(app.session.project_id); + let mut reported: Vec = ctx.data(|data| data.get_temp(reported_id)).unwrap_or_default(); reported.retain(|name| failures.iter().any(|(failed, _)| failed == name)); for (name, error) in failures { if !reported.contains(&name) { @@ -118,12 +119,12 @@ fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { reported.push(name); } } - ctx.data_mut(|data| data.insert_temp(reported_failures_id(), reported)); + ctx.data_mut(|data| data.insert_temp(reported_id, reported)); } -/// The files whose failure to read was already shown (ctx temp data) -fn reported_failures_id() -> Id { - Id::unique("shelf_updates_reported_failures") +/// The files of project `project_id` whose failure to read was already shown (ctx temp data) +fn reported_failures_id(project_id: u64) -> Id { + Id::unique(("shelf_updates_reported_failures", project_id)) } /// The refresh button with its popup of update settings, opening upward from the toolbar `panel` with its left edge on the panel's diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 34748b34..0394df49 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -946,7 +946,8 @@ mod tests { #[test] fn adopting_a_layout_keeps_the_shelf_query_saved_searches_favorites_and_custom_previews() { - let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; + let saved = + crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()], favorites_only: false }; let favorite = crate::shelf_favorite::ShelfFavorite { kind: "material".into(), id: "gold".into() }; let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], shelf_favorites_only: true, ..UiState::default() }; diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 23686275..6a8032bb 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -19,6 +19,8 @@ const MATERIALS_TYPE: usize = 0; const SMART_MASKS_TYPE: usize = 2; const BRUSHES_TYPE: usize = 4; const ENVIRONMENTS_TYPE: usize = 7; +/// The type row with no type picked: every type shows +const EVERY_TYPE: usize = 8; /// How far the saved brush's spacing differs from the current brush's, so loading it shows const SAVED_SPACING_CHANGE: f32 = 0.25; /// Tile columns the reference shows at its panel width @@ -203,7 +205,13 @@ fn many_saved_searches_keep_the_path_filter_reachable() { harness.state_mut().ui.shelf_panes.saved_searches = true; harness.state_mut().ui.shelf_panes.filter_by_path = true; harness.state_mut().ui.shelf_saved_searches = (0..100) - .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .map(|index| SavedSearch { + name: format!("search {index}"), + filter: format!("filter {index}"), + tab: MATERIALS_TYPE, + path: Vec::new(), + favorites_only: false, + }) .collect(); harness.run_steps(3); @@ -217,7 +225,13 @@ fn a_long_saved_search_list_can_select_the_last_query() { let mut harness = shelf(NARROW_WINDOW); harness.state_mut().ui.shelf_panes.saved_searches = true; harness.state_mut().ui.shelf_saved_searches = (0..1000) - .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .map(|index| SavedSearch { + name: format!("search {index}"), + filter: format!("filter {index}"), + tab: MATERIALS_TYPE, + path: Vec::new(), + favorites_only: false, + }) .collect(); harness.run_steps(3); assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); @@ -457,7 +471,7 @@ fn the_smallest_saved_search_pane_can_scroll_to_and_select_the_last_query() { harness.state_mut().ui.shelf_panes.filter_by_path = true; harness.state_mut().ui.shelf_panes_split = 0.0; harness.state_mut().ui.shelf_saved_searches = - vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new() }]; + vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new(), favorites_only: false }]; harness.run_steps(3); scroll_pane_to_end(&mut harness, "SAVED SEARCHES"); @@ -545,6 +559,55 @@ fn the_favorites_search_shows_only_favorites_until_all_is_picked() { assert!(harness.query_by_label("My brushes").is_some(), "All shows the saved brushes list again"); } +/// The shelf on the Materials type with the first plain material made a favorite through its menu +fn shelf_with_a_favorite(session: texturecraft_engine::Session) -> Harness<'static, TextureCraftApp> { + let favorite = plain_materials()[0].label; + let mut harness = Harness::builder().with_size(REFERENCE_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; + harness.run_steps(4); + button(&harness, favorite).click_secondary(); + harness.run_steps(3); + button(&harness, "Add to favorites").click(); + harness.run_steps(3); + harness +} + +#[test] +fn a_search_saved_under_favorites_shows_only_favorites_again() { + let mut harness = shelf_with_a_favorite(texturecraft_engine::sample_session(256, 64).unwrap()); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + button(&harness, "Favorites").click(); + harness.run_steps(3); + button(&harness, "Save the current search").click(); + harness.run_steps(2); + button(&harness, "All").click(); + harness.run_steps(3); + + // The saved search lists below the fixed Favorites row, under the same name + harness.get_all_by_label("Favorites").last().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1); + assert!(harness.state().ui.shelf_favorites_only, "the saved search shows only favorites, as when it was saved"); +} + +#[test] +fn hiding_non_applicable_folders_under_favorites_hides_the_folders_of_other_assets() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + session.import_resource_bytes("photo.png", png).unwrap(); + let mut harness = shelf_with_a_favorite(session); + harness.state_mut().ui.shelf_tab = EVERY_TYPE; + harness.state_mut().ui.shelf_favorites_only = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.state_mut().ui.shelf_panes.hide_non_applicable = true; + harness.run_steps(4); + + assert!(harness.query_by_label("Starter assets").is_some(), "the favorite's library shows"); + assert!(harness.query_by_label("Project").is_none(), "the project image is no favorite, so its library hides"); +} + #[test] fn the_edge_between_the_panes_and_the_grid_drags_and_the_width_is_saved() { let mut harness = shelf(REFERENCE_WINDOW); diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs index 0a3e06fd..17ad5051 100644 --- a/crates/ui-egui/tests/it/shelf_updates.rs +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -77,6 +77,7 @@ fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { harness.run_steps(2); std::fs::write(&path, grey_png(0.8)).unwrap(); + let steps_before_stroke = harness.state().session.history_labels().len(); harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); pass_a_minute(&mut harness); let during_stroke = harness.state().session.images[&name].rgba.clone(); @@ -88,4 +89,36 @@ fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { assert_eq!(during_stroke, before, "nothing is read again while a stroke is under way"); assert_ne!(after_stroke, before, "the update runs once the stroke ended"); assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.8).as_slice(), "the stroke's undo state didn't swallow the update"); + + harness.state_mut().session.undo().unwrap(); + + assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.2).as_slice(), "one undo takes back the update"); + assert_eq!(harness.state().session.history_labels().len(), steps_before_stroke + 1, "the stroke is still its own step"); +} + +#[test] +fn a_file_that_fails_to_read_is_reported_again_in_the_next_project() { + let mut harness = refresh_popup(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + + let mut reported = Vec::new(); + for project in ["first", "second"] { + if project == "second" { + harness.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); + } + let folder = std::env::temp_dir().join(format!("texturecraft-failed-read-{project}-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("photo.png"); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + std::fs::remove_dir_all(&folder).unwrap(); + harness.state_mut().toasts.clear(); + + pass_a_minute(&mut harness); + + reported.push(harness.state().toasts.iter().any(|toast| toast.error && toast.text.starts_with(&format!("{name}:")))); + } + + assert_eq!(reported, [true, true], "each project says once that its file can't be read"); } From 758474a9124bc672d2456cee94cd54faea09b5d0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:42:41 +0000 Subject: [PATCH 067/190] Export: the export tests install the framework runtime, as main's tests do since #800 --- crates/ui-egui/src/export_templates.rs | 2 +- crates/ui-egui/tests/it/export_shader_parameters.rs | 5 ++++- crates/ui-egui/tests/ui_snapshots.rs | 8 ++++++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index a7ece23a..70f708b4 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1875,7 +1875,7 @@ mod tests { use egui_kittest::Harness; let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); let app = harness.state_mut(); let ts = app.session.ts(); let saved = app.session.export_preset("Unreal Engine (Packed)").unwrap(); diff --git a/crates/ui-egui/tests/it/export_shader_parameters.rs b/crates/ui-egui/tests/it/export_shader_parameters.rs index 07c1b479..7480cd63 100644 --- a/crates/ui-egui/tests/it/export_shader_parameters.rs +++ b/crates/ui-egui/tests/it/export_shader_parameters.rs @@ -10,7 +10,10 @@ use super::temp_dir::TempDir; #[test] fn ticking_export_shader_settings_writes_the_json_listing_every_exported_set() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let dir = TempDir::new("export-shader-parameters"); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 367fccb8..c9f43e43 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3230,8 +3230,12 @@ fn export_window_snapshots() { set.name = format!("Set {}", session.doc.project.texture_sets.len() + 1); session.doc.project.texture_sets.push(set); } - let mut harness = - Harness::builder().with_size(egui::vec2(1112.0, 662.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1112.0, 662.0)) + .with_pixels_per_point(2.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .wgpu() + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.prefs.brightness = brightness; harness.set_render_cursor(false); From 948f6446aabcc9630f8b7d20672deb7cb603757b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:09:40 +0000 Subject: [PATCH 068/190] List of exports: a texture set's folding header reports itself as a disclosure triangle, as egui's CollapsingHeader does --- crates/ui-egui/src/export_window.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3230c7cc..a3f6661b 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1505,7 +1505,8 @@ fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui::Id) -> bool { let look = ExportLook::get(ui.ctx()); let response = ui.interact(rect, id, egui::Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name)); + // A folding header, as egui's CollapsingHeader reports one + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, name)); let y = rect.center().y; let chevron = if open { ic::CARET_DOWN From 2efb7bd74739358e81068be59f2f177829d6255c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:03:12 +0000 Subject: [PATCH 069/190] Snapshot the paint tool's Properties tabs, the mask Grayscale tab and the right-click popup --- crates/ui-egui/tests/ui_snapshots.rs | 96 ++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index d78b23db..9d7c7a32 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3204,3 +3204,99 @@ fn sheet_scroll_end_snapshots() { harness.run_steps(30); save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); } + +/// The paint tool's Properties: the Brush tab with every section open and scrolled down, the Alpha and Material tabs, a stencil on the Projection tool, a mask's Grayscale tab, the right-click popup, and the Clone and Eraser tools' tabs; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn paint_tool_properties_snapshots() { + use egui::{Event, Modifiers, PointerButton}; + use serde_json::json; + use texturecraft_engine::execute; + use texturecraft_ui_egui::state::PropsTab; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let stripes = image::RgbaImage::from_fn(64, 64, |x, _| { + let value = if (x / 8) % 2 == 0 { 230 } else { 40 }; + image::Rgba([value, value, value, 255]) + }); + let mut bytes = Vec::new(); + stripes.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let image = session.import_resource_bytes("stripes.png", bytes).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "paint"})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.set_render_cursor(false); + harness.run_steps(6); + save(&mut harness, &output_dir, "paint-brush"); + + // The top bar has a Lazy mouse button too: Properties is the rightmost + let in_properties = |harness: &Harness<'_, TextureCraftApp>, label: &str| { + harness.get_all_by_label(label).map(|node| node.rect().center()).max_by(|a, b| a.x.total_cmp(&b.x)).unwrap() + }; + for header in ["Angle", "Jitters", "Alignment and culling", "Particles", "Lazy mouse"] { + harness.get_all_by_label(header).max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); + harness.run_steps(3); + let at = in_properties(&harness, header); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + } + harness.get_by_label_contains("Brush presets").scroll_to_me(); + harness.run_steps(3); + save(&mut harness, &output_dir, "paint-brush-open"); + harness.get_all_by_label("Lazy mouse").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); + harness.run_steps(6); + save(&mut harness, &output_dir, "paint-brush-scrolled"); + + let themes = std::env::var_os("TC_UI_THEMES").is_some(); + let tab = |harness: &mut Harness<'_, TextureCraftApp>, tab: PropsTab, name: &str| { + harness.state_mut().ui.props_tab = tab; + harness.run_steps(6); + save(harness, &output_dir, name); + if themes { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(harness, &output_dir, &format!("{name}-{theme}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + }; + tab(&mut harness, PropsTab::Brush, "paint-brush-top"); + tab(&mut harness, PropsTab::Alpha, "paint-alpha"); + tab(&mut harness, PropsTab::Material, "paint-material"); + + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "eraser"})).unwrap(); + tab(&mut harness, PropsTab::Material, "eraser-material"); + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "clone"})).unwrap(); + tab(&mut harness, PropsTab::Brush, "clone-brush"); + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "projection"})).unwrap(); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": image})).unwrap(); + tab(&mut harness, PropsTab::Brush, "projection-stencil"); + + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "paint"})).unwrap(); + let layer = harness.state().session.selected_layer().map(|id| id.0); + execute(&mut harness.state_mut().session, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap(); + tab(&mut harness, PropsTab::Material, "mask-grayscale"); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": "content"})).unwrap(); + + harness.state_mut().ui.props_tab = PropsTab::Brush; + harness.run_steps(4); + let at = harness.state().viewport_rect.center() - egui::vec2(150.0, 250.0); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + harness.run_steps(6); + save(&mut harness, &output_dir, "paint-popup"); +} From 06614b74e0431528a5ff12f7ff046e7df2aa05b1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:36:51 +0700 Subject: [PATCH 070/190] Export: the long-filename tree test looks up the set by its disclosure-triangle role 948f6446 made a texture set's folding header report itself as a DisclosureTriangle, as CollapsingHeader does. The tree-node test was updated to match; long_filenames_leave_the_export_details_reachable_by_scrolling still queried Role::Button and failed on Ubuntu (run 45798885802). --- crates/ui-egui/tests/it/export_progress.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 06d3f913..8a756d8a 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -174,9 +174,9 @@ fn long_filenames_leave_the_export_details_reachable_by_scrolling() { }) }; assert!(!bits_fit(&h), "the bit-depth column starts beyond the viewport"); - h.get_by_role_and_label(egui::Role::Button, &name).focus(); + h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).focus(); h.run_steps(3); - assert!(h.get_by_role_and_label(egui::Role::Button, &name).is_focused()); + assert!(h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).is_focused()); for _ in 0..12 { h.key_press(egui::Key::ArrowRight); From ab78d69fd8d2c626cba3073bec03f54141e0d2a2 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 08:27:01 -0500 Subject: [PATCH 071/190] Make the project renamable --- crates/engine/src/project_cmds.rs | 29 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/rename_project.rs | 34 ++++++++++++++++++++++ crates/ui-egui/src/project_config.rs | 19 ++++++++++++ crates/ui-egui/src/state/project_config.rs | 2 ++ crates/ui-egui/tests/it/project_config.rs | 21 +++++++++++++ 6 files changed, 106 insertions(+) create mode 100644 crates/engine/tests/it/rename_project.rs diff --git a/crates/engine/src/project_cmds.rs b/crates/engine/src/project_cmds.rs index 33432cda..c5da6d34 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -9,6 +9,9 @@ use crate::commands::{CommandSpec, always, bad, boolp, strp, u64p}; use crate::materials::Place; use crate::{Result, Session, cmd}; +/// Longest project name, in characters; it goes into export file names. +pub const MAX_PROJECT_NAME_CHARS: usize = 128; + pub fn specs() -> Vec { vec![ cmd!( @@ -22,6 +25,15 @@ pub fn specs() -> Vec { ), cmd!("project.sample", "Open sample project", ["File"], None, "{}", always, sample), cmd!("project.inspect", "Inspect project", [], None, "{}", always, |s, _| Ok(crate::inspect::session(s))), + cmd!( + "project.rename", + "Rename project", + [], + None, + "{name: 1-128 characters without control characters} — the name `$project` stands for in export file names; the project file keeps its own name", + always, + rename + ), cmd!( "material.apply", "Add smart material", @@ -51,6 +63,23 @@ fn new(s: &mut Session, p: &Value) -> Result { Ok(crate::inspect::session(s)) } +fn rename(s: &mut Session, p: &Value) -> Result { + let name = strp(p, "name") + .map(str::trim) + .filter(|name| !name.is_empty() && name.chars().count() <= MAX_PROJECT_NAME_CHARS && !name.chars().any(char::is_control)) + .ok_or_else(|| bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters")))?; + + // The same name is not an undo step and leaves a saved project unmodified + if name != s.doc.project.name { + s.edit("Rename project", |s| { + s.doc.project.name = name.to_string(); + Ok(()) + })?; + } + + Ok(json!({ "name": name })) +} + fn material(s: &mut Session, p: &Value) -> Result { let id = strp(p, "material").ok_or_else(|| bad("material.apply", "`material` is required"))?; let l = crate::materials::apply_at(s, id, Place::from_params(p))?; diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11cfaf41..23517f4a 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -63,6 +63,7 @@ mod perf; mod polygon_fill; mod project_recovery; mod rebuilt_uv_layout; +mod rename_project; mod resources_used; mod sample; mod solo; diff --git a/crates/engine/tests/it/rename_project.rs b/crates/engine/tests/it/rename_project.rs new file mode 100644 index 00000000..5510163b --- /dev/null +++ b/crates/engine/tests/it/rename_project.rs @@ -0,0 +1,34 @@ +//! `project.rename`: the name `$project` stands for in export file names. + +use serde_json::json; +use texturecraft_engine::{Session, execute}; + +use texturecraft_engine::geom::primitives; + +#[test] +fn a_renamed_project_exports_under_its_new_name_until_undone() { + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut preset = execute(&mut session, "export.preset.get", &json!({"name": "Document channels + Normal + AO (No Alpha)"})).unwrap(); + preset["maps"][0]["file"] = json!("$project_$textureSet"); + + execute(&mut session, "project.rename", &json!({"name": " Knight final "})).unwrap(); + + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap().to_string(); + assert!(plan.contains("Knight_final_") && !plan.contains("hero_"), "{plan}"); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.name, "hero"); +} + +#[test] +fn an_unusable_or_unchanged_project_name_edits_nothing() { + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + for name in [json!(null), json!(7), json!(" "), json!("a\nb"), json!("x".repeat(129))] { + assert!(execute(&mut session, "project.rename", &json!({"name": name.clone()})).is_err(), "{name}"); + } + + execute(&mut session, "project.rename", &json!({"name": "hero"})).unwrap(); + + assert_eq!(session.doc.project.name, "hero"); + assert!(!session.modified, "nothing changed"); +} diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index a399aa4e..cb887ca1 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -8,6 +8,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use egui::{Key, Modifiers}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; +use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS; use crate::TextureCraftApp; use crate::dock::info_icon; @@ -44,6 +45,7 @@ pub(crate) fn open(app: &mut TextureCraftApp) { mesh: None, reimport: false, preserve: true, + name: None, normal_format: None, color_management: crate::project_form::ColorManagement::Legacy, confirm: false, @@ -211,6 +213,18 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add_space(12.0); ui.label(caption(tr("PROJECT SETTINGS"))); ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + let label = ui.label(tr("Project name")).id; + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, tr("The name $project stands for in export file names. The project file keeps its own name.")); + let mut name = config.name.clone().unwrap_or_else(|| project.name.clone()); + let field = egui::TextEdit::singleline(&mut name).char_limit(MAX_PROJECT_NAME_CHARS).desired_width(FIELD_WIDTH_POINTS); + if ui.add(field).labelled_by(label).changed() { + config.name = Some(name); + } + }); + }); let shown_format = config.normal_format.unwrap_or(current_normal_format); row( ui, @@ -328,6 +342,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } None => true, } + // An untouched name is left alone, even one longer than a typed name may be + && match config.name.as_deref() { + Some(name) => app.run("project.rename", json!({"name": name})).is_some(), + None => true, + } }; if !done && !cancel && open { diff --git a/crates/ui-egui/src/state/project_config.rs b/crates/ui-egui/src/state/project_config.rs index 174b0987..6c7eb95c 100644 --- a/crates/ui-egui/src/state/project_config.rs +++ b/crates/ui-egui/src/state/project_config.rs @@ -7,6 +7,8 @@ pub struct ProjectConfig { pub reimport: bool, /// Whether painted strokes follow the surface of a newly imported mesh pub preserve: bool, + /// The project name as typed, when the field was edited + pub name: Option, /// The selected normal map format when it differs from the project's pub normal_format: Option, /// Color management as chosen in the window; nothing is applied (the project stays Legacy) diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index a44c4640..700ae461 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -765,3 +765,24 @@ fn project_config_snapshots() { h.run_steps(6); h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap(); } + +#[test] +fn a_typed_project_name_applies_only_with_ok() { + let dir = temp_dir("project-name"); + let mut h = app_on_a_quad(&dir); + let before = h.state().session.doc.project.name.clone(); + + for button in ["Cancel", "OK"] { + open_window(&mut h); + in_window(&h, Role::TextInput, "Project name").focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + in_window(&h, Role::TextInput, "Project name").type_text("Knight"); + h.run_steps(2); + click_in_window(&mut h, Role::Button, button); + + let expected = if button == "OK" { "Knight" } else { before.as_str() }; + assert_eq!(h.state().session.doc.project.name, expected, "after {button}"); + assert!(!window_is_open(&h), "{button} closes the window"); + } +} From 3e879cbc0d96658dcadd3d77c469c6c400f1f08e Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:46:39 +0000 Subject: [PATCH 072/190] Apply review fixes - crates/render/src/headless.rs - docs/control-protocol.md --- crates/render/src/headless.rs | 5 +++-- docs/control-protocol.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index 225b6f9b..5babad0a 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -10,7 +10,7 @@ pub struct Headless { } /// The adapter for work without a window (renders, path tracing, GPU baking). Like the desktop app, -/// it honours `WGPU_ADAPTER_NAME` (part of the adapter's name, any case) and `WGPU_POWER_PREF` +/// it honours `WGPU_ADAPTER_NAME` (part of the adapter's name or backend, any case) and `WGPU_POWER_PREF` /// (`high`, the default, `low` or `none`); the instance reads wgpu's other variables /// (`WGPU_BACKEND`, `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER`, ...). pub fn adapter() -> Result { @@ -37,7 +37,7 @@ fn pick_adapter(infos: &[wgpu::AdapterInfo], name: &str, power: wgpu::PowerPrefe infos .iter() .enumerate() - .filter(|(_, info)| info.name.to_lowercase().contains(&wanted)) + .filter(|(_, info)| info.name.to_lowercase().contains(&wanted) || format!("{:?}", info.backend).to_lowercase().contains(&wanted)) .min_by_key(|(index, info)| { let lower = info.name.to_lowercase(); let software = info.device_type == DeviceType::Cpu || ["llvmpipe", "lavapipe", "warp"].iter().any(|s| lower.contains(s)); @@ -126,6 +126,7 @@ mod tests { assert_eq!(pick_adapter(&gpus, "INTEL", P::None), Some(0)); assert_eq!(pick_adapter(&gpus, "", P::HighPerformance), Some(1)); assert_eq!(pick_adapter(&gpus, "llvm", P::HighPerformance), Some(2)); + assert_eq!(pick_adapter(&gpus, "gl", P::HighPerformance), Some(2)); assert_eq!(pick_adapter(&gpus, "nvidia", P::HighPerformance), None); // One GPU on two backends: the native one before OpenGL. let twice = [info("D3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Gl), info("Microsoft Direct3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Vulkan)]; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 77555785..179e8756 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -334,5 +334,5 @@ steps or an object with an optional input and output (paths relative to the curr Errors print `texturecraft-cli : error: …` and exit 1; usage errors exit 2. The CLI is a console program and never opens a window; `render` needs a GPU or software adapter, unless it path traces (`--samples`). Like the desktop app, it takes the high-performance GPU; `WGPU_ADAPTER_NAME` -(part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low` or `none`) picks another. +(part of the adapter's name or backend) or `WGPU_POWER_PREF` (`high`, `low` or `none`) picks another. `WGPU_BACKEND` narrows the list first, so a name on a backend it leaves out matches nothing. From c7a896d0789dd8f6654dbac39bd163678374e264 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 26 Nov 2026 21:01:46 +0100 Subject: [PATCH 073/190] Resources Updater tests: install the headless framework runtime in their harnesses Main's ui-contract runtime panics when a harness does not set it up; the notice unit test and the integration tests now use framework::install_headless like main's harness tests. --- crates/ui-egui/src/resources_updater.rs | 2 +- crates/ui-egui/tests/it/resources_updater.rs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 21cf648b..75b5a8fc 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -386,7 +386,7 @@ mod tests { let path = dir.path().join("notice.png"); write_png(&path, 4); let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); - let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); let app = harness.state_mut(); let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 20609aec..27209132 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -17,7 +17,10 @@ use super::temp_dir::TempDir; fn app() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); From f2205d559188c4cc43d6d1c0af16897840ddc6e3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 26 Nov 2026 21:18:37 +0100 Subject: [PATCH 074/190] Resources Updater: list linked MaterialCraft materials as rows without a file resource.status gains the status material for the package of every linked MaterialCraft material (fill layers and material effects); such a row cannot be updated or relinked from disk, and its status tooltip says it updates when MaterialCraft cooks it again. Tests also check that an environment map and a brush alpha are tracked like other images. --- crates/engine/src/resource_status.rs | 12 +++++++--- crates/engine/src/resource_update_cmds.rs | 25 +++++++++++++++++++- crates/engine/tests/it/resource_updater.rs | 24 ++++++++++++++++--- crates/ui-egui/src/resources_updater.rs | 16 +++++++++---- crates/ui-egui/tests/it/resources_updater.rs | 15 +++++++++++- docs/control-protocol.md | 2 +- 6 files changed, 80 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/resource_status.rs b/crates/engine/src/resource_status.rs index 8e8efc70..b2ae9961 100644 --- a/crates/engine/src/resource_status.rs +++ b/crates/engine/src/resource_status.rs @@ -1,6 +1,6 @@ -//! Whether an image resource still matches the file it was imported from +//! Whether a resource still matches the file it was imported from -/// How an image resource compares with its file on disk. The order is the Resources Updater's +/// How a resource compares with its file on disk (materials have none). The order is the Resources Updater's /// list order: what needs attention first. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ResourceStatus { @@ -12,10 +12,14 @@ pub enum ResourceStatus { UpToDate, /// Made in the app or imported without a file path: there is nothing to compare with. NoSource, + /// A linked MaterialCraft material's package: it has no file to compare with and updates by + /// cooking it again (`material.link.cook`). + Material, } impl ResourceStatus { - pub const ALL: [ResourceStatus; 4] = [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource]; + pub const ALL: [ResourceStatus; 5] = + [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource, ResourceStatus::Material]; /// The id used by the control protocol pub fn id(self) -> &'static str { @@ -24,6 +28,7 @@ impl ResourceStatus { ResourceStatus::Missing => "missing", ResourceStatus::UpToDate => "upToDate", ResourceStatus::NoSource => "noSource", + ResourceStatus::Material => "material", } } @@ -34,6 +39,7 @@ impl ResourceStatus { ResourceStatus::Missing => "Missing", ResourceStatus::UpToDate => "Up to date", ResourceStatus::NoSource => "No source file", + ResourceStatus::Material => "Material", } } } diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs index 0fc56e7d..665516e3 100644 --- a/crates/engine/src/resource_update_cmds.rs +++ b/crates/engine/src/resource_update_cmds.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Check resources on disk", [], None, - "{} → {resources: [{name, status: outdated|missing|upToDate|noSource, path?, error?}] (outdated first), total, outdated}", + "{} → {resources: [{name, status: outdated|missing|upToDate|noSource|material, path?, error?}] (outdated first; material: a linked MaterialCraft package, updated by material.link.cook), total, outdated}", always, |s, _| Ok(status(s)) ), @@ -49,10 +49,33 @@ impl Session { /// not, and that verdict is kept until the file's size or time changes again. pub fn resource_states(&mut self) -> Vec { let mut states = self.compare_resources(); + let materials = self.material_packages().into_iter(); + states.extend(materials.map(|name| ResourceState { name, status: ResourceStatus::Material, path: None, error: None })); states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); states } + /// The packages of linked MaterialCraft materials (fill layers and material effects) the project holds + fn material_packages(&self) -> std::collections::BTreeSet { + use texturecraft_core::{EffectKind, Fill, LayerKind}; + + let package_of = |fill: &Fill| fill.link.as_ref().map(|link| link.package.clone()); + let mut packages = std::collections::BTreeSet::new(); + for layer in self.doc.project.layers.values() { + if let LayerKind::Fill(fill) = &layer.kind { + packages.extend(package_of(fill)); + } + for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + if let EffectKind::Material(fill) = &effect.kind { + packages.extend(package_of(fill)); + } + } + } + + packages.retain(|name| self.doc.resources.contains_key(name)); + packages + } + /// Whether `name` is an image resource the Resources Updater lists fn is_image_resource(&self, name: &str) -> bool { self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name)) diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index 43a9120b..aa306838 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -102,7 +102,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() } #[test] -fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { +fn outdated_resources_come_first_then_missing_up_to_date_unlinked_and_materials() { let dir = tempfile::tempdir().unwrap(); let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name)); for file in [&fine, &gone, &changed] { @@ -114,12 +114,30 @@ fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { for file in [&fine, &gone, &changed] { import(&mut s, file); } + + // The environment map and the brush alpha are image resources like any other + let environment = format!("{}b_fine.png", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX); + execute(&mut s, "display.set", &json!({"environment": environment})).unwrap(); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "d_changed.png"}})).unwrap(); + + // A linked MaterialCraft material keeps its package as a resource without a file + s.doc.resources.insert("a_brick.mcmat".to_string(), Arc::new(b"package".to_vec())); + let layer = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let link = serde_json::from_value(json!({"name": "Brick", "package": "a_brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap(); + if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut s.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind { + fill.link = Some(link); + } + std::fs::remove_file(&gone).unwrap(); write_png(&changed, 8, GREEN); - let order: Vec = s.resource_states().into_iter().map(|state| state.name).collect(); + let states = s.resource_states(); + let order: Vec<&str> = states.iter().map(|state| state.name.as_str()).collect(); + let statuses: Vec<&str> = states.iter().map(|state| state.status.id()).collect(); - assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png"], "by status first, against the name order"); + assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png", "a_brick.mcmat"], "by status first, against the name order"); + assert_eq!(statuses, ["outdated", "missing", "upToDate", "noSource", "material"], "the alpha's and the environment's files are checked too"); + assert!(execute(&mut s, "resource.update", &json!({"names": ["a_brick.mcmat"]})).is_err(), "a material has no file to read again"); } #[test] diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 75b5a8fc..5cf20018 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -329,11 +329,15 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: request = Some(RowRequest::Update(row.name.clone())); } - let select = ui.button(tr("Select new resource")); - let select_name = format!("{} {}", tr("Select new resource"), row.name); - select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); - if select.clicked() { - request = Some(RowRequest::SelectNew(row.name.clone())); + // A material is no image file, so it cannot point at one + let material = row.status == ResourceStatus::Material; + if !material { + let select = ui.button(tr("Select new resource")); + let select_name = format!("{} {}", tr("Select new resource"), row.name); + select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); + if select.clicked() { + request = Some(RowRequest::SelectNew(row.name.clone())); + } } if let Some(path) = &row.path { @@ -353,6 +357,8 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: let status = ui.label(tr(row.status.label())); if let Some(error) = &row.error { status.on_hover_text(error); + } else if material { + status.on_hover_text(tr("A MaterialCraft material has no file on disk: it updates when MaterialCraft cooks it again")); } }); }); diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 27209132..050fedb4 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -130,11 +130,21 @@ fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_l } #[test] -fn show_in_folder_shows_the_folder_of_the_resource_file() { +fn show_in_folder_shows_the_folder_of_the_resource_file_and_materials_have_no_file() { let dir = TempDir::new("resources-updater-folder"); let file = png(&dir, "bricks.png", 4); let mut h = app(); import(&mut h, &file); + + // A linked MaterialCraft material keeps its package as a resource without a file + let layer = h.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + let session = &mut h.state_mut().session; + session.doc.resources.insert("brick.mcmat".to_string(), std::sync::Arc::new(b"package".to_vec())); + let link = serde_json::from_value(json!({"name": "Brick", "package": "brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap(); + if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut session.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind + { + fill.link = Some(link); + } activate(&mut h, "Resources Updater"); activate(&mut h, "Show in folder bricks.png"); @@ -142,6 +152,9 @@ fn show_in_folder_shows_the_folder_of_the_resource_file() { let shown = h.state().file_dialogs.shown_folders().to_vec(); assert_eq!(shown.len(), 1); assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); + assert!(shows(&h, "Name : brick.mcmat"), "the material is listed"); + assert!(h.query_by_label("Select new resource brick.mcmat").is_none(), "a material cannot point at an image file"); + assert!(h.query_by_label("Show in folder brick.mcmat").is_none(), "it has no file"); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3db7a106..4bc4d42f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -506,7 +506,7 @@ read once; its verdict is kept until its size or time changes again. | Command | Params and result | |---|---| -| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | +| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate`, `noSource` (made in the app or imported without a path) or `material` (the package of a linked MaterialCraft material: it has no file and updates with `material.link.cook`); outdated first, then by name. A file is read only when its size matches but its modification time does not | | `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | | `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | From ed5bb4ed697a72c8333209f0826d7488d7aa9ba9 Mon Sep 17 00:00:00 2001 From: supersfera Date: Thu, 26 Nov 2026 12:58:03 -0800 Subject: [PATCH 075/190] ru: remove the per-file translation notices The translation is under the repository's licence, and authorship is in git history. --- packaging/linux/ai.storyteller.texturecraft.desktop | 1 - packaging/linux/ai.storyteller.texturecraft.mime.xml | 1 - 2 files changed, 2 deletions(-) diff --git a/packaging/linux/ai.storyteller.texturecraft.desktop b/packaging/linux/ai.storyteller.texturecraft.desktop index e1cb409a..07ebda06 100644 --- a/packaging/linux/ai.storyteller.texturecraft.desktop +++ b/packaging/linux/ai.storyteller.texturecraft.desktop @@ -1,4 +1,3 @@ -# Russian translation © 2026 SuperSfera LLC, MIT OR Apache-2.0 [Desktop Entry] Type=Application Name=TextureCraft diff --git a/packaging/linux/ai.storyteller.texturecraft.mime.xml b/packaging/linux/ai.storyteller.texturecraft.mime.xml index 2b1b811e..cb7c1b99 100644 --- a/packaging/linux/ai.storyteller.texturecraft.mime.xml +++ b/packaging/linux/ai.storyteller.texturecraft.mime.xml @@ -1,5 +1,4 @@ - From c54e1eb75eed104d6bb7c9db42e31705ee2c18c1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 26 Nov 2026 21:58:59 +0100 Subject: [PATCH 076/190] Xwayland for the pen only when its X server answers; hand the chosen backend to the title bar and UI runtime A DISPLAY left over from another session could force X11 with no X server to connect to, and winit can't fall back to Wayland then. The title bar decision and the UI runtime read the backend from the environment and saw Wayland while the window opened on Xwayland. --- Cargo.lock | 1 + apps/texturecraft/Cargo.toml | 2 ++ apps/texturecraft/src/main.rs | 13 +++++++---- apps/texturecraft/src/xwayland_pen.rs | 31 ++++++++++++++++++++++----- crates/ui-egui/src/framework.rs | 6 +++--- crates/ui-egui/src/titlebar.rs | 6 +++--- 6 files changed, 44 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index acafef1d..a80cac9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5819,6 +5819,7 @@ dependencies = [ name = "texturecraft" version = "0.6.1" dependencies = [ + "craft-host", "craft-image-codecs", "craft-menu", "craft-update", diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 39fb3c7c..52626627 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -23,6 +23,8 @@ serde_json = { workspace = true } log = { workspace = true } # The message box for errors that end the app (a Windows release build has no console). rfd = { workspace = true } +# The window's backend (Xwayland for a pen, src/xwayland_pen.rs) for the title bar and the UI runtime. +craft-host = { workspace = true } # Reads the saved System title bar setting before the window opens (eframe's settings format). ron = "0.12" diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index d0c26efc..04d3b23a 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -395,7 +395,13 @@ fn main() { prefs.apply_work_threads(); prefs.apply_resource_limits(); let session = initial_session(&args); - let frame_decision = TitleBar::decide(prefs.system_title_bar); + // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; a pen works only through Xwayland there + #[cfg(target_os = "linux")] + let pen_needs_x11 = xwayland_pen::opens_through_xwayland(); + #[cfg(not(target_os = "linux"))] + let pen_needs_x11 = false; + let backend = if pen_needs_x11 { craft_host::target::Backend::X11 } else { craft_host::target::Backend::from_env() }; + let frame_decision = TitleBar::decide(prefs.system_title_bar, backend); let title_bar = TitleBar::of(&frame_decision.frame); let mut viewport = egui::ViewportBuilder::default() .with_app_id(os_window::app_id()) @@ -407,9 +413,8 @@ fn main() { } let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport); let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; - // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; a pen works only through Xwayland there #[cfg(target_os = "linux")] - if xwayland_pen::opens_through_xwayland() { + if pen_needs_x11 { use winit::platform::x11::EventLoopBuilderExtX11 as _; options.event_loop_builder = Some(Box::new(|builder| { builder.with_x11(); @@ -460,7 +465,7 @@ fn main() { if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) { log::warn!("the app menu could not be installed: {e}"); } - texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?; + texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision, backend)?; let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; diff --git a/apps/texturecraft/src/xwayland_pen.rs b/apps/texturecraft/src/xwayland_pen.rs index 6c3f7d3a..10d44314 100644 --- a/apps/texturecraft/src/xwayland_pen.rs +++ b/apps/texturecraft/src/xwayland_pen.rs @@ -31,11 +31,13 @@ const X11_LIBRARIES: &[&str] = &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; /// Whether the window opens through Xwayland: a pen is attached on a Wayland desktop and Xwayland -/// can run the window. Says so on stderr when it does. +/// can run the window (the X11 libraries are installed and the X server answers). Says so on +/// stderr when it does. pub fn opens_through_xwayland() -> bool { let var = |name: &str| std::env::var(name).ok(); let pen = || std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)); - if !pen_needs_xwayland(var, pen, x11_libraries_available) { + let xwayland_ready = || x11_libraries_available() && var("DISPLAY").is_some_and(|display| x_server_answers(&display)); + if !pen_needs_xwayland(var, pen, xwayland_ready) { return false; } @@ -45,11 +47,29 @@ pub fn opens_through_xwayland() -> bool { /// [`opens_through_xwayland`]'s decision. winit picks Wayland when `WAYLAND_DISPLAY` or /// `WAYLAND_SOCKET` is set; Xwayland needs `DISPLAY`. The system probes run only on Wayland. -fn pen_needs_xwayland(var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool, x11_libraries: impl FnOnce() -> bool) -> bool { +fn pen_needs_xwayland(var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool, xwayland_ready: impl FnOnce() -> bool) -> bool { let set = |name: &str| var(name).is_some_and(|value| !value.is_empty()); let wayland = set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET"); let keeps_wayland = var(NATIVE_WAYLAND_VARIABLE).is_some_and(|value| !value.is_empty() && value != "0"); - wayland && !keeps_wayland && set("DISPLAY") && pen() && x11_libraries() + wayland && !keeps_wayland && set("DISPLAY") && pen() && xwayland_ready() +} + +/// Does the X server `display` names accept a connection? winit can't fall back to Wayland once +/// X11 is chosen, so a `DISPLAY` left over from another session must keep the window on Wayland. +/// Only a local display is tried, by its socket path or the abstract socket of the same name. +fn x_server_answers(display: &str) -> bool { + use std::os::linux::net::SocketAddrExt as _; + use std::os::unix::net::{SocketAddr, UnixStream}; + + let Some(socket) = local_x_socket(display) else { return false }; + UnixStream::connect(&socket).is_ok() || SocketAddr::from_abstract_name(socket.as_bytes()).and_then(|address| UnixStream::connect_addr(&address)).is_ok() +} + +/// The socket of a local X display (`:0`, `:0.0`, `unix:0`); `None` for a remote one +fn local_x_socket(display: &str) -> Option { + let number = display.strip_prefix(':').or_else(|| display.strip_prefix("unix:"))?; + let number: u32 = number.split('.').next()?.parse().ok()?; + Some(format!("/tmp/.X11-unix/X{number}")) } /// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen's `B: KEY=` bitmap has @@ -141,10 +161,11 @@ mod tests { assert!(pen_needs_xwayland(env(WAYLAND), || true, || true)); assert!(!pen_needs_xwayland(env(WAYLAND), || false, || true), "no pen"); - assert!(!pen_needs_xwayland(env(WAYLAND), || true, || false), "no X11 libraries"); + assert!(!pen_needs_xwayland(env(WAYLAND), || true, || false), "Xwayland can't run the window"); assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0")]), || true, || true), "no Xwayland"); assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "1")]), || true, || true), "kept"); assert!(pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "0")]), || true, || true)); assert!(!pen_needs_xwayland(env(&[("DISPLAY", ":0")]), || panic!("probed off Wayland"), || panic!("probed off Wayland")), "X11 already has the pen"); + assert_eq!([":1.0", "unix:0", "remote:0"].map(local_x_socket), [Some("/tmp/.X11-unix/X1".into()), Some("/tmp/.X11-unix/X0".into()), None]); } } diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs index 187d0de6..f617d398 100644 --- a/crates/ui-egui/src/framework.rs +++ b/crates/ui-egui/src/framework.rs @@ -52,10 +52,10 @@ fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc Result<(), String> { - let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env()); +pub fn install(ctx: &egui::Context, frame: Decision, backend: craft_host::target::Backend) -> Result<(), String> { + let shell = ShellInfo::default().backend(backend); install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows), Some(frame)) } diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index 024675b1..5817e7a8 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -68,12 +68,12 @@ const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [ impl TitleBar { /// Decide who draws the title bar; call once at startup, before the window is created, and /// hand the decision to the window ([`viewport`]) and the runtime (`framework::install`). - /// `system` is Settings › Interface › System title bar. - pub fn decide(system: bool) -> Decision { + /// `system` is Settings › Interface › System title bar; `backend` is the one the window opens on. + pub fn decide(system: bool, backend: craft_host::target::Backend) -> Decision { let choice = craft_window::Choice::probe(PREFIX); let wanted = Self::from_choice(choice.frame(), choice.overridden(), system); let pref = if wanted == TitleBar::System { TitleBarPref::System } else { TitleBarPref::Integrated }; - craft_window::policy::decide_for(PREFIX, craft_host::target::Backend::from_env(), pref) + craft_window::policy::decide_for(PREFIX, backend, pref) } /// The bar a decided `frame` gives. From fd54b7819a7da1649d161d1cf9ed795633e7655f Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:29:47 +0000 Subject: [PATCH 077/190] Apply review fixes - crates/engine/tests/session.rs --- crates/engine/tests/session.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 87d0cb34..28a51a8f 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -536,8 +536,7 @@ fn a_panic_inside_an_edit_restores_the_document() { assert_eq!(s.history_labels(), history, "no undo step was recorded"); } -/// A command that fails leaves the document and history as they were (AGENTS rule 5: commands -/// are atomic). +/// A command that fails leaves the document and history as they were (commands are atomic). #[test] fn failed_commands_leave_the_document_unchanged() { let hostile = [ @@ -554,7 +553,10 @@ fn failed_commands_leave_the_document_unchanged() { continue; // slow (bakes); covered elsewhere } for p in &hostile { - let mut s = session(); + let mut s = session_at(MIN_RESOLUTION); + for texture_set in &mut s.doc.project.texture_sets { + texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R64; + } let (before, history) = (s.doc.clone(), s.history_labels()); if execute(&mut s, spec.id, p).is_err() && (!same_document(&s.doc, &before) || s.history_labels() != history) { offenders.push(format!("{} {p}", spec.id)); From e237eae4cb51f93509316f7e3558d09d1893ab06 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:50:15 +0000 Subject: [PATCH 078/190] Texture set normal mixing: set it by command, and Replace keeps height out of the viewport normal textureSet.settings takes normalMixing (combine or replace) as one undo step and textureSet.inspect reports it. Replace already left the height slope out of exported normals; the viewport, the normal view and both path tracers now follow it too, while height still displaces. Projects without the field stay Combine. --- crates/automation/src/render.rs | 8 ++++++- crates/core/src/project.rs | 5 ++++ crates/engine/src/inspect.rs | 4 ++++ crates/engine/src/set_cmds.rs | 36 +++++++++++++++++++++++++++-- crates/formats/src/export/mod.rs | 4 ++-- crates/render/src/displace.rs | 2 +- crates/render/src/gpu_trace.rs | 6 ++--- crates/render/src/renderer.rs | 5 +++- crates/render/src/shaders/mesh.wgsl | 6 ++--- crates/render/src/trace.rs | 13 +++++++++-- crates/ui-egui/src/render_mode.rs | 9 ++++++-- crates/ui-egui/src/viewport.rs | 5 +++- 12 files changed, 85 insertions(+), 18 deletions(-) diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index c12ce621..024e183a 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -162,7 +162,12 @@ fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) { .texture_sets .iter() .zip(&s.caches) - .map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() }) + .map(|(ts, c)| TraceSet { + material: ts.material, + composite: c.composite.clone(), + height_strength: ts.atlas_height_strength(), + height_in_normal: ts.height_in_normal(), + }) .collect(); let d = &s.doc.project.display; let env_image = d.environment_resource().and_then(|n| s.images.get(n)); @@ -199,6 +204,7 @@ pub fn shade(s: &Session) -> Shade { }; Shade { height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0), + height_in_normal: s.doc.project.texture_sets.get(s.ts()).is_none_or(|t| t.height_in_normal()), view_mode, channel, // Only the 2D view uses this default diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 4212d787..b0d8d846 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -193,6 +193,11 @@ impl TextureSet { self.height_strength / self.tile_grid().map_or(1.0, |g| g.cols as f32) } + /// Whether the height slope joins the shaded normal ([`NormalMixing::Replace`] leaves it out) + pub fn height_in_normal(&self) -> bool { + self.normal_mixing == NormalMixing::Combine + } + /// Texels across and down: [`TextureSet::block_resolution`] per block of the atlas grid. pub fn size(&self) -> (u32, u32) { let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 14863420..421aec82 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -274,6 +274,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), "visible": texture_set.visible, + "normalMixing": match texture_set.normal_mixing { + texturecraft_core::NormalMixing::Combine => "combine", + texturecraft_core::NormalMixing::Replace => "replace", + }, "active": index == session.ts(), }) } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 2251a182..5fa7fd49 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -1,7 +1,7 @@ //! Texture set commands (Texture Set List / Texture Set Settings). use serde_json::{Value, json}; -use texturecraft_core::{Channel, ChannelBlend, ChannelFormat}; +use texturecraft_core::{Channel, ChannelBlend, ChannelFormat, NormalMixing}; use std::sync::Arc; @@ -38,7 +38,15 @@ pub fn specs() -> Vec { visibility ), cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename), - cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings), + cmd!( + "textureSet.settings", + "Texture set settings", + [], + None, + "{ts?, description?, heightStrength?, normalMixing?: combine|replace, normalFormat?: openGl|directX}", + always, + settings + ), cmd!( "textureSet.parts", "List mesh parts", @@ -281,6 +289,12 @@ fn rename(s: &mut Session, p: &Value) -> Result { fn settings(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.settings")?; let nf = normal_format_param("textureSet.settings", p)?; + let normal_mixing = match strp(p, "normalMixing") { + None => None, + Some("combine") => Some(NormalMixing::Combine), + Some("replace") => Some(NormalMixing::Replace), + Some(other) => return Err(bad("textureSet.settings", format!("unknown normal mixing {other:?} (combine or replace)"))), + }; s.edit("Texture set settings", |s| { if let Some(n) = nf { s.doc.project.normal_format = n; @@ -292,6 +306,9 @@ fn settings(s: &mut Session, p: &Value) -> Result { if let Some(h) = f32p(p, "heightStrength") { set.height_strength = h.clamp(0.0, 100.0); } + if let Some(mixing) = normal_mixing { + set.normal_mixing = mixing; + } Ok(()) })?; Ok(Value::Null) @@ -314,4 +331,19 @@ mod tests { assert_eq!(run(json!({"mode": "showAll"})).unwrap(), json!([true, true])); assert!(run(json!({"mode": "sideways"})).is_err() && run(json!({"mode": "solo", "ts": 9})).is_err()); } + + #[test] + fn normal_mixing_replace_keeps_height_out_of_the_normal_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mixing = |s: &Session| crate::inspect::texture_set(s, 0)["normalMixing"].clone(); + assert_eq!(mixing(&s), json!("combine")); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "normalMixing": "replace"})).unwrap(); + assert_eq!(mixing(&s), json!("replace")); + assert!(!s.doc.project.texture_sets[0].height_in_normal() && s.doc.project.texture_sets[1].height_in_normal()); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"normalMixing": "blend"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(mixing(&s), json!("combine")); + } } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f2134a0c..17086f28 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -19,7 +19,7 @@ use craft_image_codecs::{ChannelLayout, EncodeOptions, Format as CodecFormat, Im use rayon::prelude::*; use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; -use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; +use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, Project, TextureSet}; use texturecraft_geom::glam::Vec3; use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; @@ -826,7 +826,7 @@ impl Sampler<'_> { let At::Texel(x, y) = at else { return Vec3::Z }; let base = if self.set.baked.contains(&BakedMap::Normal) { unpack(self.baked(BakedMap::Normal, at)) } else { Vec3::Z }; let mut detail = if self.set.has_channel(Channel::Normal) { unpack(self.channel(Channel::Normal, at)) } else { Vec3::Z }; - if self.set.normal_mixing == NormalMixing::Combine && self.set.has_channel(Channel::Height) && self.set.height_strength != 0.0 { + if self.set.height_in_normal() && self.set.has_channel(Channel::Height) && self.set.height_strength != 0.0 { detail = rnm(self.height_normal(x, y), detail); } rnm(base, detail) diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index f2e2b19a..1ebed5dc 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -141,7 +141,7 @@ mod tests { img.tile_mut(x, y, &[texturecraft_texel::to_u16_signed(height)]); } } - TraceSet { material: 0, composite, height_strength: strength } + TraceSet { material: 0, composite, height_strength: strength, height_in_normal: true } } #[test] diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 5b04af34..5778d88a 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -416,7 +416,7 @@ impl GpuTracer { sigma: scene.scatter_sigma, rotation: scene.env_rotation, env_camera: scene.env_camera, - heights: scene.sets.iter().map(|s| s.height_strength).collect(), + heights: scene.sets.iter().map(crate::trace::TraceSet::normal_height_strength).collect(), ior: scene.ior, lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]), }); @@ -826,7 +826,7 @@ mod tests { } let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); - TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0) + TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], Arc::new(env), 0.0) } fn gpu() -> Option<(Headless, GpuTracer)> { @@ -1006,7 +1006,7 @@ mod tests { let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); let env = crate::ibl::environment("Studio Contrast", 256); - let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0); + let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], Arc::new(env), 0.0); let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false, background: crate::DEFAULT_BACKGROUND }; let settings = TraceSettings { bounces: 4 }; let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap(); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 0fd677bf..fea99716 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -157,6 +157,8 @@ pub struct Shade { pub env_opacity: f32, pub ao_intensity: f32, pub height_strength: f32, + /// The height slope joins the shaded normal (normal mixing Combine; Replace leaves it out) + pub height_in_normal: bool, /// -1 for DirectX normal maps in the normal channel, 1 for OpenGL. pub normal_y: f32, /// 0 material, 1 channel, 2 mesh map (aux texture), 3 UV checker. @@ -295,6 +297,7 @@ impl Default for Shade { env_opacity: 0.0, ao_intensity: 0.75, height_strength: 1.0, + height_in_normal: true, normal_y: 1.0, view_mode: 0, channel: 0, @@ -2130,7 +2133,7 @@ impl Renderer { material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, s.ior], scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }], fwd: [fwd.x, fwd.y, fwd.z, 0.0], - disp, + disp: [disp[0], disp[1], disp[2], if s.height_in_normal { 1.0 } else { 0.0 }], refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data), highlight_shift: highlight_shift(frame.size), diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 8e82daa9..1c6a08ba 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -22,7 +22,7 @@ struct Globals { material: vec4, // x specular/glossiness shading (1), y parallax occlusion (1), z accumulation sample index, w IOR of transmission scatter: vec4, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w G-buffer holds the scattering light (1) fwd: vec4, // xyz camera view direction (unit), w - - disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w - + disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w height slope in the shaded normal (1) or not (0) refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - @@ -483,7 +483,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { // Match export: a unit height over 1/16 of the width tilts 45° // Combine the height gradient with the tangent-space normal - let k = g.mode.z * dims.x / 16.0 * tile_scale(uv); + let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(uv); let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); // The Normal texture holds the signed normal in half floats (flat is exactly +z) @@ -728,7 +728,7 @@ fn fs_uv(i: VOut) -> @location(0) vec4 { let hr = textureSample(t_height, samp, i.uv + vec2(ts.x, 0.0)).r; let hu = textureSample(t_height, samp, i.uv - vec2(0.0, ts.y)).r; let hd = textureSample(t_height, samp, i.uv + vec2(0.0, ts.y)).r; - let k = g.mode.z * dims.x / 16.0 * tile_scale(i.uv); + let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(i.uv); let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); var n_detail = clamp(textureSample(t_nrm, samp, i.uv).rgb, vec3(-1.0), vec3(1.0)); n_detail.y *= g.mode.w; diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 034330b0..01e973d7 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -35,7 +35,16 @@ pub struct TraceSet { /// Mesh material the set covers. pub material: usize, pub composite: Composite, + /// Height displacement and, with `height_in_normal`, height-to-normal strength pub height_strength: f32, + pub height_in_normal: bool, +} + +impl TraceSet { + /// The strength of the height slope in the shaded normal (0 when normal mixing replaces it) + pub fn normal_height_strength(&self) -> f32 { + if self.height_in_normal { self.height_strength } else { 0.0 } + } } /// Everything a pass reads (cheap to clone: shared or copy-on-write data). @@ -575,7 +584,7 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 // A UV tile smaller than its atlas block has fewer texels per UV unit: slopes per texel shrink. let k = set.map_or(0.0, |s| { let (x, y) = texel(s, 0, 0); - s.height_strength * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) + s.normal_height_strength() * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) }); let n_height = if k != 0.0 { let h = |dx, dy| ch(Channel::Height, dx, dy)[0]; @@ -1233,7 +1242,7 @@ mod tests { } } } - TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], env, 0.0) + TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], env, 0.0) } /// Mean radiance of parallel rays over the whole disc of the sphere (grazing hits included) diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 7fa38fe1..56dbe6af 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -268,7 +268,12 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { .texture_sets .iter() .zip(&session.caches) - .map(|(set, cache)| TraceSet { material: set.material, composite: cache.composite.clone(), height_strength: set.atlas_height_strength() }) + .map(|(set, cache)| TraceSet { + material: set.material, + composite: cache.composite.clone(), + height_strength: set.atlas_height_strength(), + height_in_normal: set.height_in_normal(), + }) .collect(); let env_image = display.environment_resource().and_then(|n| session.images.get(n)); @@ -327,7 +332,7 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work { /// revisions bump with every composited chunk, so while textures load this changes every frame). fn scene_key(session: &texturecraft_engine::Session, composites: bool) -> String { let revisions: Vec = if composites { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() }; - let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength())).collect(); + let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength(), set.height_in_normal())).collect(); let display = &session.doc.project.display; let env_image = display.environment_resource().and_then(|name| session.images.get(name)).map(Arc::as_ptr); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4c1fe3c7..30922d2f 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -381,12 +381,15 @@ fn shade(app: &TextureCraftApp) -> Shade { ViewMode::NormalHeightMesh => (VIEW_MODE_NORMAL_HEIGHT_MESH, 0), }; let set_index = app.session.ts(); - let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + let active_set = app.session.doc.project.texture_sets.get(set_index); + let height_strength = active_set.map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + let height_in_normal = active_set.is_none_or(|texture_set| texture_set.height_in_normal()); // Polygon fill shows the polygons it fills without changing the saved wireframe toggles let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, + height_in_normal, view_mode, channel, wireframe: wireframe_shown(&app.ui, polygon_fill_tool), From 19d8ecf79c1a40a97d20c2362efbfa580a52e69d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:53:33 +0000 Subject: [PATCH 079/190] Texture set ambient occlusion mixing: set it by command, and None keeps the baked map out of the viewport textureSet.settings takes aoMixing (multiply or none) and textureSet.inspect reports it. The viewport's occlusion texture multiplied the baked ambient occlusion in whatever the setting said, while export already followed it; display tiles now take the set's mixing, and changing it (or undoing the change) resends that set's textures. --- crates/automation/src/render.rs | 4 +- crates/automation/tests/perf.rs | 3 +- crates/compose/src/display.rs | 53 ++++++++++++++--------- crates/engine/src/inspect.rs | 4 ++ crates/engine/src/session.rs | 6 +++ crates/engine/src/set_cmds.rs | 38 +++++++++++++++- crates/engine/tests/it/bake_resolution.rs | 9 ++-- crates/engine/tests/it/perf.rs | 4 +- crates/render/src/gpu_trace.rs | 20 ++++++++- crates/ui-egui/src/gpu.rs | 5 ++- 10 files changed, 112 insertions(+), 34 deletions(-) diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 024e183a..236ebc95 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -6,6 +6,7 @@ use std::sync::{Arc, Weak}; use rayon::prelude::*; use texturecraft_engine::compose::{DisplayKind, ImageRes, all_tiles, tile_bytes}; +use texturecraft_engine::core::AoMixing; use texturecraft_engine::{Session, ViewMode}; use texturecraft_render::displace::trace_geometry; use texturecraft_render::gpu_trace::GpuTracer; @@ -67,6 +68,7 @@ impl Gpu { let empty = Default::default(); let baked = session.doc.baked.get(&set_index).unwrap_or(&empty); let composite = &cache.composite; + let ao_mixing = session.doc.project.texture_sets.get(set_index).map_or(AoMixing::Multiply, |set| set.ao_mixing); // Limit live converted pixels while retaining parallel conversion within each batch const UPLOAD_TILES_PER_BATCH: usize = 64; @@ -74,7 +76,7 @@ impl Gpu { let bytes: Vec<_> = batch .par_iter() .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y))) - .map(|(kind, tile_x, tile_y)| (kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (kind, tile_x, tile_y, tile_bytes(composite, baked, ao_mixing, kind, tile_x, tile_y))) .collect(); for (kind, tile_x, tile_y, pixels) in bytes { headless.renderer.upload_tile(&headless.device, &headless.queue, set_index, kind, tile_x, tile_y, &pixels); diff --git a/crates/automation/tests/perf.rs b/crates/automation/tests/perf.rs index ef73dc98..cdd80201 100644 --- a/crates/automation/tests/perf.rs +++ b/crates/automation/tests/perf.rs @@ -57,9 +57,10 @@ fn display_all(session: &mut Session) -> usize { let tiles = session.take_uploads(texture_set); let baked = session.baked(texture_set).cloned().unwrap_or_default(); let composite = &session.caches[texture_set].composite; + let ao_mixing = session.doc.project.texture_sets[texture_set].ao_mixing; bytes += tiles .par_iter() - .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.map(|kind| tile_bytes(composite, &baked, kind, tile_x, tile_y).len())) + .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.map(|kind| tile_bytes(composite, &baked, ao_mixing, kind, tile_x, tile_y).len())) .sum::(); } diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 9fce5480..4a09573c 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -25,7 +25,7 @@ //! the extra lobes off, so the renderer can keep Lobes and Sheen as 1×1 placeholders until a //! tile with a non-default value arrives. -use texturecraft_core::{BakedMap, Channel}; +use texturecraft_core::{AoMixing, BakedMap, Channel}; use texturecraft_texel::{TILE, TILE_AREA, srgb_lut}; use crate::eval::Composite; @@ -93,7 +93,7 @@ impl DisplayKind { /// The texel of a set that has none of this texture's channels (the GPU clear value). pub fn default_texel(self) -> Vec { - let mut px = tile_bytes(&Composite::new(&[], TILE), &BakedMaps::default(), self, 0, 0); + let mut px = tile_bytes(&Composite::new(&[], TILE), &BakedMaps::default(), AoMixing::Multiply, self, 0, 0); px.truncate(self.bytes_per_texel()); px } @@ -110,8 +110,8 @@ fn u8_of(v: u16) -> u8 { (v >> 8) as u8 } -/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles. -pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { +/// Tile bytes (`TILE × TILE`, row-major) for `kind` mixing baked occlusion by `ao_mixing`, with channel defaults for absent source tiles +pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32) -> Vec { let bytes_per_texel = kind.bytes_per_texel(); let mut out = vec![0u8; TILE_AREA * bytes_per_texel]; let srgb = srgb_lut(); @@ -183,9 +183,12 @@ pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, t for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked - .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales) - .map_or(1.0, |value| value[0]); + let baked_ao = match ao_mixing { + AoMixing::Multiply => baked + .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales) + .map_or(1.0, |value| value[0]), + AoMixing::None => 1.0, + }; let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); let pixel = &mut out[i * 4..i * 4 + 4]; @@ -263,7 +266,7 @@ mod tests { } for kind in DisplayKind::ALL.into_iter().filter(|k| !kinds_for(channels).any(|n| n == *k)) { let want = kind.default_texel().repeat(TILE_AREA); - assert!(tile_bytes(&comp, &BakedMaps::default(), kind, 0, 0) == want, "{kind:?} for {channels:?}"); + assert!(tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, kind, 0, 0) == want, "{kind:?} for {channels:?}"); } } } @@ -274,7 +277,7 @@ mod tests { comp.channels.get_mut(&Channel::BaseColor).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]); comp.channels.get_mut(&Channel::Opacity).unwrap().set(0, 0, &[to_u16(0.5)]); - let b = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::BaseColor, 0, 0); + let b = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::BaseColor, 0, 0); assert_eq!(b[0], 255); assert!((b[1] as i32 - 188).abs() <= 1, "{}", b[1]); @@ -288,7 +291,7 @@ mod tests { set.uv_tiles = vec![1001, 1002]; set.tile_resolutions.insert(1002, 64); let comp = Composite { block_scales: set.block_scales(), ..Composite::new(&[], 512) }; - let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, tx, 0)[3]; + let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Extra, tx, 0)[3]; // Tile 1001 fills its block; 1002 fills a quarter, encoded as 32 × log2(4) assert_eq!((alpha(0), alpha(3), alpha(4), alpha(7)), (0, 0, 64, 64)); @@ -297,20 +300,28 @@ mod tests { #[test] fn missing_channels_fall_back_to_defaults() { let comp = Composite::new(&[], 64); - let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0); + let orm = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Orm, 0, 0); assert_eq!(&orm[..4], &[255, 128, 0, 128]); assert_eq!(normal_texel(&comp, &BakedMaps::default(), 0), [0.0, 0.0, 1.0, 0.5], "flat, sheen roughness 0.5 rides in alpha"); - assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]); - assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Lobes, 0, 0)[..4], &[0, 25, 0, 0], "lobes off, coat roughness 0.1"); - assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]); - assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, 0, 0)[..4], &[128, 128, 0, 0], "flat coat normal, no transmission"); + assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]); + assert_eq!( + &tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Lobes, 0, 0)[..4], + &[0, 25, 0, 0], + "lobes off, coat roughness 0.1" + ); + assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]); + assert_eq!( + &tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Extra, 0, 0)[..4], + &[128, 128, 0, 0], + "flat coat normal, no transmission" + ); for k in DisplayKind::ALL { - assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), k, 3, 5)[..k.bytes_per_texel()]); + assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, k, 3, 5)[..k.bytes_per_texel()]); } - let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0); + let h = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Height, 0, 0); assert_eq!(h.len(), TILE_AREA * 8); assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0"); } @@ -339,7 +350,7 @@ mod tests { /// Decode texel `i` of the Normal display tile (0, 0). fn normal_texel(comp: &Composite, baked: &BakedMaps, i: usize) -> [f32; 4] { - let bytes = tile_bytes(comp, baked, DisplayKind::Normal, 0, 0); + let bytes = tile_bytes(comp, baked, AoMixing::Multiply, DisplayKind::Normal, 0, 0); [0, 1, 2, 3].map(|k| half::f16::from_le_bytes([bytes[i * 8 + k * 2], bytes[i * 8 + k * 2 + 1]]).to_f32()) } @@ -374,11 +385,11 @@ mod tests { comp.channels.get_mut(&Channel::Glossiness).unwrap().set(0, 0, &[to_u16(0.8)]); comp.channels.get_mut(&Channel::Specular).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]); - let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0); + let orm = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Orm, 0, 0); assert!((orm[1] as i32 - 51).abs() <= 1, "roughness = 1 - 0.8, got {}", orm[1]); - let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0); + let h = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Height, 0, 0); let at = |k: usize| half::f16::from_le_bytes([h[k * 2], h[k * 2 + 1]]).to_f32(); assert_eq!(at(0), 0.0); @@ -402,7 +413,7 @@ mod tests { set(Channel::Transmission, &[to_u16(0.6)]); set(Channel::CoatNormal, &[to_u16(1.0), to_u16(0.5), to_u16(1.0)]); - let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), k, 0, 0)[4..8].to_vec(); + let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, k, 0, 0)[4..8].to_vec(); let near = |a: &[u8], b: &[u8]| a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1); assert!(near(&px(DisplayKind::Lobes), &[255, 51, 153, 64]), "{:?}", px(DisplayKind::Lobes)); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 421aec82..d849f77c 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -278,6 +278,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value { texturecraft_core::NormalMixing::Combine => "combine", texturecraft_core::NormalMixing::Replace => "replace", }, + "aoMixing": match texture_set.ao_mixing { + texturecraft_core::AoMixing::Multiply => "multiply", + texturecraft_core::AoMixing::None => "none", + }, "active": index == session.ts(), }) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e1d83ead..0864bf7b 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -825,6 +825,12 @@ impl Session { ) }; for (texture_set_index, cache) in self.caches.iter_mut().enumerate() { + // Display-only settings change the uploaded textures, not the composite + let ao_mixing = |document: &Document| document.project.texture_sets.get(texture_set_index).map(|set| set.ao_mixing); + if ao_mixing(previous_document) != ao_mixing(&self.doc) { + cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1)); + } + if uses_added_resource(texture_set_index) { cache.invalidate_all(); continue; diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 5fa7fd49..6b078b46 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -1,7 +1,7 @@ //! Texture set commands (Texture Set List / Texture Set Settings). use serde_json::{Value, json}; -use texturecraft_core::{Channel, ChannelBlend, ChannelFormat, NormalMixing}; +use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, NormalMixing}; use std::sync::Arc; @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Texture set settings", [], None, - "{ts?, description?, heightStrength?, normalMixing?: combine|replace, normalFormat?: openGl|directX}", + "{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, normalFormat?: openGl|directX}", always, settings ), @@ -289,12 +289,19 @@ fn rename(s: &mut Session, p: &Value) -> Result { fn settings(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.settings")?; let nf = normal_format_param("textureSet.settings", p)?; + let ao_mixing_before = s.doc.project.texture_set(ts)?.ao_mixing; let normal_mixing = match strp(p, "normalMixing") { None => None, Some("combine") => Some(NormalMixing::Combine), Some("replace") => Some(NormalMixing::Replace), Some(other) => return Err(bad("textureSet.settings", format!("unknown normal mixing {other:?} (combine or replace)"))), }; + let ao_mixing = match strp(p, "aoMixing") { + None => None, + Some("multiply") => Some(AoMixing::Multiply), + Some("none") => Some(AoMixing::None), + Some(other) => return Err(bad("textureSet.settings", format!("unknown ambient occlusion mixing {other:?} (multiply or none)"))), + }; s.edit("Texture set settings", |s| { if let Some(n) = nf { s.doc.project.normal_format = n; @@ -309,8 +316,18 @@ fn settings(s: &mut Session, p: &Value) -> Result { if let Some(mixing) = normal_mixing { set.normal_mixing = mixing; } + if let Some(mixing) = ao_mixing { + set.ao_mixing = mixing; + } Ok(()) })?; + + // The viewport's occlusion texture mixes the baked map in: resend the set + if s.doc.project.texture_set(ts)?.ao_mixing != ao_mixing_before + && let Some(cache) = s.caches.get_mut(ts) + { + cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1)); + } Ok(Value::Null) } @@ -346,4 +363,21 @@ mod tests { crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert_eq!(mixing(&s), json!("combine")); } + + #[test] + fn ao_mixing_resends_the_set_to_the_viewport_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + s.update(); + let _ = (s.take_uploads(0), s.take_uploads(1)); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "aoMixing": "none"})).unwrap(); + assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("none")); + assert!(!s.take_uploads(0).is_empty() && s.take_uploads(1).is_empty(), "only the changed set is resent"); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"aoMixing": "screen"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("multiply")); + assert!(!s.take_uploads(0).is_empty(), "undo resends the set too"); + } } diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs index f690d2ae..1505700d 100644 --- a/crates/engine/tests/it/bake_resolution.rs +++ b/crates/engine/tests/it/bake_resolution.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use serde_json::json; use texturecraft_engine::bake::Progress; -use texturecraft_engine::core::BakedMap; +use texturecraft_engine::core::{AoMixing, BakedMap}; use texturecraft_engine::geom::{NO_TRI, UvGBuffer, primitives}; use texturecraft_engine::{Session, execute}; @@ -103,8 +103,11 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { let map = BakedMap::AmbientOcclusion; assert!((baked.scalar(map, 248, 120, (256, 128)).unwrap() - 240.0 / 255.0).abs() < 0.001); let composite = &session.caches[0].composite; - let display = tile_bytes(composite, baked, DisplayKind::Orm, 5, 1); - assert_eq!(display[((56 * 64 + 56) * 4) as usize], 240, "the viewport samples the far corner of the smaller working tile"); + let corner = ((56 * 64 + 56) * 4) as usize; + let display = tile_bytes(composite, baked, AoMixing::Multiply, DisplayKind::Orm, 5, 1); + assert_eq!(display[corner], 240, "the viewport samples the far corner of the smaller working tile"); + let unmixed = tile_bytes(composite, baked, AoMixing::None, DisplayKind::Orm, 5, 1); + assert!(unmixed[corner] > display[corner], "ambient occlusion mixing None leaves the baked map out of the viewport"); let options = ExportOptions::new(ExportPreset { name: "Bake detail".into(), diff --git a/crates/engine/tests/it/perf.rs b/crates/engine/tests/it/perf.rs index d40cde56..2acafc3d 100644 --- a/crates/engine/tests/it/perf.rs +++ b/crates/engine/tests/it/perf.rs @@ -5,7 +5,7 @@ use std::time::{Duration, Instant}; use rayon::prelude::*; use serde_json::{Value, json}; use texturecraft_engine::compose::{DisplayKind, kinds_for, tile_bytes}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{AoMixing, Channel}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; use texturecraft_engine::texel::TILE; @@ -64,7 +64,7 @@ fn upload_bytes(session: &mut Session) -> (usize, usize) { let selected_bytes = tiles .par_iter() .flat_map_iter(|&(tile_x, tile_y)| kinds.iter().map(move |&kind| (kind, tile_x, tile_y))) - .map(|(kind, tile_x, tile_y)| tile_bytes(composite, baked, kind, tile_x, tile_y).len()) + .map(|(kind, tile_x, tile_y)| tile_bytes(composite, baked, AoMixing::Multiply, kind, tile_x, tile_y).len()) .sum(); let all_bytes_per_tile: usize = DisplayKind::ALL.iter().map(|kind| kind.bytes_per_texel() * (TILE * TILE) as usize).sum(); diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 5778d88a..6fd95f70 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -821,7 +821,15 @@ mod tests { h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1); for (tx, ty) in all_tiles(64, 64) { for k in DisplayKind::ALL { - h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty)); + h.renderer.upload_tile( + &h.device, + &h.queue, + 0, + k, + tx, + ty, + &tile_bytes(&composite, &BakedMaps::default(), texturecraft_core::AoMixing::Multiply, k, tx, ty), + ); } } let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); @@ -997,7 +1005,15 @@ mod tests { h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1); for (tx, ty) in all_tiles(64, 64) { for k in DisplayKind::ALL { - h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty)); + h.renderer.upload_tile( + &h.device, + &h.queue, + 0, + k, + tx, + ty, + &tile_bytes(&composite, &BakedMaps::default(), texturecraft_core::AoMixing::Multiply, k, tx, ty), + ); } } let sizes: Vec = h.renderer.display_textures()[0].iter().map(|t| t.width()).collect(); diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index e9460184..87e7e17f 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -9,7 +9,7 @@ use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor use rayon::prelude::*; use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, kinds_for, tile_bytes}; -use texturecraft_engine::core::{BakedMap, Channel, LayerId}; +use texturecraft_engine::core::{AoMixing, BakedMap, Channel, LayerId}; use texturecraft_engine::geom::Mesh; use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu}; @@ -260,6 +260,7 @@ impl GpuLink { let empty = Default::default(); let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); let composite = &cache.composite; + let ao_mixing = session.doc.project.texture_sets.get(texture_set).map_or(AoMixing::Multiply, |set| set.ao_mixing); let channels: Vec = composite.channels.keys().copied().collect(); let sent = self.sent.entry(texture_set).or_default(); let kinds: Vec = @@ -271,7 +272,7 @@ impl GpuLink { let bytes: Vec<_> = chunk .par_iter() .flat_map_iter(|&(tile_x, tile_y)| kinds.iter().map(move |&kind| (kind, tile_x, tile_y))) - .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, ao_mixing, kind, tile_x, tile_y))) .collect(); queued += bytes.len(); out.tiles.extend(bytes); From 1ccef56f98131235cb2a7d9af4b5a4db52aea276 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 18:53:01 -0500 Subject: [PATCH 080/190] Autosave: open a copy as an unsaved project The project a copy came from autosaves to that same file again, so work saved into an opened copy was replaced. Opening a copy now leaves the project without a file: Save asks for one, and its autosave goes to a copy of its own. --- crates/ui-egui/src/autosave_name.rs | 44 ++++++---- crates/ui-egui/src/control.rs | 5 ++ crates/ui-egui/src/lib.rs | 8 ++ crates/ui-egui/tests/autosave_recovery.rs | 100 ++++++++++++++++++++++ docs/features.md | 2 +- 5 files changed, 139 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/tests/autosave_recovery.rs diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs index 69d0ab4d..c5383827 100644 --- a/crates/ui-egui/src/autosave_name.rs +++ b/crates/ui-egui/src/autosave_name.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; use texturecraft_engine::core::PROJECT_EXT; use texturecraft_engine::formats::export::sanitize_file_stem; -use crate::TextureCraftApp; +use crate::{TextureCraftApp, user_dir}; /// Hex digits of a copy's suffix const SUFFIX_DIGITS: usize = 16; @@ -18,6 +18,16 @@ const COPY_MARK: &str = "-copy-"; const MAX_STEM_CHARS: usize = 170; impl TextureCraftApp { + /// A project just opened from an autosave copy becomes an unsaved one: the project the copy came from + /// autosaves there again, so work saved into it would be lost + pub(crate) fn detach_autosave_copy(&mut self) { + let folder = absolute(&user_dir("autosave")); + if self.session.path.as_deref().is_some_and(|path| is_copy_in(&absolute(Path::new(path)), &folder)) { + self.session.path = None; + self.session.modified = true; + } + } + /// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the /// same across restarts; an unsaved project gets one that no other open project or running instance shares pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf { @@ -35,12 +45,6 @@ impl TextureCraftApp { }; let saved = absolute(Path::new(saved)); - - // A project opened from its autosave copy keeps writing there, rather than chaining suffixes - if is_copy_in(&saved, &absolute(folder)) { - return saved; - } - let stem = saved.file_stem().map_or_else(|| self.session.doc.project.name.clone(), |stem| stem.to_string_lossy().into_owned()); folder.join(file_name(&stem, hash(saved.as_os_str().as_encoded_bytes()))) } @@ -142,22 +146,24 @@ mod tests { } #[test] - fn a_project_opened_from_its_copy_keeps_writing_to_it() { - let folder = std::env::temp_dir().join("tc-autosave"); + fn only_a_project_opened_from_a_copy_is_detached_from_its_file() { + let folder = user_dir("autosave"); let mut app = app(project("hero")); let copy = app.autosave_path(&folder); + // A file there that is not a copy is the user's own, and so is a copy kept somewhere else + let elsewhere = folder.join("kept").join(name_of(©)); + for own in [folder.join("hero.tcraft"), folder.join("hero-20240115.tcraft"), elsewhere] { + let own = own.display().to_string(); + app.session.path = Some(own.clone()); + app.detach_autosave_copy(); + assert_eq!(app.session.path, Some(own)); + } + app.session.path = Some(copy.display().to_string()); - assert_eq!(app.autosave_path(&folder), copy); - - // A file there that is not a copy is the user's own: autosave leaves it alone - let own = folder.join("hero.tcraft"); - app.session.path = Some(own.display().to_string()); - assert_ne!(app.autosave_path(&folder), own); - - let dated = folder.join("hero-20240115.tcraft"); - app.session.path = Some(dated.display().to_string()); - assert_ne!(app.autosave_path(&folder), dated); + app.detach_autosave_copy(); + assert_eq!(app.session.path, None, "Save asks for a file"); + assert!(app.session.modified, "closing asks to save the recovered work"); } #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 8359fbe9..6a551cfd 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -162,6 +162,11 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para app.thumbs.forget_saved_files(); } + #[cfg(not(target_arch = "wasm32"))] + if id == "file.open" { + app.detach_autosave_copy(); + } + // Work from the old project must not reach its replacement if matches!(id, "file.open" | "file.new" | "file.close" | "project.new" | "project.sample") { app.resize = None; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9f0b6d70..aa3f32b7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -555,6 +555,9 @@ impl TextureCraftApp { } } + // A copy named on the command line is already open + app.detach_autosave_copy(); + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); @@ -604,6 +607,11 @@ impl TextureCraftApp { self.thumbs.forget_saved_files(); } + #[cfg(not(target_arch = "wasm32"))] + if id == "file.open" { + self.detach_autosave_copy(); + } + // Pending work and thumbnail snapshots belong to the old project if matches!(id, "file.open" | "file.new" | "file.close" | "project.new" | "project.sample") { self.pbr_import = None; diff --git a/crates/ui-egui/tests/autosave_recovery.rs b/crates/ui-egui/tests/autosave_recovery.rs new file mode 100644 index 00000000..46fd747f --- /dev/null +++ b/crates/ui-egui/tests/autosave_recovery.rs @@ -0,0 +1,100 @@ +//! Work recovered from an autosave copy survives the next autosave of the project the copy came from. This is a test +//! binary of its own because it points the process's data folder at a temporary one + +#![cfg(not(target_arch = "wasm32"))] + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::{TextureCraftApp, control}; + +/// App time each frame advances by, so a few frames pass any autosave interval +const FRAME_SECONDS: f32 = 600.0; + +/// How long the worker thread gets to write a copy +const WRITE_TIMEOUT: Duration = Duration::from_secs(60); + +fn load(path: &Path) -> Option { + texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).ok() +} + +fn layers(session: &Session) -> usize { + session.doc.project.layers.len() +} + +fn start(session: Session) -> Harness<'static, TextureCraftApp> { + Harness::builder() + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)) +} + +fn add_layers(app: &mut TextureCraftApp, count: usize) { + for _ in 0..count { + execute(&mut app.session, "layer.add.paint", &json!({})).unwrap(); + } +} + +/// Runs the app until a copy in `folder` holds a project of `count` layers, and returns it +fn autosave(harness: &mut Harness<'_, TextureCraftApp>, folder: &Path, count: usize) -> PathBuf { + let started = Instant::now(); + loop { + harness.step(); + let files = std::fs::read_dir(folder).map(|entries| entries.flatten().map(|entry| entry.path()).collect::>()).unwrap_or_default(); + let found = files + .into_iter() + .find(|path| path.extension().is_some_and(|extension| extension == "tcraft") && load(path).is_some_and(|session| layers(&session) == count)); + if let Some(copy) = found { + return copy; + } + + assert!(started.elapsed() < WRITE_TIMEOUT, "autosave wrote no copy of {count} layers"); + std::thread::sleep(Duration::from_millis(20)); + } +} + +#[test] +fn recovered_work_survives_the_originals_next_autosave() { + let data = std::env::temp_dir().join(format!("tc-autosave-recovery-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&data); + std::fs::create_dir_all(&data).unwrap(); + texturecraft_ui_egui::set_data_root(data.clone()); + let folder = data.join("autosave"); + let own = data.join("hero.tcraft"); + let own_param = json!({ "path": own.to_str().unwrap() }); + + let mut session = Session::new_project("hero", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + execute(&mut session, "file.saveAs", &own_param).unwrap(); + let saved = layers(&session); + + let mut harness = start(session); + add_layers(harness.state_mut(), 1); + let copy = autosave(&mut harness, &folder, saved + 1); + let copy_param = json!({ "path": copy.to_str().unwrap() }); + + // Opening the copy gives an unsaved project: Save cannot write into it + assert!(harness.state_mut().run("file.open", copy_param.clone()).is_some()); + assert_eq!(harness.state().session.path, None); + add_layers(harness.state_mut(), 3); + let recovered = layers(&harness.state().session); + autosave(&mut harness, &folder, recovered); + + assert!(harness.state_mut().run("file.open", own_param).is_some()); + add_layers(harness.state_mut(), 2); + assert_eq!(autosave(&mut harness, &folder, saved + 2), copy, "the original keeps its copy"); + autosave(&mut harness, &folder, recovered); + + // The control channel and a copy named on the command line open it the same way + let ctx = harness.ctx.clone(); + let result = control::handle(harness.state_mut(), &ctx, "command.run", &json!({ "id": "file.open", "params": copy_param })); + assert_eq!(result["ok"], true, "{result}"); + assert_eq!(harness.state().session.path, None); + assert_eq!(start(load(©).unwrap()).state().session.path, None); + + drop(harness); + std::fs::remove_dir_all(&data).unwrap(); +} diff --git a/docs/features.md b/docs/features.md index 2826868c..81f77af5 100644 --- a/docs/features.md +++ b/docs/features.md @@ -281,7 +281,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA the default). Nightly shows its fixed profile path in the same row. - **Autosave**: each project keeps its own copy in the data folder's `autosave`, named `-copy-.tcraft` after its saved file (or, until it is saved, the project), so projects made from - one mesh never overwrite each other's copy. + one mesh never overwrite each other's copy. A copy opens as an unsaved project, so Save asks for a new file. - A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's rotation, zoom and wheel speeds with inverse directions, GPU or CPU bake rays, resource limits From 9e2917098f7ecdc200afeb48741179c6a85e0a43 Mon Sep 17 00:00:00 2001 From: a2 Date: Thu, 26 Nov 2026 19:54:14 -0500 Subject: [PATCH 081/190] chore(i18n): leave the language registration to #691; keep the Russian packaging metadata Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/fonts.rs | 5 ++--- crates/ui-egui/src/i18n.rs | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index b9f5530f..95080619 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -279,9 +279,8 @@ mod tests { assert_eq!(Script::of_language("ar"), Some(Script::Arabic)); assert_eq!(Script::of_language("de"), None); for l in &crate::i18n::LANGUAGES { - // Past the Latin blocks and their diacritics. Cyrillic is already in the - // interface font (Inter / Ubuntu-Light), so Russian needs no fallback script. - let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c)); + // Past the Latin blocks and their diacritics. + let other_script = l.name.chars().any(|c| c > '\u{036F}'); assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code); } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index be1da30c..2210638e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -37,7 +37,7 @@ pub struct Language { pub english: &'static str, } -const COUNT: usize = 11; +const COUNT: usize = 10; pub static LANGUAGES: [Language; COUNT] = [ Language { code: "en", name: "English", english: "English" }, @@ -50,7 +50,6 @@ pub static LANGUAGES: [Language; COUNT] = [ Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" }, Language { code: "ko", name: "한국어", english: "Korean" }, Language { code: "ar", name: "العربية", english: "Arabic" }, - Language { code: "ru", name: "Русский", english: "Russian" }, ]; // Rendering and preferences use the UI thread, including independent test harnesses. From beea46c9e22126681df3ddbc7884fb424fb979b5 Mon Sep 17 00:00:00 2001 From: a2 Date: Thu, 26 Nov 2026 21:00:18 -0500 Subject: [PATCH 082/190] fix(engine): Open in MaterialCraft stages its package in a private folder The button wrote /.mcraft with a plain fs::write. On a shared temp folder another local user could plant a file or link at that guessable name first, and the write went through it. The package now goes into a new random folder made exclusively (0700 on Unix), as a create_new file; folders over a week old are swept. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/link_cmds.rs | 130 +++++++++++++++++++++++++++++++++ crates/ui-egui/src/dock.rs | 6 +- 2 files changed, 133 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index a20182f6..f22b0f6e 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -344,6 +344,59 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { }) } +/// Prefix of the folders [`stage_handoff_package`] makes in the temp folder. +#[cfg(not(target_arch = "wasm32"))] +const HANDOFF_PREFIX: &str = "texturecraft-open-"; + +/// Folders from earlier hand-offs older than this are removed (MaterialCraft may still have a young one open). +#[cfg(not(target_arch = "wasm32"))] +const HANDOFF_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600); + +/// Write `package` as `file_name` inside a new folder only this call can have made under the temp folder, and return the +/// file's path (for [`open_in_materialcraft`]). A fixed `/` is guessable: on a shared `/tmp` another user +/// could plant a file or link there first and the write would go through it. The folder name is random, is created +/// exclusively (mode `0700` on Unix) and the file is created with `create_new`, so nothing planted is ever written through. +/// The folder stays after the call because MaterialCraft needs the file while it is open; folders over a week old go. +#[cfg(not(target_arch = "wasm32"))] +pub fn stage_handoff_package(file_name: &str, package: &[u8]) -> Result { + stage_handoff_package_in(&std::env::temp_dir(), file_name, package) +} + +#[cfg(not(target_arch = "wasm32"))] +fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[u8]) -> Result { + use std::io::Write; + let io = |e: std::io::Error| EngineError::Other(format!("cannot stage the package for MaterialCraft: {e}")); + if file_name.is_empty() || std::path::Path::new(file_name).file_name() != Some(std::ffi::OsStr::new(file_name)) { + return Err(EngineError::Other(format!("`{file_name}` is not a plain file name"))); + } + sweep_old_handoffs(base, HANDOFF_MAX_AGE); + // Dropped (and removed) on any early return, so a failed write leaves no empty folder behind. + let dir = tempfile::Builder::new().prefix(HANDOFF_PREFIX).tempdir_in(base).map_err(io)?; + let path = dir.path().join(file_name); + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(io)?; + file.write_all(package).map_err(io)?; + file.sync_all().map_err(io)?; + let _ = dir.keep(); + Ok(path) +} + +/// Remove hand-off folders in `base` last changed more than `max_age` ago. Only real folders with our prefix are +/// touched (never a link), and every failure is ignored: a leftover folder costs disk space, not work. +#[cfg(not(target_arch = "wasm32"))] +fn sweep_old_handoffs(base: &std::path::Path, max_age: std::time::Duration) { + let Ok(entries) = std::fs::read_dir(base) else { return }; + for entry in entries.flatten() { + if !entry.file_name().to_string_lossy().starts_with(HANDOFF_PREFIX) { + continue; + } + let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; + let old = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age); + if meta.is_dir() && old { + let _ = std::fs::remove_dir_all(entry.path()); + } + } +} + /// Source file extensions are chosen from the linked resource name, never an untrusted path. pub fn source_extension(name: &str) -> &'static str { if name.to_ascii_lowercase().ends_with(".mcmat") { @@ -711,4 +764,81 @@ mod tests { assert_eq!(typed(&p, &json!("#+f+f+f")), None); assert!(typed(&p, &json!("#ff8000")).is_some()); } + + #[cfg(not(target_arch = "wasm32"))] + fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// A file another user planted at the old, guessable `/` is never written through. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_package_is_not_written_through_a_planted_link() { + let base = scratch("planted"); + let victim = base.join("victim.txt"); + std::fs::write(&victim, b"precious").unwrap(); + // The old code wrote `/` with `fs::write`; a hard link there reaches the victim on every platform. + std::fs::hard_link(&victim, base.join("wood.mcraft")).unwrap(); + + let path = super::stage_handoff_package_in(&base, "wood.mcraft", b"package").unwrap(); + + assert_eq!(std::fs::read(&victim).unwrap(), b"precious"); + assert_eq!(std::fs::read(&path).unwrap(), b"package"); + assert_ne!(path.parent().unwrap(), base, "the file is inside a folder of its own"); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// Every hand-off gets its own empty-until-written folder, even when the name repeats. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_packages_get_distinct_folders() { + let base = scratch("distinct"); + let a = super::stage_handoff_package_in(&base, "m.mcraft", b"a").unwrap(); + let b = super::stage_handoff_package_in(&base, "m.mcraft", b"b").unwrap(); + assert_ne!(a.parent(), b.parent()); + assert_eq!((std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()), (b"a".to_vec(), b"b".to_vec())); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(a.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700); + } + std::fs::remove_dir_all(&base).unwrap(); + } + + /// A name with a path in it cannot leave the new folder. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_package_rejects_names_that_are_paths() { + let base = scratch("names"); + for bad in ["", "..", "a/b.mcraft", "../x.mcraft"] { + assert!(super::stage_handoff_package_in(&base, bad, b"x").is_err(), "{bad}"); + } + assert_eq!(std::fs::read_dir(&base).unwrap().count(), 0, "a rejected name leaves nothing behind"); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// Old hand-off folders are swept; young ones, other folders and files stay. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_sweep_removes_only_old_handoff_folders() { + let base = scratch("sweep"); + let old = base.join("texturecraft-open-old"); + let other = base.join("somebody-elses-folder"); + let file = base.join("texturecraft-open-file"); + for dir in [&old, &other] { + std::fs::create_dir(dir).unwrap(); + } + std::fs::write(&file, b"x").unwrap(); + // Zero age limit: everything with the prefix that is a folder counts as old. + super::sweep_old_handoffs(&base, std::time::Duration::ZERO); + assert!(!old.exists() && other.exists() && file.exists()); + let young = base.join("texturecraft-open-young"); + std::fs::create_dir(&young).unwrap(); + super::sweep_old_handoffs(&base, std::time::Duration::from_secs(3600)); + assert!(young.exists()); + std::fs::remove_dir_all(&base).unwrap(); + } } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index a59a5f4d..9d79bf30 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2787,12 +2787,12 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn open_link_in_materialcraft(app: &mut TextureCraftApp, layer: LayerId, link: &texturecraft_engine::core::MaterialLink) { let ext = texturecraft_engine::link_cmds::source_extension(&link.package); - let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); + let file_name = format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name)); let opened = app .session .link_package(layer) - .and_then(|package| std::fs::write(&path, package.as_slice()).map_err(|err| texturecraft_engine::EngineError::Other(err.to_string()))) - .and_then(|()| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); + .and_then(|package| texturecraft_engine::link_cmds::stage_handoff_package(&file_name, package.as_slice())) + .and_then(|path| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); match opened { Ok(()) => app.toast(tr("Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back"), false), Err(e) => app.toast(e.to_string(), true), From 89a906a5c1b817a50a8b9f19b3fc1dbec090835c Mon Sep 17 00:00:00 2001 From: a2 Date: Thu, 26 Nov 2026 21:17:04 -0500 Subject: [PATCH 083/190] fix(engine): hand-off folder and file get explicit 0700 and 0600 on Unix tempfile creates folders with the default mode (0755 under the usual umask), so the 0700 the first version asserted was not what Linux produced. Ask for it, and for 0600 on the package file. Found by CodeRabbit. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/link_cmds.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index f22b0f6e..f3cd84ad 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -355,7 +355,7 @@ const HANDOFF_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * /// Write `package` as `file_name` inside a new folder only this call can have made under the temp folder, and return the /// file's path (for [`open_in_materialcraft`]). A fixed `/` is guessable: on a shared `/tmp` another user /// could plant a file or link there first and the write would go through it. The folder name is random, is created -/// exclusively (mode `0700` on Unix) and the file is created with `create_new`, so nothing planted is ever written through. +/// exclusively (mode `0700` on Unix) and the file is created with `create_new` (mode `0600`), so nothing planted is ever written through. /// The folder stays after the call because MaterialCraft needs the file while it is open; folders over a week old go. #[cfg(not(target_arch = "wasm32"))] pub fn stage_handoff_package(file_name: &str, package: &[u8]) -> Result { @@ -371,9 +371,18 @@ fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[ } sweep_old_handoffs(base, HANDOFF_MAX_AGE); // Dropped (and removed) on any early return, so a failed write leaves no empty folder behind. - let dir = tempfile::Builder::new().prefix(HANDOFF_PREFIX).tempdir_in(base).map_err(io)?; + let mut builder = tempfile::Builder::new(); + builder.prefix(HANDOFF_PREFIX); + // tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly. + #[cfg(unix)] + builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)); + let dir = builder.tempdir_in(base).map_err(io)?; let path = dir.path().join(file_name); - let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(io)?; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options.open(&path).map_err(io)?; file.write_all(package).map_err(io)?; file.sync_all().map_err(io)?; let _ = dir.keep(); @@ -804,6 +813,7 @@ mod tests { { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(a.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700); + assert_eq!(std::fs::metadata(&a).unwrap().permissions().mode() & 0o777, 0o600); } std::fs::remove_dir_all(&base).unwrap(); } From 40830d012809744eb125f4a36356526336296094 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:05:39 +0000 Subject: [PATCH 084/190] Texture set height to normal method: Sharp or Smooth (Sobel), set by command and followed by export, viewport and path tracers textureSet.settings takes heightToNormal (sharp or smooth) as one undo step and textureSet.inspect reports it. Smooth is the 3x3 Sobel filter export already used; Sharp takes the two neighbours across, which the viewport and both path tracers used until now. All four now read the set's method from one rule (HeightToNormalMethod::slope, mirrored in mesh.wgsl and trace.wgsl). Projects without the field stay Smooth, so their exports are unchanged; their viewport normal now matches the export. --- crates/automation/src/render.rs | 2 ++ crates/core/src/height_to_normal_method.rs | 40 +++++++++++++++++++++ crates/core/src/lib.rs | 2 ++ crates/core/src/project.rs | 8 ++++- crates/engine/src/inspect.rs | 4 +++ crates/engine/src/set_cmds.rs | 27 ++++++++++++-- crates/formats/src/export/mod.rs | 11 +++--- crates/formats/src/export/tests.rs | 14 ++++++++ crates/render/src/displace.rs | 8 ++++- crates/render/src/gpu_trace.rs | 42 ++++++++++++++++++++-- crates/render/src/renderer.rs | 10 +++++- crates/render/src/shaders/mesh.wgsl | 31 ++++++++++------ crates/render/src/shaders/trace.wgsl | 23 +++++++++--- crates/render/src/trace.rs | 21 ++++++++--- crates/ui-egui/src/render_mode.rs | 4 ++- crates/ui-egui/src/viewport.rs | 2 ++ 16 files changed, 215 insertions(+), 34 deletions(-) create mode 100644 crates/core/src/height_to_normal_method.rs diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 236ebc95..bdcf9fe8 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -169,6 +169,7 @@ fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) { composite: c.composite.clone(), height_strength: ts.atlas_height_strength(), height_in_normal: ts.height_in_normal(), + height_to_normal: ts.height_to_normal, }) .collect(); let d = &s.doc.project.display; @@ -207,6 +208,7 @@ pub fn shade(s: &Session) -> Shade { Shade { height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0), height_in_normal: s.doc.project.texture_sets.get(s.ts()).is_none_or(|t| t.height_in_normal()), + height_to_normal: s.doc.project.texture_sets.get(s.ts()).map_or_else(Default::default, |t| t.height_to_normal), view_mode, channel, // Only the 2D view uses this default diff --git a/crates/core/src/height_to_normal_method.rs b/crates/core/src/height_to_normal_method.rs new file mode 100644 index 00000000..0ed30bd0 --- /dev/null +++ b/crates/core/src/height_to_normal_method.rs @@ -0,0 +1,40 @@ +//! How a texture set turns its Height into normal slopes + +use serde::{Deserialize, Serialize}; + +/// Height to normal method: the slope filter a texture set's height-to-normal uses +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum HeightToNormalMethod { + /// Sharp: the difference of the two neighbours across, so single-texel detail stays crisp + Sharp, + /// Smooth (Sobel): a 3×3 Sobel filter, so the slope also reads the diagonal neighbours + #[default] + Smooth, +} + +impl HeightToNormalMethod { + pub const ALL: [HeightToNormalMethod; 2] = [HeightToNormalMethod::Sharp, HeightToNormalMethod::Smooth]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + HeightToNormalMethod::Sharp => "sharp", + HeightToNormalMethod::Smooth => "smooth", + } + } + + pub fn parse(id: &str) -> Option { + HeightToNormalMethod::ALL.into_iter().find(|value| value.id() == id) + } + + /// The change of height per texel to the right and down, from the heights `h(dx, dy)` around a texel + pub fn slope(self, h: impl Fn(i32, i32) -> f32) -> [f32; 2] { + match self { + HeightToNormalMethod::Sharp => [(h(1, 0) - h(-1, 0)) * 0.5, (h(0, 1) - h(0, -1)) * 0.5], + HeightToNormalMethod::Smooth => [ + (h(1, -1) + 2.0 * h(1, 0) + h(1, 1) - h(-1, -1) - 2.0 * h(-1, 0) - h(-1, 1)) / 8.0, + (h(-1, 1) + 2.0 * h(0, 1) + h(1, 1) - h(-1, -1) - 2.0 * h(0, -1) - h(1, -1)) / 8.0, + ], + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index eedf93ec..6c7776c7 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -34,6 +34,7 @@ pub mod gradient_input; pub mod grayscale_conversion; pub mod grayscale_mode; pub mod height_to_normal; +mod height_to_normal_method; pub mod highpass_space; pub mod image_input; pub mod layer; @@ -108,6 +109,7 @@ pub use gradient_input::GradientInput; pub use grayscale_conversion::GrayscaleConversion; pub use grayscale_mode::GrayscaleMode; pub use height_to_normal::HeightToNormal; +pub use height_to_normal_method::HeightToNormalMethod; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index b0d8d846..03939e3d 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,9 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{ + BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, HeightToNormalMethod, Layer, LayerId, LayerKind, Result, +}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -61,6 +63,9 @@ pub struct TextureSet { pub normal_mixing: NormalMixing, #[serde(default)] pub ao_mixing: AoMixing, + /// Height to normal method; projects without it keep Smooth, the filter their exports already used + #[serde(default)] + pub height_to_normal: HeightToNormalMethod, /// Height-to-normal strength. #[serde(default = "one")] pub height_strength: f32, @@ -168,6 +173,7 @@ impl TextureSet { stack: Vec::new(), normal_mixing: NormalMixing::Combine, ao_mixing: AoMixing::Multiply, + height_to_normal: HeightToNormalMethod::Smooth, height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index d849f77c..ada4d0fe 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -282,6 +282,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value { texturecraft_core::AoMixing::Multiply => "multiply", texturecraft_core::AoMixing::None => "none", }, + "heightToNormal": match texture_set.height_to_normal { + texturecraft_core::HeightToNormalMethod::Sharp => "sharp", + texturecraft_core::HeightToNormalMethod::Smooth => "smooth", + }, "active": index == session.ts(), }) } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 6b078b46..4060ba8d 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -1,7 +1,7 @@ //! Texture set commands (Texture Set List / Texture Set Settings). use serde_json::{Value, json}; -use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, NormalMixing}; +use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, HeightToNormalMethod, NormalMixing}; use std::sync::Arc; @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Texture set settings", [], None, - "{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, normalFormat?: openGl|directX}", + "{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, heightToNormal?: sharp|smooth, normalFormat?: openGl|directX}", always, settings ), @@ -302,6 +302,12 @@ fn settings(s: &mut Session, p: &Value) -> Result { Some("none") => Some(AoMixing::None), Some(other) => return Err(bad("textureSet.settings", format!("unknown ambient occlusion mixing {other:?} (multiply or none)"))), }; + let height_to_normal = match strp(p, "heightToNormal") { + None => None, + Some("sharp") => Some(HeightToNormalMethod::Sharp), + Some("smooth") => Some(HeightToNormalMethod::Smooth), + Some(other) => return Err(bad("textureSet.settings", format!("unknown height to normal method {other:?} (sharp or smooth)"))), + }; s.edit("Texture set settings", |s| { if let Some(n) = nf { s.doc.project.normal_format = n; @@ -319,6 +325,9 @@ fn settings(s: &mut Session, p: &Value) -> Result { if let Some(mixing) = ao_mixing { set.ao_mixing = mixing; } + if let Some(method) = height_to_normal { + set.height_to_normal = method; + } Ok(()) })?; @@ -364,6 +373,20 @@ mod tests { assert_eq!(mixing(&s), json!("combine")); } + #[test] + fn height_to_normal_method_is_set_by_command_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let method = |s: &Session, ts: usize| crate::inspect::texture_set(s, ts)["heightToNormal"].clone(); + assert_eq!(method(&s, 0), json!("smooth")); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "heightToNormal": "sharp"})).unwrap(); + assert_eq!((method(&s, 0), method(&s, 1)), (json!("sharp"), json!("smooth"))); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"heightToNormal": "blurry"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(method(&s, 0), json!("smooth")); + } + #[test] fn ao_mixing_resends_the_set_to_the_viewport_and_undoes() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 17086f28..404980df 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -762,7 +762,7 @@ struct Sampler<'a> { coverage: &'a [bool], /// Composite width. res: u32, - /// Texels per atlas block (`res` for a classic set): the height slope and the Sobel window + /// Texels per atlas block (`res` for a classic set): the height slope and the slope window /// follow the block. tile_res: u32, /// The share of its block each tile fills: a smaller tile's height slope shrinks with it. @@ -804,18 +804,17 @@ impl Sampler<'_> { self.coverage.get((y as usize) * self.res as usize + x as usize).copied().unwrap_or(false) } - /// Normal from the height channel (3×3 Sobel; uncovered neighbours repeat the centre). + /// Normal from the height channel (the set's height to normal method; uncovered neighbours repeat the centre). fn height_normal(&self, x: u32, y: u32) -> Vec3 { let center = self.channel(Channel::Height, At::Texel(x, y))[0]; // Clamped to the texel's UV tile. let t = self.tile_res.max(1); let (x0, y0, last) = ((x / t * t) as i64, (y / t * t) as i64, t as i64 - 1); - let h = |dx: i64, dy: i64| { - let (sx, sy) = ((x as i64 + dx).clamp(x0, x0 + last) as u32, (y as i64 + dy).clamp(y0, y0 + last) as u32); + let h = |dx: i32, dy: i32| { + let (sx, sy) = ((x as i64 + dx as i64).clamp(x0, x0 + last) as u32, (y as i64 + dy as i64).clamp(y0, y0 + last) as u32); if self.covered(sx, sy) { self.channel(Channel::Height, At::Texel(sx, sy))[0] } else { center } }; - let gx = (h(1, -1) + 2.0 * h(1, 0) + h(1, 1) - h(-1, -1) - 2.0 * h(-1, 0) - h(-1, 1)) / 8.0; - let gy = (h(-1, 1) + 2.0 * h(0, 1) + h(1, 1) - h(-1, -1) - 2.0 * h(0, -1) - h(1, -1)) / 8.0; + let [gx, gy] = self.set.height_to_normal.slope(h); let s = self.set.height_strength * self.tile_res as f32 * self.scales.at(x, y) / HEIGHT_SPAN; // Image y points down; OpenGL normals have +Y up the image. Vec3::new(-gx * s, gy * s, 1.0).try_normalize().unwrap_or(Vec3::Z) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 392148a1..71435ae0 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -223,6 +223,20 @@ fn height_becomes_normal_detail() { assert_eq!(flat.get_pixel(30, 30).0, [128, 128, 255]); } +#[test] +fn height_to_normal_method_smooth_reaches_the_diagonal_neighbours() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Height]); + fx.set(Channel::Height, 30, 30, [1.0; 3]); + let normal_at = |fx: &Fx, x: u32, y: u32| decode(find(&fx.render_preset("Separate maps"), "_normal.png")).to_rgb8().get_pixel(x, y).0; + let flat = [128, 128, 255]; + + assert_eq!(fx.project.texture_sets[0].height_to_normal, texturecraft_core::HeightToNormalMethod::Smooth); + assert_ne!(normal_at(&fx, 31, 31), flat, "Sobel reads the bump from the diagonal"); + fx.project.texture_sets[0].height_to_normal = texturecraft_core::HeightToNormalMethod::Sharp; + assert_eq!(normal_at(&fx, 31, 31), flat, "Sharp only reads the neighbours across"); + assert_ne!(normal_at(&fx, 31, 30), flat, "Sharp still tilts beside the bump"); +} + #[test] fn reoriented_normal_mapping_identities() { let d = Vec3::new(0.2, -0.3, 0.9).normalize(); diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index 1ebed5dc..001b6feb 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -141,7 +141,13 @@ mod tests { img.tile_mut(x, y, &[texturecraft_texel::to_u16_signed(height)]); } } - TraceSet { material: 0, composite, height_strength: strength, height_in_normal: true } + TraceSet { + material: 0, + composite, + height_strength: strength, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, + } } #[test] diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 6fd95f70..8b53a605 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -14,6 +14,7 @@ use std::task::{Context, Poll, Waker}; use bytemuck::{Pod, Zeroable}; use texturecraft_compose::DisplayKind; +use texturecraft_core::HeightToNormalMethod; use texturecraft_geom::glam::{Vec3, Vec4}; use texturecraft_geom::{Mesh, OrbitCamera}; use wgpu::util::DeviceExt; @@ -27,6 +28,12 @@ pub const MAX_SETS: usize = 255; /// Depth of the shader's BVH traversal stack (`STACK` in trace.wgsl). pub(crate) const STACK: usize = 64; const KINDS: usize = DisplayKind::ALL.len(); +// trace.wgsl reads the smooth bit as `>> 8u` +const _: () = assert!(KINDS == 8); + +/// The placeholder mask word's bit for a set with Smooth (Sobel) height to normal (trace.wgsl reads it) +const SMOOTH_HEIGHT_BIT: f32 = (1 << KINDS) as f32; + /// Bytes of the trace uniform: [`Head`] then 256 texture-set entries (`MAX_SETS` in trace.wgsl). const PARAMS_SIZE: u64 = (size_of::() + 256 * 16) as u64; /// Post uniform slots: resolve and denoise init, then the five à-trous steps. @@ -96,6 +103,8 @@ struct SceneConst { rotation: f32, env_camera: bool, heights: Vec, + /// Per set: Smooth (Sobel) height to normal + smooth: Vec, ior: f32, /// Focus depth (0: the orbit target) and lens radius in world units (0: pinhole). lens: [f32; 2], @@ -417,6 +426,7 @@ impl GpuTracer { rotation: scene.env_rotation, env_camera: scene.env_camera, heights: scene.sets.iter().map(crate::trace::TraceSet::normal_height_strength).collect(), + smooth: scene.sets.iter().map(|s| s.height_to_normal == HeightToNormalMethod::Smooth).collect(), ior: scene.ior, lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]), }); @@ -613,7 +623,9 @@ impl GpuTracer { }; let mut sets = [[0.0f32; 4]; 256]; for (i, (slot, m)) in sets.iter_mut().zip(&mat.info).enumerate() { - *slot = [m[0], m[1], m[2], sc.heights.get(i).copied().unwrap_or(0.0)]; + // The bit past the placeholder mask bits: Smooth (Sobel) height to normal + let smooth = if sc.smooth.get(i).copied().unwrap_or(false) { SMOOTH_HEIGHT_BIT } else { 0.0 }; + *slot = [m[0], m[1], m[2] + smooth, sc.heights.get(i).copied().unwrap_or(0.0)]; } let mut bytes = bytemuck::bytes_of(&head).to_vec(); bytes.extend_from_slice(bytemuck::cast_slice(&sets)); @@ -834,7 +846,19 @@ mod tests { } let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); - TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], Arc::new(env), 0.0) + TraceScene::new( + mesh, + bvh, + vec![TraceSet { + material: 0, + composite, + height_strength: 0.0, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, + }], + Arc::new(env), + 0.0, + ) } fn gpu() -> Option<(Headless, GpuTracer)> { @@ -1022,7 +1046,19 @@ mod tests { let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); let env = crate::ibl::environment("Studio Contrast", 256); - let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], Arc::new(env), 0.0); + let scene = TraceScene::new( + mesh, + bvh, + vec![TraceSet { + material: 0, + composite, + height_strength: 0.0, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, + }], + Arc::new(env), + 0.0, + ); let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false, background: crate::DEFAULT_BACKGROUND }; let settings = TraceSettings { bounces: 4 }; let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap(); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index fea99716..8f3f8fc8 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -159,6 +159,8 @@ pub struct Shade { pub height_strength: f32, /// The height slope joins the shaded normal (normal mixing Combine; Replace leaves it out) pub height_in_normal: bool, + /// How the height becomes normal slopes + pub height_to_normal: texturecraft_core::HeightToNormalMethod, /// -1 for DirectX normal maps in the normal channel, 1 for OpenGL. pub normal_y: f32, /// 0 material, 1 channel, 2 mesh map (aux texture), 3 UV checker. @@ -298,6 +300,7 @@ impl Default for Shade { ao_intensity: 0.75, height_strength: 1.0, height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, normal_y: 1.0, view_mode: 0, channel: 0, @@ -2120,7 +2123,12 @@ impl Renderer { mode: [s.view_mode as f32, s.channel as f32, s.height_strength, s.normal_y], bg: [s.env_opacity, s.env_blur * (ENV_LEVELS - 1) as f32, uv_view, s.wireframe_opacity.clamp(0.0, 1.0)], uv_xform, - uv_rotation, + uv_rotation: [ + uv_rotation[0], + uv_rotation[1], + uv_rotation[2], + f32::from(u8::from(s.height_to_normal == texturecraft_core::HeightToNormalMethod::Smooth)), + ], light: [light.x, light.y, light.z, lw], light_vp: shadow_vp.unwrap_or(Mat4::IDENTITY).to_cols_array_2d(), // Offset by 1.5 shadow texels to avoid self-shadowing diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 1c6a08ba..cd6a54ee 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -35,7 +35,7 @@ struct Globals { bake_neutral_color: vec4, // rgb the neutral material's color, a its reflection samples this frame bake_neutral: vec4, // x roughness, y metallic, z AO intensity of the neutral material, w on (1) bake_bent_normal: vec4, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw - - uv_rotation: vec4, // UV view: x cos, y sin of the view rotation (counter-clockwise on screen), z view aspect (width / height), w - + uv_rotation: vec4, // UV view: x cos, y sin of the view rotation (counter-clockwise on screen), z view aspect (width / height); w Smooth (Sobel) height to normal (1) or Sharp (0) }; @group(0) @binding(0) var g: Globals; @@ -430,6 +430,21 @@ const UV_CHECKER_FINE_CELLS: f32 = 256.0; // Offset alpha dithering between accumulated frames const DITHER_FRAME_STEP: vec2 = vec2(17.0, 59.0); +// The change of height per texel (`ts` = one texel in UV) to the right and down: Sobel when g.uv_rotation.w is 1, else the neighbours across (as HeightToNormalMethod::slope) +fn height_slope(uv: vec2, ts: vec2) -> vec2 { + let r = textureSample(t_height, samp, uv + vec2(ts.x, 0.0)).r; + let l = textureSample(t_height, samp, uv - vec2(ts.x, 0.0)).r; + let d = textureSample(t_height, samp, uv + vec2(0.0, ts.y)).r; + let u = textureSample(t_height, samp, uv - vec2(0.0, ts.y)).r; + let ru = textureSample(t_height, samp, uv + vec2(ts.x, -ts.y)).r; + let rd = textureSample(t_height, samp, uv + ts).r; + let lu = textureSample(t_height, samp, uv - ts).r; + let ld = textureSample(t_height, samp, uv + vec2(-ts.x, ts.y)).r; + let sharp = vec2(r - l, d - u) * 0.5; + let sobel = vec2(ru + 2.0 * r + rd - lu - 2.0 * l - ld, ld + 2.0 * d + rd - lu - 2.0 * u - ru) / 8.0; + return select(sharp, sobel, g.uv_rotation.w > 0.5); +} + fn shade_mesh(i: VOut, front: bool) -> Shaded { var n_geo = normalize(i.nrm); if (!front) { @@ -476,15 +491,12 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let ts = 1.0 / dims; let hgt = textureSample(t_height, samp, uv); let hc = hgt.r; - let hl = textureSample(t_height, samp, uv - vec2(ts.x, 0.0)).r; - let hr = textureSample(t_height, samp, uv + vec2(ts.x, 0.0)).r; - let hu = textureSample(t_height, samp, uv - vec2(0.0, ts.y)).r; - let hd = textureSample(t_height, samp, uv + vec2(0.0, ts.y)).r; // Match export: a unit height over 1/16 of the width tilts 45° // Combine the height gradient with the tangent-space normal let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(uv); - let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); + let slope = height_slope(uv, ts); + let n_height = normalize(vec3(-slope.x * k, slope.y * k, 1.0)); // The Normal texture holds the signed normal in half floats (flat is exactly +z) var n_detail = clamp(nrm_s, vec3(-1.0), vec3(1.0)); @@ -724,12 +736,9 @@ fn fs_uv(i: VOut) -> @location(0) vec4 { // The tangent-space normal the shading uses: the height slope turned by the normal channel let dims = vec2(textureDimensions(t_height)); let ts = 1.0 / dims; - let hl = textureSample(t_height, samp, i.uv - vec2(ts.x, 0.0)).r; - let hr = textureSample(t_height, samp, i.uv + vec2(ts.x, 0.0)).r; - let hu = textureSample(t_height, samp, i.uv - vec2(0.0, ts.y)).r; - let hd = textureSample(t_height, samp, i.uv + vec2(0.0, ts.y)).r; let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(i.uv); - let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); + let slope = height_slope(i.uv, ts); + let n_height = normalize(vec3(-slope.x * k, slope.y * k, 1.0)); var n_detail = clamp(textureSample(t_nrm, samp, i.uv).rgb, vec3(-1.0), vec3(1.0)); n_detail.y *= g.mode.w; return raw_out(rnm(n_height, normalize(n_detail)) * 0.5 + 0.5); diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index 5f6258e0..2e2ea99a 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -18,7 +18,7 @@ struct Params { sigma: vec4, // subsurface extinction per color channel eye: vec4, // camera position lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR - // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds, height strength. + // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds (bit 8: Smooth (Sobel) height to normal), height strength. sets: array, MAX_SETS>, }; @@ -210,6 +210,22 @@ fn occluded(o: vec3, d: vec3) -> bool { // ---- Materials ---- // Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy). +// The change of height per texel to the right and down: Sobel when smooth, else the neighbours across (as HeightToNormalMethod::slope) +fn height_slope(layer: u32, uv: vec2, sobel: bool) -> vec2 { + let r = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r; + let l = textureLoad(t_height, texel(layer, 3u, uv, -1, 0), layer, 0).r; + let d = textureLoad(t_height, texel(layer, 3u, uv, 0, 1), layer, 0).r; + let u = textureLoad(t_height, texel(layer, 3u, uv, 0, -1), layer, 0).r; + if (!sobel) { + return vec2(r - l, d - u) * 0.5; + } + let ru = textureLoad(t_height, texel(layer, 3u, uv, 1, -1), layer, 0).r; + let rd = textureLoad(t_height, texel(layer, 3u, uv, 1, 1), layer, 0).r; + let lu = textureLoad(t_height, texel(layer, 3u, uv, -1, -1), layer, 0).r; + let ld = textureLoad(t_height, texel(layer, 3u, uv, -1, 1), layer, 0).r; + return vec2(ru + 2.0 * r + rd - lu - 2.0 * l - ld, ld + 2.0 * d + rd - lu - 2.0 * u - ru) / 8.0; +} + fn texel(layer: u32, k: u32, uv: vec2, dx: i32, dy: i32) -> vec2 { let info = P.sets[layer]; let small = ((u32(info.z) >> k) & 1u) == 1u; @@ -302,9 +318,8 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { let k = info.w * info.x / 16.0 * exp2(-extra.a * 255.0 / 32.0); var n_height = vec3(0.0, 0.0, 1.0); if (k != 0.0) { - let hx = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, -1, 0), layer, 0).r; - let hy = textureLoad(t_height, texel(layer, 3u, uv, 0, 1), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, 0, -1), layer, 0).r; - n_height = normalize_or(vec3(-hx * 0.5 * k, hy * 0.5 * k, 1.0), vec3(0.0, 0.0, 1.0)); + let slope = height_slope(layer, uv, ((u32(info.z) >> 8u) & 1u) == 1u); + n_height = normalize_or(vec3(-slope.x * k, slope.y * k, 1.0), vec3(0.0, 0.0, 1.0)); } // The signed normal in half floats, as in mesh.wgsl (flat is exactly +z) diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 01e973d7..bc458eae 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -22,8 +22,8 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_compose::{Composite, ImageRes}; -use texturecraft_core::Channel; use texturecraft_core::project::{DisplaySettings, EnvAlignment, ToneMapping}; +use texturecraft_core::{Channel, HeightToNormalMethod}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera}; @@ -38,6 +38,7 @@ pub struct TraceSet { /// Height displacement and, with `height_in_normal`, height-to-normal strength pub height_strength: f32, pub height_in_normal: bool, + pub height_to_normal: HeightToNormalMethod, } impl TraceSet { @@ -587,8 +588,8 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 s.normal_height_strength() * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) }); let n_height = if k != 0.0 { - let h = |dx, dy| ch(Channel::Height, dx, dy)[0]; - Vec3::new(-(h(1, 0) - h(-1, 0)) * 0.5 * k, (h(0, 1) - h(0, -1)) * 0.5 * k, 1.0).normalize_or(Vec3::Z) + let [gx, gy] = set.map_or(HeightToNormalMethod::Smooth, |s| s.height_to_normal).slope(|dx, dy| ch(Channel::Height, dx, dy)[0]); + Vec3::new(-gx * k, gy * k, 1.0).normalize_or(Vec3::Z) } else { Vec3::Z }; @@ -1242,7 +1243,19 @@ mod tests { } } } - TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], env, 0.0) + TraceScene::new( + mesh, + bvh, + vec![TraceSet { + material: 0, + composite, + height_strength: 0.0, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, + }], + env, + 0.0, + ) } /// Mean radiance of parallel rays over the whole disc of the sphere (grazing hits included) diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 56dbe6af..743ddbc8 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -273,6 +273,7 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { composite: cache.composite.clone(), height_strength: set.atlas_height_strength(), height_in_normal: set.height_in_normal(), + height_to_normal: set.height_to_normal, }) .collect(); let env_image = display.environment_resource().and_then(|n| session.images.get(n)); @@ -332,7 +333,8 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work { /// revisions bump with every composited chunk, so while textures load this changes every frame). fn scene_key(session: &texturecraft_engine::Session, composites: bool) -> String { let revisions: Vec = if composites { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() }; - let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength(), set.height_in_normal())).collect(); + let sets: Vec<_> = + session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength(), set.height_in_normal(), set.height_to_normal)).collect(); let display = &session.doc.project.display; let env_image = display.environment_resource().and_then(|name| session.images.get(name)).map(Arc::as_ptr); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 30922d2f..036c2ab7 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -384,12 +384,14 @@ fn shade(app: &TextureCraftApp) -> Shade { let active_set = app.session.doc.project.texture_sets.get(set_index); let height_strength = active_set.map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); let height_in_normal = active_set.is_none_or(|texture_set| texture_set.height_in_normal()); + let height_to_normal = active_set.map_or_else(Default::default, |texture_set| texture_set.height_to_normal); // Polygon fill shows the polygons it fills without changing the saved wireframe toggles let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, height_in_normal, + height_to_normal, view_mode, channel, wireframe: wireframe_shown(&app.ui, polygon_fill_tool), From 3f38644c9145044126514f265f2230b8a69ae74d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:49:58 +0000 Subject: [PATCH 085/190] Dock the Baking Log at the bottom of the bake layout The default bake layout put the general Log under the settings columns; the Baking Log now takes that place (the Log stays in Window > Views). The bake layout version moves to 3 so saved bake docks pick up the new layout. --- crates/ui-egui/src/docking.rs | 10 +++++----- crates/ui-egui/src/state.rs | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 6c4f5f97..85edb126 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -308,7 +308,7 @@ impl Dock { self.replaced_unreadable } - /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport + /// Texture sets over the bakers, the two settings tabs, the Baking Log under both, then the viewport pub(crate) fn for_baking() -> Self { let painting = default_workspace(); let mut hidden = painting.hidden().to_vec(); @@ -318,14 +318,14 @@ impl Dock { } } - let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log]; + let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::BakingLog]; hidden.retain(|(panel, _)| !bake_panels.contains(panel)); let gutter_width = f32::from(crate::theme::GUTTER); let list_column = split(Axis::Y, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]); let columns = split(Axis::X, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); - let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); + let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::BakingLog])); let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH; let root = split(Axis::X, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); let workspace = Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, painting.floated().to_vec()); @@ -759,12 +759,12 @@ mod tests { } #[test] - fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() { + fn the_bake_dock_round_trips_with_the_baking_log_under_both_settings_columns() { let dock = Dock::for_baking(); assert!(validate(dock.workspace()).is_ok()); assert_eq!( panels_of(dock.workspace()), - [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::Log, Panel::Viewport] + [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::BakingLog, Panel::Viewport] ); assert!(dock.is_visible(Panel::CommonSettings) && !dock.is_visible(Panel::MeshMapSettings)); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 54daa752..ff897d80 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -543,7 +543,7 @@ fn default_true() -> bool { } /// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` -const BAKE_LAYOUT_VERSION: u32 = 2; +const BAKE_LAYOUT_VERSION: u32 = 3; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { @@ -1018,6 +1018,24 @@ mod tests { } } + #[test] + fn a_saved_bake_dock_with_the_log_at_the_bottom_gets_the_baking_log_there() { + use crate::docking::Panel; + + let mut ui = UiState { mode: Mode::Baking, ..UiState::default() }; + ui.sync_mode_dock(); + ui.dock.close(Panel::BakingLog); + ui.dock.focus(Panel::Log); + let mut saved = serde_json::to_value(&ui).unwrap(); + saved["bake_layout_version"] = serde_json::json!(2); + + let mut loaded: UiState = serde_json::from_value(saved).unwrap(); + loaded.sync_mode_dock(); + + assert!(loaded.dock.is_visible(Panel::BakingLog), "the Baking Log takes the bottom of the bake layout"); + assert!(!loaded.dock.is_open(Panel::Log), "the general Log stays in Window > Views"); + } + #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { From 03600e447a7c1a0338d14f9da293ab54e4714fb7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:52:36 +0000 Subject: [PATCH 086/190] Record each bake map by map for the Baking Log The session keeps the latest bake as one row per texture set and map (waiting, baking, baked, failed, canceled), filled from the bake's own state by the app's background bake and by bake.run, never from Log lines. --- crates/engine/src/bake/bake_log.rs | 81 ++++++++++++++++++++++ crates/engine/src/bake/bake_log_map.rs | 15 ++++ crates/engine/src/bake/bake_map_state.rs | 26 +++++++ crates/engine/src/bake/mesh_map_command.rs | 34 +++++++-- crates/engine/src/bake/mod.rs | 6 ++ crates/engine/src/session.rs | 3 + crates/engine/tests/it/bake_log.rs | 50 +++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/lib.rs | 11 ++- 9 files changed, 220 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/bake/bake_log.rs create mode 100644 crates/engine/src/bake/bake_log_map.rs create mode 100644 crates/engine/src/bake/bake_map_state.rs create mode 100644 crates/engine/tests/it/bake_log.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs new file mode 100644 index 00000000..2f263cf2 --- /dev/null +++ b/crates/engine/src/bake/bake_log.rs @@ -0,0 +1,81 @@ +use serde::Serialize; +use texturecraft_core::{BakedMap, Project}; + +use super::{BakeLogMap, BakeMapState}; + +/// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct BakeLog { + pub maps: Vec, +} + +impl BakeLog { + /// Start over for a bake of `sets`: every checked map of each set, waiting, in bake order + pub fn begin(&mut self, project: &Project, sets: &[usize]) { + self.maps = sets + .iter() + .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) + .flat_map(|(index, set)| { + set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting }) + }) + .collect(); + } + + /// `set` starts baking: its first map is the one in progress + pub fn set_started(&mut self, set: usize) { + self.start_next(set); + } + + /// `map` of `set` is baked; the set's next map starts + pub fn map_baked(&mut self, set: usize, map: BakedMap) { + if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) { + row.state = BakeMapState::Baked; + } + self.start_next(set); + } + + /// `set`'s bake was kept: a map it did not hand over is not baked + pub fn set_finished(&mut self, set: usize) { + for row in self.maps.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) { + row.state = BakeMapState::Canceled; + } + } + + /// Nothing of `set` was kept: every one of its maps failed for `reason` + pub fn set_failed(&mut self, set: usize, reason: &str) { + for row in self.maps.iter_mut().filter(|row| row.texture_set == set) { + row.state = BakeMapState::Failed(reason.to_owned()); + } + } + + /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled + pub fn cancel(&mut self, current: Option) { + for row in &mut self.maps { + if row.state.is_pending() || (Some(row.texture_set) == current && row.state == BakeMapState::Baked) { + row.state = BakeMapState::Canceled; + } + } + } + + /// The whole bake was rolled back: every map that did not fail is canceled + pub fn discard(&mut self) { + for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) { + row.state = BakeMapState::Canceled; + } + } + + /// Whether a map is still waiting or baking + pub fn is_running(&self) -> bool { + self.maps.iter().any(|row| row.state.is_pending()) + } + + fn start_next(&mut self, set: usize) { + if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) { + return; + } + + if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.state == BakeMapState::Waiting) { + row.state = BakeMapState::Baking; + } + } +} diff --git a/crates/engine/src/bake/bake_log_map.rs b/crates/engine/src/bake/bake_log_map.rs new file mode 100644 index 00000000..4a04bd7d --- /dev/null +++ b/crates/engine/src/bake/bake_log_map.rs @@ -0,0 +1,15 @@ +use serde::Serialize; +use texturecraft_core::BakedMap; + +use super::BakeMapState; + +/// One row of the Baking Log's process list: a map of a texture set in the latest bake +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BakeLogMap { + pub texture_set: usize, + pub set_name: String, + pub map: BakedMap, + #[serde(flatten)] + pub state: BakeMapState, +} diff --git a/crates/engine/src/bake/bake_map_state.rs b/crates/engine/src/bake/bake_map_state.rs new file mode 100644 index 00000000..fec7583b --- /dev/null +++ b/crates/engine/src/bake/bake_map_state.rs @@ -0,0 +1,26 @@ +use serde::Serialize; + +/// Where one map of a bake stands, as the Baking Log shows it +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state", content = "reason")] +pub enum BakeMapState { + Waiting, + Baking, + Baked, + /// The bake of its texture set failed; the reason is the error + Failed(String), + /// The bake stopped before this map was kept + Canceled, +} + +impl BakeMapState { + /// Whether the map can still change in this bake + pub fn is_pending(&self) -> bool { + matches!(self, Self::Waiting | Self::Baking) + } + + /// Whether the map counts as an issue in the log + pub fn is_issue(&self) -> bool { + matches!(self, Self::Failed(_) | Self::Canceled) + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 844c533a..a76561fb 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,16 +843,21 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } + session.bake_log.begin(&session.doc.project, &sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { - let mut task = session.bake_task(index)?; - if cpu { - task.tracer = None; + session.bake_log.set_started(index); + let baked = bake_one_set(session, index, cpu); + match baked { + Ok(tracer) => tracers.push(tracer), + Err(error) => { + session.bake_log.set_failed(index, &error.to_string()); + // The edit rolls back the sets baked before this one too + session.bake_log.discard(); + return Err(error); + } } - let output = task.run(&Progress::new())?; - tracers.push(output.tracer.clone()); - session.store_bake(index, output)?; } Ok(tracers) })?; @@ -863,6 +868,23 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { Ok(json!({ "baked": sets, "tracer": tracers })) } +/// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log +fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result { + let mut task = session.bake_task(index)?; + if cpu { + task.tracer = None; + } + + let maps = task.maps(); + let output = task.run(&Progress::new())?; + let tracer = output.tracer.clone(); + session.store_bake(index, output)?; + for map in maps { + session.bake_log.map_baked(index, map); + } + Ok(tracer) +} + #[cfg(test)] mod named_tracer; diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 1be548db..736b00bb 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -2,6 +2,9 @@ mod bake_cage_inputs; mod bake_checks; +mod bake_log; +mod bake_log_map; +mod bake_map_state; mod bake_mesh; mod bake_meshes; mod bake_task; @@ -19,6 +22,9 @@ mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; +pub use bake_log::BakeLog; +pub use bake_log_map::BakeLogMap; +pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e1d83ead..f0a8df58 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -451,6 +451,8 @@ pub struct Session { pub solo: Option, /// The live bake preview while the app bakes (see [`crate::bake_preview`]). pub bake_preview: Option, + /// The latest bake, map by map (the Baking Log) + pub bake_log: crate::bake::BakeLog, /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, @@ -543,6 +545,7 @@ impl Session { view_image: None, solo: None, bake_preview: None, + bake_log: Default::default(), viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs new file mode 100644 index 00000000..965295e1 --- /dev/null +++ b/crates/engine/tests/it/bake_log.rs @@ -0,0 +1,50 @@ +//! The Baking Log's record of the latest bake, map by map + +use std::collections::BTreeSet; + +use serde_json::json; +use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute, sample_session}; + +#[test] +fn bake_run_lists_every_checked_map_of_the_set_as_baked() { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + + let set_name = &session.doc.project.texture_sets[0].name; + let rows = &session.bake_log.maps; + let maps: BTreeSet = rows.iter().map(|row| row.map).collect(); + assert_eq!(maps, BTreeSet::from([BakedMap::Position, BakedMap::Opacity])); + assert!(rows.iter().all(|row| row.state == BakeMapState::Baked && &row.set_name == set_name), "{rows:?}"); + assert!(!session.bake_log.is_running()); +} + +#[test] +fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { + let mut session = sample_session(256, 64).unwrap(); + for set in &mut session.doc.project.texture_sets { + set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]); + } + let log = &mut session.bake_log; + log.begin(&session.doc.project, &[0, 1]); + + log.set_started(0); + log.map_baked(0, BakedMap::Normal); + log.map_baked(0, BakedMap::Curvature); + log.set_finished(0); + log.set_started(1); + log.map_baked(1, BakedMap::Normal); + let baking: Vec<_> = log.maps.iter().filter(|row| row.state == BakeMapState::Baking).map(|row| (row.texture_set, row.map)).collect(); + assert_eq!(baking, [(1, BakedMap::Curvature)], "the next map of the running set is the one in progress"); + + log.cancel(Some(1)); + + let state_of = |set: usize| log.maps.iter().filter(move |row| row.texture_set == set).map(|row| row.state.clone()).collect::>(); + assert!(state_of(0).iter().all(|state| *state == BakeMapState::Baked), "{:?}", log.maps); + assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps); + assert!(!log.is_running()); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b1879df3..11b199c9 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -4,6 +4,7 @@ mod add_mask_items; mod bake; mod bake_checks; +mod bake_log; mod bake_resolution; mod bake_settings; mod bake_tiles; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9f0b6d70..16cbee1e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -706,6 +706,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); + self.session.bake_log.begin(&self.session.doc.project, &sets); self.bake_report = bake_report::BakeReport::started(self.last_time); self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } @@ -824,6 +825,7 @@ impl TextureCraftApp { if let Some(running) = &job.current { running.progress.cancel.store(true, Ordering::Relaxed); } + self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); self.bake = None; return; } @@ -835,6 +837,7 @@ impl TextureCraftApp { // Wait for the sender to close so the last map also gets a preview frame match running.maps.try_recv() { Ok(map) => { + self.session.bake_log.map_baked(set_index, map.map); self.session.bake_preview_map(set_index, map); return; } @@ -848,7 +851,10 @@ impl TextureCraftApp { job.current = None; match self.session.apply_streamed_bake(set_index, output) { - Ok(()) => self.bake_report.map_count += maps_baked, + Ok(()) => { + self.session.bake_log.set_finished(set_index); + self.bake_report.map_count += maps_baked; + } Err(error) => self.bake_failed(set_index, &error.to_string()), } } @@ -882,6 +888,7 @@ impl TextureCraftApp { let only = job.only; self.session.bake_preview_set_current(set_index); + self.session.bake_log.set_started(set_index); let task = match only { Some(map) => self.session.bake_task_only(set_index, map), None => self.session.bake_task(set_index), @@ -914,6 +921,7 @@ impl TextureCraftApp { /// Note a texture set whose bake failed: one Log line, counted in the summary fn bake_failed(&mut self, set_index: usize, error: &str) { self.session.log.error("Baker", format!("Bake of texture set {set_index} failed: {error}")); + self.session.bake_log.set_failed(set_index, error); self.bake_report.failed_set_count += 1; } @@ -937,6 +945,7 @@ impl TextureCraftApp { pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; + self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); if let Some(running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); } From e24f4e28d89abc09bb654a701ae880e6b31e2302 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:55:44 +0000 Subject: [PATCH 087/190] Show the latest bake in the Baking Log's tabs The Baking Log gets the three tabs from the issue's mock-ups (Baking Process, High Poly Parameters, Matching by Name) in the Properties section-tab look. Baking Process lists one row per texture set and map: a tick when baked, orange dots and bold for the map being baked (kept in view), dim while waiting, a red cross or a warning when not kept, with the reason on hover. The tab's icon turns into orange dots while a bake runs. --- crates/ui-egui/src/baking_log.rs | 146 ++++++++++++++++++ .../ui-egui/src/baking_log/baking_log_tab.rs | 36 +++++ crates/ui-egui/src/docking.rs | 8 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/property_sheet/mod.rs | 3 +- .../src/property_sheet/section_tabs.rs | 2 +- .../src/property_sheet/switch_control.rs | 2 +- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/tests/it/baking_log.rs | 60 +++++++ crates/ui-egui/tests/it/main.rs | 1 + 10 files changed, 253 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/baking_log.rs create mode 100644 crates/ui-egui/src/baking_log/baking_log_tab.rs create mode 100644 crates/ui-egui/tests/it/baking_log.rs diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs new file mode 100644 index 00000000..bacf194e --- /dev/null +++ b/crates/ui-egui/src/baking_log.rs @@ -0,0 +1,146 @@ +//! The Baking Log panel: the latest bake under three tabs, read from the session's bake record + +use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr}; +use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_TEXT_SIZE, TAB_TOP, shown_tab_box}; +use crate::theme::{Tokens, semibold}; + +mod baking_log_tab; + +pub use baking_log_tab::BakingLogTab; + +/// Height of the tab strip, as the Properties section tabs +const STRIP_HEIGHT: f32 = 30.0; + +/// How far the first tab reaches left of the rows' side padding, as the Properties section tabs +const FIRST_TAB_OUTDENT: f32 = 4.0; + +/// Height of one row of a list +const ROW_HEIGHT: f32 = 24.0; + +/// Air above the first row +const LIST_TOP: f32 = 4.0; + +/// How far a hovered row's fill stays inside the panel's sides +const HOVER_INSET: f32 = 3.0; + +/// From the panel's left edge to a row's glyph centre, and to its name +const GLYPH_CENTER: f32 = SIDE_PADDING_POINTS + 6.0; +const NAME_LEFT: f32 = SIDE_PADDING_POINTS + 22.0; + +/// Size of a row's glyph and of its name +const GLYPH_SIZE: f32 = 13.0; +const NAME_SIZE: f32 = 12.0; + +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + let running = app.session.bake_log.is_running(); + if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { + app.ui.baking_log_tab = tab; + } + + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + ui.add_space(LIST_TOP); + if app.ui.baking_log_tab == BakingLogTab::BakingProcess { + baking_process(ui, &app.session.bake_log.maps); + } + }); +} + +/// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); + + let mut picked = None; + let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; + for tab in BakingLogTab::ALL { + let name = tr(tab.name()); + let on = tab == shown; + let width = ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING; + let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom())); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_tab", tab)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); + if response.clicked() { + picked = Some(tab); + } + + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, rect); + } + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let in_progress = running && tab == BakingLogTab::BakingProcess; + let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); + } + + left += width + TAB_GAP; + } + picked +} + +/// One row per texture set and map, in bake order; the map being baked stays in view +fn baking_process(ui: &mut Ui, maps: &[BakeLogMap]) { + let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); + let follow_id = Id::unique("baking_log_followed_map"); + let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); + ui.data_mut(|data| data.insert_temp(follow_id, followed)); + + for (index, row) in maps.iter().enumerate() { + let rect = map_row(ui, row); + if newly_followed && followed == Some(index) { + ui.scroll_to_rect(rect, None); + } + } +} + +/// A map's row: its state's glyph, then " "; a map that was not baked tells why on hover +fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let name = format!("{} {}", row.set_name, tr(baked_map_label(row.map))); + let (glyph, glyph_color, state) = match &row.state { + BakeMapState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")), + BakeMapState::Baking => (ic::DOTS_THREE, tokens.accent, tr("Baking")), + BakeMapState::Baked => (ic::CHECK, tokens.text, tr("Baked")), + BakeMapState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not baked")), + BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), + }; + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color); + let (font, color) = match row.state { + BakeMapState::Baking => (semibold(NAME_SIZE), tokens.text), + BakeMapState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), + _ => (FontId::proportional(NAME_SIZE), tokens.text), + }; + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + + let reason = match &row.state { + BakeMapState::Failed(reason) => Some(reason.as_str()), + BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } + rect +} diff --git a/crates/ui-egui/src/baking_log/baking_log_tab.rs b/crates/ui-egui/src/baking_log/baking_log_tab.rs new file mode 100644 index 00000000..ccff71b0 --- /dev/null +++ b/crates/ui-egui/src/baking_log/baking_log_tab.rs @@ -0,0 +1,36 @@ +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::i18n::n_; + +/// The Baking Log panel's tabs +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum BakingLogTab { + /// Every map of the latest bake and how it went + #[default] + BakingProcess, + /// The high poly files each texture set bakes from + HighPolyParameters, + /// Which low poly part bakes from which high poly part + MatchingByName, +} + +impl BakingLogTab { + pub const ALL: [BakingLogTab; 3] = [BakingLogTab::BakingProcess, BakingLogTab::HighPolyParameters, BakingLogTab::MatchingByName]; + + pub fn name(self) -> &'static str { + match self { + BakingLogTab::BakingProcess => n_("Baking Process"), + BakingLogTab::HighPolyParameters => n_("High Poly Parameters"), + BakingLogTab::MatchingByName => n_("Matching by Name"), + } + } + + pub(crate) fn icon(self) -> &'static str { + match self { + BakingLogTab::BakingProcess => ic::LIST_CHECKS, + BakingLogTab::HighPolyParameters => ic::CUBE, + BakingLogTab::MatchingByName => ic::ARROWS_LEFT_RIGHT, + } + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 85edb126..f1acd9e7 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -612,13 +612,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { Panel::Shader => crate::shader_settings::body(app, ui), Panel::History => crate::windows::history(app, ui), Panel::Log => crate::log_panel::body(app, ui), - Panel::BakingLog => { - egui::ScrollArea::vertical().show(ui, |ui| { - for entry in app.session.log.entries().iter().filter(|entry| entry.source == "Baker") { - ui.label(entry.line()); - } - }); - } + Panel::BakingLog => crate::baking_log::body(app, ui), Panel::Export => crate::export_panel::body(app, ui), Panel::Renderer => crate::render_mode::settings_body(app, ui), Panel::Viewport => {} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 16cbee1e..a786eef7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -14,6 +14,7 @@ mod ask; mod autosave_name; mod bake_job; pub mod bake_mode; +pub mod baking_log; mod bake_preset; pub mod bake_presets; mod bake_report; diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 51c6ecfb..def4354d 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -75,13 +75,14 @@ pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection}; pub(crate) use row_lead::RowLead; pub(crate) use section_tabs::{ SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, in_scope, - room_past_end, section_tabs, + room_past_end, section_tabs, shown_tab_box, }; pub(crate) use sheet::PropertySheet; pub(crate) use size_columns_response::SizeColumnsResponse; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; pub(crate) use stacked_rows::{CHECK_SIZE, paint_check}; +pub(crate) use switch_control::paint_focus_outline; pub(crate) fn paint_keyboard_focus(ui: &egui::Ui, response: &egui::Response, tokens: &crate::theme::Tokens) { if response.has_focus() { diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 595116ca..754c3fd2 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -110,7 +110,7 @@ fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect { } /// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip -fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { +pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 8f700a6d..c6b8fa18 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -63,7 +63,7 @@ pub(super) fn untinted(_index: usize) -> &'static [Color32] { &[] } -pub(super) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) { +pub(crate) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) { painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(FOCUS_OUTLINE_WIDTH, color), StrokeKind::Inside); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ff897d80..6afa5c9b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -681,6 +681,9 @@ pub struct UiState { /// The Log panel's shown channel tab #[serde(default)] pub log_channel: crate::log_panel::LogChannel, + /// The Baking Log panel's shown tab + #[serde(default)] + pub baking_log_tab: crate::baking_log::BakingLogTab, /// The project template the last New project was created from (name or label) #[serde(default)] pub last_template: String, @@ -844,6 +847,7 @@ impl Default for UiState { bake_preset_name: String::new(), layout_dialog: None, log_channel: crate::log_panel::LogChannel::default(), + baking_log_tab: crate::baking_log::BakingLogTab::default(), last_template: String::new(), log_selection: Default::default(), log_anchor: None, diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs new file mode 100644 index 00000000..c69c2fcc --- /dev/null +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -0,0 +1,60 @@ +//! The Baking Log panel: the latest bake, map by map + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.select([BakedMap::Id, BakedMap::Position]); + } + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness +} + +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..4000 { + harness.run_steps(1); + if harness.state().bake.is_none() { + harness.run_steps(2); + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { + let mut harness = harness(); + { + // Set 1 has no tile left to bake, so its bake fails + let set = &mut harness.state_mut().session.doc.project.texture_sets[1]; + set.uv_tiles = vec![1001]; + set.bake_excluded_tiles.insert(1001); + set.bake.maps.select([BakedMap::Id]); + } + assert!(harness.state().ui.dock.is_visible(Panel::BakingLog), "the bake layout shows the Baking Log"); + + harness.state_mut().start_bake(vec![0, 1]); + run_to_the_end(&mut harness); + + let names: Vec = harness.state().session.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); + for map in ["ID", "Position"] { + assert!(harness.query_by_label(&format!("{} {map}, Baked", names[0])).is_some(), "set 0's {map} row is ticked"); + } + assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0129eb7a..045d3d57 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -10,6 +10,7 @@ mod bake_mode; mod bake_presets; mod bake_reset_menus; mod bake_sync; +mod baking_log; mod brush_drag; mod brush_section_reset; mod camera_views; From d908c4a49e7d40a221ab5c4c666df43f2f137b96 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:04:36 +0000 Subject: [PATCH 088/190] Open a not-baked map's settings from its Baking Log row A failed or canceled row shows an arrow at its right end while hovered or focused; it makes the row's texture set active and shows the map in Mesh Map Settings, as picking it in Mesh Map Bakers does. --- crates/ui-egui/src/baking_log.rs | 85 ++++++++++++++++++++++----- crates/ui-egui/tests/it/baking_log.rs | 46 ++++++++++++--- 2 files changed, 107 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index bacf194e..7d59cd29 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -2,10 +2,13 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; +use serde_json::json; use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; -use crate::i18n::{baked_map_label, tr}; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr, trf}; use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_TEXT_SIZE, TAB_TOP, shown_tab_box}; use crate::theme::{Tokens, semibold}; @@ -36,18 +39,43 @@ const NAME_LEFT: f32 = SIDE_PADDING_POINTS + 22.0; const GLYPH_SIZE: f32 = 13.0; const NAME_SIZE: f32 = 12.0; +/// Size of the open-settings arrow at an issue row's right end, and of the square it answers clicks in +const OPEN_ICON_SIZE: f32 = 14.0; +const OPEN_BUTTON_SIZE: f32 = 20.0; + pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let running = app.session.bake_log.is_running(); if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { app.ui.baking_log_tab = tab; } - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.add_space(LIST_TOP); - if app.ui.baking_log_tab == BakingLogTab::BakingProcess { - baking_process(ui, &app.session.bake_log.maps); - } - }); + let opened = egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.add_space(LIST_TOP); + match app.ui.baking_log_tab { + BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps), + _ => None, + } + }) + .inner; + if let Some((texture_set, map)) = opened { + open_map_settings(app, texture_set, map); + } +} + +/// Show `map`'s settings of `texture_set` in Mesh Map Settings, as picking it in Mesh Map Bakers does +fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { + // The set may have been deleted since the bake + if texture_set >= app.session.set_count() { + return; + } + + if texture_set != app.session.ts() { + app.run("textureSet.select", json!({ "ts": texture_set })); + } + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); } /// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon @@ -89,23 +117,28 @@ fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option Option<(usize, BakedMap)> { let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); let follow_id = Id::unique("baking_log_followed_map"); let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); ui.data_mut(|data| data.insert_temp(follow_id, followed)); + let mut opened = None; for (index, row) in maps.iter().enumerate() { - let rect = map_row(ui, row); + let (rect, open_clicked) = map_row(ui, row); if newly_followed && followed == Some(index) { ui.scroll_to_rect(rect, None); } + if open_clicked { + opened = Some((row.texture_set, row.map)); + } } + opened } -/// A map's row: its state's glyph, then " "; a map that was not baked tells why on hover -fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { +/// A map's row: glyph, then " "; a map not baked tells why on hover and has an arrow to its settings; returns the row and whether the arrow was clicked +fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { let tokens = Tokens::get(ui.ctx()); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let name = format!("{} {}", row.set_name, tr(baked_map_label(row.map))); @@ -117,9 +150,11 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + let open = row.state.is_issue().then(|| open_settings_button(ui, rect, &name)); + let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); let painter = ui.painter(); - if response.hovered() { + if row_hovered { painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); } let center_y = rect.center().y; @@ -129,7 +164,16 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { BakeMapState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), _ => (FontId::proportional(NAME_SIZE), tokens.text), }; - painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, &name, font, color); + if let Some(open) = &open + && (row_hovered || open.has_focus()) + { + let color = if open.hovered() || open.has_focus() { tokens.text } else { tokens.text_dim }; + painter.text(open.rect.center(), Align2::CENTER_CENTER, ic::ARROW_SQUARE_OUT, FontId::proportional(OPEN_ICON_SIZE), color); + if open.has_focus() { + crate::property_sheet::paint_focus_outline(painter, open.rect, tokens.text_strong); + } + } let reason = match &row.state { BakeMapState::Failed(reason) => Some(reason.as_str()), @@ -142,5 +186,16 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); }); } - rect + let open_clicked = open.is_some_and(|open| open.clicked()); + (rect, open_clicked) +} + +/// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus +fn open_settings_button(ui: &mut Ui, row: Rect, name: &str) -> egui::Response { + let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); + let rect = Rect::from_center_size(center, vec2(OPEN_BUTTON_SIZE, OPEN_BUTTON_SIZE)); + let label = trf("Open the {name} settings", &[("name", &name)]); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", name)), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label)); + response.on_hover_text(label) } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index c69c2fcc..d10d63cc 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -37,20 +37,23 @@ fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { panic!("the bake did not finish"); } +/// Bake sets 0 and 1, where set 1 has no tile left to bake, so its bake fails +fn bake_with_set_1_failing(harness: &mut Harness<'static, TextureCraftApp>, set_1_maps: &[BakedMap]) { + let set = &mut harness.state_mut().session.doc.project.texture_sets[1]; + set.uv_tiles = vec![1001]; + set.bake_excluded_tiles.insert(1001); + set.bake.maps.select(set_1_maps.iter().copied()); + + harness.state_mut().start_bake(vec![0, 1]); + run_to_the_end(harness); +} + #[test] fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { let mut harness = harness(); - { - // Set 1 has no tile left to bake, so its bake fails - let set = &mut harness.state_mut().session.doc.project.texture_sets[1]; - set.uv_tiles = vec![1001]; - set.bake_excluded_tiles.insert(1001); - set.bake.maps.select([BakedMap::Id]); - } assert!(harness.state().ui.dock.is_visible(Panel::BakingLog), "the bake layout shows the Baking Log"); - harness.state_mut().start_bake(vec![0, 1]); - run_to_the_end(&mut harness); + bake_with_set_1_failing(&mut harness, &[BakedMap::Id]); let names: Vec = harness.state().session.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); for map in ["ID", "Position"] { @@ -58,3 +61,28 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { } assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } + +#[test] +fn a_failed_maps_arrow_opens_its_settings() { + let mut harness = harness(); + + // Three rows fit the docked log without scrolling + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Id]); + bake_with_set_1_failing(&mut harness, &[BakedMap::Id, BakedMap::Position]); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + assert_eq!(harness.state().session.ts(), 0); + assert!(harness.query_by_label("Normalization Scale").is_none(), "Position's settings are not shown yet"); + + let set_name = harness.state().session.doc.project.texture_sets[1].name.clone(); + harness.get_by_label(&format!("Open the {set_name} Position settings")).click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.ts(), 1, "the failed map's texture set is the active one"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "the arrow fronts Mesh Map Settings"); + harness.get_by_label("Normalization Scale"); + assert!( + harness.query_by_label(&format!("Open the {} ID settings", harness.state().session.doc.project.texture_sets[0].name)).is_none(), + "a baked map has no arrow" + ); +} From ec17def3375aa78e0e2d697c4d44512c9f8456f1 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:06:33 +0000 Subject: [PATCH 089/190] Keep only the issues in the Baking Log on demand A warning toggle at the right end of the tab strip counts the shown tab's issues and, while pressed, keeps only the rows with one. With no issue left the tab says so in one line, with how to see every row under it. --- crates/ui-egui/src/baking_log.rs | 111 +++++++++++++++++++++++--- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/tests/it/baking_log.rs | 41 ++++++++++ 3 files changed, 143 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 7d59cd29..1688d940 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -1,6 +1,6 @@ //! The Baking Log panel: the latest bake under three tabs, read from the session's bake record -use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; @@ -43,18 +43,56 @@ const NAME_SIZE: f32 = 12.0; const OPEN_ICON_SIZE: f32 = 14.0; const OPEN_BUTTON_SIZE: f32 = 20.0; +/// Height of the issues filter toggle, and its width without a count +const FILTER_HEIGHT: f32 = 22.0; +const FILTER_BUTTON_WIDTH: f32 = 30.0; + +/// How far the issues filter sits below the strip's centre, and how far it reaches past the side padding +const FILTER_DROP: f32 = 1.0; +const FILTER_OUTDENT: f32 = 4.0; + +/// Corner rounding of the issues filter's pressed and hovered fill +const FILTER_ROUNDING: f32 = 5.0; + +/// From the issues filter's left edge to its glyph's centre and to its count, and the glyph's size +const FILTER_GLYPH_CENTER: f32 = 15.0; +const FILTER_COUNT_LEFT: f32 = 26.0; +const FILTER_GLYPH_SIZE: f32 = 14.0; + +/// Air between the issue count and the toggle's right end +const FILTER_COUNT_GAP: f32 = 4.0; + +/// Height of the two lines the issues filter leaves when nothing is wrong, to centre them +const EMPTY_TEXT_HEIGHT: f32 = 40.0; + pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let running = app.session.bake_log.is_running(); - if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); + if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, app.session.bake_log.is_running()) { app.ui.baking_log_tab = tab; } + let tab = app.ui.baking_log_tab; + let issue_count = match tab { + BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), + _ => 0, + }; + if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { + app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; + } + + let issues_only = app.ui.baking_log_issues_only; + if issues_only && issue_count == 0 { + no_issues(ui, tab); + return; + } let opened = egui::ScrollArea::vertical() .auto_shrink([false, false]) .show(ui, |ui| { ui.add_space(LIST_TOP); - match app.ui.baking_log_tab { - BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps), + match tab { + BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), _ => None, } }) @@ -78,12 +116,9 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa app.ui.dock.focus(Panel::MeshMapSettings); } -/// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon -fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option { +/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option { let tokens = Tokens::get(ui.ctx()); - let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); - ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - let mut picked = None; let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; for tab in BakingLogTab::ALL { @@ -117,15 +152,65 @@ fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option Option<(usize, BakedMap)> { +/// The toggle at the `strip`'s right end that keeps only the rows with an issue: a warning glyph and how many there are +fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); + let count = (issue_count > 0).then(|| issue_count.to_string()); + let count_width = + count.as_ref().map_or(0.0, |count| ui.painter().layout_no_wrap(count.clone(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP); + let right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT; + let center_y = strip.center().y + FILTER_DROP; + let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); + + let name = match &count { + Some(count) => trf("{count}, Show Only Issues", &[("count", count)]), + None => tr("Show Only Issues").to_owned(), + }; + let response = ui.interact(rect, ui.scope_id().with("baking_log_issues_filter"), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, on, &name)); + + let painter = ui.painter(); + if on { + painter.rect(rect, FILTER_ROUNDING, tokens.tool_active, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, FILTER_ROUNDING, tokens.row_hover); + } + let glyph_color = if count.is_some() { tokens.warning } else { tokens.text_dim }; + painter.text(pos2(rect.left() + FILTER_GLYPH_CENTER, center_y), Align2::CENTER_CENTER, ic::WARNING, FontId::proportional(FILTER_GLYPH_SIZE), glyph_color); + if let Some(count) = count { + painter.text(pos2(rect.left() + FILTER_COUNT_LEFT, center_y), Align2::LEFT_CENTER, count, semibold(NAME_SIZE), tokens.text); + } + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + response.on_hover_text(tr("Show Only Issues")).clicked() +} + +/// What the issues filter leaves when `tab` has no issue: the reference's words for that tab, and how to see every row +fn no_issues(ui: &mut Ui, tab: BakingLogTab) { + let tokens = Tokens::get(ui.ctx()); + let message = match tab { + BakingLogTab::BakingProcess => tr("All textures baked successfully so far."), + BakingLogTab::HighPolyParameters => tr("No issues encountered so far."), + BakingLogTab::MatchingByName => tr("No matching issues encountered"), + }; + let area = ui.available_rect_before_wrap(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); + child.add_space((area.height() - EMPTY_TEXT_HEIGHT).max(0.0) / 2.0); + child.label(egui::RichText::new(message).font(semibold(NAME_SIZE)).color(tokens.text)); + child.label(egui::RichText::new(tr("Deselect filter to view.")).size(NAME_SIZE).color(tokens.text_dim)); + ui.allocate_rect(area, Sense::hover()); +} + +/// One row per texture set and map (with an issue, if `issues_only`) in bake order, following the map being baked; returns the map to open +fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option<(usize, BakedMap)> { let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); let follow_id = Id::unique("baking_log_followed_map"); let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); ui.data_mut(|data| data.insert_temp(follow_id, followed)); let mut opened = None; - for (index, row) in maps.iter().enumerate() { + for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) { let (rect, open_clicked) = map_row(ui, row); if newly_followed && followed == Some(index) { ui.scroll_to_rect(rect, None); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6afa5c9b..c30cb883 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -684,6 +684,9 @@ pub struct UiState { /// The Baking Log panel's shown tab #[serde(default)] pub baking_log_tab: crate::baking_log::BakingLogTab, + /// Whether the Baking Log keeps only the rows with an issue + #[serde(default)] + pub baking_log_issues_only: bool, /// The project template the last New project was created from (name or label) #[serde(default)] pub last_template: String, @@ -848,6 +851,7 @@ impl Default for UiState { layout_dialog: None, log_channel: crate::log_panel::LogChannel::default(), baking_log_tab: crate::baking_log::BakingLogTab::default(), + baking_log_issues_only: false, last_template: String::new(), log_selection: Default::default(), log_anchor: None, diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index d10d63cc..9f56d585 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,6 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; +use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -86,3 +87,43 @@ fn a_failed_maps_arrow_opens_its_settings() { "a baked map has no arrow" ); } + +/// Put a finished bake of set 0's ID and Position maps in the log, the Position map ending as `position` +fn log_a_bake(harness: &mut Harness<'static, TextureCraftApp>, position: BakeMapState) -> String { + let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); + let row = |map, state| BakeLogMap { texture_set: 0, set_name: set_name.clone(), map, state }; + harness.state_mut().session.bake_log.maps = vec![row(BakedMap::Id, BakeMapState::Baked), row(BakedMap::Position, position)]; + harness.run_steps(3); + set_name +} + +#[test] +fn the_issues_filter_keeps_only_the_maps_with_a_problem() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Failed("The high poly file could not be read.".into())); + harness.get_by_label(&format!("{set_name} ID, Baked")); + + harness.get_by_label("1, Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none(), "a baked map is filtered out"); + harness.get_by_label(&format!("{set_name} Position, Not baked")); + assert!(harness.query_by_label("Deselect filter to view.").is_none(), "an issue left: no empty text"); +} + +#[test] +fn the_issues_filter_says_so_when_nothing_went_wrong() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Baked); + harness.get_by_label("Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none()); + harness.get_by_label("All textures baked successfully so far."); + harness.get_by_label("Deselect filter to view."); + + harness.get_by_label("Show Only Issues").click(); + harness.run_steps(3); + harness.get_by_label(&format!("{set_name} ID, Baked")); + assert!(harness.query_by_label("All textures baked successfully so far.").is_none(), "off again: every row is back"); +} From dfafec43c14e0738ca12c28cb094df48a6b5aa66 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:09:06 +0000 Subject: [PATCH 090/190] Report the Baking Log's rows through bake.log Automation gets the latest bake map by map with each map's state and the error of a failed one, the same rows the Baking Log shows. --- crates/engine/src/bake/bake_log.rs | 3 +-- crates/engine/src/bake/bake_log_map.rs | 5 +--- crates/engine/src/bake_log_cmds.rs | 36 ++++++++++++++++++++++++++ crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/tests/it/bake_log.rs | 17 ++++++++++++ docs/control-protocol.md | 8 ++++++ 7 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/bake_log_cmds.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 2f263cf2..d8705039 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,10 +1,9 @@ -use serde::Serialize; use texturecraft_core::{BakedMap, Project}; use super::{BakeLogMap, BakeMapState}; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines -#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct BakeLog { pub maps: Vec, } diff --git a/crates/engine/src/bake/bake_log_map.rs b/crates/engine/src/bake/bake_log_map.rs index 4a04bd7d..6f5d714a 100644 --- a/crates/engine/src/bake/bake_log_map.rs +++ b/crates/engine/src/bake/bake_log_map.rs @@ -1,15 +1,12 @@ -use serde::Serialize; use texturecraft_core::BakedMap; use super::BakeMapState; /// One row of the Baking Log's process list: a map of a texture set in the latest bake -#[derive(Clone, Debug, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] +#[derive(Clone, Debug, PartialEq)] pub struct BakeLogMap { pub texture_set: usize, pub set_name: String, pub map: BakedMap, - #[serde(flatten)] pub state: BakeMapState, } diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs new file mode 100644 index 00000000..dc8e243e --- /dev/null +++ b/crates/engine/src/bake_log_cmds.rs @@ -0,0 +1,36 @@ +//! The `bake.log` query: the Baking Log's rows for automation + +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "bake.log", + "Baking log", + [], + None, + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, as the Baking Log shows it; `reason` says why a map failed. Empty before the first bake", + always, + log + )] +} + +fn log(session: &mut Session, _: &Value) -> Result { + let maps = session + .bake_log + .maps + .iter() + .map(|row| { + let mut entry = serde_json::to_value(&row.state).map_err(|error| bad("bake.log", error.to_string()))?; + if let Some(fields) = entry.as_object_mut() { + fields.insert("textureSet".into(), json!(row.texture_set)); + fields.insert("setName".into(), json!(row.set_name)); + fields.insert("map".into(), json!(row.map.id())); + } + Ok(entry) + }) + .collect::>>()?; + Ok(json!({ "running": session.bake_log.is_running(), "maps": maps })) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 49cead62..41e7d619 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -139,6 +139,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::project_cmds::specs()); v.extend(crate::bake::specs()); v.extend(crate::bake_preview::specs()); + v.extend(crate::bake_log_cmds::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::pbr_cmds::specs()); v.extend(crate::file_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 148af463..ab6319f7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod add_mask_cmds; mod anchored_micro_edit; pub mod bake; +pub mod bake_log_cmds; pub mod bake_preview; pub mod brush_preset_cmds; pub mod camera_cmds; diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 965295e1..955d5561 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -48,3 +48,20 @@ fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps); assert!(!log.is_running()); } + +#[test] +fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["running"], false); + let maps: BTreeSet<&str> = log["maps"].as_array().unwrap().iter().map(|row| row["map"].as_str().unwrap()).collect(); + assert_eq!(maps, BTreeSet::from(["opacity", "position"])); + assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "baked" && row["textureSet"] == 0 && row.get("reason").is_none()), "{log}"); + + session.bake_log.set_failed(0, "The high poly file could not be read."); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3abb3a97..feb3627f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -305,6 +305,14 @@ also `session.inspect`'s `bakePreview`: "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} ``` +`bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). +`state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`: + +```json +{"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}]} +``` + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From c0839e873e26ec920b7a8368d3cb8eeea37327bf Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:21:07 +0000 Subject: [PATCH 091/190] List each set's high poly files in the Baking Log --- crates/engine/src/bake/bake_high_state.rs | 27 +++++ crates/engine/src/bake/bake_log.rs | 50 +++++++++- crates/engine/src/bake/bake_log_high.rs | 11 +++ crates/engine/src/bake/mesh_map_command.rs | 3 +- crates/engine/src/bake/mod.rs | 4 + crates/engine/src/bake_log_cmds.rs | 32 +++--- crates/engine/tests/it/bake_log.rs | 37 ++++++- crates/ui-egui/src/baking_log.rs | 22 +++-- .../ui-egui/src/baking_log/high_poly_list.rs | 98 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/tests/it/baking_log.rs | 35 ++++++- docs/control-protocol.md | 7 +- 12 files changed, 296 insertions(+), 33 deletions(-) create mode 100644 crates/engine/src/bake/bake_high_state.rs create mode 100644 crates/engine/src/bake/bake_log_high.rs create mode 100644 crates/ui-egui/src/baking_log/high_poly_list.rs diff --git a/crates/engine/src/bake/bake_high_state.rs b/crates/engine/src/bake/bake_high_state.rs new file mode 100644 index 00000000..8ecbd0a5 --- /dev/null +++ b/crates/engine/src/bake/bake_high_state.rs @@ -0,0 +1,27 @@ +use serde::Serialize; + +/// Where one high poly file of a bake stands, as the Baking Log shows it +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state", content = "reason")] +pub enum BakeHighState { + /// Its texture set has not started baking + Waiting, + Loading, + Loaded, + /// Its texture set's bake failed while getting the high polys ready; the reason is the error + Failed(String), + /// The bake stopped before the file was loaded + Canceled, +} + +impl BakeHighState { + /// Whether the file can still change in this bake + pub fn is_pending(&self) -> bool { + matches!(self, Self::Waiting | Self::Loading) + } + + /// Whether the file counts as an issue in the log + pub fn is_issue(&self) -> bool { + matches!(self, Self::Failed(_) | Self::Canceled) + } +} diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index d8705039..82f63c90 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,16 +1,18 @@ use texturecraft_core::{BakedMap, Project}; -use super::{BakeLogMap, BakeMapState}; +use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState, BakeMesh}; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines #[derive(Clone, Debug, Default, PartialEq)] pub struct BakeLog { pub maps: Vec, + /// Each high poly file of each texture set that bakes from the high polys, in bake order + pub highs: Vec, } impl BakeLog { - /// Start over for a bake of `sets`: every checked map of each set, waiting, in bake order - pub fn begin(&mut self, project: &Project, sets: &[usize]) { + /// Start over for a bake of `sets`: every checked map of each set and the `high_polys` of each set that bakes from them, waiting, in bake order + pub fn begin(&mut self, project: &Project, high_polys: &[BakeMesh], sets: &[usize]) { self.maps = sets .iter() .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) @@ -18,13 +20,36 @@ impl BakeLog { set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting }) }) .collect(); + self.highs = sets + .iter() + .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) + .filter(|(_, set)| !set.bake.high_poly.use_low_as_high) + .flat_map(|(index, set)| { + high_polys.iter().map(move |high| BakeLogHigh { + texture_set: index, + set_name: set.name.clone(), + file: high.name.clone(), + state: BakeHighState::Waiting, + }) + }) + .collect(); } - /// `set` starts baking: its first map is the one in progress + /// `set` starts baking: its high polys load and its first map is the one in progress pub fn set_started(&mut self, set: usize) { + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Waiting) { + row.state = BakeHighState::Loading; + } self.start_next(set); } + /// `set`'s bake has its high polys ready + pub fn high_polys_loaded(&mut self, set: usize) { + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Loading) { + row.state = BakeHighState::Loaded; + } + } + /// `map` of `set` is baked; the set's next map starts pub fn map_baked(&mut self, set: usize, map: BakedMap) { if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) { @@ -45,6 +70,10 @@ impl BakeLog { for row in self.maps.iter_mut().filter(|row| row.texture_set == set) { row.state = BakeMapState::Failed(reason.to_owned()); } + // A file that loaded is not what failed + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) { + row.state = BakeHighState::Failed(reason.to_owned()); + } } /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled @@ -54,6 +83,7 @@ impl BakeLog { row.state = BakeMapState::Canceled; } } + self.cancel_pending_highs(); } /// The whole bake was rolled back: every map that did not fail is canceled @@ -61,6 +91,7 @@ impl BakeLog { for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) { row.state = BakeMapState::Canceled; } + self.cancel_pending_highs(); } /// Whether a map is still waiting or baking @@ -68,6 +99,17 @@ impl BakeLog { self.maps.iter().any(|row| row.state.is_pending()) } + /// Whether a high poly file is still waiting or loading + pub fn is_loading_high_polys(&self) -> bool { + self.highs.iter().any(|row| row.state.is_pending()) + } + + fn cancel_pending_highs(&mut self) { + for row in self.highs.iter_mut().filter(|row| row.state.is_pending()) { + row.state = BakeHighState::Canceled; + } + } + fn start_next(&mut self, set: usize) { if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) { return; diff --git a/crates/engine/src/bake/bake_log_high.rs b/crates/engine/src/bake/bake_log_high.rs new file mode 100644 index 00000000..7c6de83d --- /dev/null +++ b/crates/engine/src/bake/bake_log_high.rs @@ -0,0 +1,11 @@ +use super::BakeHighState; + +/// One row of the Baking Log's high poly list: a high poly file a texture set bakes from in the latest bake +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogHigh { + pub texture_set: usize, + pub set_name: String, + /// The file's name as the project keeps it (the project carries the file itself, not where it came from) + pub file: String, + pub state: BakeHighState, +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index a76561fb..e3f16c22 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,7 +843,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } - session.bake_log.begin(&session.doc.project, &sets); + session.bake_log.begin(&session.doc.project, &session.bake_meshes.high, &sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { @@ -871,6 +871,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { /// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result { let mut task = session.bake_task(index)?; + session.bake_log.high_polys_loaded(index); if cpu { task.tracer = None; } diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 736b00bb..873c2f35 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -2,7 +2,9 @@ mod bake_cage_inputs; mod bake_checks; +mod bake_high_state; mod bake_log; +mod bake_log_high; mod bake_log_map; mod bake_map_state; mod bake_mesh; @@ -22,7 +24,9 @@ mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; +pub use bake_high_state::BakeHighState; pub use bake_log::BakeLog; +pub use bake_log_high::BakeLogHigh; pub use bake_log_map::BakeLogMap; pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs index dc8e243e..edfbd15a 100644 --- a/crates/engine/src/bake_log_cmds.rs +++ b/crates/engine/src/bake_log_cmds.rs @@ -11,26 +11,26 @@ pub fn specs() -> Vec { "Baking log", [], None, - "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, as the Baking Log shows it; `reason` says why a map failed. Empty before the first bake", + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, and the high poly files each set bakes from, as the Baking Log shows them; `reason` says why a map or file failed. Empty before the first bake", always, log )] } fn log(session: &mut Session, _: &Value) -> Result { - let maps = session - .bake_log - .maps - .iter() - .map(|row| { - let mut entry = serde_json::to_value(&row.state).map_err(|error| bad("bake.log", error.to_string()))?; - if let Some(fields) = entry.as_object_mut() { - fields.insert("textureSet".into(), json!(row.texture_set)); - fields.insert("setName".into(), json!(row.set_name)); - fields.insert("map".into(), json!(row.map.id())); - } - Ok(entry) - }) - .collect::>>()?; - Ok(json!({ "running": session.bake_log.is_running(), "maps": maps })) + let log = &session.bake_log; + let maps = log.maps.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "map", json!(row.map.id()))).collect::>>()?; + let highs = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::>>()?; + Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": highs })) +} + +/// One row: its `state` (and `reason`), its texture set, and what it is under `key` +fn entry(state: &impl serde::Serialize, texture_set: usize, set_name: &str, key: &str, what: Value) -> Result { + let mut entry = serde_json::to_value(state).map_err(|error| bad("bake.log", error.to_string()))?; + if let Some(fields) = entry.as_object_mut() { + fields.insert("textureSet".into(), json!(texture_set)); + fields.insert("setName".into(), json!(set_name)); + fields.insert(key.into(), what); + } + Ok(entry) } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 955d5561..36ce7772 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -3,7 +3,7 @@ use std::collections::BTreeSet; use serde_json::json; -use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::bake::{BakeHighState, BakeMapState}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -30,7 +30,7 @@ fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]); } let log = &mut session.bake_log; - log.begin(&session.doc.project, &[0, 1]); + log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); log.set_started(0); log.map_baked(0, BakedMap::Normal); @@ -65,3 +65,36 @@ fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() { let log = execute(&mut session, "bake.log", &json!({})).unwrap(); assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}"); } + +#[test] +fn a_bake_lists_the_high_polys_each_set_loads_and_skips_a_set_baking_from_its_low_poly() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + session.doc.project.texture_sets[1].bake.high_poly.use_low_as_high = true; + + execute(&mut session, "bake.run", &json!({ "ts": [0, 1], "resolution": 64, "maps": ["opacity"], "dilation": 0 })).unwrap(); + + let highs: Vec<_> = session.bake_log.highs.iter().map(|row| (row.texture_set, row.file.as_str(), row.state.clone())).collect(); + assert_eq!(highs, [(0, "ball_high.obj", BakeHighState::Loaded)]); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["highPolys"][0]["state"], "loaded", "{log}"); +} + +#[test] +fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_cancel_the_rest_canceled() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let log = &mut session.bake_log; + log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); + + log.set_started(0); + assert_eq!(log.highs[0].state, BakeHighState::Loading); + assert!(log.is_loading_high_polys()); + log.set_failed(0, "The cage file could not be read."); + log.set_started(1); + log.cancel(Some(1)); + + assert_eq!(log.highs[0].state, BakeHighState::Failed("The cage file could not be read.".into())); + assert_eq!(log.highs[1].state, BakeHighState::Canceled); + assert!(!log.is_loading_high_polys()); +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 1688d940..9b2e0257 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -3,7 +3,7 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeMapState}; use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; @@ -13,6 +13,7 @@ use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_I use crate::theme::{Tokens, semibold}; mod baking_log_tab; +mod high_poly_list; pub use baking_log_tab::BakingLogTab; @@ -69,13 +70,14 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, app.session.bake_log.is_running()) { + if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, &app.session.bake_log) { app.ui.baking_log_tab = tab; } let tab = app.ui.baking_log_tab; let issue_count = match tab { BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), - _ => 0, + BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::MatchingByName => 0, }; if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; @@ -93,7 +95,11 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(LIST_TOP); match tab { BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), - _ => None, + BakingLogTab::HighPolyParameters => { + high_poly_list::high_poly_list(ui, &app.session.bake_log.highs, issues_only); + None + } + BakingLogTab::MatchingByName => None, } }) .inner; @@ -117,7 +123,7 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa } /// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon -fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option { +fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, log: &BakeLog) -> Option { let tokens = Tokens::get(ui.ctx()); let mut picked = None; let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; @@ -137,7 +143,11 @@ fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option< shown_tab_box(painter, &tokens, rect); } let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; - let in_progress = running && tab == BakingLogTab::BakingProcess; + let in_progress = match tab { + BakingLogTab::BakingProcess => log.is_running(), + BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), + BakingLogTab::MatchingByName => false, + }; let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; let center_y = strip.center().y + TAB_TOP / 2.0; painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); diff --git a/crates/ui-egui/src/baking_log/high_poly_list.rs b/crates/ui-egui/src/baking_log/high_poly_list.rs new file mode 100644 index 00000000..5f4f5977 --- /dev/null +++ b/crates/ui-egui/src/baking_log/high_poly_list.rs @@ -0,0 +1,98 @@ +//! The Baking Log's High Poly Parameters tab: each texture set of the latest bake and the high poly files it loads + +use egui::{Align2, CornerRadius, FontId, Id, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh}; + +use super::{GLYPH_CENTER, GLYPH_SIZE, HOVER_INSET, NAME_LEFT, NAME_SIZE, ROW_HEIGHT}; +use crate::i18n::{tr, trf}; +use crate::theme::{Tokens, semibold}; + +/// How far a file's row sits right of its texture set's row +const FILE_INDENT: f32 = 22.0; + +/// A row per texture set that loads high polys, folding open onto a row per file (with an issue, if `issues_only`) +pub(super) fn high_poly_list(ui: &mut Ui, highs: &[BakeLogHigh], issues_only: bool) { + let mut start = 0; + while start < highs.len() { + let set = highs[start].texture_set; + let end = highs[start..].iter().position(|row| row.texture_set != set).map_or(highs.len(), |length| start + length); + let files: Vec<&BakeLogHigh> = highs[start..end].iter().filter(|row| !issues_only || row.state.is_issue()).collect(); + start = end; + if files.is_empty() { + continue; + } + + if set_row(ui, set, &files[0].set_name) { + for row in files { + file_row(ui, row); + } + } + } +} + +/// A texture set's row: a caret and its name in SemiBold, named for what it holds; a click folds it. Returns whether it is open +fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool { + let tokens = Tokens::get(ui.ctx()); + let id = Id::unique(("baking_log_high_poly_set", set)); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, trf("{set}, High poly files", &[("set", &name)]))); + let mut open = ui.data(|data| data.get_temp::(id)).unwrap_or(true); + if response.clicked() { + open = !open; + ui.data_mut(|data| data.insert_temp(id, open)); + } + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + let caret = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, caret, FontId::proportional(GLYPH_SIZE), tokens.text_dim); + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, semibold(NAME_SIZE), tokens.text); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + open +} + +/// A high poly file's row under its texture set: glyph and file name; a file not loaded tells why on hover +fn file_row(ui: &mut Ui, row: &BakeLogHigh) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let (glyph, glyph_color, state) = match &row.state { + BakeHighState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")), + BakeHighState::Loading => (ic::DOTS_THREE, tokens.accent, tr("Loading")), + BakeHighState::Loaded => (ic::CHECK, tokens.text, tr("Loaded")), + BakeHighState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not loaded")), + BakeHighState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), + }; + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{}, {state}", row.file))); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + painter.text(pos2(rect.left() + GLYPH_CENTER + FILE_INDENT, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color); + let (font, color) = match row.state { + BakeHighState::Loading => (semibold(NAME_SIZE), tokens.text), + BakeHighState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), + _ => (FontId::proportional(NAME_SIZE), tokens.text), + }; + painter.text(pos2(rect.left() + NAME_LEFT + FILE_INDENT, center_y), Align2::LEFT_CENTER, &row.file, font, color); + + let reason = match &row.state { + BakeHighState::Failed(reason) => Some(reason.as_str()), + BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a786eef7..f825ba7e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -707,7 +707,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.bake_log.begin(&self.session.doc.project, &sets); + self.session.bake_log.begin(&self.session.doc.project, &self.session.bake_meshes.high, &sets); self.bake_report = bake_report::BakeReport::started(self.last_time); self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } @@ -896,6 +896,7 @@ impl TextureCraftApp { }; match task { Ok(task) => { + self.session.bake_log.high_polys_loaded(set_index); let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 9f56d585..837e3403 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,7 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; -use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -127,3 +127,36 @@ fn the_issues_filter_says_so_when_nothing_went_wrong() { harness.get_by_label(&format!("{set_name} ID, Baked")); assert!(harness.query_by_label("All textures baked successfully so far.").is_none(), "off again: every row is back"); } + +#[test] +fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() { + let mut harness = harness(); + harness.state_mut().session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.state_mut().start_bake(vec![0]); + run_to_the_end(&mut harness); + + harness.get_by_label("High Poly Parameters").click(); + harness.run_steps(3); + let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); + harness.get_by_label("ball_high.obj, Loaded"); + + harness.get_by_label(&format!("{set_name}, High poly files")).click(); + harness.run_steps(3); + assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a folded set hides its files"); +} + +#[test] +fn the_high_poly_tab_counts_and_keeps_its_own_issues() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Baked); + let row = |file: &str, state| BakeLogHigh { texture_set: 0, set_name: set_name.clone(), file: file.into(), state }; + harness.state_mut().session.bake_log.highs = vec![row("ball_high.obj", BakeHighState::Loaded), row("bolt_high.obj", BakeHighState::Canceled)]; + harness.get_by_label("High Poly Parameters").click(); + harness.run_steps(3); + + harness.get_by_label("1, Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a loaded file is filtered out"); + harness.get_by_label("bolt_high.obj, Canceled"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index feb3627f..d97cd2bf 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -306,11 +306,14 @@ also `session.inspect`'s `bakePreview`: ``` `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). -`state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`: +A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. +`highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, +`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, - {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}]} + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], + "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}]} ``` `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with From 373159ec5ebccb0eefb2078a8dbeed36cdc9cba3 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:38:32 +0000 Subject: [PATCH 092/190] List how the bake paired parts by name in the Baking Log --- crates/engine/src/bake/bake_log.rs | 49 +++++++++++- crates/engine/src/bake/bake_log_matching.rs | 18 +++++ crates/engine/src/bake/mesh_map_command.rs | 2 +- crates/engine/src/bake/mod.rs | 3 + crates/engine/src/bake_log_cmds.rs | 8 +- crates/engine/tests/it/bake_log.rs | 39 +++++++-- crates/ui-egui/src/baking_log.rs | 62 +++++++++++---- .../ui-egui/src/baking_log/matching_list.rs | 79 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/tests/it/baking_log.rs | 51 +++++++++--- docs/control-protocol.md | 8 +- 11 files changed, 286 insertions(+), 35 deletions(-) create mode 100644 crates/engine/src/bake/bake_log_matching.rs create mode 100644 crates/ui-egui/src/baking_log/matching_list.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 82f63c90..7203b7c1 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,6 +1,10 @@ +use std::collections::HashSet; + +use texturecraft_bake::NamePair; use texturecraft_core::{BakedMap, Project}; -use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState, BakeMesh}; +use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh}; +use crate::Session; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines #[derive(Clone, Debug, Default, PartialEq)] @@ -8,6 +12,8 @@ pub struct BakeLog { pub maps: Vec, /// Each high poly file of each texture set that bakes from the high polys, in bake order pub highs: Vec, + /// How the parts paired by name; `None` when no set of the bake matches "By Mesh Name" + pub matching: Option, } impl BakeLog { @@ -33,6 +39,7 @@ impl BakeLog { }) }) .collect(); + self.matching = None; } /// `set` starts baking: its high polys load and its first map is the one in progress @@ -120,3 +127,43 @@ impl BakeLog { } } } + +impl Session { + /// Start the Baking Log over for a bake of `sets` ([`BakeLog::begin`]), with how their parts pair by name + pub fn begin_bake_log(&mut self, sets: &[usize]) { + let matching = self.bake_log_matching(sets); + self.bake_log.begin(&self.doc.project, &self.doc.bake_meshes.high, sets); + self.bake_log.matching = matching; + } + + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it + fn bake_log_matching(&self, sets: &[usize]) -> Option { + let mut matching: Option = None; + let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new()); + for &set in sets { + let (Ok(Some(pairs)), Ok(texture_set)) = (self.bake_name_pairs(set), self.doc.project.texture_set(set)) else { continue }; + let settings = &texture_set.bake.high_poly; + let matching = matching.get_or_insert_with(|| BakeLogMatching { + low_suffix: settings.low_suffix.clone(), + high_suffix: settings.high_suffix.clone(), + pairs: Vec::new(), + }); + for pair in pairs { + match (&pair.low, &pair.high) { + (None, Some(high)) if !unpaired_highs.contains(high) => unpaired_highs.push(high.clone()), + (None, _) => {} + (Some(_), high) => { + paired_highs.extend(high.clone()); + matching.pairs.push(pair); + } + } + } + } + + if let Some(matching) = &mut matching { + let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high)); + matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) })); + } + matching + } +} diff --git a/crates/engine/src/bake/bake_log_matching.rs b/crates/engine/src/bake/bake_log_matching.rs new file mode 100644 index 00000000..9e0ef379 --- /dev/null +++ b/crates/engine/src/bake/bake_log_matching.rs @@ -0,0 +1,18 @@ +use texturecraft_bake::NamePair; + +/// The Baking Log's matching list: how the latest bake paired low poly parts with high poly parts by name +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogMatching { + /// The suffixes the first set matching by name strips, for the column captions + pub low_suffix: String, + pub high_suffix: String, + /// Each low poly part with the high poly part it bakes from, then the high poly parts no set of the bake pairs with + pub pairs: Vec, +} + +impl BakeLogMatching { + /// How many parts found no partner + pub fn issue_count(&self) -> usize { + self.pairs.iter().filter(|pair| pair.unpaired()).count() + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index e3f16c22..fef806b1 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,7 +843,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } - session.bake_log.begin(&session.doc.project, &session.bake_meshes.high, &sets); + session.begin_bake_log(&sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 873c2f35..e5edcc07 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -6,6 +6,7 @@ mod bake_high_state; mod bake_log; mod bake_log_high; mod bake_log_map; +mod bake_log_matching; mod bake_map_state; mod bake_mesh; mod bake_meshes; @@ -28,6 +29,7 @@ pub use bake_high_state::BakeHighState; pub use bake_log::BakeLog; pub use bake_log_high::BakeLogHigh; pub use bake_log_map::BakeLogMap; +pub use bake_log_matching::BakeLogMatching; pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; @@ -39,6 +41,7 @@ pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, pub use model_patch::settings_patch; pub use streamed_bake::StreamedBake; pub use streamed_map::StreamedMap; +pub use texturecraft_bake::NamePair; pub use texturecraft_bake::*; use crate::CommandSpec; diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs index edfbd15a..4be8c268 100644 --- a/crates/engine/src/bake_log_cmds.rs +++ b/crates/engine/src/bake_log_cmds.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Baking log", [], None, - "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, and the high poly files each set bakes from, as the Baking Log shows them; `reason` says why a map or file failed. Empty before the first bake", + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}], matching: null | {lowSuffix, highSuffix, pairs: [{low: name | null, high: name | null}]}}. The latest bake map by map in bake order, the high poly files each set bakes from, and how parts paired by name, as the Baking Log shows them; `reason` says why a map or file failed; a `null` side of a pair is a part with no partner; `matching` is null when no set matched by mesh name. Empty before the first bake", always, log )] @@ -21,7 +21,11 @@ fn log(session: &mut Session, _: &Value) -> Result { let log = &session.bake_log; let maps = log.maps.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "map", json!(row.map.id()))).collect::>>()?; let highs = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::>>()?; - Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": highs })) + let matching = log.matching.as_ref().map(|matching| { + let pairs: Vec = matching.pairs.iter().map(|pair| json!({ "low": pair.low, "high": pair.high })).collect(); + json!({ "lowSuffix": matching.low_suffix, "highSuffix": matching.high_suffix, "pairs": pairs }) + }); + Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": highs, "matching": matching })) } /// One row: its `state` (and `reason`), its texture set, and what it is under `key` diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 36ce7772..419ce6b4 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -3,8 +3,8 @@ use std::collections::BTreeSet; use serde_json::json; -use texturecraft_engine::bake::{BakeHighState, BakeMapState}; -use texturecraft_engine::core::BakedMap; +use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair}; +use texturecraft_engine::core::{BakedMap, MeshMatchMode}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -86,15 +86,44 @@ fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_canc session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let log = &mut session.bake_log; log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); + let state = |log: &BakeLog, set: usize| log.highs.iter().find(|high| high.texture_set == set).map(|high| high.state.clone()); log.set_started(0); - assert_eq!(log.highs[0].state, BakeHighState::Loading); + assert_eq!(state(log, 0), Some(BakeHighState::Loading)); assert!(log.is_loading_high_polys()); log.set_failed(0, "The cage file could not be read."); log.set_started(1); log.cancel(Some(1)); - assert_eq!(log.highs[0].state, BakeHighState::Failed("The cage file could not be read.".into())); - assert_eq!(log.highs[1].state, BakeHighState::Canceled); + assert_eq!(state(log, 0), Some(BakeHighState::Failed("The cage file could not be read.".into()))); + assert_eq!(state(log, 1), Some(BakeHighState::Canceled)); assert!(!log.is_loading_high_polys()); } + +#[test] +fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_with() { + let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.begin_bake_log(&[0, 1]); + assert_eq!(session.bake_log.matching, None, "matching \"Always\" lists no pairs"); + + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + } + session.begin_bake_log(&[0, 1]); + + let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) }; + let matching = session.bake_log.matching.clone().unwrap(); + assert_eq!( + matching.pairs, + [pair(Some("Box_low"), Some("Box_high")), pair(Some("Lid_low"), None), pair(None, Some("Extra_high"))], + "Box_high is paired by the other set" + ); + assert_eq!(matching.issue_count(), 2); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 9b2e0257..1ee11974 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -14,6 +14,7 @@ use crate::theme::{Tokens, semibold}; mod baking_log_tab; mod high_poly_list; +mod matching_list; pub use baking_log_tab::BakingLogTab; @@ -77,13 +78,19 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let issue_count = match tab { BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::MatchingByName => 0, + BakingLogTab::MatchingByName => app.session.bake_log.matching.as_ref().map_or(0, |matching| matching.issue_count()), }; if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; } let issues_only = app.ui.baking_log_issues_only; + let log = &app.session.bake_log; + let baked = !log.maps.is_empty(); + if tab == BakingLogTab::MatchingByName && baked && log.matching.is_none() { + matching_not_enabled(ui); + return; + } if issues_only && issue_count == 0 { no_issues(ui, tab); return; @@ -92,6 +99,8 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let opened = egui::ScrollArea::vertical() .auto_shrink([false, false]) .show(ui, |ui| { + // Rows sit edge to edge at ROW_HEIGHT, as the matching list's rules need + ui.spacing_mut().item_spacing.y = 0.0; ui.add_space(LIST_TOP); match tab { BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), @@ -99,7 +108,12 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { high_poly_list::high_poly_list(ui, &app.session.bake_log.highs, issues_only); None } - BakingLogTab::MatchingByName => None, + BakingLogTab::MatchingByName => { + if let Some(matching) = &app.session.bake_log.matching { + matching_list::matching_list(ui, matching, issues_only); + } + None + } } }) .inner; @@ -173,8 +187,8 @@ fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); let name = match &count { - Some(count) => trf("{count}, Show Only Issues", &[("count", count)]), - None => tr("Show Only Issues").to_owned(), + Some(count) => trf("{count}, Show only rows with an issue", &[("count", count)]), + None => tr("Show only rows with an issue").to_owned(), }; let response = ui.interact(rect, ui.scope_id().with("baking_log_issues_filter"), Sense::click()); response.widget_info(|| WidgetInfo::selected(Role::Button, true, on, &name)); @@ -193,22 +207,41 @@ fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool if response.has_focus() { crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); } - response.on_hover_text(tr("Show Only Issues")).clicked() + response.on_hover_text(tr("Show only rows with an issue")).clicked() } -/// What the issues filter leaves when `tab` has no issue: the reference's words for that tab, and how to see every row +/// What the issues filter leaves when `tab` has no issue: one line for that tab, and how to see every row fn no_issues(ui: &mut Ui, tab: BakingLogTab) { let tokens = Tokens::get(ui.ctx()); let message = match tab { - BakingLogTab::BakingProcess => tr("All textures baked successfully so far."), - BakingLogTab::HighPolyParameters => tr("No issues encountered so far."), - BakingLogTab::MatchingByName => tr("No matching issues encountered"), + BakingLogTab::BakingProcess => tr("Every map so far baked without a problem."), + BakingLogTab::HighPolyParameters => tr("Every high poly file so far loaded."), + BakingLogTab::MatchingByName => tr("Every part so far has its partner."), }; let area = ui.available_rect_before_wrap(); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); child.add_space((area.height() - EMPTY_TEXT_HEIGHT).max(0.0) / 2.0); child.label(egui::RichText::new(message).font(semibold(NAME_SIZE)).color(tokens.text)); - child.label(egui::RichText::new(tr("Deselect filter to view.")).size(NAME_SIZE).color(tokens.text_dim)); + child.label(egui::RichText::new(tr("Turn off the issues filter to see every row.")).size(NAME_SIZE).color(tokens.text_dim)); + ui.allocate_rect(area, Sense::hover()); +} + +/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting's name in SemiBold +fn matching_not_enabled(ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let mut text = egui::text::LayoutJob::default(); + let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() }; + // One sentence to translate, its setting kept apart to set it in SemiBold + let sentence = tr("{setting} was off for this bake."); + let (before, after) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + text.append(before, 0.0, format(FontId::proportional(NAME_SIZE))); + text.append(tr("Matching by name"), 0.0, format(semibold(NAME_SIZE))); + text.append(after, 0.0, format(FontId::proportional(NAME_SIZE))); + + let area = ui.available_rect_before_wrap(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); + child.add_space((area.height() - EMPTY_TEXT_HEIGHT / 2.0).max(0.0) / 2.0); + child.label(text); ui.allocate_rect(area, Sense::hover()); } @@ -222,8 +255,9 @@ fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option let mut opened = None; for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) { let (rect, open_clicked) = map_row(ui, row); + // Bring the next map into view too, so the list shows what comes after the map being baked if newly_followed && followed == Some(index) { - ui.scroll_to_rect(rect, None); + ui.scroll_to_rect(rect.with_max_y(rect.bottom() + ROW_HEIGHT), None); } if open_clicked { opened = Some((row.texture_set, row.map)); @@ -245,7 +279,7 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); - let open = row.state.is_issue().then(|| open_settings_button(ui, rect, &name)); + let open = row.state.is_issue().then(|| open_settings_button(ui, rect, (row.texture_set, row.map), &name)); let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); let painter = ui.painter(); @@ -286,11 +320,11 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { } /// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus -fn open_settings_button(ui: &mut Ui, row: Rect, name: &str) -> egui::Response { +fn open_settings_button(ui: &mut Ui, row: Rect, set_map: (usize, BakedMap), name: &str) -> egui::Response { let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); let rect = Rect::from_center_size(center, vec2(OPEN_BUTTON_SIZE, OPEN_BUTTON_SIZE)); let label = trf("Open the {name} settings", &[("name", &name)]); - let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", name)), Sense::click()); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", set_map)), Sense::click()); response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label)); response.on_hover_text(label) } diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs new file mode 100644 index 00000000..22ad6c46 --- /dev/null +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -0,0 +1,79 @@ +//! The Baking Log's Matching by Name tab: which low poly part the latest bake paired with which high poly part + +use egui::{Align2, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeLogMatching, NamePair}; + +use super::{GLYPH_SIZE, HOVER_INSET, NAME_SIZE, ROW_HEIGHT}; +use crate::i18n::{tr, trf}; +use crate::property_sheet::SIDE_PADDING_POINTS; +use crate::theme::{Tokens, semibold}; + +/// Size of the column captions +const CAPTION_SIZE: f32 = 11.0; + +/// The two columns' captions and a row per pair (only the parts with no partner, if `issues_only`), each ruled off below +pub(super) fn matching_list(ui: &mut Ui, matching: &BakeLogMatching, issues_only: bool) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let captions = [caption(tr("Low poly mesh ({suffix})"), &matching.low_suffix), caption(tr("High poly mesh ({suffix})"), &matching.high_suffix)]; + for (left, caption) in columns(rect).into_iter().zip(captions) { + ui.painter().text(pos2(left, rect.center().y), Align2::LEFT_CENTER, caption, FontId::proportional(CAPTION_SIZE), tokens.text_dim); + } + rule(ui, rect); + + for pair in matching.pairs.iter().filter(|pair| !issues_only || pair.unpaired()) { + pair_row(ui, pair); + } +} + +/// A column caption in capitals, with the set's `suffix` kept as typed +fn caption(template: &str, suffix: &str) -> String { + template.split("{suffix}").map(str::to_uppercase).collect::>().join(suffix) +} + +/// The left edges of the low and high poly columns of `row` +fn columns(row: Rect) -> [f32; 2] { + [row.left() + SIDE_PADDING_POINTS, row.center().x] +} + +/// The hairline under `row`, inside the side padding +fn rule(ui: &Ui, row: Rect) { + let tokens = Tokens::get(ui.ctx()); + let x = row.left() + SIDE_PADDING_POINTS..=row.right() - SIDE_PADDING_POINTS; + ui.painter().hline(x, row.bottom() - 0.5, Stroke::new(1.0, tokens.separator)); +} + +/// A pair's row: the low poly part, then the high poly part; a side with no partner is a warning glyph that tells why on hover +fn pair_row(ui: &mut Ui, pair: &NamePair) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let no_match = tr("No match"); + let name = format!("{}, {}", pair.low.as_deref().unwrap_or(no_match), pair.high.as_deref().unwrap_or(no_match)); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name)); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + for (left, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { + match part { + Some(part) => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, part, FontId::proportional(NAME_SIZE), tokens.text), + None => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning), + }; + } + rule(ui, rect); + + let reason = match (&pair.low, &pair.high) { + (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), + (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f825ba7e..4346c304 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -707,7 +707,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.bake_log.begin(&self.session.doc.project, &self.session.bake_meshes.high, &sets); + self.session.begin_bake_log(&sets); self.bake_report = bake_report::BakeReport::started(self.last_time); self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 837e3403..3d098b6f 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,7 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; -use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -103,29 +103,29 @@ fn the_issues_filter_keeps_only_the_maps_with_a_problem() { let set_name = log_a_bake(&mut harness, BakeMapState::Failed("The high poly file could not be read.".into())); harness.get_by_label(&format!("{set_name} ID, Baked")); - harness.get_by_label("1, Show Only Issues").click(); + harness.get_by_label("1, Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none(), "a baked map is filtered out"); harness.get_by_label(&format!("{set_name} Position, Not baked")); - assert!(harness.query_by_label("Deselect filter to view.").is_none(), "an issue left: no empty text"); + assert!(harness.query_by_label("Turn off the issues filter to see every row.").is_none(), "an issue left: no empty text"); } #[test] fn the_issues_filter_says_so_when_nothing_went_wrong() { let mut harness = harness(); let set_name = log_a_bake(&mut harness, BakeMapState::Baked); - harness.get_by_label("Show Only Issues").click(); + harness.get_by_label("Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none()); - harness.get_by_label("All textures baked successfully so far."); - harness.get_by_label("Deselect filter to view."); + harness.get_by_label("Every map so far baked without a problem."); + harness.get_by_label("Turn off the issues filter to see every row."); - harness.get_by_label("Show Only Issues").click(); + harness.get_by_label("Show only rows with an issue").click(); harness.run_steps(3); harness.get_by_label(&format!("{set_name} ID, Baked")); - assert!(harness.query_by_label("All textures baked successfully so far.").is_none(), "off again: every row is back"); + assert!(harness.query_by_label("Every map so far baked without a problem.").is_none(), "off again: every row is back"); } #[test] @@ -154,9 +154,42 @@ fn the_high_poly_tab_counts_and_keeps_its_own_issues() { harness.get_by_label("High Poly Parameters").click(); harness.run_steps(3); - harness.get_by_label("1, Show Only Issues").click(); + harness.get_by_label("1, Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a loaded file is filtered out"); harness.get_by_label("bolt_high.obj, Canceled"); } + +#[test] +fn the_matching_tab_lists_the_pairs_and_its_filter_keeps_the_parts_with_no_partner() { + let mut harness = harness(); + log_a_bake(&mut harness, BakeMapState::Baked); + let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) }; + harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { + low_suffix: "_low".into(), + high_suffix: "_high".into(), + pairs: vec![pair(Some("Barrel_low"), Some("Barrel_high")), pair(Some("Strap_low"), None)], + }); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + harness.get_by_label("Barrel_low, Barrel_high"); + + harness.get_by_label("1, Show only rows with an issue").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("Barrel_low, Barrel_high").is_none(), "a pair is filtered out"); + harness.get_by_label("Strap_low, No match"); +} + +#[test] +fn the_matching_tab_says_when_no_set_matched_by_name() { + let mut harness = harness(); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + assert!(harness.query_by_label("Matching by name was off for this bake.").is_none(), "nothing baked yet: nothing to say"); + + log_a_bake(&mut harness, BakeMapState::Baked); + + harness.get_by_label("Matching by name was off for this bake."); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d97cd2bf..a682a901 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -308,12 +308,16 @@ also `session.inspect`'s `bakePreview`: `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. `highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, -`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`: +`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`. `matching` lists each low poly +part with the high poly part it bakes from, then the high poly parts no set paired with; a `null` side is a part +with no partner. It is `null` when no set of the bake matches by mesh name: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], - "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}]} + "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}], + "matching": {"lowSuffix": "_low", "highSuffix": "_high", + "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} ``` `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with From 530541a97a06a737b5aaaeb4b4bbf72555eef61e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:52:29 +0000 Subject: [PATCH 093/190] Remember what each baked map was baked from Each bake records, per map, fingerprints of the low poly geometry, the high poly and cage files, the settings every map shares (with the UV tiles baked) and the map's own settings, taken when the set's bake starts. A map whose inputs differ now is out of date, with what changed; project.inspect lists those per texture set as outOfDate. The record is saved with the project and left out when empty, so projects saved before it open unchanged and their maps never show out of date. Imported maps keep no record either. --- crates/core/src/bake.rs | 4 + crates/core/src/bake/bake_change.rs | 25 ++++ crates/core/src/bake/bake_source.rs | 69 +++++++++++ crates/core/src/bake/mesh_map_settings.rs | 16 +++ crates/core/src/lib.rs | 11 +- crates/core/src/project.rs | 19 ++- crates/engine/src/bake/bake_mesh.rs | 2 + crates/engine/src/bake/bake_sources.rs | 65 ++++++++++ crates/engine/src/bake/bake_task.rs | 11 +- crates/engine/src/bake/mesh_map_command.rs | 35 ++++-- crates/engine/src/bake/mod.rs | 1 + crates/engine/src/bake/streamed_bake.rs | 4 +- crates/engine/src/file_cmds.rs | 9 +- crates/engine/src/inspect.rs | 1 + crates/engine/src/meshmap_cmds.rs | 41 ++++--- crates/engine/src/session.rs | 3 + crates/engine/tests/it/bake_out_of_date.rs | 136 +++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/tests/it/bake_mode.rs | 2 +- docs/control-protocol.md | 6 + 20 files changed, 422 insertions(+), 39 deletions(-) create mode 100644 crates/core/src/bake/bake_change.rs create mode 100644 crates/core/src/bake/bake_source.rs create mode 100644 crates/engine/src/bake/bake_sources.rs create mode 100644 crates/engine/tests/it/bake_out_of_date.rs diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index a40f5ab0..8289ef42 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -4,9 +4,11 @@ mod ambient_occlusion_attenuation; mod ambient_occlusion_settings; mod backface_mode; mod bake_antialiasing; +mod bake_change; mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod bake_source; mod bake_sync; mod bake_sync_group; mod mesh_match_mode; @@ -45,8 +47,10 @@ pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation; pub use ambient_occlusion_settings::AmbientOcclusionSettings; pub use backface_mode::BackfaceMode; pub use bake_antialiasing::BakeAntialiasing; +pub use bake_change::BakeChange; pub use bake_resolution::BakeResolution; pub use bake_settings::BakeSettings; +pub use bake_source::{BakeSource, fingerprint, fingerprint_words}; pub use bake_sync::BakeSync; pub use bake_sync_group::BakeSyncGroup; pub use baked_map::BakedMap; diff --git a/crates/core/src/bake/bake_change.rs b/crates/core/src/bake/bake_change.rs new file mode 100644 index 00000000..bb73b1f2 --- /dev/null +++ b/crates/core/src/bake/bake_change.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// What changed since a mesh map was baked, which makes it out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BakeChange { + LowPoly, + HighPoly, + Cage, + Settings, + MapSettings, +} + +impl BakeChange { + /// Identifier in automation replies + pub fn id(self) -> &'static str { + match self { + BakeChange::LowPoly => "lowPoly", + BakeChange::HighPoly => "highPoly", + BakeChange::Cage => "cage", + BakeChange::Settings => "settings", + BakeChange::MapSettings => "mapSettings", + } + } +} diff --git a/crates/core/src/bake/bake_source.rs b/crates/core/src/bake/bake_source.rs new file mode 100644 index 00000000..9cc59c44 --- /dev/null +++ b/crates/core/src/bake/bake_source.rs @@ -0,0 +1,69 @@ +use super::BakeChange; +use serde::{Deserialize, Serialize}; + +/// Fingerprints of what one mesh map was baked from: a later change to any of them shows the map out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BakeSource { + /// The low poly's geometry + pub low_poly: u64, + /// The high poly files, in list order (0: none, the set bakes from the low poly) + pub high_poly: u64, + /// The cage file (0: none) + pub cage: u64, + /// The settings every map of the set shares (size, high poly, cage, skew) and its UV tiles + pub settings: u64, + /// The map's own settings + pub map_settings: u64, +} + +impl BakeSource { + /// What differs in `current` from this record, in [`BakeChange`] order (empty: up to date) + pub fn changes(&self, current: &BakeSource) -> Vec { + [ + (self.low_poly != current.low_poly, BakeChange::LowPoly), + (self.high_poly != current.high_poly, BakeChange::HighPoly), + (self.cage != current.cage, BakeChange::Cage), + (self.settings != current.settings, BakeChange::Settings), + (self.map_settings != current.map_settings, BakeChange::MapSettings), + ] + .into_iter() + .filter_map(|(changed, change)| changed.then_some(change)) + .collect() + } +} + +/// A fingerprint of `bytes` that stays the same across runs, platforms and Rust versions (unlike `std::hash`) +pub fn fingerprint(bytes: &[u8]) -> u64 { + let words = bytes.chunks(8).map(|chunk| { + let mut word_bytes = [0; 8]; + word_bytes[..chunk.len()].copy_from_slice(chunk); + u64::from_le_bytes(word_bytes) + }); + fingerprint_words(words.chain([bytes.len() as u64])) +} + +/// [`fingerprint`] of a sequence of words: FNV-1a taking a 64-bit word per step +pub fn fingerprint_words(words: impl IntoIterator) -> u64 { + // FNV-1a 64-bit offset basis and prime + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0000_0100_0000_01b3; + + words.into_iter().fold(OFFSET_BASIS, |hash, word| (hash ^ word).wrapping_mul(PRIME)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_fingerprint_changes_with_any_byte_and_with_the_length() { + let bytes: Vec = (0..=20).collect(); + let mut changed = bytes.clone(); + changed[17] ^= 1; + + assert_ne!(fingerprint(&bytes), fingerprint(&changed)); + assert_ne!(fingerprint(&bytes), fingerprint(&bytes[..20])); + assert_ne!(fingerprint(&[]), fingerprint(&[0])); + } +} diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs index 281d5c98..579141e7 100644 --- a/crates/core/src/bake/mesh_map_settings.rs +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -84,6 +84,22 @@ impl MeshMapSettings { } } + /// `map`'s typed parameters as JSON + pub fn parameters_json(&self, map: BakedMap) -> serde_json::Value { + let parameters = match map { + // These maps have no parameters of their own + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => return serde_json::Value::Null, + BakedMap::Id => serde_json::to_value(self.id.parameters), + BakedMap::AmbientOcclusion => serde_json::to_value(self.ao.parameters), + BakedMap::Curvature => serde_json::to_value(self.curvature.parameters), + BakedMap::Position => serde_json::to_value(self.position.parameters), + BakedMap::Thickness => serde_json::to_value(self.thickness.parameters), + BakedMap::Height => serde_json::to_value(self.height.parameters), + BakedMap::BentNormal => serde_json::to_value(self.bent_normal.parameters), + }; + parameters.unwrap_or_default() + } + pub fn enabled(&self) -> impl Iterator { BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index eedf93ec..772653e4 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -80,11 +80,12 @@ pub const FULL_TURN_DEGREES: f32 = 360.0; pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ - AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync, - BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, - HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, - MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, - SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeChange, BakePaintTarget, BakeResolution, BakeSettings, + BakeSource, BakeSync, BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, + GroundPlaneSettings, HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, + MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, + PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, fingerprint, + fingerprint_words, }; pub use bevel::Bevel; pub use bevel_blur::BevelBlur; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 0a4bf868..69437007 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -69,6 +69,9 @@ pub struct TextureSet { /// Mesh maps that have been baked (pixels live with the engine / project file). #[serde(default)] pub baked: BTreeSet, + /// What each baked map was baked from; a map without a record (imported, or older project) is never out of date + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub bake_sources: BTreeMap, #[serde(default = "yes")] pub visible: bool, /// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode); @@ -171,6 +174,7 @@ impl TextureSet { height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), + bake_sources: BTreeMap::new(), visible: true, uv_tiles: Vec::new(), bake_excluded_tiles: BTreeSet::new(), @@ -187,6 +191,19 @@ impl TextureSet { self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile)) } + /// Fingerprint of the shared bake settings (not the set's check) and baked UV tiles (not their working resolutions) + pub fn bake_settings_fingerprint(&self) -> u64 { + let mut common = self.bake.common; + common.is_enabled = true; + let shared = (common, &self.bake.high_poly, &self.bake.cage, &self.bake.skew, &self.uv_tiles, &self.bake_excluded_tiles); + crate::fingerprint(serde_json::to_string(&shared).unwrap_or_default().as_bytes()) + } + + /// Fingerprint of `map`'s own bake settings (not whether it is checked) + pub fn map_settings_fingerprint(&self, map: BakedMap) -> u64 { + crate::fingerprint(self.bake.maps.parameters_json(map).to_string().as_bytes()) + } + /// Height strength for slopes measured over the whole texture width (the viewport shader, /// the path tracer): a UV tile atlas is one tile per column wide. pub fn atlas_height_strength(&self) -> f32 { diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs index bcdb2bcc..d4dbfeeb 100644 --- a/crates/engine/src/bake/bake_mesh.rs +++ b/crates/engine/src/bake/bake_mesh.rs @@ -11,4 +11,6 @@ pub struct BakeMesh { pub bytes: Arc>, pub mesh: Arc, pub base_color: Vec>>, + /// [`texturecraft_core::fingerprint`] of `bytes`: what bakes from this file record + pub fingerprint: u64, } diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs new file mode 100644 index 00000000..70f7665c --- /dev/null +++ b/crates/engine/src/bake/bake_sources.rs @@ -0,0 +1,65 @@ +//! What each baked map was baked from, and which maps are out of date since + +use std::collections::BTreeMap; + +use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, fingerprint_words}; + +use crate::{Result, Session}; + +impl Session { + /// What a bake of `map` on texture set `texture_set` would read now + pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result { + let set = self.doc.project.texture_set(texture_set)?; + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + let high_poly = match from_high { + true => fingerprint_words(self.doc.bake_meshes.high.iter().map(|high| high.fingerprint)), + false => 0, + }; + let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile; + let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint); + + Ok(BakeSource { + low_poly: self.low_poly_fingerprint(), + high_poly, + cage, + settings: set.bake_settings_fingerprint(), + map_settings: set.map_settings_fingerprint(map), + }) + } + + /// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record + pub fn bake_changes(&self, texture_set: usize, map: BakedMap) -> Vec { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return Vec::new() }; + let Some(record) = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map)) else { return Vec::new() }; + + self.bake_source(texture_set, map).map(|current| record.changes(¤t)).unwrap_or_default() + } + + /// The out-of-date maps of texture set `texture_set`, each with what changed + pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap> { + BakedMap::ALL.into_iter().map(|map| (map, self.bake_changes(texture_set, map))).filter(|(_, changes)| !changes.is_empty()).collect() + } + + /// Fingerprint of the low poly's own geometry (computed once per loaded mesh) + fn low_poly_fingerprint(&self) -> u64 { + *self.low_poly_fingerprint.get_or_init(|| { + let source = &self.source; + let floats = source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array())); + let words = floats.map(|float| u64::from(float.to_bits())).chain(source.indices.iter().map(|index| u64::from(*index))); + fingerprint_words(words) + }) + } + + /// Keep `sources` as what maps of `texture_set` were baked from; without them the `stored` maps lose their record + pub(super) fn record_bake_sources(&mut self, texture_set: usize, sources: Option<&BTreeMap>, stored: &[BakedMap]) -> Result<()> { + let set = self.doc.project.texture_set_mut(texture_set)?; + match sources { + Some(sources) => set.bake_sources.extend(sources), + None => set.bake_sources.retain(|map, _| !stored.contains(map)), + } + + let baked = &set.baked; + set.bake_sources.retain(|map, _| baked.contains(map)); + Ok(()) + } +} diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index a617d97b..3c0cb59e 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -26,6 +26,8 @@ pub struct BakeTask { pub previous_maps: BakedMaps, /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). pub tracer: Option>, + /// What each map this task makes is baked from, taken when the task was made + pub sources: std::collections::BTreeMap, } impl BakeTask { @@ -66,7 +68,13 @@ impl BakeTask { // A resized partial bake also returns unchecked maps that must survive application let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); retained.insert(map, data); - combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer }); + combined = Some(StreamedBake { + resolution: output.resolution, + height: output.height, + maps: retained, + tracer: output.tracer, + sources: self.sources.clone(), + }); } } } @@ -80,6 +88,7 @@ impl BakeTask { height: output.height, maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), tracer: output.tracer, + sources: self.sources.clone(), }) } } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef806b1..49ec4ec0 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -15,8 +15,8 @@ use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ - BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, - SelfOcclusion, + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSource, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, + RaySettings, SelfOcclusion, }; use texturecraft_geom::Mesh; @@ -121,7 +121,8 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty()); - Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color }) + let fingerprint = texturecraft_core::fingerprint(&bytes); + Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color, fingerprint }) } impl Session { @@ -183,6 +184,7 @@ impl Session { let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed)); + let sources = set.bake.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; Ok(BakeTask { low_base_color, ts: texture_set, @@ -198,6 +200,7 @@ impl Session { excluded_tiles, previous_maps, tracer, + sources, }) } @@ -260,7 +263,7 @@ impl Session { /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?; + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, None))?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } @@ -269,17 +272,26 @@ impl Session { /// preview that showed them holds the same ones) pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?; + self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some(&output.sources)))?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } - fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { + /// Store `output`, recording what its maps were baked from when `sources` are known + fn store_bake(&mut self, texture_set: usize, output: BakeOutput, sources: Option<&BTreeMap>) -> Result<()> { let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); - self.store_bake_maps(texture_set, output.resolution, output.height, maps) + self.store_bake_maps(texture_set, output.resolution, output.height, maps, sources) } - fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap>>) -> Result<()> { + fn store_bake_maps( + &mut self, + texture_set: usize, + resolution: u32, + height: u32, + maps: BTreeMap>>, + sources: Option<&BTreeMap>, + ) -> Result<()> { + let stored: Vec = maps.keys().copied().collect(); let entry = self.doc.baked.entry(texture_set).or_default(); if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) { entry.maps.clear(); @@ -288,7 +300,7 @@ impl Session { entry.resolution = resolution; entry.maps.extend(maps); self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); - Ok(()) + self.record_bake_sources(texture_set, sources, &stored) } /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. @@ -299,7 +311,8 @@ impl Session { } let out = task.run(&Progress::new())?; let tracer = out.tracer.clone(); - self.apply_bake(ts, out)?; + self.edit("Bake mesh maps", |session| session.store_bake(ts, out, Some(&task.sources)))?; + self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); Ok(tracer) } @@ -879,7 +892,7 @@ fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result>>, pub tracer: String, + /// What the baked maps were baked from (the task's [`crate::BakeTask::sources`]) + pub sources: BTreeMap, } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 9c447c3c..5cfc235b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1655,7 +1655,14 @@ f 1/1 2/2 3/3 let b = dir.join("b.obj"); std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); - let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + let cage = crate::bake::BakeMesh { + name: "cage".into(), + folder: None, + bytes: Default::default(), + mesh: s.mesh.clone(), + base_color: Vec::new(), + fingerprint: 0, + }; s.doc.bake_meshes.cage = Some(cage); let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into())); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index a4258463..e9c3b2e5 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -276,6 +276,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), + "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), "visible": texture_set.visible, "active": index == session.ts(), }) diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index f08d34c4..5736c5ca 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -53,19 +53,19 @@ fn set(s: &mut Session, p: &Value) -> Result { pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width -pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { - let texture_set = s.doc.project.texture_set(ts)?; +pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = session.doc.project.texture_set(ts)?; let grid = texture_set.tile_grid(); if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { - return Err(bad(cmd, format!("no image for UV tile {tile}"))); + return Err(bad(command, format!("no image for UV tile {tile}"))); } - let (width, height) = image_map_size(s, cmd, ts)?; + let (width, height) = image_map_size(session, command, ts)?; // Bent normals are tangent-space maps like the normal map, so both follow the project's normal format - let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && s.doc.project.normal_format == NormalFormat::DirectX; + let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX; let data = match (grid, images.values().next()) { - (_, None) => return Err(bad(cmd, "no image to use")), + (_, None) => return Err(bad(command, "no image to use")), (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)), // An atlas texel reads the image of the tile its mesh UV falls in (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| { @@ -74,10 +74,13 @@ pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, i }), }; - let entry = s.doc.baked.entry(ts).or_default(); + let entry = session.doc.baked.entry(ts).or_default(); entry.resolution = width; entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); + // An imported map is never out of date: nothing records what it was made from + let set = session.doc.project.texture_set_mut(ts)?; + set.baked.insert(map); + set.bake_sources.remove(&map); Ok(width) } @@ -153,18 +156,20 @@ fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn( out } -fn clear(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.meshMap.clear"; - let ts = ts_param(s, p, CMD)?; - let map = map_param(p, CMD)?; - if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { - return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id()))); +fn clear(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.meshMap.clear"; + let ts = ts_param(session, params, COMMAND)?; + let map = map_param(params, COMMAND)?; + if !session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) { + return Err(bad(COMMAND, format!("texture set {ts} has no {} map", map.id()))); } - s.edit("Clear mesh map", |s| { - if let Some(b) = s.doc.baked.get_mut(&ts) { - b.maps.remove(&map); + session.edit("Clear mesh map", |session| { + if let Some(baked) = session.doc.baked.get_mut(&ts) { + baked.maps.remove(&map); } - s.doc.project.texture_set_mut(ts)?.baked.remove(&map); + let set = session.doc.project.texture_set_mut(ts)?; + set.baked.remove(&map); + set.bake_sources.remove(&map); Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index f0a8df58..05a0c779 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -425,6 +425,8 @@ pub struct Session { pub project_id: u64, /// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas). pub(crate) source: Arc, + /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it + pub(crate) low_poly_fingerprint: std::sync::OnceLock, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Arc>)>, @@ -527,6 +529,7 @@ impl Session { mesh_id: next_mesh_id(), project_id: next_mesh_id(), source, + low_poly_fingerprint: Default::default(), mesh, bvh: Arc::new(bvh), mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))), diff --git a/crates/engine/tests/it/bake_out_of_date.rs b/crates/engine/tests/it/bake_out_of_date.rs new file mode 100644 index 00000000..9a5c1dcd --- /dev/null +++ b/crates/engine/tests/it/bake_out_of_date.rs @@ -0,0 +1,136 @@ +//! Out-of-date mesh maps: what each map was baked from, compared with what a bake would read now + +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeChange, BakedMap, CageType}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with its position map baked by `bake.run` +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + session +} + +fn changes(session: &Session) -> Vec { + session.bake_changes(0, BakedMap::Position) +} + +#[test] +fn a_map_goes_out_of_date_when_its_settings_or_the_shared_ones_change_and_a_bake_brings_it_back() { + let mut session = baked_plane(); + assert!(changes(&session).is_empty(), "fresh bake: {:?}", changes(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(changes(&session), [BakeChange::MapSettings]); + execute(&mut session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + assert_eq!(changes(&session), [BakeChange::Settings, BakeChange::MapSettings]); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["outOfDate"], json!({ "position": ["settings", "mapSettings"] })); + + execute(&mut session, "bake.run", &json!({})).unwrap(); + assert!(changes(&session).is_empty(), "rebaked: {:?}", changes(&session)); +} + +#[test] +fn the_record_is_saved_with_the_project() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(changes(&reopened), [BakeChange::MapSettings]); +} + +#[test] +fn maps_saved_before_records_existed_and_imported_maps_never_go_out_of_date() { + let mut old = baked_plane(); + old.doc.project.texture_sets[0].bake_sources.clear(); + let mut old = Session::from_project_bytes(&old.to_project_bytes().unwrap()).unwrap(); + execute(&mut old, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&old).is_empty(), "{:?}", changes(&old)); + + let mut imported = baked_plane(); + let mut png = Vec::new(); + image::RgbImage::from_pixel(4, 4, image::Rgb([128, 64, 32])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + imported.import_resource_bytes("position.png", png).unwrap(); + execute(&mut imported, "textureSet.meshMap.set", &json!({ "map": "position", "image": "position.png" })).unwrap(); + execute(&mut imported, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&imported).is_empty(), "{:?}", changes(&imported)); +} + +#[test] +fn adding_a_high_poly_puts_the_maps_out_of_date() { + let mut session = baked_plane(); + + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + + assert_eq!(changes(&session), [BakeChange::HighPoly]); +} + +#[test] +fn a_cage_file_counts_only_for_sets_that_bake_with_it() { + let mut session = baked_plane(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let cage: String = (0..session.mesh.triangle_count()).map(|_| "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3 -2 -1\n").collect(); + session.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap(); + assert!(changes(&session).is_empty(), "the cage type is not Custom File: {:?}", changes(&session)); + + session.doc.project.texture_sets[0].bake.cage.kind = CageType::CustomFile; + assert!(changes(&session).contains(&BakeChange::Cage), "{:?}", changes(&session)); +} + +#[test] +fn a_setting_changed_while_the_bake_runs_leaves_the_new_map_out_of_date() { + let mut session = baked_plane(); + let task = session.bake_task(0).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let streamed_once = AtomicBool::new(false); + let output = task.run_streaming(&Progress::new(), &mut |_| streamed_once.store(true, Ordering::Relaxed)).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(streamed_once.load(Ordering::Relaxed)); + assert_eq!(changes(&session), [BakeChange::MapSettings]); +} + +/// Two quads side by side, one texture set each, lifted by `lift` where a high poly or cage stands off the low poly +fn two_parts(lift: f32) -> String { + let mut obj = String::new(); + for left in [0.0, 2.0] { + let right = left + 1.0; + obj += &format!("v {left} 0 {lift}\nv {right} 0 {lift}\nv {right} 1 {lift}\nv {left} 1 {lift}\n"); + } + obj += "vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n"; + obj += "usemtl Left\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\nusemtl Right\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n"; + obj +} + +#[test] +fn a_reopened_project_keeps_every_sets_maps_up_to_date() { + let mut session = Session::from_mesh_bytes_with_uvs("parts.obj", two_parts(0.0).as_bytes(), 128, "parts", None, false).unwrap(); + session.add_high_poly_bytes("parts_high.obj", two_parts(0.05).into_bytes()).unwrap(); + session.set_cage_bytes("parts_cage.obj", two_parts(0.2).into_bytes()).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake.cage.kind = CageType::CustomFile; + } + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position", "normal"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 1, "map": "normal" })).unwrap(); + let records = |session: &Session| session.doc.project.texture_sets.iter().map(|set| set.bake_sources.clone()).collect::>(); + assert_eq!(session.set_count(), 2); + assert!(records(&session).iter().all(|sources| sources.len() == 2), "both maps of both sets are recorded"); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(records(&reopened), records(&session), "the records are saved as they were"); + for texture_set in 0..reopened.set_count() { + assert!(reopened.out_of_date_maps(texture_set).is_empty(), "set {texture_set}: {:?}", reopened.out_of_date_maps(texture_set)); + } + assert!(reopened.auto_rebake_due().is_empty(), "opening the project starts no rebake"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11b199c9..f43035f4 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -5,6 +5,7 @@ mod add_mask_items; mod bake; mod bake_checks; mod bake_log; +mod bake_out_of_date; mod bake_resolution; mod bake_settings; mod bake_tiles; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 1f7253ac..720d4c49 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -595,7 +595,7 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let mesh = session.mesh.clone(); session.doc.bake_meshes.cage = - Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() }); + Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new(), fingerprint: 0 }); let settings = &mut session.doc.project.texture_sets[0].bake; (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); harness.run_steps(3); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a682a901..91fad894 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -320,6 +320,12 @@ with no partner. It is `null` when no set of the bake matches by mesh name: "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} ``` +Each texture set in `project.inspect` / `session.inspect` lists its out-of-date mesh maps as +`outOfDate`: map id → what changed since that map was baked, any of `lowPoly`, `highPoly`, `cage`, +`settings` (the bake settings every map shares, or the UV tiles baked) and `mapSettings` (the map's +own). Imported maps, and maps saved before this record existed, never show: +`"outOfDate": {"ambientOcclusion": ["mapSettings"]}`. + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From 5b4411ee9a5e1c5012f5670bd3558dc257ad23aa Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:20:12 +0000 Subject: [PATCH 094/190] Note a generator's missing or out-of-date mesh map A generator that reads a mesh map the active texture set has not baked, or baked before its mesh, files or settings changed, shows one line under its kind: what is wrong, the reasons on hover, and a Bake button that bakes the set in the background (turning the map on first when it is off). Nothing shows once the map is up to date, and nothing pops up. The line replaces the old warning at the end of the panel, which showed for every generator, even those that read no mesh map. --- crates/ui-egui/src/generator_panel.rs | 6 +- .../ui-egui/src/generator_panel/bake_note.rs | 107 ++++++++++++++++++ .../ui-egui/tests/it/generator_bake_note.rs | 75 ++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 4 files changed, 186 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/generator_panel/bake_note.rs create mode 100644 crates/ui-egui/tests/it/generator_bake_note.rs diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 95d3fcd7..745d93fd 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -18,6 +18,8 @@ use crate::property_sheet::PropertySheet; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +mod bake_note; + /// The outline on the preview while it can open enlarged under the pointer, or is open, in points const ENLARGE_OUTLINE_WIDTH: f32 = 1.0; @@ -35,6 +37,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, PropertySheet::show(ui, ("generator_sheet", id), |sheet| { sheet.section(tr("Generator"), false); slot_card(app, sheet, id, generator); + bake_note::bake_notes(app, sheet, generator); let band = sheet.band(tr("Parameters"), true, Some(differs_from_defaults(generator)), None); if band.reset { @@ -68,9 +71,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, if sheet.band(tr("Attributes"), false, None, None).open { attributes(sheet, generator.kind); } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - sheet.caption(tr("Bake mesh maps for curvature, AO and thickness based generators.")); - } }); } diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs new file mode 100644 index 00000000..4953261d --- /dev/null +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -0,0 +1,107 @@ +//! One quiet line under a generator's kind when a mesh map it reads is not baked or out of date, with a Bake button + +use egui::{Align, Layout, RichText, Stroke, Ui, UiBuilder, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeChange, BakedMap, Generator}; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::{PropertySheet, SIDE_PADDING_POINTS}; +use crate::theme::{Tokens, semibold}; + +/// Height of the note's line, in points (the mock's 28 px row) +const NOTE_HEIGHT: f32 = 28.0; + +/// Height of the Bake button, in points (the panels' 24 px controls) +const BUTTON_HEIGHT: f32 = 24.0; + +/// Size of the tooltip's title and reasons, in points +const TOOLTIP_TEXT_SIZE: f32 = 12.0; + +/// The note for each mesh map `generator` reads from the active texture set that is not baked or out of date +pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, generator: &Generator) { + let texture_set = app.session.ts(); + for map in generator.inputs_in_use() { + if generator.inputs.contains_key(map) { + continue; + } + + let baked = app.session.baked(texture_set).is_some_and(|baked| baked.maps.contains_key(map)); + let changes = if baked { app.session.bake_changes(texture_set, *map) } else { Vec::new() }; + if baked && changes.is_empty() { + continue; + } + + // A full-width line inside the sheet's side padding + let (line, _) = sheet.ui.allocate_exact_size(vec2(sheet.ui.available_width(), NOTE_HEIGHT), egui::Sense::hover()); + let builder = UiBuilder::new().id_salt(map).max_rect(line.shrink2(vec2(SIDE_PADDING_POINTS, 0.0))).layout(Layout::left_to_right(Align::Center)); + sheet.ui.scope_builder(builder, |ui| note(app, ui, (texture_set, *map), &changes)); + } +} + +/// The line for `map` of `texture_set`: not baked when `changes` is empty, else out of date because of them +fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, BakedMap), changes: &[BakeChange]) { + let tokens = Tokens::get(ui.ctx()); + let name = tr(baked_map_label(map)); + let (glyph, text, title) = match changes.is_empty() { + true => (ic::WARNING, trf("{map} map not baked", &[("map", &name)]), tr("Not baked")), + false => (ic::CLOCK, trf("{map} map out of date", &[("map", &name)]), tr("Out of date")), + }; + let checked = app.session.doc.project.texture_sets.get(texture_set).is_some_and(|set| set.bake.maps.is_enabled(map)); + + ui.label(RichText::new(glyph).color(tokens.warning)); + ui.add(egui::Label::new(&text).truncate()).on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + for reason in reasons(changes, checked) { + ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + } + }); + let bake = ui + .with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = egui::Button::new(tr("Bake")).stroke(Stroke::new(1.0, tokens.button_border)).min_size(vec2(0.0, BUTTON_HEIGHT)); + ui.add_enabled(app.bake.is_none(), button) + .on_hover_text(tr("Bake this texture set's mesh maps in the background")) + .on_disabled_hover_text(tr("A bake is already running")) + }) + .inner; + + if bake.clicked() { + bake_map(app, texture_set, map); + } +} + +/// Why the line shows: what changed since the bake, or what a missing map does to the generator +fn reasons(changes: &[BakeChange], checked: bool) -> Vec<&'static str> { + if changes.is_empty() { + let mut reasons = vec![tr("The generator reads a flat value until this map is baked.")]; + if !checked { + reasons.push(tr("Bake turns this map on in the bake settings first.")); + } + return reasons; + } + + changes + .iter() + .map(|change| match change { + BakeChange::LowPoly => tr("The mesh changed after this bake."), + BakeChange::HighPoly => tr("The high poly files changed after this bake."), + BakeChange::Cage => tr("The cage changed after this bake."), + BakeChange::Settings => tr("The common bake settings changed after this bake."), + BakeChange::MapSettings => tr("This map's bake settings changed after this bake."), + }) + .collect() +} + +/// Bake `texture_set` in the background, turning `map` on in its bake settings first when it is off +fn bake_map(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { + let Some(before) = app.session.doc.project.texture_sets.get(texture_set).map(|set| set.bake.clone()) else { return }; + + if !before.maps.is_enabled(map) { + let mut after = before.clone(); + after.maps.set_enabled(map, true); + app.run("bake.settings", json!({ "ts": texture_set, "patch": settings_patch(&before, &after) })); + } + app.start_bake(vec![texture_set]); +} diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs new file mode 100644 index 00000000..d26019c7 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -0,0 +1,75 @@ +//! The generator's note when a mesh map it reads is not baked or out of date, and its Bake button + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +/// A plane whose bake makes only the position map, with a curvature generator selected in a fill layer's mask +fn harness() -> Harness<'static, TextureCraftApp> { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({ "color": [0.8, 0.3, 0.1] })).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({ "generator": "curvature" })).unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + harness +} + +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..4000 { + harness.run_steps(1); + if harness.state().bake.is_none() { + harness.run_steps(2); + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() { + let mut harness = harness(); + harness.get_by_label("Curvature map not baked"); + + execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["curvature"] })).unwrap(); + harness.run_steps(3); + assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); + assert!(harness.query_by_label("Curvature map out of date").is_none(), "baked: no note"); + + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.run_steps(3); + harness.get_by_label("Curvature map out of date"); +} + +#[test] +fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() { + let mut harness = harness(); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature)); + + harness.get_by_label("Bake").click(); + harness.run_steps(1); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature), "turned on"); + assert!(harness.state().bake.is_some(), "a background bake started"); + run_to_the_end(&mut harness); + + assert!(harness.state().session.baked(0).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Curvature))); + assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 045d3d57..0abd9441 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -44,6 +44,7 @@ mod fill_symmetry_rows; mod filter_picker; mod folder_properties; mod frame_selection; +mod generator_bake_note; mod generator_panel; mod generator_picker; mod help_menu_664; From 9e36885648d969560d050f30704bff97c98ef6ef Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:41:02 +0000 Subject: [PATCH 095/190] Rebake the auto-rebake map when its settings change Each texture set can turn on Auto-rebake for one mesh map (bake.autoRebake, saved with the project; older projects have none). In Bake mode the app rebakes that map alone in the background once what it is baked from has stopped changing for half a second; a change during that bake cancels it and the newest settings bake instead. Only a failed rebake makes a toast. --- crates/core/src/project.rs | 4 + crates/engine/src/bake/auto_rebake.rs | 51 +++++++++++++ crates/engine/src/bake/bake_log.rs | 13 ++++ crates/engine/src/bake/mesh_map_command.rs | 15 ++-- crates/engine/src/bake/mod.rs | 2 + crates/engine/src/inspect.rs | 1 + crates/engine/tests/it/auto_rebake.rs | 68 +++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/auto_rebake.rs | 79 ++++++++++++++++++++ crates/ui-egui/src/bake_job.rs | 2 + crates/ui-egui/src/bake_report.rs | 6 +- crates/ui-egui/src/lib.rs | 27 +++++-- crates/ui-egui/src/updates_ui.rs | 2 +- crates/ui-egui/tests/bake_preview.rs | 1 + crates/ui-egui/tests/it/auto_rebake.rs | 87 ++++++++++++++++++++++ crates/ui-egui/tests/it/bake_job_mesh.rs | 2 +- crates/ui-egui/tests/it/baking_log.rs | 12 +++ crates/ui-egui/tests/it/main.rs | 1 + docs/control-protocol.md | 7 ++ 19 files changed, 365 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/bake/auto_rebake.rs create mode 100644 crates/engine/tests/it/auto_rebake.rs create mode 100644 crates/ui-egui/src/auto_rebake.rs create mode 100644 crates/ui-egui/tests/it/auto_rebake.rs diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 69437007..ca70f6ff 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -72,6 +72,9 @@ pub struct TextureSet { /// What each baked map was baked from; a map without a record (imported, or older project) is never out of date #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub bake_sources: BTreeMap, + /// The one mesh map the app rebakes by itself when what it is baked from changes + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto_rebake: Option, #[serde(default = "yes")] pub visible: bool, /// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode); @@ -175,6 +178,7 @@ impl TextureSet { bake: BakeSettings::default(), baked: BTreeSet::new(), bake_sources: BTreeMap::new(), + auto_rebake: None, visible: true, uv_tiles: Vec::new(), bake_excluded_tiles: BTreeSet::new(), diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs new file mode 100644 index 00000000..45831b82 --- /dev/null +++ b/crates/engine/src/bake/auto_rebake.rs @@ -0,0 +1,51 @@ +//! Auto-rebake: the one mesh map per texture set that is baked again whenever what it is baked from changes + +use serde_json::{Value, json}; +use texturecraft_core::{BakeSource, BakedMap}; + +use crate::commands::{CommandSpec, always, bad, strp, u64p}; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "bake.autoRebake", + "Auto-rebake", + [], + None, + "{ts?: index (default: the active set), map: id | null} → {ts, autoRebake: id | null}. Turn on Auto-rebake for one mesh map of the set (it replaces the set's previous one), or turn it off with null. The app then rebakes that map in the background once what it is baked from changes", + always, + set_auto_rebake + )] +} + +fn set_auto_rebake(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.autoRebake"; + let texture_set = match params.get("ts") { + None => session.ts(), + Some(_) => u64p(params, "ts").map(|index| index as usize).filter(|index| *index < session.set_count()).ok_or_else(|| bad(COMMAND, "invalid `ts`"))?, + }; + let map = match params.get("map") { + Some(Value::Null) => None, + Some(_) => Some(strp(params, "map").and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, "`map` must be a mesh map id or null"))?), + None => return Err(bad(COMMAND, "`map` is required (a mesh map id or null)")), + }; + + if session.doc.project.texture_set(texture_set)?.auto_rebake != map { + session.edit("Auto-rebake", |session| { + session.doc.project.texture_set_mut(texture_set)?.auto_rebake = map; + Ok(()) + })?; + } + Ok(json!({ "ts": texture_set, "autoRebake": map.map(BakedMap::id) })) +} + +impl Session { + /// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now) + pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> { + let sets = self.doc.project.texture_sets.iter().enumerate(); + sets.filter_map(|(index, set)| Some((index, set.auto_rebake?))) + .filter(|(index, map)| !self.bake_changes(*index, *map).is_empty()) + .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) + .collect() + } +} diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 7203b7c1..18ab8e2a 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -136,6 +136,19 @@ impl Session { self.bake_log.matching = matching; } + /// Start the Baking Log for a bake of only `map` of each of `sets`, checked or not + pub fn begin_map_bake_log(&mut self, sets: &[usize], map: BakedMap) { + self.begin_bake_log(sets); + let project = &self.doc.project; + self.bake_log.maps = sets + .iter() + .filter_map(|&texture_set| { + let set_name = project.texture_sets.get(texture_set)?.name.clone(); + Some(BakeLogMap { texture_set, set_name, map, state: BakeMapState::Waiting }) + }) + .collect(); + } + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it fn bake_log_matching(&self, sets: &[usize]) -> Option { let mut matching: Option = None; diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 49ec4ec0..474a5266 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -131,9 +131,14 @@ impl Session { self.bake_task_of(texture_set, None) } + /// A task that bakes only `maps` of texture set `texture_set`, checked or not; its other baked maps stay as they are + pub fn bake_task_for(&self, texture_set: usize, maps: &[BakedMap]) -> Result { + self.bake_task_of(texture_set, Some(maps)) + } + /// The bake of texture set `texture_set`'s map `map` alone, checked or not pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result { - self.bake_task_of(texture_set, Some(map)) + self.bake_task_of(texture_set, Some(&[map])) } /// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles @@ -143,15 +148,15 @@ impl Session { Ok(task) } - fn bake_task_of(&self, texture_set: usize, only: Option) -> Result { + fn bake_task_of(&self, texture_set: usize, only: Option<&[BakedMap]>) -> Result { let set = self.doc.project.texture_set(texture_set)?; if !set.has_enabled_bake_tiles() { return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); } let mut settings = set.bake.clone(); - if let Some(map) = only { - settings.maps.select([map]); + if let Some(maps) = only { + settings.maps.select(maps.iter().copied()); } // Read from the maps that bake, so a map baked alone while unchecked still gets the colours @@ -184,7 +189,7 @@ impl Session { let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed)); - let sources = set.bake.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; + let sources = settings.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; Ok(BakeTask { low_base_color, ts: texture_set, diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index ee75d670..da0599bd 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,5 +1,6 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API +mod auto_rebake; mod bake_cage_inputs; mod bake_checks; mod bake_high_state; @@ -52,6 +53,7 @@ type MaterialColors = std::sync::Arc Vec { let mut commands = mesh_map_command::specs(); commands.extend(paint_command::specs()); + commands.extend(auto_rebake::specs()); commands.extend(tile_command::specs()); commands.extend(sync_command::specs()); commands diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index e9c3b2e5..04af908b 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -277,6 +277,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), + "autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id), "visible": texture_set.visible, "active": index == session.ts(), }) diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs new file mode 100644 index 00000000..c424ef47 --- /dev/null +++ b/crates/engine/tests/it/auto_rebake.rs @@ -0,0 +1,68 @@ +//! Auto-rebake: one map per texture set, due when it goes out of date, rebaked alone + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with its position and ID maps baked +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + session +} + +fn due_maps(session: &Session) -> Vec<(usize, BakedMap)> { + session.auto_rebake_due().into_iter().map(|(set, map, _)| (set, map)).collect() +} + +#[test] +fn one_map_per_set_is_auto_rebaked_and_it_is_due_only_once_out_of_date() { + let mut session = baked_plane(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "id" })).unwrap(); + let turned_on = execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + assert_eq!(turned_on, json!({ "ts": 0, "autoRebake": "position" }), "the second map replaces the first"); + assert!(due_maps(&session).is_empty(), "up to date: {:?}", due_maps(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(due_maps(&session), [(0, BakedMap::Position)]); + + execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + assert!(due_maps(&session).is_empty(), "turned off: {:?}", due_maps(&session)); + assert!(execute(&mut session, "bake.autoRebake", &json!({ "map": "glow" })).is_err()); +} + +#[test] +fn the_auto_rebake_map_is_saved_with_the_project_and_undone_like_an_edit() { + let mut session = baked_plane(); + let before = session.to_project_bytes().unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position)); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["autoRebake"], json!("position")); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None); + assert_eq!(Session::from_project_bytes(&before).unwrap().doc.project.texture_sets[0].auto_rebake, None, "older projects have none"); +} + +#[test] +fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "maps": ["id"], "positionMode": "boundingBox" })).unwrap(); + let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + + let task = session.bake_task_for(0, &[BakedMap::Position]).unwrap(); + assert_eq!(task.maps(), [BakedMap::Position], "an unchecked map bakes when asked for"); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", session.bake_changes(0, BakedMap::Position)); + let baked = session.baked(0).unwrap(); + assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::>(), [BakedMap::Id], "the checks stay"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f43035f4..843ab3d3 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone session.rs target remains available. mod add_mask_items; +mod auto_rebake; mod bake; mod bake_checks; mod bake_log; diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs new file mode 100644 index 00000000..8f20e7b0 --- /dev/null +++ b/crates/ui-egui/src/auto_rebake.rs @@ -0,0 +1,79 @@ +//! Auto-rebake: a texture set's auto-rebake map is baked again in the background once what it is baked from has stopped changing + +use texturecraft_engine::core::{BakeSource, BakedMap}; + +use crate::{BakeJob, TextureCraftApp, bake_report, state}; + +/// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts +const SETTLE_SECONDS: f64 = 0.5; + +/// An out-of-date auto-rebake map: its texture set, the map and what a bake would read now +pub type Due = (usize, BakedMap, BakeSource); + +/// What the app has seen of the out-of-date auto-rebake maps +#[derive(Default)] +pub struct AutoRebake { + /// The due maps and the frame time they were first seen as they are + pending: Option<(Vec, f64)>, + /// The due maps when the last rebake started: a failed or canceled rebake is not tried again until something changes + started: Vec, +} + +/// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed +pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + if app.ui.mode != state::Mode::Baking { + app.auto_rebake.pending = None; + return; + } + + let due = app.session.auto_rebake_due(); + if let Some(job) = &app.bake { + // Newest wins: a rebake whose map changed again while it ran starts over with the new settings + if job.rebake.is_some_and(|rebake| !due.contains(&rebake)) { + app.cancel_bake(); + } + return; + } + + if due.is_empty() || due == app.auto_rebake.started { + app.auto_rebake.pending = None; + return; + } + + let now = app.last_time; + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); + match &app.auto_rebake.pending { + Some((seen, since)) if *seen == due && now - since >= SETTLE_SECONDS => {} + Some((seen, _)) if *seen == due => return, + _ => { + app.auto_rebake.pending = Some((due, now)); + return; + } + } + + app.auto_rebake.pending = None; + app.auto_rebake.started = due.clone(); + if let Some(rebake) = due.first().copied() { + start(app, rebake); + } +} + +/// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake +fn start(app: &mut TextureCraftApp, rebake: Due) { + let (set, map, _) = rebake; + let orders = match app.session.bake_preview_orders(&[set], Some(map)) { + Ok(orders) => orders, + Err(error) => { + app.toast(error.to_string(), true); + return; + } + }; + + // Restore the previous view before the rebake takes it over + app.live_preview.release(&mut app.session); + crate::id_color_pick::IdColorPick::end(app); + app.session.bake_preview_begin(orders); + app.session.begin_map_bake_log(&[set], map); + app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; + app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); +} diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index 97dd4610..431999db 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -11,4 +11,6 @@ pub struct BakeJob { pub mesh_id: u64, /// The one map to bake (a row's quick bake) instead of the checked ones pub only: Option, + /// An auto-rebake: the set, the one map it bakes and what that map was baked from when it started; `None` bakes every checked map + pub rebake: Option, } diff --git a/crates/ui-egui/src/bake_report.rs b/crates/ui-egui/src/bake_report.rs index d0423de9..89e1ebf6 100644 --- a/crates/ui-egui/src/bake_report.rs +++ b/crates/ui-egui/src/bake_report.rs @@ -10,6 +10,8 @@ pub struct BakeReport { pub map_count: usize, /// Number of texture sets whose bake failed pub failed_set_count: usize, + /// A rebake the app started by itself (Auto-rebake): only a failure makes a toast + pub auto_rebake: bool, } impl BakeReport { @@ -57,7 +59,7 @@ mod tests { #[test] fn success_names_maps_and_time() { - let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0 }; + let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0, auto_rebake: false }; let (text, line, failed) = report.summary(22.34); @@ -68,7 +70,7 @@ mod tests { #[test] fn failures_are_counted_and_point_to_the_log() { - let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2 }; + let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2, auto_rebake: false }; let (text, _, failed) = report.summary(125.0); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4346c304..2816c247 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,15 +10,16 @@ mod anchor_properties; mod angle_dial; mod ask; +mod auto_rebake; #[cfg(not(target_arch = "wasm32"))] mod autosave_name; mod bake_job; pub mod bake_mode; -pub mod baking_log; mod bake_preset; pub mod bake_presets; mod bake_report; mod bake_scene; +pub mod baking_log; mod color_management; mod color_picker; mod color_selection_editor; @@ -290,6 +291,8 @@ pub struct TextureCraftApp { pub bake: Option, /// What the bake running now has done so far, for the summary when it ends pub bake_report: bake_report::BakeReport, + /// When the out-of-date auto-rebake maps are rebaked + auto_rebake: auto_rebake::AutoRebake, /// The Import PBR textures dialog while it is open. pub pbr_import: Option, pub resize: Option, @@ -466,6 +469,7 @@ impl TextureCraftApp { gpu_memory: (Vec::new(), None), bake: None, bake_report: Default::default(), + auto_rebake: Default::default(), pbr_import: None, resize: None, #[cfg(not(target_arch = "wasm32"))] @@ -707,9 +711,12 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.begin_bake_log(&sets); + match only { + Some(map) => self.session.begin_map_bake_log(&sets, map), + None => self.session.begin_bake_log(&sets), + } self.bake_report = bake_report::BakeReport::started(self.last_time); - self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only, rebake: None }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -886,13 +893,14 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); - let only = job.only; + let (only, rebake) = (job.only, job.rebake); self.session.bake_preview_set_current(set_index); self.session.bake_log.set_started(set_index); - let task = match only { - Some(map) => self.session.bake_task_only(set_index, map), - None => self.session.bake_task(set_index), + let task = match (rebake, only) { + (Some((_, map, _)), _) => self.session.bake_task_for(set_index, &[map]), + (None, Some(map)) => self.session.bake_task_only(set_index, map), + (None, None) => self.session.bake_task(set_index), }; match task { Ok(task) => { @@ -936,6 +944,10 @@ impl TextureCraftApp { self.session.log.info("Baker", line); } + if self.bake_report.auto_rebake && !failed { + return; + } + self.toast(text, failed); if let Some(toast) = self.toasts.last_mut() { toast.show_log = failed; @@ -1223,6 +1235,7 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.bake_map_thumbnails.retain_mesh(self.session.mesh_id); bake_mode::poll_live_preview(self, ctx); + auto_rebake::poll(self, ctx); self.poll_resize(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_high_poly_job(ctx); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index aeaaea1f..ce719304 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -297,7 +297,7 @@ mod tests { assert!(!safe_to_close(h.state()), "unsaved changes"); h.state_mut().session.modified = false; - h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None, rebake: None }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 6de467e4..9bb1eae2 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -134,6 +134,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { total: 1, mesh_id, only: None, + rebake: None, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs new file mode 100644 index 00000000..5358fcf1 --- /dev/null +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -0,0 +1,87 @@ +//! Auto-rebake in the app: a settings change rebakes the auto-rebake map alone, in the background + +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; + +/// A plane in Bake mode with its position and ID maps baked and Auto-rebake on for the position map +fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": resolution, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness +} + +fn change_settings(harness: &mut Harness<'static, TextureCraftApp>, params: serde_json::Value) { + execute(&mut harness.state_mut().session, "bake.settings", ¶ms).unwrap(); +} + +/// Step frames until `done` holds, up to a generous limit +fn step_until(harness: &mut Harness<'static, TextureCraftApp>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) { + for _ in 0..4000 { + harness.run_steps(1); + if done(harness.state()) { + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("{what} did not happen"); +} + +#[test] +fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { + let mut harness = harness(64); + let id_before = harness.state().session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + + let app = harness.state(); + assert!(app.session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", app.session.bake_changes(0, BakedMap::Position)); + assert!(std::sync::Arc::ptr_eq(&app.session.baked(0).unwrap().maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); + let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect(); + assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); + assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); +} + +#[test] +fn nothing_is_rebaked_outside_bake_mode() { + let mut harness = harness(64); + harness.state_mut().ui.mode = Mode::Painting; + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + harness.run_steps(120); + + assert!(harness.state().bake.is_none()); + assert!(!harness.state().session.bake_changes(0, BakedMap::Position).is_empty()); +} + +#[test] +fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { + let mut harness = harness(64); + execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["ambientOcclusion"], "ao": { "rays": 1 } })).unwrap(); + execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": "ambientOcclusion" })).unwrap(); + + // A slow rebake, so the next change lands while it runs + change_settings(&mut harness, json!({ "resolution": 2048, "ao": { "rays": 256 } })); + step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + change_settings(&mut harness, json!({ "ao": { "rays": 128 } })); + harness.run_steps(1); + + let app = harness.state(); + assert!(app.bake.is_none(), "the outdated rebake stopped"); + assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); + execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); +} diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 309bb67e..f805bfc9 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -22,7 +22,7 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes let job_mesh_id = mesh_id(harness.state().session.mesh_id); let running = RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; - harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None }); + harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); harness.step(); check(&harness, &progress); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 3d098b6f..11251da2 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -63,6 +63,18 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } +#[test] +fn a_one_map_bake_lists_only_that_map() { + let mut harness = harness(); + + harness.state_mut().start_bake_of(vec![0], Some(BakedMap::Position)); + run_to_the_end(&mut harness); + + let name = harness.state().session.doc.project.texture_sets[0].name.clone(); + assert!(harness.query_by_label(&format!("{name} Position, Baked")).is_some(), "the baked map is ticked"); + assert!(harness.query_by_label_contains(&format!("{name} ID")).is_none(), "a checked map the bake left alone has no row"); +} + #[test] fn a_failed_maps_arrow_opens_its_settings() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0abd9441..0aa4441d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -3,6 +3,7 @@ mod alpha_parameters; mod anchor_point; +mod auto_rebake; mod bake_job_mesh; mod bake_live_preview; mod bake_map_rows; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 91fad894..308849f3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -326,6 +326,13 @@ Each texture set in `project.inspect` / `session.inspect` lists its out-of-date own). Imported maps, and maps saved before this record existed, never show: `"outOfDate": {"ambientOcclusion": ["mapSettings"]}`. +`bake.autoRebake` `{ts?, map: id | null}` turns on Auto-rebake for one mesh map of a texture set +(the active one by default), replacing its previous one, or turns it off with `null`; it is saved +with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web +app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the +background, alone, once its settings have stopped changing for half a second; a change during +that bake restarts it. The headless CLI does not rebake by itself: run `bake.run` there. + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From 4a56683bb9a5cadf297fcdfdfa856704e01dddc9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:03:40 +0000 Subject: [PATCH 096/190] Rebake the auto-rebake map inside a skew or cage stroke A skew or cage stroke on a set that bakes from a high poly marks its UV box; in Bake mode the app then bakes the set's auto-rebake map again only there (one texel wider, for the paint map's sampling), keeps the rest of the stored map and pads the whole map, so its pixels match a whole bake. Maps scaled by their whole range (curvature, height, thickness), UV-tiled sets and a map stored at another size bake whole. A stroke painted while that bake runs is baked by the next one. The bake crate gains bake_tiles_in with a texel box. --- crates/bake/src/bake_passes.rs | 19 +++++- crates/bake/src/lib.rs | 60 ++++++++++++++++-- crates/bake/src/progress.rs | 5 +- crates/bake/src/region_bake.rs | 12 ++++ crates/bake/src/test/tile_selection.rs | 2 +- crates/bake/src/tests.rs | 2 +- crates/bake/src/texel_box.rs | 27 ++++++++ crates/engine/src/bake/auto_rebake.rs | 12 ++++ crates/engine/src/bake/bake_log.rs | 10 +-- crates/engine/src/bake/bake_sources.rs | 19 ++++-- crates/engine/src/bake/bake_task.rs | 33 ++++++---- crates/engine/src/bake/mesh_map_command.rs | 30 +++++---- crates/engine/src/bake/mod.rs | 2 + crates/engine/src/bake/paint_command.rs | 9 +++ crates/engine/src/bake/painted_region.rs | 74 ++++++++++++++++++++++ crates/engine/src/bake/streamed_bake.rs | 2 + crates/engine/src/session.rs | 6 ++ crates/engine/tests/it/auto_rebake.rs | 73 +++++++++++++++++++++ crates/engine/tests/it/bake.rs | 2 +- crates/ui-egui/src/auto_rebake.rs | 33 ++++++---- crates/ui-egui/src/lib.rs | 11 ++-- crates/ui-egui/tests/it/auto_rebake.rs | 28 ++++++++ docs/control-protocol.md | 5 +- 23 files changed, 406 insertions(+), 70 deletions(-) create mode 100644 crates/bake/src/region_bake.rs create mode 100644 crates/bake/src/texel_box.rs create mode 100644 crates/engine/src/bake/painted_region.rs diff --git a/crates/bake/src/bake_passes.rs b/crates/bake/src/bake_passes.rs index eb7d5846..503bd45d 100644 --- a/crates/bake/src/bake_passes.rs +++ b/crates/bake/src/bake_passes.rs @@ -1,7 +1,7 @@ use crate::cage::RayFrame; use crate::map::BakeContext; use crate::tracing::{CpuTracer, Tracer}; -use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress}; +use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress, RegionBake}; use std::sync::atomic::Ordering::Relaxed; use texturecraft_core::{BakeSettings, BakedMap}; @@ -23,10 +23,22 @@ impl<'a> BakePasses<'a> { progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>, + ) -> Result { + self.bake_map_in(map, progress, excluded_tiles, None, tracer) + } + + /// [`BakePasses::bake_map`] sampling only `region`'s texels, as [`crate::bake_tiles_in`] does + pub fn bake_map_in( + &mut self, + map: BakedMap, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + region: Option, + tracer: Option<&dyn Tracer>, ) -> Result { let mut settings = self.request.settings.clone(); settings.maps.select([map]); - self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS) + self.run(&settings, progress, excluded_tiles, region, tracer, super::STRIP_TEXELS) } pub(super) fn run( @@ -34,6 +46,7 @@ impl<'a> BakePasses<'a> { settings: &BakeSettings, progress: &Progress, excluded_tiles: &[(u32, u32)], + region: Option, tracer: Option<&dyn Tracer>, strip_texels: usize, ) -> Result { @@ -56,7 +69,7 @@ impl<'a> BakePasses<'a> { } }; let context = BakeContext::with_frame(&request, *extent, frame); - let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles); + let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles, region); match tracer { Some(tracer) => match bake(tracer) { Err(BakeError::Tracer(error)) => { diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 5c8c3ba8..50f2f54c 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -12,6 +12,8 @@ mod high_poly; mod mesh_extent; mod name_pair; mod progress; +mod region_bake; +mod texel_box; pub use bake_error::BakeError; pub use bake_output::BakeOutput; @@ -22,6 +24,8 @@ pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; pub use name_pair::NamePair; pub use progress::Progress; +pub use region_bake::RegionBake; +pub use texel_box::{TexelBox, region_keeps_pixels}; mod map; mod skew; @@ -50,6 +54,8 @@ const STRIP_TEXELS: usize = 1 << 24; const BATCH: usize = 1 << 18; // Curvature batches stay small so progress and cancellation remain responsive const CURVATURE_BATCH: usize = 1 << 15; +/// Smallest mesh extent the maps are normalized by, so a flat mesh never divides by zero +const MIN_MESH_EXTENT: f32 = 1e-6; fn validate(request: &BakeRequest) -> Result<(), BakeError> { let settings = request.settings; @@ -161,7 +167,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) /// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { - BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS) + bake_tiles_in(request, progress, excluded_tiles, None, tracer) +} + +/// [`bake_tiles`] sampling only `region`'s texels and padding a whole map; equal to a whole bake for [`region_keeps_pixels`] maps +pub fn bake_tiles_in( + request: &BakeRequest, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + region: Option, + tracer: Option<&dyn Tracer>, +) -> Result { + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, tracer, STRIP_TEXELS) } type OutRow<'a> = Vec<&'a mut [f32]>; @@ -173,8 +190,9 @@ fn bake_in_strips( strip_texels: usize, tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], + region: Option, ) -> Result { - BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels) + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, Some(tracer), strip_texels) } fn bake_prepared( @@ -184,6 +202,7 @@ fn bake_prepared( strip_texels: usize, tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], + region: Option, ) -> Result { if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); @@ -211,7 +230,7 @@ fn bake_prepared( let mut padding_map = None; let total_rows = height.max(1) as u64; let mut rows_done = 0u64; - let strip_error = || BakeError::Invalid("strip output of range".into()); + let strip_error = || BakeError::Invalid("strip output out of range".into()); let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis); let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height); @@ -250,6 +269,18 @@ fn bake_prepared( } }); + // Coverage stays the whole map's, so padding matches a whole bake; only the region is sampled + if let Some(region) = region { + for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() { + let y = (sample_start_y + row_index) / samples_per_axis; + for (sample_x, triangle) in row.iter_mut().enumerate() { + if !region.texels.contains(sample_x / samples_per_axis, y) { + *triangle = NO_TRI; + } + } + } + } + let mut output_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect(); for (map, data) in maps.iter().zip(buffers.iter_mut()) { let component_count = map.components(); @@ -258,6 +289,7 @@ fn bake_prepared( row.push(chunk); } } + let mut bake_strip = || { for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() { if progress.cancel.load(Relaxed) { @@ -276,10 +308,11 @@ fn bake_prepared( (width, samples_per_axis, sample_start_y * sample_width), )?; rows_done += batch.len() as u64; - progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed); + progress.done.store((rows_done.saturating_mul(u64::from(Progress::DONE)) / total_rows).min(u64::from(Progress::DONE)) as u32, Relaxed); } Ok(()) }; + if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) { bake_strip()?; } else { @@ -291,6 +324,19 @@ fn bake_prepared( } } + if let Some(region) = region { + for (map, pixels) in maps.iter().zip(buffers.iter_mut()) { + let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len()); + let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?; + let components = map.components(); + for (index, (pixel, kept)) in pixels.chunks_exact_mut(components).zip(previous.chunks_exact(components)).enumerate() { + if !region.texels.contains(index % width, index / width) { + pixel.copy_from_slice(kept); + } + } + } + } + let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { let world_normal = @@ -306,7 +352,8 @@ fn bake_prepared( } let (bounds_min, bounds_max) = request.mesh.bounds(); - map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6)); + map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(MIN_MESH_EXTENT)); + if let Some(padding_map) = padding_map { for (map, data) in output.iter_mut() { padding_map.apply(data, map.components()); @@ -315,11 +362,12 @@ fn bake_prepared( } } } + if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } - progress.done.store(10_000, Relaxed); + progress.done.store(Progress::DONE, Relaxed); Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } diff --git a/crates/bake/src/progress.rs b/crates/bake/src/progress.rs index 5bb924ec..4f0a740c 100644 --- a/crates/bake/src/progress.rs +++ b/crates/bake/src/progress.rs @@ -8,12 +8,15 @@ pub struct Progress { } impl Progress { + /// The basis points of a finished bake + pub const DONE: u32 = 10_000; + pub fn new() -> Self { Self::default() } pub fn fraction(&self) -> f32 { - self.done.load(Relaxed).min(10_000) as f32 / 10_000.0 + self.done.load(Relaxed).min(Self::DONE) as f32 / Self::DONE as f32 } pub fn cancel(&self) { diff --git a/crates/bake/src/region_bake.rs b/crates/bake/src/region_bake.rs new file mode 100644 index 00000000..20a14849 --- /dev/null +++ b/crates/bake/src/region_bake.rs @@ -0,0 +1,12 @@ +use std::collections::BTreeMap; +use std::sync::Arc; +use texturecraft_core::BakedMap; + +use crate::TexelBox; + +/// A bake that samples only `texels` and takes every other texel from `previous`, a whole bake of the same size +#[derive(Clone, Copy, Debug)] +pub struct RegionBake<'a> { + pub texels: TexelBox, + pub previous: &'a BTreeMap>>, +} diff --git a/crates/bake/src/test/tile_selection.rs b/crates/bake/src/test/tile_selection.rs index 18f13968..a1176668 100644 --- a/crates/bake/src/test/tile_selection.rs +++ b/crates/bake/src/test/tile_selection.rs @@ -31,7 +31,7 @@ fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() { let full = bake(&request, &Progress::new()).unwrap(); for excluded in [[(0, 0)], [(1, 0)]] { let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap(); - let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap(); + let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded, None).unwrap(); let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap(); assert_eq!(strips.maps, partial.maps); assert_eq!(fallback.maps, partial.maps); diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 7d94031e..e0d63b05 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -390,7 +390,7 @@ fn strips_match_a_single_pass() { tiles: (1, 1), }; let whole = bake(&req, &Progress::new()).unwrap(); - let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap(); + let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[], None).unwrap(); for (map, a) in &whole.maps { let b = &strips.maps[map]; let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count(); diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs new file mode 100644 index 00000000..85be4fc0 --- /dev/null +++ b/crates/bake/src/texel_box.rs @@ -0,0 +1,27 @@ +/// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TexelBox { + pub min: (u32, u32), + pub max: (u32, u32), +} + +impl TexelBox { + /// Whether texel (`x`, `y`) lies inside the box + pub fn contains(&self, x: usize, y: usize) -> bool { + (self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y) + } + + /// The box grown by `texels` on every side, kept inside a `width` x `height` image + pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox { + TexelBox { + min: (self.min.0.saturating_sub(texels), self.min.1.saturating_sub(texels)), + max: (self.max.0.saturating_add(texels).min(width), self.max.1.saturating_add(texels).min(height)), + } + } +} + +/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours +pub fn region_keeps_pixels(map: texturecraft_core::BakedMap) -> bool { + use texturecraft_core::BakedMap; + !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) +} diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index 45831b82..e1e3cb1f 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -48,4 +48,16 @@ impl Session { .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) .collect() } + + /// The maps an auto-rebake of `map` bakes: that map alone, or with every checked map once the output size changed (storing a new size drops the old maps) + pub fn auto_rebake_maps(&self, texture_set: usize, map: BakedMap) -> Vec { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return vec![map] }; + let (width, height) = set.bake.common.output_size(); + let stored = self.doc.baked.get(&texture_set); + let resized = stored.is_some_and(|stored| stored.resolution != width || stored.maps.keys().any(|baked| stored.height(*baked) != height)); + match resized { + true => BakedMap::ALL.into_iter().filter(|baked| *baked == map || set.bake.maps.is_enabled(*baked)).collect(), + false => vec![map], + } + } } diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 18ab8e2a..90e8feaf 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -136,15 +136,15 @@ impl Session { self.bake_log.matching = matching; } - /// Start the Baking Log for a bake of only `map` of each of `sets`, checked or not - pub fn begin_map_bake_log(&mut self, sets: &[usize], map: BakedMap) { + /// Start the Baking Log for a bake of only `maps` of each of `sets`, checked or not + pub fn begin_map_bake_log(&mut self, sets: &[usize], maps: &[BakedMap]) { self.begin_bake_log(sets); let project = &self.doc.project; self.bake_log.maps = sets .iter() - .filter_map(|&texture_set| { - let set_name = project.texture_sets.get(texture_set)?.name.clone(); - Some(BakeLogMap { texture_set, set_name, map, state: BakeMapState::Waiting }) + .filter_map(|&texture_set| Some((texture_set, project.texture_sets.get(texture_set)?.name.clone()))) + .flat_map(|(texture_set, set_name)| { + maps.iter().map(move |&map| BakeLogMap { texture_set, set_name: set_name.clone(), map, state: BakeMapState::Waiting }) }) .collect(); } diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs index 70f7665c..e835c97c 100644 --- a/crates/engine/src/bake/bake_sources.rs +++ b/crates/engine/src/bake/bake_sources.rs @@ -44,22 +44,31 @@ impl Session { fn low_poly_fingerprint(&self) -> u64 { *self.low_poly_fingerprint.get_or_init(|| { let source = &self.source; - let floats = source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array())); + let floats = + source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array())); let words = floats.map(|float| u64::from(float.to_bits())).chain(source.indices.iter().map(|index| u64::from(*index))); fingerprint_words(words) }) } - /// Keep `sources` as what maps of `texture_set` were baked from; without them the `stored` maps lose their record - pub(super) fn record_bake_sources(&mut self, texture_set: usize, sources: Option<&BTreeMap>, stored: &[BakedMap]) -> Result<()> { + /// Keep what the `stored` maps of `texture_set` were baked from and the newest stroke their bake saw; without it they lose their record + pub(super) fn record_bake_sources( + &mut self, + texture_set: usize, + recorded: Option<(&BTreeMap, u64)>, + stored: &[BakedMap], + ) -> Result<()> { let set = self.doc.project.texture_set_mut(texture_set)?; - match sources { - Some(sources) => set.bake_sources.extend(sources), + match recorded { + Some((sources, _)) => set.bake_sources.extend(sources), None => set.bake_sources.retain(|map, _| !stored.contains(map)), } let baked = &set.baked; set.bake_sources.retain(|map, _| baked.contains(map)); + if let Some((_, painted_stroke)) = recorded { + self.forget_painted_region(texture_set, stored, painted_stroke); + } Ok(()) } } diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 3c0cb59e..35bee3b4 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,12 +1,12 @@ use super::{MergedHigh, StreamedBake, StreamedMap}; use crate::{EngineError, Result}; use std::sync::Arc; -use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, RegionBake, TexelBox, bake_tiles_in, tracing::Tracer}; use texturecraft_compose::BakedMaps; use texturecraft_core::{BakeSettings, BakedMap}; use texturecraft_geom::{Bvh, Mesh}; -/// A self-contained bake task that can run on another thread. +/// A self-contained bake task that can run on another thread pub struct BakeTask { pub low_base_color: super::MaterialColors, pub ts: usize, @@ -14,20 +14,24 @@ pub struct BakeTask { pub bvh: Arc, pub material: usize, pub settings: BakeSettings, - /// The merged high polys, unless the set bakes from the low poly. + /// The merged high polys, unless the set bakes from the low poly pub high: Option, pub cage: Option>, pub skew: Option>, pub cage_paint: Option>, - /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. + /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles pub tiles: (u32, u32), /// Snapshot of tile selection and pixels to retain while the worker runs pub excluded_tiles: Vec<(u32, u32)>, pub previous_maps: BakedMaps, - /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). + /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`) pub tracer: Option>, /// What each map this task makes is baked from, taken when the task was made pub sources: std::collections::BTreeMap, + /// The newest skew or cage stroke when the task was made; a later stroke still needs a rebake + pub painted_stroke: u64, + /// Sample only these texels and take the rest from `previous_maps` (the same size); `None` samples every texel + pub region: Option, } impl BakeTask { @@ -36,13 +40,7 @@ impl BakeTask { self.settings.maps.enabled().collect() } - /// Bake the maps one after another, handing each one to `on_map` as soon as it is padded, - /// and return all of them together. Each map is a bake of its own, so with a high poly - /// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several - /// maps, in exchange for showing them as they land. The pixels are the same as `run`'s. - /// The handed-over buffers are the returned ones too (no copy is made), so a preview that - /// keeps them costs no second set of maps. A cancel or an error leaves the maps already - /// handed over whole. + /// Bake the maps one by one (same pixels as [`BakeTask::run`], rays cast per map), handing each padded map's shared buffer to `on_map`, then return them all pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result { let maps = self.maps(); let total = maps.len(); @@ -50,7 +48,7 @@ impl BakeTask { let mut passes = BakePasses::new(self.request()); for (index, map) in maps.iter().copied().enumerate() { - let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + let mut output = passes.bake_map_in(map, progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; let Some(data) = output.maps.remove(&map) else { continue }; if combined.is_none() { @@ -74,6 +72,7 @@ impl BakeTask { maps: retained, tracer: output.tracer, sources: self.sources.clone(), + painted_stroke: self.painted_stroke, }); } } @@ -89,18 +88,24 @@ impl BakeTask { maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), tracer: output.tracer, sources: self.sources.clone(), + painted_stroke: self.painted_stroke, }) } } } pub fn run(&self, progress: &Progress) -> Result { - let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + let mut output = bake_tiles_in(&self.request(), progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?; Ok(output) } + /// The texels to sample, with the stored maps to take the rest from; `None` samples every texel + fn region(&self) -> Option> { + self.region.map(|texels| RegionBake { texels, previous: &self.previous_maps.maps }) + } + fn request(&self) -> BakeRequest<'_> { let high = self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color }); diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 474a5266..49d25503 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -206,6 +206,8 @@ impl Session { previous_maps, tracer, sources, + painted_stroke: self.painted_strokes, + region: None, }) } @@ -273,19 +275,20 @@ impl Session { Ok(()) } - /// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the - /// preview that showed them holds the same ones) + /// Apply a streamed bake like [`Session::apply_bake`], keeping the buffers the preview that showed them shares pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some(&output.sources)))?; + self.edit("Bake mesh maps", |session| { + session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some((&output.sources, output.painted_stroke))) + })?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } - /// Store `output`, recording what its maps were baked from when `sources` are known - fn store_bake(&mut self, texture_set: usize, output: BakeOutput, sources: Option<&BTreeMap>) -> Result<()> { + /// Store `output`, recording what its maps were baked from when known (see [`Session::record_bake_sources`]) + fn store_bake(&mut self, texture_set: usize, output: BakeOutput, recorded: Option<(&BTreeMap, u64)>) -> Result<()> { let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); - self.store_bake_maps(texture_set, output.resolution, output.height, maps, sources) + self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded) } fn store_bake_maps( @@ -294,7 +297,7 @@ impl Session { resolution: u32, height: u32, maps: BTreeMap>>, - sources: Option<&BTreeMap>, + recorded: Option<(&BTreeMap, u64)>, ) -> Result<()> { let stored: Vec = maps.keys().copied().collect(); let entry = self.doc.baked.entry(texture_set).or_default(); @@ -305,18 +308,19 @@ impl Session { entry.resolution = resolution; entry.maps.extend(maps); self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); - self.record_bake_sources(texture_set, sources, &stored) + self.record_bake_sources(texture_set, recorded, &stored) } - /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. + /// 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 { let mut task = self.bake_task(ts)?; if cpu { task.tracer = None; } - let out = task.run(&Progress::new())?; - let tracer = out.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(ts, out, Some(&task.sources)))?; + + let output = task.run(&Progress::new())?; + let tracer = output.tracer.clone(); + self.edit("Bake mesh maps", |session| session.store_bake(ts, output, Some((&task.sources, task.painted_stroke))))?; self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); Ok(tracer) } @@ -897,7 +901,7 @@ fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result Re session.doc.bake_paint.insert((texture_set, target), Arc::new(map)); Ok(()) })?; + session.note_bake_paint(texture_set, None); Ok(super::meshes_json(session)) } @@ -75,6 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> session.doc.bake_paint.remove(&(texture_set, target)); Ok(()) })?; + session.note_bake_paint(texture_set, None); } Ok(super::meshes_json(session)) } @@ -123,6 +125,13 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string())) })?; + + // The dabs reach `radius` from each point, and the paint map's bilinear sampling one of its texels further + let paint_texel = session.doc.bake_paint.get(&(texture_set, target)).map_or(0.0, |map| 1.0 / map.width.min(map.height).max(1) as f32); + let reach = Vec2::splat(radius + paint_texel); + let low = points.iter().fold(Vec2::INFINITY, |low, point| low.min(*point)) - reach; + let high = points.iter().fold(Vec2::NEG_INFINITY, |high, point| high.max(*point)) + reach; + session.note_bake_paint(texture_set, Some((low, high))); Ok(super::meshes_json(session)) } diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs new file mode 100644 index 00000000..4c31b533 --- /dev/null +++ b/crates/engine/src/bake/painted_region.rs @@ -0,0 +1,74 @@ +//! Where skew or cage painting changed what a texture set's transfer rays read since its maps were baked + +use texturecraft_bake::{TexelBox, region_keeps_pixels}; +use texturecraft_core::{BakeSource, BakedMap}; +use texturecraft_geom::glam::Vec2; + +use crate::{Result, Session}; + +/// The UV box painted since the last bake of a texture set's auto-rebake map +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PaintedRegion { + pub uv_min: Vec2, + pub uv_max: Vec2, + /// Counts up with every stroke, so a rebake can tell a newer stroke from the one it bakes + pub stroke: u64, +} + +/// Texels added around a painted box: bilinear sampling of the paint map and antialiasing samples reach one texel past it +const MARGIN_TEXELS: u32 = 1; + +impl Session { + /// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`) + pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) { + let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE)); + let (uv_min, uv_max) = match self.painted_regions.get(&texture_set) { + Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)), + None => (uv_min, uv_max), + }; + self.painted_strokes += 1; + self.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); + } + + /// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke` + pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) { + let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake); + let painted_since = self.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); + if !painted_since && auto.is_none_or(|map| stored.contains(&map)) { + self.painted_regions.remove(&texture_set); + } + } + + /// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke) + pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> { + let regions = self.painted_regions.iter(); + regions + .filter_map(|(index, region)| { + let set = self.doc.project.texture_sets.get(*index)?; + let map = set.auto_rebake.filter(|map| set.baked.contains(map))?; + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + (from_high && self.bake_changes(*index, map).is_empty()).then_some(())?; + Some((*index, map, self.bake_source(*index, map).ok()?, region.stroke)) + }) + .collect() + } + + /// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map + pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result { + let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?; + let Some(region) = self.painted_regions.get(&texture_set) else { return Ok(task) }; + let (width, height) = task.settings.common.output_size(); + let stored = + self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map)); + let Some(stored) = stored.filter(|_| task.tiles == (1, 1) && region_keeps_pixels(map)) else { return Ok(task) }; + + let texel = |uv: f32, size: u32, round: fn(f32) -> f32| (round(uv.clamp(0.0, 1.0) * size as f32) as u32).min(size); + let painted = TexelBox { + min: (texel(region.uv_min.x, width, f32::floor), texel(region.uv_min.y, height, f32::floor)), + max: (texel(region.uv_max.x, width, f32::ceil), texel(region.uv_max.y, height, f32::ceil)), + }; + task.previous_maps = stored.clone(); + task.region = Some(painted.grown(MARGIN_TEXELS, width, height)); + Ok(task) + } +} diff --git a/crates/engine/src/bake/streamed_bake.rs b/crates/engine/src/bake/streamed_bake.rs index 67d9be30..4b2895df 100644 --- a/crates/engine/src/bake/streamed_bake.rs +++ b/crates/engine/src/bake/streamed_bake.rs @@ -13,4 +13,6 @@ pub struct StreamedBake { pub tracer: String, /// What the baked maps were baked from (the task's [`crate::BakeTask::sources`]) pub sources: BTreeMap, + /// The task's [`crate::BakeTask::painted_stroke`] + pub painted_stroke: u64, } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 05a0c779..35922e64 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -427,6 +427,10 @@ pub struct Session { pub(crate) source: Arc, /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it pub(crate) low_poly_fingerprint: std::sync::OnceLock, + /// Where skew or cage painting changed each texture set since its auto-rebake map was baked + pub(crate) painted_regions: std::collections::BTreeMap, + /// Skew and cage strokes so far + pub(crate) painted_strokes: u64, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Arc>)>, @@ -530,6 +534,8 @@ impl Session { project_id: next_mesh_id(), source, low_poly_fingerprint: Default::default(), + painted_regions: Default::default(), + painted_strokes: 0, mesh, bvh: Arc::new(bvh), mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))), diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index c424ef47..e5f9978a 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -66,3 +66,76 @@ fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() { assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::>(), [BakedMap::Id], "the checks stay"); } + +#[test] +fn a_new_output_size_rebakes_every_checked_map_so_none_is_lost() { + let mut session = baked_plane(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "resolution": 128 })).unwrap(); + + let maps = session.auto_rebake_maps(0, BakedMap::Position); + let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let baked = session.baked(0).unwrap(); + assert!(baked.maps.contains_key(&BakedMap::Id), "the ID map survives the new size: {:?}", baked.maps.keys().collect::>()); + assert!(session.out_of_date_maps(0).is_empty(), "{:?}", session.out_of_date_maps(0)); +} + +#[test] +fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "nothing painted since the bake"); + let before = session.baked(0).unwrap().maps[&BakedMap::Position].clone(); + + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3], [0.4, 0.35]], "radius": 0.05, "size": 64 })).unwrap(); + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)]); + assert!(session.auto_rebake_due().is_empty(), "painting is not a settings change: {:?}", due_maps(&session)); + + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + let region = task.region.expect("a stroke rebakes only its box"); + let mut whole = session.bake_task_for(0, &[BakedMap::Position]).unwrap(); + whole.tracer = None; + let whole = whole.run(&Progress::new()).unwrap().maps.remove(&BakedMap::Position).unwrap(); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + + let width = output.resolution as usize; + assert!(((region.max.0 - region.min.0) as usize) < width / 2, "the box is far smaller than the map: {region:?}"); + let components = BakedMap::Position.components(); + let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components)); + let mut changed = 0; + for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() { + if region.contains(index % width, index / width) { + assert_eq!(rebaked, baked_whole, "texel {index} inside the box"); + changed += usize::from(rebaked != kept); + } else { + assert_eq!(rebaked, kept, "texel {index} outside the box"); + } + } + assert!(changed > 0, "the stroke changed the map inside its box"); + + session.apply_streamed_bake(0, output).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); +} + +#[test] +fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + let stroke = |at: f32| json!({ "points": [[at, at]], "radius": 0.05, "size": 64 }); + execute(&mut session, "bake.skew.paint", &stroke(0.3)).unwrap(); + + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + execute(&mut session, "bake.skew.paint", &stroke(0.7)).unwrap(); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); +} diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 4035c0f1..ef79a439 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -527,7 +527,7 @@ fn opacity_samples_textures_next_to_a_high_poly() { } /// A plane session whose vertex normals lean, with a high poly plane `dy` above it. -fn leaning_session(lean: bool) -> Session { +pub(super) fn leaning_session(lean: bool) -> Session { let mut mesh = primitives::builtin("plane").unwrap(); if lean { mesh.normals = vec![texturecraft_engine::geom::glam::Vec3::new(0.6, 0.8, 0.0); mesh.positions.len()]; diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 8f20e7b0..49221003 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -7,16 +7,16 @@ use crate::{BakeJob, TextureCraftApp, bake_report, state}; /// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts const SETTLE_SECONDS: f64 = 0.5; -/// An out-of-date auto-rebake map: its texture set, the map and what a bake would read now -pub type Due = (usize, BakedMap, BakeSource); +/// An out-of-date auto-rebake map: set, map, what a bake reads now, and the newest stroke when only painting changed it +pub type Due = (usize, BakedMap, BakeSource, Option); /// What the app has seen of the out-of-date auto-rebake maps #[derive(Default)] pub struct AutoRebake { /// The due maps and the frame time they were first seen as they are pending: Option<(Vec, f64)>, - /// The due maps when the last rebake started: a failed or canceled rebake is not tried again until something changes - started: Vec, + /// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes + tried: Vec, } /// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed @@ -26,16 +26,20 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - let due = app.session.auto_rebake_due(); + let stale = app.session.auto_rebake_due().into_iter().map(|(set, map, source)| (set, map, source, None)); + let painted = app.session.auto_rebake_painted().into_iter().map(|(set, map, source, stroke)| (set, map, source, Some(stroke))); + let due: Vec = stale.chain(painted).collect(); if let Some(job) = &app.bake { // Newest wins: a rebake whose map changed again while it ran starts over with the new settings - if job.rebake.is_some_and(|rebake| !due.contains(&rebake)) { + if job.rebake.as_ref().is_some_and(|rebake| !due.contains(rebake)) { app.cancel_bake(); } return; } - if due.is_empty() || due == app.auto_rebake.started { + app.auto_rebake.tried.retain(|tried| due.contains(tried)); + let waiting: Vec = due.into_iter().filter(|due| !app.auto_rebake.tried.contains(due)).collect(); + if waiting.is_empty() { app.auto_rebake.pending = None; return; } @@ -43,24 +47,24 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { let now = app.last_time; ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); match &app.auto_rebake.pending { - Some((seen, since)) if *seen == due && now - since >= SETTLE_SECONDS => {} - Some((seen, _)) if *seen == due => return, + Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} + Some((seen, _)) if *seen == waiting => return, _ => { - app.auto_rebake.pending = Some((due, now)); + app.auto_rebake.pending = Some((waiting, now)); return; } } app.auto_rebake.pending = None; - app.auto_rebake.started = due.clone(); - if let Some(rebake) = due.first().copied() { + if let Some(rebake) = waiting.first().copied() { + app.auto_rebake.tried.push(rebake); start(app, rebake); } } /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { - let (set, map, _) = rebake; + let (set, map) = (rebake.0, rebake.1); let orders = match app.session.bake_preview_orders(&[set], Some(map)) { Ok(orders) => orders, Err(error) => { @@ -73,7 +77,8 @@ fn start(app: &mut TextureCraftApp, rebake: Due) { app.live_preview.release(&mut app.session); crate::id_color_pick::IdColorPick::end(app); app.session.bake_preview_begin(orders); - app.session.begin_map_bake_log(&[set], map); + let maps = app.session.auto_rebake_maps(set, map); + app.session.begin_map_bake_log(&[set], &maps); app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2816c247..24373d2e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -712,7 +712,7 @@ impl TextureCraftApp { let total = sets.len(); match only { - Some(map) => self.session.begin_map_bake_log(&sets, map), + Some(map) => self.session.begin_map_bake_log(&sets, &[map]), None => self.session.begin_bake_log(&sets), } self.bake_report = bake_report::BakeReport::started(self.last_time); @@ -893,12 +893,14 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); - let (only, rebake) = (job.only, job.rebake); + let only = job.only; + let rebake = job.rebake.as_ref().map(|(_, map, _, stroke)| (*map, stroke.is_some())); self.session.bake_preview_set_current(set_index); self.session.bake_log.set_started(set_index); let task = match (rebake, only) { - (Some((_, map, _)), _) => self.session.bake_task_for(set_index, &[map]), + (Some((map, true)), _) => self.session.bake_painted_task(set_index, map), + (Some((map, false)), _) => self.session.bake_task_for(set_index, &self.session.auto_rebake_maps(set_index, map)), (None, Some(map)) => self.session.bake_task_only(set_index, map), (None, None) => self.session.bake_task(set_index), }; @@ -954,8 +956,7 @@ impl TextureCraftApp { } } - /// Cancel the active worker, discard queued sets and restore the view. The current set's - /// preview maps are discarded; previously applied sets keep their results and undo steps. + /// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 5358fcf1..af6062e2 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -85,3 +85,31 @@ fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); } + +#[test] +fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { + let mut harness = harness(64); + let plane = primitives::builtin("plane").unwrap(); + let mut high = String::from("o Part_high\n"); + for position in &plane.positions { + high += &format!("v {} {} {}\n", position.x, position.y + 0.1, position.z); + } + for triangle in plane.indices.as_chunks::<3>().0 { + high += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1); + } + let session = &mut harness.state_mut().session; + session.add_high_poly_bytes("high.obj", high.into_bytes()).unwrap(); + execute(session, "bake.run", &json!({ "maps": ["position"] })).unwrap(); + harness.run_steps(4); + assert!(harness.state().bake.is_none(), "up to date after the bake"); + + execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + + let app = harness.state(); + assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); + let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect(); + assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); + assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 308849f3..fa72d973 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -331,7 +331,10 @@ own). Imported maps, and maps saved before this record existed, never show: with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the background, alone, once its settings have stopped changing for half a second; a change during -that bake restarts it. The headless CLI does not rebake by itself: run `bake.run` there. +that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that +bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV +box, keeping the rest; maps scaled by their whole range (curvature, height, thickness) are baked +whole. The headless CLI does not rebake by itself: run `bake.run` there. `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) From f39e99069c5dd436251b0a4c08bf4b2c430b1613 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:05:31 +0000 Subject: [PATCH 097/190] Turn Auto-rebake on for the Normal map when skew painting starts The first skew stroke of a texture set turns Auto-rebake on for its Normal map, unless the set already has an auto-rebake map; it is part of the stroke's undo step. --- crates/engine/src/bake/mesh_map_command.rs | 7 ++-- crates/engine/src/bake/paint_command.rs | 32 +++++++++++++---- crates/engine/tests/it/auto_rebake.rs | 40 +++++++++++++++++++++- docs/control-protocol.md | 16 +++++---- 4 files changed, 78 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 49d25503..70b9fe7d 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -861,7 +861,9 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { let next = with_sync_partners(&session.doc.project, next, "bake.run")?; let cpu = boolp(params, "cpu") == Some(true); - let tracers = session.edit("Bake mesh maps", |session| { + // The painted boxes are not in the document, so a rolled-back bake puts them back by hand + let painted_regions = session.painted_regions.clone(); + let baked = session.edit("Bake mesh maps", |session| { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } @@ -882,7 +884,8 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { } } Ok(tracers) - })?; + }); + let tracers = baked.inspect_err(|_| session.painted_regions = painted_regions)?; for (index, tracer) in sets.iter().zip(&tracers) { session.log.info("Baker", format!("Baked texture set {index} ({tracer})")); } diff --git a/crates/engine/src/bake/paint_command.rs b/crates/engine/src/bake/paint_command.rs index 2f6c6fc0..840b097e 100644 --- a/crates/engine/src/bake/paint_command.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -3,7 +3,7 @@ use crate::{Result, Session, cmd}; use serde_json::Value; use std::sync::Arc; use texturecraft_bake::BakePaintMap; -use texturecraft_core::BakePaintTarget; +use texturecraft_core::{BakePaintTarget, BakedMap}; use texturecraft_geom::glam::Vec2; pub(super) fn specs() -> Vec { @@ -81,14 +81,22 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Ok(super::meshes_json(session)) } +/// Most UV points one `bake.paint` call takes +const MAX_POINTS: usize = 100_000; +/// Brush radius in UV units: the default, and the smallest that still paints +const DEFAULT_RADIUS: f32 = 0.03; +const MIN_RADIUS: f32 = 0.00001; +/// Side of a new paint map in texels: the default, and the range a call may ask for +const DEFAULT_PAINT_SIZE: u64 = 1024; +const PAINT_SIZES: std::ops::RangeInclusive = 16..=4096; + fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { - const MAX_POINTS: usize = 100_000; let texture_set = texture_set(session, parameters)?; let points = parameters .get("points") .and_then(Value::as_array) .filter(|points| !points.is_empty() && points.len() <= MAX_POINTS) - .ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?; + .ok_or_else(|| bad("bake.paint", format!("points must contain 1 to {MAX_POINTS} UV coordinates")))?; let points = points .iter() .map(|point| { @@ -99,17 +107,19 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } }) .collect::>>()?; + let value = number(parameters, "value", 1.0, 0.0, 1.0)?; - let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?; + let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?; let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?; let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; let size = match parameters.get("size") { - None => 1024, + None => DEFAULT_PAINT_SIZE, Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?, }; - if !(16..=4096).contains(&size) { - return Err(bad("bake.paint", "size must be between 16 and 4096")); + if !PAINT_SIZES.contains(&size) { + return Err(bad("bake.paint", format!("size must be between {} and {}", PAINT_SIZES.start(), PAINT_SIZES.end()))); } + let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0, @@ -118,7 +128,15 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> BakePaintTarget::Cage => "Paint Cage", BakePaintTarget::Skew => "Paint Skew Correction", }; + session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| { + // Skew painting starts with Auto-rebake on for the Normal map, which shows the skew best, unless the set picked one + let first_skew = target == BakePaintTarget::Skew && !session.doc.bake_paint.contains_key(&(texture_set, target)); + let set = session.doc.project.texture_set_mut(texture_set)?; + if first_skew && set.auto_rebake.is_none() { + set.auto_rebake = Some(BakedMap::Normal); + } + let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default))); if map.values.len() == 1 { *map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?); diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index e5f9978a..8dd1d80a 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -4,7 +4,7 @@ use serde_json::json; use texturecraft_engine::bake::Progress; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::{Session, execute, sample_session}; /// A plane with its position and ID maps baked fn baked_plane() -> Session { @@ -139,3 +139,41 @@ fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); } + +#[test] +fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 0, "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "ts": 0, "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + let second = &mut session.doc.project.texture_sets[1].bake.maps.ao; + second.is_enabled = true; + second.parameters.rays.rays = 0; + + assert!(execute(&mut session, "bake.run", &json!({ "ts": "all" })).is_err(), "set 1's AO has no rays to cast"); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "set 0's stroke is still waiting for its rebake"); +} + +#[test] +fn the_first_skew_stroke_turns_auto_rebake_on_for_the_normal_map_once() { + let mut session = super::bake::leaning_session(true); + let stroke = json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 }); + execute(&mut session, "bake.cage.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "cage painting leaves it alone"); + + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Normal)); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "undone with the stroke"); + + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position), "a map picked before stays"); + + execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "turned off after skew painting started, it stays off"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index fa72d973..8c74d39a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -305,6 +305,10 @@ also `session.inspect`'s `bakePreview`: "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} ``` +`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with +`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) +until `baking` is `null`. + `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. `highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, @@ -314,7 +318,7 @@ with no partner. It is `null` when no set of the bake matches by mesh name: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, - {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "texture set Head has no UV tiles selected for baking"}], "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}], "matching": {"lowSuffix": "_low", "highSuffix": "_high", "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} @@ -330,15 +334,13 @@ own). Imported maps, and maps saved before this record existed, never show: (the active one by default), replacing its previous one, or turns it off with `null`; it is saved with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the -background, alone, once its settings have stopped changing for half a second; a change during +background, alone (with every checked map when the output size changed), once what it is baked from has stopped changing for half a second; a change during that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV box, keeping the rest; maps scaled by their whole range (curvature, height, thickness) are baked -whole. The headless CLI does not rebake by itself: run `bake.run` there. - -`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with -`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) -until `baking` is `null`. +whole. The first `bake.skew.paint` stroke of a set (no skew map yet) turns Auto-rebake on for its +`normal` map when the set has none, in the stroke's undo step. The headless CLI does not rebake by +itself: run `bake.run` there. A minimal client (Python, for illustration): From 7f3b16d434552acd984d96b4c899254cd1cf939f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:32:34 +0000 Subject: [PATCH 098/190] Mark out-of-date maps in Mesh Map Bakers A baked map whose mesh, high poly, cage or settings changed after its bake gets a yellow clock at the right end of its row; hovering it lists what changed. The reasons are shared with the generator's bake note. --- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 52 ++++++++++++++----- .../ui-egui/src/generator_panel/bake_note.rs | 13 +---- crates/ui-egui/src/i18n.rs | 13 +++++ crates/ui-egui/tests/it/bake_mode.rs | 22 ++++++++ 4 files changed, 77 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 7ec44f70..d6a7d741 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,15 +1,15 @@ -use egui::{Align, CornerRadius, FontId, Layout, Pos2, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; +use egui::{Align, Align2, CornerRadius, FontId, Layout, Pos2, Rect, RichText, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::ViewMode; -use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use texturecraft_engine::core::{BakeChange, BakeSettings, BakeSyncGroup, BakedMap}; use super::glyph_look::GlyphLook; use super::set_picker::SetPicker; use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; use crate::docking::Panel; -use crate::i18n::{baked_map_label, tr, trf}; +use crate::i18n::{bake_change_reason, baked_map_label, tr, trf}; use crate::property_sheet::{CHECK_SIZE, paint_check}; use crate::theme::{Tokens, semibold}; @@ -46,6 +46,8 @@ const ROW_RADIUS: u8 = 4; const HOVER_FACE_OPACITY: f32 = 0.5; /// Air above and below the hairline under Check All const RULE_AIR: f32 = 4.0; +/// Size of a row icon's tooltip title and reasons +const TOOLTIP_TEXT_SIZE: f32 = 12.0; /// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { @@ -85,8 +87,10 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let drag_from_id = ui.scope_id().with("check_drag_from"); let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); + let out_of_date = app.session.out_of_date_maps(app.session.ts()); for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); + if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, changes, &mut check_drag, drag_from)).inner { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); } @@ -239,13 +243,14 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked +/// One baker row, with a clock at its right end while `changes` make the map out of date (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked fn row( app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, + changes: &[BakeChange], check_drag: &mut Option, drag_from: Option, ) -> bool { @@ -253,7 +258,7 @@ fn row( let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, name)); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_selected, name)); let hovered = ui.rect_contains_pointer(rect); if is_selected { @@ -280,18 +285,17 @@ fn row( thumbnail(ui, thumbnail_rect, texture.as_ref()); let mut icons_left = rect.right(); + if !changes.is_empty() { + let clock = icon_slot(&mut icons_left, rect.center().y); + out_of_date_mark(ui, clock, name, changes); + } let focus_in_row = || { ui.memory(|memory| memory.focused()) .and_then(|id| ui.ctx().read_response(id)) .is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center())) }; if is_selected || hovered || focus_in_row() { - let mut next_icon = || { - let slot = - Rect::from_center_size(pos2(icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); - icons_left = slot.left() - ROW_INSET / 2.0; - slot - }; + let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); if several_sets { let shares = settings.sync.shares(BakeSyncGroup::Map(map)); let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; @@ -430,3 +434,27 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); response } + +/// The yellow clock in `rect` of a map that `changes` made out of date since its bake; hover tells what changed +fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("out_of_date"), Sense::hover()); + let title = tr("Out of date"); + let label = trf("Out of date: {map}", &[("map", &name)]); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(ROW_GLYPH_SIZE), tokens.warning); + + response.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + for change in changes { + ui.label(RichText::new(tr(bake_change_reason(*change))).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + } + }); +} + +/// The next icon slot leftwards from `icons_left`, centred on `center_y`; moves `icons_left` past it +fn icon_slot(icons_left: &mut f32, center_y: f32) -> Rect { + let slot = Rect::from_center_size(pos2(*icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, center_y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + *icons_left = slot.left() - ROW_INSET / 2.0; + slot +} diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 4953261d..2e46ef22 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -7,7 +7,7 @@ use texturecraft_engine::bake::settings_patch; use texturecraft_engine::core::{BakeChange, BakedMap, Generator}; use crate::TextureCraftApp; -use crate::i18n::{baked_map_label, tr, trf}; +use crate::i18n::{bake_change_reason, baked_map_label, tr, trf}; use crate::property_sheet::{PropertySheet, SIDE_PADDING_POINTS}; use crate::theme::{Tokens, semibold}; @@ -82,16 +82,7 @@ fn reasons(changes: &[BakeChange], checked: bool) -> Vec<&'static str> { return reasons; } - changes - .iter() - .map(|change| match change { - BakeChange::LowPoly => tr("The mesh changed after this bake."), - BakeChange::HighPoly => tr("The high poly files changed after this bake."), - BakeChange::Cage => tr("The cage changed after this bake."), - BakeChange::Settings => tr("The common bake settings changed after this bake."), - BakeChange::MapSettings => tr("This map's bake settings changed after this bake."), - }) - .collect() + changes.iter().map(|change| tr(bake_change_reason(*change))).collect() } /// Bake `texture_set` in the background, turning `map` on in its bake settings first when it is off diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2210638e..0b94a4fe 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -96,6 +96,19 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta } } +/// Why a baked map is out of date: one sentence for what changed after its bake +pub(crate) fn bake_change_reason(change: texturecraft_engine::core::BakeChange) -> &'static str { + use texturecraft_engine::core::BakeChange; + + match change { + BakeChange::LowPoly => n_("The mesh changed after this bake."), + BakeChange::HighPoly => n_("The high poly files changed after this bake."), + BakeChange::Cage => n_("The cage changed after this bake."), + BakeChange::Settings => n_("The common bake settings changed after this bake."), + BakeChange::MapSettings => n_("This map's bake settings changed after this bake."), + } +} + /// The saved language that follows the operating system's (Settings > Language > Default (System Language)). pub const SYSTEM_LANGUAGE: &str = ""; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 720d4c49..ca4cede4 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -697,3 +697,25 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() { assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); } + +#[test] +fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { + use serde_json::json; + use texturecraft_engine::execute; + + let mesh = texturecraft_engine::geom::primitives::builtin("plane").unwrap(); + let mut session = texturecraft_engine::Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + assert!(harness.query_by_label("Out of date: Position").is_none(), "just baked"); + + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.run_steps(3); + harness.get_by_label("Out of date: Position"); + assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); +} From 23f27ba16d22d9dbeac2c20addadb83192ccb4c4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:35:55 +0000 Subject: [PATCH 099/190] Toggle Auto-rebake from a Mesh Map Bakers row Each row gets an Auto-rebake icon at its right end. It stays shown and bright on the set's auto-rebake map; on the other rows it shows dim while the row is hovered, and bright while the icon is hovered or has focus. Clicking it makes that map the set's auto-rebake map, or turns Auto-rebake off. --- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 104 +++++++++++++----- crates/ui-egui/src/bake_mode/mod.rs | 1 + crates/ui-egui/src/bake_mode/row_click.rs | 5 + crates/ui-egui/src/baking_log.rs | 15 ++- crates/ui-egui/tests/it/auto_rebake.rs | 77 +++++++++---- crates/ui-egui/tests/it/bake_mode.rs | 18 +++ crates/ui-egui/tests/it/baking_log.rs | 17 +-- .../ui-egui/tests/it/generator_bake_note.rs | 13 +-- crates/ui-egui/tests/it/main.rs | 17 +++ 9 files changed, 193 insertions(+), 74 deletions(-) create mode 100644 crates/ui-egui/src/bake_mode/row_click.rs diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index d6a7d741..afea363c 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,10 +1,11 @@ use egui::{Align, Align2, CornerRadius, FontId, Layout, Pos2, Rect, RichText, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; -use serde_json::json; +use serde_json::{Value, json}; use texturecraft_engine::ViewMode; use texturecraft_engine::core::{BakeChange, BakeSettings, BakeSyncGroup, BakedMap}; use super::glyph_look::GlyphLook; +use super::row_click::RowClick; use super::set_picker::SetPicker; use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; @@ -34,8 +35,13 @@ const ROW_INSET: f32 = 6.0; /// Side of a row's map thumbnail, and the air on its sides const THUMBNAIL_SIZE: f32 = 22.0; const THUMBNAIL_AIR: f32 = 9.0; -/// Side of a row's icon buttons and of the list menu button +/// Side of the header icon slots and of the list menu button const ROW_BUTTON_SIZE: f32 = 20.0; +/// Side of a row's hover icons, and the air right of each: four icons stay right of the row's middle in the Bakers column, so a click there selects the row +const ROW_ICON_SIZE: f32 = 18.0; +const ROW_ICON_GAP: f32 = 1.0; +/// Radius of the out-of-date clock on a thumbnail's corner +const CLOCK_BADGE_RADIUS: f32 = 6.0; /// Size of a row's glyphs const ROW_GLYPH_SIZE: f32 = 14.0; /// Size of the map names @@ -49,7 +55,7 @@ const RULE_AIR: f32 = 4.0; /// Size of a row icon's tooltip title and reasons const TOOLTIP_TEXT_SIZE: f32 = 12.0; -/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects) +/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects, a hover icon toggles Auto-rebake) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { let several_sets = app.session.doc.project.texture_sets.len() > 1; ui.add_space(HEADER_AIR); @@ -87,12 +93,18 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let drag_from_id = ui.scope_id().with("check_drag_from"); let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); - let out_of_date = app.session.out_of_date_maps(app.session.ts()); + let texture_set = app.session.ts(); for map in BakedMap::ALL { - let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, changes, &mut check_drag, drag_from)).inner { - app.ui.selected_baked_map = Some(map); - app.ui.dock.focus(Panel::MeshMapSettings); + match ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + Some(RowClick::Row) => { + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); + } + Some(RowClick::AutoRebake) => { + let map = if auto_rebake_map(app, texture_set) == Some(map) { Value::Null } else { json!(map.id()) }; + app.run("bake.autoRebake", json!({ "ts": texture_set, "map": map })); + } + None => {} } } @@ -243,17 +255,16 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row, with a clock at its right end while `changes` make the map out of date (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked +/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check fn row( app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, - changes: &[BakeChange], check_drag: &mut Option, drag_from: Option, -) -> bool { +) -> Option { let several_sets = app.session.doc.project.texture_sets.len() > 1; let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); @@ -284,27 +295,36 @@ fn row( let thumbnail_rect = Rect::from_min_size(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - THUMBNAIL_SIZE / 2.0), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); thumbnail(ui, thumbnail_rect, texture.as_ref()); - let mut icons_left = rect.right(); + let texture_set = app.session.ts(); + let changes = app.session.bake_changes(texture_set, map); if !changes.is_empty() { - let clock = icon_slot(&mut icons_left, rect.center().y); - out_of_date_mark(ui, clock, name, changes); + out_of_date_mark(ui, thumbnail_rect, name, &changes); } + + // From the right: sync (with several sets), Auto-rebake, bolt, eye; Auto-rebake alone stays while on let focus_in_row = || { ui.memory(|memory| memory.focused()) .and_then(|id| ui.ctx().read_response(id)) .is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center())) }; - if is_selected || hovered || focus_in_row() { - let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); - if several_sets { + let is_active = is_selected || hovered || focus_in_row(); + let is_auto_rebake = auto_rebake_map(app, texture_set) == Some(map); + let mut icons_left = rect.right(); + let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); + let sync_slot = several_sets.then(&mut next_icon); + let toggle = next_icon(); + let mut toggled = false; + if is_active { + if let Some(slot) = sync_slot { let shares = settings.sync.shares(BakeSyncGroup::Map(map)); let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; let glyph = if shares { icon::LINK } else { icon::LINK_BREAK }; - let sync = glyph_button(ui, next_icon(), glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); + let sync = glyph_button(ui, slot, glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); if sync.clicked() { SetPicker::open(app, &sync, SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); } } + toggled = auto_rebake_toggle(ui, toggle, name, is_auto_rebake).clicked(); let baking = app.bake_progress().is_some(); let bolt = next_icon(); let bolt_label = trf("Bake {map} Only", &[("map", &name)]); @@ -318,6 +338,10 @@ fn row( let mode = if shown { "material".to_owned() } else { format!("map:{}", map.id()) }; app.run("viewport.view", json!({ "mode": mode })); } + } else if is_auto_rebake { + toggled = auto_rebake_toggle(ui, toggle, name, true).clicked(); + } else { + icons_left = rect.right(); } let name_left = thumbnail_rect.right() + THUMBNAIL_AIR; @@ -360,7 +384,35 @@ fn row( response.request_focus(); } - response.clicked() + if toggled { + Some(RowClick::AutoRebake) + } else if response.clicked() { + Some(RowClick::Row) + } else { + None + } +} + +/// The map texture set `texture_set` rebakes on its own, if any +fn auto_rebake_map(app: &TextureCraftApp, texture_set: usize) -> Option { + app.session.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake) +} + +/// The Auto-rebake toggle in `rect`: bright while on or pointed at, dim while off +fn auto_rebake_toggle(ui: &mut Ui, rect: Rect, name: &str, is_on: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("auto_rebake"), Sense::click()); + let title = tr("Auto-rebake"); + let label = trf("Auto-rebake {map}", &[("map", &name)]); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_on, &label)); + + let is_pointed = response.hovered() || response.has_focus(); + let color = if is_on || is_pointed { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::ARROWS_CLOCKWISE, FontId::proportional(ROW_GLYPH_SIZE), color); + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + response.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + }) } /// Start a checkbox drag at a primary press on `checkbox`; returns whether the drag's pointer crossed this row's checkbox column (the whole row height counts) since `drag_from` @@ -435,14 +487,16 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { response } -/// The yellow clock in `rect` of a map that `changes` made out of date since its bake; hover tells what changed -fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) { +/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail tells what changed +fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeChange]) { let tokens = Tokens::get(ui.ctx()); - let response = ui.interact(rect, ui.scope_id().with("out_of_date"), Sense::hover()); + let response = ui.interact(thumbnail, ui.scope_id().with("out_of_date"), Sense::hover()); let title = tr("Out of date"); let label = trf("Out of date: {map}", &[("map", &name)]); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); - ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(ROW_GLYPH_SIZE), tokens.warning); + let badge = thumbnail.right_bottom() - vec2(CLOCK_BADGE_RADIUS, CLOCK_BADGE_RADIUS) * 0.5; + ui.painter().circle_filled(badge, CLOCK_BADGE_RADIUS, tokens.panel); + ui.painter().text(badge, Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(CLOCK_BADGE_RADIUS * 2.0), tokens.warning); response.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); @@ -454,7 +508,7 @@ fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) /// The next icon slot leftwards from `icons_left`, centred on `center_y`; moves `icons_left` past it fn icon_slot(icons_left: &mut f32, center_y: f32) -> Rect { - let slot = Rect::from_center_size(pos2(*icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, center_y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); - *icons_left = slot.left() - ROW_INSET / 2.0; + let slot = Rect::from_center_size(pos2(*icons_left - ROW_ICON_SIZE / 2.0 - ROW_ICON_GAP, center_y), vec2(ROW_ICON_SIZE, ROW_ICON_SIZE)); + *icons_left = slot.left(); slot } diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 1efb19d3..cf81d8d1 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -23,6 +23,7 @@ mod map_settings; mod map_thumbnails; mod mesh_map_bakers; pub use map_thumbnails::MapThumbnails; +mod row_click; mod set_picker; mod set_picker_purpose; mod set_picker_row; diff --git a/crates/ui-egui/src/bake_mode/row_click.rs b/crates/ui-egui/src/bake_mode/row_click.rs new file mode 100644 index 00000000..5f77dfd0 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/row_click.rs @@ -0,0 +1,5 @@ +/// What a click on a Mesh Map Bakers row hit +pub(super) enum RowClick { + Row, + AutoRebake, +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 1ee11974..e490ff85 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -124,7 +124,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// Show `map`'s settings of `texture_set` in Mesh Map Settings, as picking it in Mesh Map Bakers does fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { - // The set may have been deleted since the bake + // A guard against a row naming a set the session no longer has if texture_set >= app.session.set_count() { return; } @@ -226,16 +226,19 @@ fn no_issues(ui: &mut Ui, tab: BakingLogTab) { ui.allocate_rect(area, Sense::hover()); } -/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting's name in SemiBold +/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting and its value in SemiBold fn matching_not_enabled(ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let mut text = egui::text::LayoutJob::default(); let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() }; - // One sentence to translate, its setting kept apart to set it in SemiBold - let sentence = tr("{setting} was off for this bake."); - let (before, after) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + // One sentence to translate, its setting and value kept apart to set them in SemiBold + let sentence = tr("Set {setting} to {value} to pair parts by name."); + let (before, rest) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + let (between, after) = rest.split_once("{value}").unwrap_or((rest, "")); text.append(before, 0.0, format(FontId::proportional(NAME_SIZE))); - text.append(tr("Matching by name"), 0.0, format(semibold(NAME_SIZE))); + text.append(tr("Match"), 0.0, format(semibold(NAME_SIZE))); + text.append(between, 0.0, format(FontId::proportional(NAME_SIZE))); + text.append(tr("By Mesh Name"), 0.0, format(semibold(NAME_SIZE))); text.append(after, 0.0, format(FontId::proportional(NAME_SIZE))); let area = ui.available_rect_before_wrap(); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index af6062e2..027b3243 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -16,7 +16,10 @@ fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { execute(&mut session, "bake.run", &json!({ "resolution": resolution, "maps": ["position", "id"], "dilation": 0 })).unwrap(); execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness @@ -26,27 +29,14 @@ fn change_settings(harness: &mut Harness<'static, TextureCraftApp>, params: serd execute(&mut harness.state_mut().session, "bake.settings", ¶ms).unwrap(); } -/// Step frames until `done` holds, up to a generous limit -fn step_until(harness: &mut Harness<'static, TextureCraftApp>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) { - for _ in 0..4000 { - harness.run_steps(1); - if done(harness.state()) { - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("{what} did not happen"); -} - #[test] fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { let mut harness = harness(64); let id_before = harness.state().session.baked(0).unwrap().maps[&BakedMap::Id].clone(); change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); - step_until(&mut harness, "the rebake", |app| app.bake.is_some()); - step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); let app = harness.state(); assert!(app.session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", app.session.bake_changes(0, BakedMap::Position)); @@ -76,14 +66,36 @@ fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { // A slow rebake, so the next change lands while it runs change_settings(&mut harness, json!({ "resolution": 2048, "ao": { "rays": 256 } })); - step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); change_settings(&mut harness, json!({ "ao": { "rays": 128 } })); harness.run_steps(1); let app = harness.state(); assert!(app.bake.is_none(), "the outdated rebake stopped"); - assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); - execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + let ambient_occlusion = app.session.bake_log.maps.iter().find(|row| row.map == BakedMap::AmbientOcclusion).map(|row| row.state.clone()); + assert_eq!(ambient_occlusion, Some(BakeMapState::Canceled)); +} + +#[test] +fn a_canceled_rebake_holds_back_only_its_own_texture_set() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + for set in [0, 1] { + execute(&mut session, "bake.autoRebake", &json!({ "ts": set, "map": "position" })).unwrap(); + } + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let rebaking = |app: &TextureCraftApp, set: usize| app.bake.as_ref().and_then(|job| job.rebake.as_ref()).is_some_and(|rebake| rebake.0 == set); + + change_settings(&mut harness, json!({ "ts": "all", "positionMode": "boundingBox" })); + super::step_until(&mut harness, "the first set's rebake", |app| rebaking(app, 0)); + harness.state_mut().cancel_bake(); + + super::step_until(&mut harness, "the second set's rebake", |app| rebaking(app, 1)); } #[test] @@ -104,8 +116,8 @@ fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { assert!(harness.state().bake.is_none(), "up to date after the bake"); execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); - step_until(&mut harness, "the rebake", |app| app.bake.is_some()); - step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); let app = harness.state(); assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); @@ -113,3 +125,26 @@ fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); } + +#[test] +fn the_rows_icon_turns_auto_rebake_on_for_its_map_and_off_again() { + use egui_kittest::kittest::Queryable; + + let mut harness = harness(64); + let auto_rebake = |harness: &Harness<'static, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].auto_rebake; + assert_eq!(auto_rebake(&harness), Some(BakedMap::Position)); + + assert!(harness.query_by_label("Auto-rebake Normal").is_none(), "off: shown only on a hovered, focused or selected row"); + harness.get_by_role_and_label(egui::Role::Button, "Normal").hover(); + harness.run_steps(2); + harness.get_by_label("Auto-rebake Normal"); + + // ID is the selected row (the first checked map), which shows its icons + harness.get_by_label("Auto-rebake ID").click(); + harness.run_steps(2); + assert_eq!(auto_rebake(&harness), Some(BakedMap::Id), "one map per set: ID replaces Position"); + + harness.get_by_label("Auto-rebake ID").click(); + harness.run_steps(2); + assert_eq!(auto_rebake(&harness), None); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index ca4cede4..43096b28 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -698,6 +698,24 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() { assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); } +#[test] +fn a_click_on_the_middle_of_an_out_of_date_row_selects_its_map_and_bakes_nothing() { + use serde_json::json; + use texturecraft_engine::execute; + + // Two sets show every hover icon (sync, Auto-rebake, bolt, eye) and the changed settings add the out-of-date clock + let mut harness = harness(None); + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_label("Out of date: Ambient Occlusion"); + + select_map(&mut harness, "Ambient Occlusion"); + assert!(harness.state().bake_progress().is_none(), "the click landed on the row, not its Bake Only icon"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "selecting a map fronts its settings"); + harness.get_by_label("Attenuation"); +} + #[test] fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { use serde_json::json; diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 11251da2..133ac592 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -25,17 +25,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { harness } +/// Run frames until the bake ends, then a few more for its result to show fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { - for _ in 0..4000 { - harness.run_steps(1); - if harness.state().bake.is_none() { - harness.run_steps(2); - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("the bake did not finish"); + super::step_until(harness, "the end of the bake", |app| app.bake.is_none()); + harness.run_steps(super::SETTLE_FRAMES); } /// Bake sets 0 and 1, where set 1 has no tile left to bake, so its bake fails @@ -199,9 +192,9 @@ fn the_matching_tab_says_when_no_set_matched_by_name() { let mut harness = harness(); harness.get_by_label("Matching by Name").click(); harness.run_steps(3); - assert!(harness.query_by_label("Matching by name was off for this bake.").is_none(), "nothing baked yet: nothing to say"); + assert!(harness.query_by_label("Set Match to By Mesh Name to pair parts by name.").is_none(), "nothing baked yet: nothing to say"); log_a_bake(&mut harness, BakeMapState::Baked); - harness.get_by_label("Matching by name was off for this bake."); + harness.get_by_label("Set Match to By Mesh Name to pair parts by name."); } diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index d26019c7..aa049fdc 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -31,17 +31,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { harness } +/// Run frames until the bake ends, then a few more for its result to show fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { - for _ in 0..4000 { - harness.run_steps(1); - if harness.state().bake.is_none() { - harness.run_steps(2); - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("the bake did not finish"); + super::step_until(harness, "the end of the bake", |app| app.bake.is_none()); + harness.run_steps(super::SETTLE_FRAMES); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0aa4441d..bdb3c483 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -196,6 +196,23 @@ fn assert_list_leaves_the_wheel_and_closes(harness: &mut Harness<'_, TextureCraf assert!(!egui::Popup::is_any_open(&harness.ctx), "a click outside closes the list"); } +/// Most frames [`step_until`] waits, and its pause between them for background work +const STEP_UNTIL_FRAMES: usize = 4000; +const STEP_UNTIL_PAUSE: std::time::Duration = std::time::Duration::from_millis(2); + +/// Step frames until `done` holds, up to a generous limit +fn step_until(harness: &mut Harness<'_, TextureCraftApp>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) { + for _ in 0..STEP_UNTIL_FRAMES { + harness.run_steps(1); + if done(harness.state()) { + return; + } + + std::thread::sleep(STEP_UNTIL_PAUSE); + } + panic!("{what} did not happen"); +} + /// Presses and releases the primary button at `at` without moving, as a pointer click does fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { harness.hover_at(at); From ff513841646f362aebbd9db41e8a90b9aa35e1d7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:18:22 +0000 Subject: [PATCH 100/190] Keep a canceled bake's finished maps and name the rebaked map in the footer Cancelling a bake threw away the maps the running texture set had already finished, so the Baking Log turned their ticks into warnings. The set now keeps them as one undo step, also when the preview closed because Bake mode was left; only maps that had not finished warn, and a map it did not finish keeps its out-of-date mark. A bake at a new output size keeps none, since storing them would drop the set's other maps. An auto-rebake started its preview with every checked map of the set, so the progress footer named the set's first map ("Baking Normal (1/7)") while it rebaked AO. The preview now lists only the maps the rebake makes. --- crates/engine/src/bake/bake_log.rs | 6 +-- crates/engine/src/bake/canceled_bake.rs | 37 +++++++++++++++++ crates/engine/src/bake/mesh_map_command.rs | 2 +- crates/engine/src/bake/mod.rs | 1 + crates/engine/src/bake_preview.rs | 4 +- crates/engine/tests/bake_preview.rs | 4 +- crates/engine/tests/it/bake_log.rs | 31 ++++++++++++++ crates/ui-egui/src/auto_rebake.rs | 13 ++---- crates/ui-egui/src/lib.rs | 48 +++++++++++++++++----- crates/ui-egui/src/running_bake.rs | 5 +++ crates/ui-egui/tests/bake_preview.rs | 8 +++- crates/ui-egui/tests/it/auto_rebake.rs | 11 +++++ crates/ui-egui/tests/it/bake_job_mesh.rs | 14 ++++++- crates/ui-egui/tests/it/baking_log.rs | 30 ++++++++++++++ docs/control-protocol.md | 7 ++-- 15 files changed, 186 insertions(+), 35 deletions(-) create mode 100644 crates/engine/src/bake/canceled_bake.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 90e8feaf..2f7936c8 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -83,10 +83,10 @@ impl BakeLog { } } - /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled - pub fn cancel(&mut self, current: Option) { + /// The bake stopped: every map still waiting or baking is canceled, and so are the finished maps of `discarded` (the set being baked, when they were not kept) + pub fn cancel(&mut self, discarded: Option) { for row in &mut self.maps { - if row.state.is_pending() || (Some(row.texture_set) == current && row.state == BakeMapState::Baked) { + if row.state.is_pending() || (Some(row.texture_set) == discarded && row.state == BakeMapState::Baked) { row.state = BakeMapState::Canceled; } } diff --git a/crates/engine/src/bake/canceled_bake.rs b/crates/engine/src/bake/canceled_bake.rs new file mode 100644 index 00000000..ed9d8a98 --- /dev/null +++ b/crates/engine/src/bake/canceled_bake.rs @@ -0,0 +1,37 @@ +//! A canceled bake keeps the maps it finished: the Baking Log ticked them and the 3D view may have shown them + +use std::collections::BTreeMap; + +use texturecraft_compose::BakedMaps; +use texturecraft_core::{BakeSource, BakedMap}; + +use crate::{Result, Session}; + +impl Session { + /// Store the maps the canceled bake of `texture_set` `finished` as one undo step and return them; none at a new output size, which would drop the set's other maps + pub fn keep_canceled_bake( + &mut self, + texture_set: usize, + finished: BakedMaps, + sources: &BTreeMap, + painted_stroke: u64, + ) -> Result> { + let Some(height) = finished.maps.keys().next().map(|map| finished.height(*map)) else { return Ok(Vec::new()) }; + let resized = self.doc.baked.get(&texture_set).is_some_and(|stored| { + !stored.maps.is_empty() && (stored.resolution != finished.resolution || stored.maps.keys().any(|map| stored.height(*map) != height)) + }); + if resized { + return Ok(Vec::new()); + } + + // A map the bake did not finish keeps the record of what its stored pixels were baked from + let kept_sources: BTreeMap = + sources.iter().filter(|(map, _)| finished.maps.contains_key(*map)).map(|(map, source)| (*map, *source)).collect(); + let kept: Vec = finished.maps.keys().copied().collect(); + self.edit("Bake mesh maps", |session| { + session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke))) + })?; + self.log.info("Baker", format!("Kept {} baked maps of texture set {texture_set} from the canceled bake", kept.len())); + Ok(kept) + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 70b9fe7d..c4361180 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -291,7 +291,7 @@ impl Session { self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded) } - fn store_bake_maps( + pub(super) fn store_bake_maps( &mut self, texture_set: usize, resolution: u32, diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 8ee7bc98..6065034f 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -13,6 +13,7 @@ mod bake_mesh; mod bake_meshes; mod bake_sources; mod bake_task; +mod canceled_bake; mod high_poly_load; mod high_poly_missed; mod layout; diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index d8a03d8b..6835d13b 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -1,8 +1,8 @@ //! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon //! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in //! the document: nothing enters the undo history until a texture set's bake is applied -//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already -//! applied keep their results and undo steps. The preview shows one map at a time, raw on the +//! ([`Session::apply_streamed_bake`]). Cancellation keeps the maps the current set finished +//! ([`Session::keep_canceled_bake`], even when the preview closed); applied sets keep their results and undo steps. The preview shows one map at a time, raw on the //! model; maps and texture sets not baked yet show their neutral value. mod preview_set; diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs index d416e183..e4c6a031 100644 --- a/crates/engine/tests/bake_preview.rs +++ b/crates/engine/tests/bake_preview.rs @@ -1,5 +1,5 @@ //! Live bake preview: maps stream into the view while a bake runs, the view mode comes back, -//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it +//! painting is paused, ending the preview leaves the set it was baking alone (sets finished before it //! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the //! document share each map's buffer instead of holding two copies. @@ -215,7 +215,7 @@ fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { assert!(**data == full.maps[map], "{map:?}"); } - // What the app does on cancel: end the preview; the document keeps what it had + // Ending the preview alone leaves the document as it was; the app keeps finished maps through keep_canceled_bake session.bake_preview_end(); assert_eq!(session.doc.baked.get(&0).cloned(), before); diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 419ce6b4..d79d0430 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -4,6 +4,7 @@ use std::collections::BTreeSet; use serde_json::json; use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair}; +use texturecraft_engine::compose::BakedMaps; use texturecraft_engine::core::{BakedMap, MeshMatchMode}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -127,3 +128,33 @@ fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_ let log = execute(&mut session, "bake.log", &json!({})).unwrap(); assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); } + +#[test] +fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() { + let mut session = sample_session(256, 64).unwrap(); + let before = session.baked(0).cloned().unwrap(); + let resolution = before.resolution * 2; + let data = std::sync::Arc::new(vec![0.5; (resolution * resolution) as usize * BakedMap::Normal.components()]); + let finished = BakedMaps { resolution, maps: [(BakedMap::Normal, data)].into() }; + + let kept = session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap(); + + assert!(kept.is_empty(), "{kept:?}"); + assert_eq!(session.baked(0).map(|baked| baked.maps.keys().copied().collect::>()), Some(before.maps.keys().copied().collect())); + assert_eq!(session.baked(0).map(|baked| baked.resolution), Some(before.resolution)); +} + +#[test] +fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() { + let mut session = sample_session(256, 64).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["id", "position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + let task = session.bake_task_for(0, &[BakedMap::Id, BakedMap::Position]).unwrap(); + let stored = session.baked(0).cloned().unwrap(); + let finished = BakedMaps { resolution: stored.resolution, maps: [(BakedMap::Id, stored.maps[&BakedMap::Id].clone())].into() }; + + let kept = session.keep_canceled_bake(0, finished, &task.sources, task.painted_stroke).unwrap(); + + assert_eq!(kept, [BakedMap::Id]); + assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date"); +} diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 49221003..8d16ca41 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -65,20 +65,15 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { let (set, map) = (rebake.0, rebake.1); - let orders = match app.session.bake_preview_orders(&[set], Some(map)) { - Ok(orders) => orders, - Err(error) => { - app.toast(error.to_string(), true); - return; - } - }; // Restore the previous view before the rebake takes it over app.live_preview.release(&mut app.session); crate::id_color_pick::IdColorPick::end(app); - app.session.bake_preview_begin(orders); + + // The progress footer names the maps this rebake makes, not every checked map of the set let maps = app.session.auto_rebake_maps(set, map); + app.session.bake_preview_begin(vec![(set, maps.clone())]); app.session.begin_map_bake_log(&[set], &maps); app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; - app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); + app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: None, rebake: Some(rebake) }); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 24373d2e..cb772815 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -839,12 +839,14 @@ impl TextureCraftApp { } ctx.request_repaint_after(BAKE_POLL_INTERVAL); - if let Some(running) = &job.current { + if let Some(running) = &mut job.current { let set_index = running.set_index; // Wait for the sender to close so the last map also gets a preview frame match running.maps.try_recv() { Ok(map) => { + running.finished.resolution = map.resolution; + running.finished.maps.insert(map.map, map.data.clone()); self.session.bake_log.map_baked(set_index, map.map); self.session.bake_preview_map(set_index, map); return; @@ -868,16 +870,12 @@ impl TextureCraftApp { } Ok(Err(error)) => { // The worker's error ends the whole bake; the maps of the sets before it stay - self.bake_failed(set_index, &error.to_string()); - self.cancel_bake(); - self.finish_bake_report(); + self.end_failed_bake(set_index, &error.to_string()); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.bake_failed(set_index, i18n::tr("The bake worker stopped")); - self.cancel_bake(); - self.finish_bake_report(); + self.end_failed_bake(set_index, i18n::tr("The bake worker stopped")); return; } } @@ -910,6 +908,7 @@ impl TextureCraftApp { let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); + let (sources, painted_stroke) = (task.sources.clone(), task.painted_stroke); let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let worker_done = maps_done.clone(); let (sender, maps) = std::sync::mpsc::channel(); @@ -923,13 +922,25 @@ impl TextureCraftApp { }); if let Some(job) = self.bake.as_mut() { - job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); + job.current = + Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total, finished: Default::default(), sources, painted_stroke }); } } Err(error) => self.bake_failed(set_index, &error.to_string()), } } + /// End the bake at texture set `set_index`, whose worker failed: none of its maps are kept, the queued sets are canceled + fn end_failed_bake(&mut self, set_index: usize, error: &str) { + if let Some(job) = &mut self.bake { + job.current = None; + } + + self.bake_failed(set_index, error); + self.cancel_bake(); + self.finish_bake_report(); + } + /// Note a texture set whose bake failed: one Log line, counted in the summary fn bake_failed(&mut self, set_index: usize, error: &str) { self.session.log.error("Baker", format!("Bake of texture set {set_index} failed: {error}")); @@ -956,16 +967,31 @@ impl TextureCraftApp { } } - /// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps + /// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps, the running set keeps the maps it finished pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; - self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); + let mut discarded = None; if let Some(running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); + + // Maps baked for a mesh that has since been replaced are never kept + let same_mesh = job.mesh_id == self.session.mesh_id; + let kept = match same_mesh { + true => { + self.session.keep_canceled_bake(running.set_index, running.finished, &running.sources, running.painted_stroke).unwrap_or_else(|error| { + self.toast(error.to_string(), true); + Vec::new() + }) + } + false => Vec::new(), + }; + if kept.is_empty() { + discarded = Some(running.set_index); + } } - // Only the current set is uncommitted; completed sets remain applied + self.session.bake_log.cancel(discarded); self.session.bake_preview_end(); } diff --git a/crates/ui-egui/src/running_bake.rs b/crates/ui-egui/src/running_bake.rs index 512af28a..76427ad4 100644 --- a/crates/ui-egui/src/running_bake.rs +++ b/crates/ui-egui/src/running_bake.rs @@ -12,4 +12,9 @@ pub struct RunningBake { /// Maps finished so far, and how many the set makes. pub maps_done: Arc, pub maps_total: usize, + /// The maps received so far, kept when the bake is canceled even if the preview has closed + pub finished: texturecraft_engine::compose::BakedMaps, + /// What the task bakes from and the newest stroke it saw, recorded with the finished maps a cancel keeps + pub sources: std::collections::BTreeMap, + pub painted_stroke: u64, } diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 9bb1eae2..ce7be5e7 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -71,12 +71,13 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { } #[test] -fn cancelling_restores_the_view_and_leaves_the_document_alone() { +fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_alone() { let mut harness = harness(); let before = harness.state().session.doc.baked.get(&0).cloned(); + // One frame starts the worker; a finished map shows only from the next one harness.state_mut().start_bake(vec![0]); - harness.run_steps(2); + harness.run_steps(1); assert!(harness.state().session.bake_preview_active()); let (at, viewport) = (texturecraft_engine::geom::glam::Vec2::new(5.0, 5.0), texturecraft_engine::geom::glam::Vec2::new(100.0, 100.0)); @@ -142,6 +143,9 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { maps, maps_done: Arc::new(AtomicUsize::new(MAPS.len())), maps_total: MAPS.len(), + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, }), }); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 027b3243..4e74f0be 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -46,6 +46,17 @@ fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); } +#[test] +fn the_progress_footer_names_the_map_the_rebake_makes() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + + let stage = harness.state().session.bake_preview.as_ref().and_then(|preview| preview.stage()); + assert_eq!(stage.map(|stage| (stage.map, stage.total)), Some((BakedMap::Position, 1)), "not the set's first checked map, not all its maps"); +} + #[test] fn nothing_is_rebaked_outside_bake_mode() { let mut harness = harness(64); diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index f805bfc9..c3292beb 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -20,8 +20,18 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes let (_result_sender, receiver) = std::sync::mpsc::channel(); let (_map_sender, maps) = std::sync::mpsc::channel(); let job_mesh_id = mesh_id(harness.state().session.mesh_id); - let running = - RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; + let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let running = RunningBake { + set_index: 0, + progress: progress.clone(), + receiver, + maps, + maps_done, + maps_total: 1, + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, + }; harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); harness.step(); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 133ac592..29099a64 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -68,6 +68,36 @@ fn a_one_map_bake_lists_only_that_map() { assert!(harness.query_by_label_contains(&format!("{name} ID")).is_none(), "a checked map the bake left alone has no row"); } +#[test] +fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() { + let mut harness = harness(); + let before = harness.state().session.baked(0).cloned().unwrap_or_default(); + harness.state_mut().start_bake(vec![0, 1]); + + // Leaving Bake mode closes the preview; the bake and the maps it finishes go on + harness.state_mut().ui.mode = Mode::Painting; + let state = |app: &TextureCraftApp, set: usize, map: BakedMap| { + app.session.bake_log.maps.iter().find(|row| row.texture_set == set && row.map == map).map(|row| row.state.clone()) + }; + super::step_until(&mut harness, "set 0's first map", |app| state(app, 0, BakedMap::Id) == Some(BakeMapState::Baked)); + assert!(!harness.state().session.bake_preview_active()); + + harness.state_mut().cancel_bake(); + + let app = harness.state(); + assert_eq!(state(app, 0, BakedMap::Id), Some(BakeMapState::Baked), "a ticked map keeps its tick"); + for (set, map) in [(0, BakedMap::Position), (1, BakedMap::Id), (1, BakedMap::Position)] { + assert_eq!(state(app, set, map), Some(BakeMapState::Canceled), "set {set}'s unfinished {map:?} warns"); + } + let after = app.session.baked(0).cloned().unwrap_or_default(); + let changed = |map: BakedMap| match (before.maps.get(&map), after.maps.get(&map)) { + (Some(old), Some(new)) => !std::sync::Arc::ptr_eq(old, new), + (old, new) => old.is_some() != new.is_some(), + }; + assert!(changed(BakedMap::Id), "the ticked map is in the document"); + assert!(!changed(BakedMap::Position), "the unfinished map stays as it was"); +} + #[test] fn a_failed_maps_arrow_opens_its_settings() { let mut harness = harness(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8c74d39a..b68a5c77 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -242,7 +242,7 @@ keeps its state in a throwaway file. | `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before | | `ui.reset` | | resets the panels, view settings and interface language without asking for confirmation. Other preferences and shortcuts stay | | `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running | -| `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it had, sets already finished stay applied, and the previous view mode comes back | +| `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it finished (one undo step), sets already finished stay applied, and the previous view mode comes back | | `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log`, `BakingLog`, `MeshMapBakers`, `BakeMaps`, `BakeSettings`, `Export` and `Renderer` (a floating window holding one right-bar panel is that panel undocked); `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | @@ -285,8 +285,9 @@ bake of its own, so with a high poly the transfer rays are cast once per map; th same as a single bake's. `bake.run` and the CLI bake all maps at once and never show a preview. The streamed maps are held by the session, not the document: nothing enters the undo history -until a texture set's bake is applied (one undo step); a cancelled bake leaves the set it was baking -as it was, while sets that finished before the cancel stay applied. When +until a texture set's bake is applied (one undo step); a cancelled bake applies the maps the set it was +baking had finished (one undo step; none when the bake had a new output size, since they would replace +the set's other maps), while sets that finished before the cancel stay applied. When the bake ends, is cancelled or Bake mode is left, the view mode that was in use comes back. Bake setup overlays are hidden during the preview so they cannot cover the maps; their visibility settings take effect again when the preview ends. From cb8a46deb7037525de9340c81d5ca1b9f313ce54 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:40:27 +0000 Subject: [PATCH 101/190] Name the set in a canceled bake's log line, make a bake setting drag one undo step and hold Auto-rebake while it is held A drag stays one undo step while a panel is open in its own floating window: the press is kept in egui memory, not in a frame cache that the floating window's own pass clears every frame. --- crates/engine/src/bake/canceled_bake.rs | 4 +++- crates/engine/tests/it/bake_log.rs | 14 ++++++++++++ crates/ui-egui/src/auto_rebake.rs | 6 ++++++ crates/ui-egui/src/bake_mode/mod.rs | 8 +++---- crates/ui-egui/src/property_sheet/tests.rs | 22 +++++++++++++++++++ crates/ui-egui/src/widgets.rs | 20 +++++++++++------ crates/ui-egui/tests/it/auto_rebake.rs | 15 +++++++++++++ crates/ui-egui/tests/it/bake_mode.rs | 25 ++++++++++++++++++++++ 8 files changed, 103 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/bake/canceled_bake.rs b/crates/engine/src/bake/canceled_bake.rs index ed9d8a98..08cc2bf9 100644 --- a/crates/engine/src/bake/canceled_bake.rs +++ b/crates/engine/src/bake/canceled_bake.rs @@ -31,7 +31,9 @@ impl Session { self.edit("Bake mesh maps", |session| { session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke))) })?; - self.log.info("Baker", format!("Kept {} baked maps of texture set {texture_set} from the canceled bake", kept.len())); + // Named like the Texture Set List and the progress footer, which count sets from 1 + let name = self.doc.project.texture_sets.get(texture_set).map_or_else(|| format!("{}", texture_set + 1), |set| set.name.clone()); + self.log.info("Baker", format!("Kept {} baked maps of texture set {name} from the canceled bake", kept.len())); Ok(kept) } } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index d79d0430..ee26594a 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -158,3 +158,17 @@ fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() { assert_eq!(kept, [BakedMap::Id]); assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date"); } + +#[test] +fn a_canceled_bakes_log_line_names_the_set_as_the_texture_set_list_does() { + let mut session = sample_session(256, 64).unwrap(); + let stored = session.baked(0).cloned().unwrap(); + let (map, data) = stored.maps.iter().next().map(|(map, data)| (*map, data.clone())).unwrap(); + let finished = BakedMaps { resolution: stored.resolution, maps: [(map, data)].into() }; + + session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap(); + + let name = session.doc.project.texture_sets[0].name.clone(); + let line = session.log.iter().find(|line| line.contains("canceled bake")).map(|line| line.message.clone()).unwrap(); + assert!(line.contains(&format!("texture set {name} ")), "the first set is not numbered 0: {line}"); +} diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 8d16ca41..a18ffae0 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -46,6 +46,12 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { let now = app.last_time; ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); + + // A held press (a slider dragged and paused) is still editing: the wait starts once it is let go + if ctx.input(|input| input.pointer.any_down()) { + app.auto_rebake.pending = Some((waiting, now)); + return; + } match &app.auto_rebake.pending { Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} Some((seen, _)) if *seen == waiting => return, diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index cf81d8d1..07a5c544 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -231,15 +231,15 @@ fn edit_settings( let mut settings = before.clone(); let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner; - if settings == before && reset.is_none() { - return false; - } + + // One drag is one undo step: a press's later changes continue its first one + let Some(merge) = crate::widgets::press_edit(ui, ui.make_persistent_id((scroll_id, "press")), settings != before || reset.is_some()) else { return false }; let mut patch = settings_patch(&before, &settings); if let (Some(fields), Some(Value::Object(reset))) = (patch.as_object_mut(), reset) { fields.extend(reset); } - app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); + app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch, "merge": merge })); true } diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 10c7ecfd..d7d45b32 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1042,6 +1042,28 @@ fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { assert_eq!(edit(Some(owner), true), Some(false), "a separate press starts an undo step after reopening"); } +/// A floating panel in its own OS window runs a pass of its own between two frames of the main window: the drag stays one undo step +#[test] +fn a_drag_stays_one_undo_step_while_another_window_draws() { + let context = egui::Context::default(); + let owner = egui::Id::unique("held editor"); + let edit = |events| { + let mut result = None; + let mut output = context.run_ui(egui::RawInput { events, ..Default::default() }, |ui| result = crate::widgets::press_edit(ui, owner, true)); + output.textures_delta.clear(); + result + }; + let press = egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + + assert_eq!(edit(vec![press]), Some(false), "the press starts an undo step"); + let viewport = egui::ViewportId::from_hash_of("floating History"); + let floating = + egui::RawInput { viewport_id: viewport, viewports: std::iter::once((viewport, egui::ViewportInfo::default())).collect(), ..Default::default() }; + context.run_ui(floating, |_| {}).textures_delta.clear(); + + assert_eq!(edit(Vec::new()), Some(true), "the held press continues its undo step"); +} + #[test] fn section_tabs_show_focus_before_a_keyboard_jump() { let mut harness = builder(Brightness::MediumDark).build_ui(|ui| { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 991585dc..b09f71d2 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -31,26 +31,34 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { return None; } - ui.memory_mut(|memory| { - let edits = memory.caches.cache::>(); + // Kept in memory, not a frame cache: a floating panel in its own OS window ends a pass of its own inside ours, which would clear it every frame + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|data| { let id = id.with("pointer edit"); - let previous = edits.get(&id).copied(); + let previous = data.get_temp::(id); let merge = match press { Some(start) => { - let continuing = previous == Some(start); + let continuing = previous.is_some_and(|previous| previous.press == start); if changed || continuing { - edits.set(id, start); + data.insert_temp(id, PressEdit { press: start, frame }); } continuing } // A final movement still belongs to the press that ended - None => release_only && previous.is_some(), + None => release_only && previous.is_some_and(|previous| previous.frame + 1 >= frame), }; changed.then_some(merge) }) } +/// The press an editor's last change belonged to, and the frame it was seen in +#[derive(Clone, Copy)] +struct PressEdit { + press: u64, + frame: u64, +} + /// [`slider`] for a value re-read from the document every frame: `Some(merge)` on every frame /// that changes `value` (live while dragging, a click on the track, a typed value). `merge` is /// true for the later changes of one drag, so the edit that applies them (with the command's diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 4e74f0be..faf87c78 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -159,3 +159,18 @@ fn the_rows_icon_turns_auto_rebake_on_for_its_map_and_off_again() { harness.run_steps(2); assert_eq!(auto_rebake(&harness), None); } + +#[test] +fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_step() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + // Held still well past the settle time, as a hand pausing mid-drag + let corner = egui::pos2(1590.0, 990.0); + harness.drag_at(corner); + harness.run_steps(120); + assert!(harness.state().bake.is_none(), "the edit is not over while the press lasts"); + + harness.drop_at(corner); + super::step_until(&mut harness, "the rebake after the release", |app| app.bake.is_some()); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 43096b28..972dc919 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -737,3 +737,28 @@ fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { harness.get_by_label("Out of date: Position"); assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); } + +#[test] +fn dragging_secondary_rays_is_one_undo_step() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + select_map(&mut harness, "Ambient Occlusion"); + let rays_before = harness.state().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays; + let history_steps = harness.state().session.history_labels().len(); + + let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect(); + let at = |share: f32| egui::pos2(track.left() + track.width() * share, track.center().y); + harness.drag_at(at(0.2)); + harness.run_steps(crate::DRAG_STEP_FRAMES); + for step in 1..=3 { + harness.hover_at(at(0.2 + 0.15 * step as f32)); + harness.run_steps(crate::DRAG_STEP_FRAMES); + } + + // The release moves too, and that last change still belongs to the drag + harness.drop_at(at(0.8)); + harness.run_steps(crate::SETTLE_FRAMES); + + let session = &harness.state().session; + assert_ne!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays, rays_before, "the drag changed the rays"); + assert_eq!(session.history_labels().len(), history_steps + 1, "{:?}", session.history_labels()); +} From de7515bf1a2b1b199e9432c919330cc1f8336bcd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:54:13 +0000 Subject: [PATCH 102/190] Keep a stroke's box and the stroke count through undo and reimport, and give the bake rows' reasons to screen readers The painted box of an auto-rebake map now lives in the document, so undoing the rebake of a stroke makes the map due again (the stroke stays painted while the map goes back to its pixels from before it), and a rolled-back bake.run needs no hand-kept copy. A mesh reimport carries the stroke count on; before, a bake after a reimport saw every earlier stroke as newer and kept its box. The Baking Log rows, the out-of-date clock and the generator's bake note put their reasons in the accessibility tree, not only in a tooltip, and a folding high poly row exposes whether it is expanded. bake.log is kept off the shortcut list. PressEdit gets its own file, region_keeps_pixels moves beside RegionBake, and auto_rebake_due computes each map's source once. --- crates/bake/src/lib.rs | 4 +- crates/bake/src/region_bake.rs | 5 +++ crates/bake/src/texel_box.rs | 6 --- crates/engine/src/bake/auto_rebake.rs | 11 ++++-- crates/engine/src/bake/mesh_map_command.rs | 17 ++++----- crates/engine/src/bake/mod.rs | 1 - crates/engine/src/bake/paint_command.rs | 4 +- crates/engine/src/bake/painted_region.rs | 12 +++--- crates/engine/src/bake_preview.rs | 4 +- crates/engine/src/commands.rs | 16 +++++++- crates/engine/src/file_cmds.rs | 3 ++ crates/engine/src/inspect.rs | 4 +- crates/engine/src/material_lib.rs | 2 + crates/engine/src/meshmap_cmds.rs | 24 ++++++------ crates/engine/src/session.rs | 6 +-- crates/engine/src/smart_masks.rs | 1 + crates/engine/tests/it/auto_rebake.rs | 38 ++++++++++++++++++- crates/ui-egui/src/auto_rebake.rs | 2 +- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 8 ++-- crates/ui-egui/src/baking_log.rs | 18 ++++++--- .../ui-egui/src/baking_log/high_poly_list.rs | 12 +++--- .../ui-egui/src/baking_log/matching_list.rs | 11 +++--- .../ui-egui/src/generator_panel/bake_note.rs | 7 +++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/press_edit.rs | 8 ++++ crates/ui-egui/src/widgets.rs | 8 +--- crates/ui-egui/tests/it/auto_rebake.rs | 4 +- crates/ui-egui/tests/it/bake_mode.rs | 3 +- crates/ui-egui/tests/it/baking_log.rs | 21 +++++++++- .../ui-egui/tests/it/generator_bake_note.rs | 5 ++- docs/control-protocol.md | 4 +- 31 files changed, 182 insertions(+), 88 deletions(-) create mode 100644 crates/ui-egui/src/press_edit.rs diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 50f2f54c..73847b5b 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -24,8 +24,8 @@ pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; pub use name_pair::NamePair; pub use progress::Progress; -pub use region_bake::RegionBake; -pub use texel_box::{TexelBox, region_keeps_pixels}; +pub use region_bake::{RegionBake, region_keeps_pixels}; +pub use texel_box::TexelBox; mod map; mod skew; diff --git a/crates/bake/src/region_bake.rs b/crates/bake/src/region_bake.rs index 20a14849..224202f3 100644 --- a/crates/bake/src/region_bake.rs +++ b/crates/bake/src/region_bake.rs @@ -10,3 +10,8 @@ pub struct RegionBake<'a> { pub texels: TexelBox, pub previous: &'a BTreeMap>>, } + +/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours +pub fn region_keeps_pixels(map: BakedMap) -> bool { + !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) +} diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs index 85be4fc0..3dc062cf 100644 --- a/crates/bake/src/texel_box.rs +++ b/crates/bake/src/texel_box.rs @@ -19,9 +19,3 @@ impl TexelBox { } } } - -/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours -pub fn region_keeps_pixels(map: texturecraft_core::BakedMap) -> bool { - use texturecraft_core::BakedMap; - !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) -} diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index e1e3cb1f..3f50f672 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -43,10 +43,13 @@ impl Session { /// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now) pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> { let sets = self.doc.project.texture_sets.iter().enumerate(); - sets.filter_map(|(index, set)| Some((index, set.auto_rebake?))) - .filter(|(index, map)| !self.bake_changes(*index, *map).is_empty()) - .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) - .collect() + sets.filter_map(|(index, set)| { + let map = set.auto_rebake?; + let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?; + let current = self.bake_source(index, map).ok()?; + (!record.changes(¤t).is_empty()).then_some((index, map, current)) + }) + .collect() } /// The maps an auto-rebake of `map` bakes: that map alone, or with every checked map once the output size changed (storing a new size drops the old maps) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index c4361180..da66bdc2 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -311,17 +311,17 @@ impl Session { self.record_bake_sources(texture_set, recorded, &stored) } - /// 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 { - let mut task = self.bake_task(ts)?; + /// Bake texture set `texture_set` now (blocking), on the CPU when `cpu`; returns where the rays ran + pub fn bake_now(&mut self, texture_set: usize, cpu: bool) -> Result { + let mut task = self.bake_task(texture_set)?; if cpu { task.tracer = None; } let output = task.run(&Progress::new())?; let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(ts, output, Some((&task.sources, task.painted_stroke))))?; - self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, Some((&task.sources, task.painted_stroke))))?; + self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(tracer) } @@ -861,9 +861,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { let next = with_sync_partners(&session.doc.project, next, "bake.run")?; let cpu = boolp(params, "cpu") == Some(true); - // The painted boxes are not in the document, so a rolled-back bake puts them back by hand - let painted_regions = session.painted_regions.clone(); - let baked = session.edit("Bake mesh maps", |session| { + let tracers = session.edit("Bake mesh maps", |session| { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } @@ -884,8 +882,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { } } Ok(tracers) - }); - let tracers = baked.inspect_err(|_| session.painted_regions = painted_regions)?; + })?; for (index, tracer) in sets.iter().zip(&tracers) { session.log.info("Baker", format!("Baked texture set {index} ({tracer})")); } diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 6065034f..54fa0faf 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -46,7 +46,6 @@ pub use model_patch::settings_patch; pub use painted_region::PaintedRegion; pub use streamed_bake::StreamedBake; pub use streamed_map::StreamedMap; -pub use texturecraft_bake::NamePair; pub use texturecraft_bake::*; use crate::CommandSpec; diff --git a/crates/engine/src/bake/paint_command.rs b/crates/engine/src/bake/paint_command.rs index 840b097e..f8edd524 100644 --- a/crates/engine/src/bake/paint_command.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -86,6 +86,8 @@ const MAX_POINTS: usize = 100_000; /// Brush radius in UV units: the default, and the smallest that still paints const DEFAULT_RADIUS: f32 = 0.03; const MIN_RADIUS: f32 = 0.00001; +/// Brush hardness when a call gives none: halfway between a soft and a hard edge +const DEFAULT_HARDNESS: f32 = 0.5; /// Side of a new paint map in texels: the default, and the range a call may ask for const DEFAULT_PAINT_SIZE: u64 = 1024; const PAINT_SIZES: std::ops::RangeInclusive = 16..=4096; @@ -110,7 +112,7 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> let value = number(parameters, "value", 1.0, 0.0, 1.0)?; let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?; - let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?; + let hardness = number(parameters, "hardness", DEFAULT_HARDNESS, 0.0, 1.0)?; let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; let size = match parameters.get("size") { None => DEFAULT_PAINT_SIZE, diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs index 4c31b533..c19db7a3 100644 --- a/crates/engine/src/bake/painted_region.rs +++ b/crates/engine/src/bake/painted_region.rs @@ -22,26 +22,26 @@ impl Session { /// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`) pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) { let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE)); - let (uv_min, uv_max) = match self.painted_regions.get(&texture_set) { + let (uv_min, uv_max) = match self.doc.painted_regions.get(&texture_set) { Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)), None => (uv_min, uv_max), }; self.painted_strokes += 1; - self.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); + self.doc.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); } /// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke` pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) { let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake); - let painted_since = self.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); + let painted_since = self.doc.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); if !painted_since && auto.is_none_or(|map| stored.contains(&map)) { - self.painted_regions.remove(&texture_set); + self.doc.painted_regions.remove(&texture_set); } } /// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke) pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> { - let regions = self.painted_regions.iter(); + let regions = self.doc.painted_regions.iter(); regions .filter_map(|(index, region)| { let set = self.doc.project.texture_sets.get(*index)?; @@ -56,7 +56,7 @@ impl Session { /// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result { let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?; - let Some(region) = self.painted_regions.get(&texture_set) else { return Ok(task) }; + let Some(region) = self.doc.painted_regions.get(&texture_set) else { return Ok(task) }; let (width, height) = task.settings.common.output_size(); let stored = self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map)); diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index 6835d13b..b0a3eac8 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -1,8 +1,8 @@ //! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon //! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in //! the document: nothing enters the undo history until a texture set's bake is applied -//! ([`Session::apply_streamed_bake`]). Cancellation keeps the maps the current set finished -//! ([`Session::keep_canceled_bake`], even when the preview closed); applied sets keep their results and undo steps. The preview shows one map at a time, raw on the +//! ([`Session::apply_streamed_bake`]). Cancellation keeps the maps the current set finished; sets +//! already applied keep their results and undo steps. The preview shows one map at a time, raw on the //! model; maps and texture sets not baked yet show their neutral value. mod preview_set; diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 41e7d619..0fb3959d 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -31,7 +31,7 @@ impl CommandSpec { /// that only return data or do nothing without parameters, and the ones that replace the /// open project (the menu asks to save first). pub fn bindable(&self) -> bool { - const NOT_FROM_A_KEY: [&str; 13] = [ + const NOT_FROM_A_KEY: [&str; 14] = [ "project.inspect", "project.templates", "project.new", @@ -43,6 +43,7 @@ impl CommandSpec { "textureSet.parts", "bake.settings", "bake.preview", + "bake.log", "camera.set", "textureSet.settings", ]; @@ -372,7 +373,18 @@ mod tests { ] { assert!(!bindable(id), "{id} needs a parameter"); } - for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] { + for id in [ + "layer.move", + "layer.list", + "project.inspect", + "edit.history", + "export.presets", + "tool.state", + "project.new", + "camera.set", + "layer.blend", + "bake.log", + ] { assert!(!bindable(id), "{id} is a query or has several forms"); } } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 5cfc235b..e5f0df92 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -289,6 +289,7 @@ impl Session { pixels: project_file.pixels, baked: project_file.baked, resources, + painted_regions: Default::default(), }, mesh, project_file.mesh, @@ -740,6 +741,8 @@ impl Session { next.modified = true; next.project_id = self.project_id; + // The painted boxes moved with the document, and a bake tells a newer stroke by this count + next.painted_strokes = self.painted_strokes; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); // Keep the stored source in the current session until reimport succeeds diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 04af908b..b914b4e7 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -264,6 +264,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value { }) }) .collect(); + let out_of_date: std::collections::BTreeMap<_, Vec<_>> = + session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect())).collect(); json!({ "index": index, "name": texture_set.name, @@ -276,7 +278,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), - "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), + "outOfDate": out_of_date, "autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id), "visible": texture_set.visible, "active": index == session.ts(), diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 758ee3b6..da5b3ea6 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -77,6 +77,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), } } @@ -145,6 +146,7 @@ impl Session { project: project_file.project, pixels: project_file.pixels, baked: BTreeMap::new(), + painted_regions: Default::default(), resources, }; diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 5736c5ca..55b110e0 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -53,14 +53,14 @@ fn set(s: &mut Session, p: &Value) -> Result { pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width -pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { - let texture_set = session.doc.project.texture_set(ts)?; - let grid = texture_set.tile_grid(); - if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { +pub(crate) fn use_images(session: &mut Session, command: &str, texture_set: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let set = session.doc.project.texture_set(texture_set)?; + let grid = set.tile_grid(); + if let Some(tile) = set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { return Err(bad(command, format!("no image for UV tile {tile}"))); } - let (width, height) = image_map_size(session, command, ts)?; + let (width, height) = image_map_size(session, command, texture_set)?; // Bent normals are tangent-space maps like the normal map, so both follow the project's normal format let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX; @@ -74,11 +74,11 @@ pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: B }), }; - let entry = session.doc.baked.entry(ts).or_default(); + let entry = session.doc.baked.entry(texture_set).or_default(); entry.resolution = width; entry.maps.insert(map, Arc::new(data)); // An imported map is never out of date: nothing records what it was made from - let set = session.doc.project.texture_set_mut(ts)?; + let set = session.doc.project.texture_set_mut(texture_set)?; set.baked.insert(map); set.bake_sources.remove(&map); Ok(width) @@ -158,16 +158,16 @@ fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn( fn clear(session: &mut Session, params: &Value) -> Result { const COMMAND: &str = "textureSet.meshMap.clear"; - let ts = ts_param(session, params, COMMAND)?; + let texture_set = ts_param(session, params, COMMAND)?; let map = map_param(params, COMMAND)?; - if !session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) { - return Err(bad(COMMAND, format!("texture set {ts} has no {} map", map.id()))); + if !session.doc.baked.get(&texture_set).is_some_and(|baked| baked.maps.contains_key(&map)) { + return Err(bad(COMMAND, format!("texture set {texture_set} has no {} map", map.id()))); } session.edit("Clear mesh map", |session| { - if let Some(baked) = session.doc.baked.get_mut(&ts) { + if let Some(baked) = session.doc.baked.get_mut(&texture_set) { baked.maps.remove(&map); } - let set = session.doc.project.texture_set_mut(ts)?; + let set = session.doc.project.texture_set_mut(texture_set)?; set.baked.remove(&map); set.bake_sources.remove(&map); Ok(()) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 35922e64..670b0cfb 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -33,6 +33,8 @@ pub struct Document { pub resources: BTreeMap>>, /// High-definition meshes and cage for baking (saved inside the project) pub bake_meshes: crate::BakeMeshes, + /// Where skew or cage painting changed each texture set since its auto-rebake map was baked; undo brings a box back with the maps baked before it, and it is not saved + pub(crate) painted_regions: BTreeMap, } /// Derived per-texture-set data (rebuilt when the mesh or resolution changes). @@ -427,8 +429,6 @@ pub struct Session { pub(crate) source: Arc, /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it pub(crate) low_poly_fingerprint: std::sync::OnceLock, - /// Where skew or cage painting changed each texture set since its auto-rebake map was baked - pub(crate) painted_regions: std::collections::BTreeMap, /// Skew and cage strokes so far pub(crate) painted_strokes: u64, pub bvh: Arc, @@ -534,7 +534,6 @@ impl Session { project_id: next_mesh_id(), source, low_poly_fingerprint: Default::default(), - painted_regions: Default::default(), painted_strokes: 0, mesh, bvh: Arc::new(bvh), @@ -656,6 +655,7 @@ impl Session { pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), }, mesh, mesh_source, diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index bbe0e243..f50026a8 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -243,6 +243,7 @@ impl Session { pixels: pf.pixels, baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), }; let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default(); diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index 8dd1d80a..9164a5ad 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -109,8 +109,8 @@ fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() { let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components)); let mut changed = 0; for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() { + assert_eq!(rebaked, baked_whole, "texel {index} matches a whole bake"); if region.contains(index % width, index / width) { - assert_eq!(rebaked, baked_whole, "texel {index} inside the box"); changed += usize::from(rebaked != kept); } else { assert_eq!(rebaked, kept, "texel {index} outside the box"); @@ -140,6 +140,42 @@ fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); } +#[test] +fn undoing_the_rebake_of_a_stroke_makes_its_box_due_again() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3]], "radius": 0.05, "size": 64 })).unwrap(); + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); + + session.undo().unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "the map is back to its pixels from before the stroke, which is still painted"); + session.redo().unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "redo brings the rebake back"); +} + +#[test] +fn a_bake_after_a_mesh_reimport_takes_the_strokes_painted_before_it() { + let quad = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n"; + let mut session = Session::from_mesh_bytes_with_uvs("quad.obj", quad.as_bytes(), 128, "quad", None, false).unwrap(); + session.add_high_poly_bytes("quad_high.obj", quad.replace("v 1 1 0", "v 1 1 0.1").into_bytes()).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + + session.reimport_mesh(None, false).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert!(painted.is_empty(), "the bake after the reimport took the stroke: {painted:?}"); +} + #[test] fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() { let mut session = sample_session(256, 64).unwrap(); diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index a18ffae0..07bbcaab 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -70,7 +70,7 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { - let (set, map) = (rebake.0, rebake.1); + let (set, map, ..) = rebake; // Restore the previous view before the rebake takes it over app.live_preview.release(&mut app.session); diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index afea363c..fd58b9a4 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -487,21 +487,23 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { response } -/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail tells what changed +/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail, or its node's description, tells what changed fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeChange]) { let tokens = Tokens::get(ui.ctx()); let response = ui.interact(thumbnail, ui.scope_id().with("out_of_date"), Sense::hover()); let title = tr("Out of date"); let label = trf("Out of date: {map}", &[("map", &name)]); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); + let reasons: Vec<&str> = changes.iter().map(|change| tr(bake_change_reason(*change))).collect(); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reasons.join(" "))); let badge = thumbnail.right_bottom() - vec2(CLOCK_BADGE_RADIUS, CLOCK_BADGE_RADIUS) * 0.5; ui.painter().circle_filled(badge, CLOCK_BADGE_RADIUS, tokens.panel); ui.painter().text(badge, Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(CLOCK_BADGE_RADIUS * 2.0), tokens.warning); response.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); - for change in changes { - ui.label(RichText::new(tr(bake_change_reason(*change))).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + for reason in reasons { + ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); } }); } diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index e490ff85..db0db2a7 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -281,7 +281,13 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { BakeMapState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not baked")), BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; + let reason = match &row.state { + BakeMapState::Failed(reason) => Some(reason.as_str()), + BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + describe(ui, &response, reason); let open = row.state.is_issue().then(|| open_settings_button(ui, rect, (row.texture_set, row.map), &name)); let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); @@ -307,11 +313,6 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { } } - let reason = match &row.state { - BakeMapState::Failed(reason) => Some(reason.as_str()), - BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); @@ -322,6 +323,13 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { (rect, open_clicked) } +/// Give a row's node the `reason` its tooltip shows, so a screen reader reads it without hovering +pub(super) fn describe(ui: &Ui, response: &egui::Response, reason: Option<&str>) { + if let Some(reason) = reason { + ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reason)); + } +} + /// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus fn open_settings_button(ui: &mut Ui, row: Rect, set_map: (usize, BakedMap), name: &str) -> egui::Response { let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); diff --git a/crates/ui-egui/src/baking_log/high_poly_list.rs b/crates/ui-egui/src/baking_log/high_poly_list.rs index 5f4f5977..ab6307ad 100644 --- a/crates/ui-egui/src/baking_log/high_poly_list.rs +++ b/crates/ui-egui/src/baking_log/high_poly_list.rs @@ -43,6 +43,7 @@ fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool { open = !open; ui.data_mut(|data| data.insert_temp(id, open)); } + ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open)); let painter = ui.painter(); if response.hovered() { @@ -69,7 +70,13 @@ fn file_row(ui: &mut Ui, row: &BakeLogHigh) { BakeHighState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not loaded")), BakeHighState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; + let reason = match &row.state { + BakeHighState::Failed(reason) => Some(reason.as_str()), + BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{}, {state}", row.file))); + super::describe(ui, &response, reason); let painter = ui.painter(); if response.hovered() { @@ -84,11 +91,6 @@ fn file_row(ui: &mut Ui, row: &BakeLogHigh) { }; painter.text(pos2(rect.left() + NAME_LEFT + FILE_INDENT, center_y), Align2::LEFT_CENTER, &row.file, font, color); - let reason = match &row.state { - BakeHighState::Failed(reason) => Some(reason.as_str()), - BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs index 22ad6c46..b64565cb 100644 --- a/crates/ui-egui/src/baking_log/matching_list.rs +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -50,7 +50,13 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let no_match = tr("No match"); let name = format!("{}, {}", pair.low.as_deref().unwrap_or(no_match), pair.high.as_deref().unwrap_or(no_match)); + let reason = match (&pair.low, &pair.high) { + (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), + (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name)); + super::describe(ui, &response, reason.as_deref()); let painter = ui.painter(); if response.hovered() { @@ -65,11 +71,6 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { } rule(ui, rect); - let reason = match (&pair.low, &pair.high) { - (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), - (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 2e46ef22..44a9b4f7 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -52,9 +52,12 @@ fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, Bake let checked = app.session.doc.project.texture_sets.get(texture_set).is_some_and(|set| set.bake.maps.is_enabled(map)); ui.label(RichText::new(glyph).color(tokens.warning)); - ui.add(egui::Label::new(&text).truncate()).on_hover_ui(|ui| { + let reasons = reasons(changes, checked); + let line = ui.add(egui::Label::new(&text).truncate()); + ui.ctx().accesskit_node_builder(line.id, |node| node.set_description(reasons.join(" "))); + line.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); - for reason in reasons(changes, checked) { + for reason in reasons { ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); } }); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cb772815..4d6ff3eb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -123,6 +123,7 @@ mod placed_fill_slot; mod placement; mod pointer_lock; mod popup_drag; +mod press_edit; mod preview_dots; mod preview_image; mod preview_request; diff --git a/crates/ui-egui/src/press_edit.rs b/crates/ui-egui/src/press_edit.rs new file mode 100644 index 00000000..22376088 --- /dev/null +++ b/crates/ui-egui/src/press_edit.rs @@ -0,0 +1,8 @@ +//! What [`crate::widgets::press_edit`] keeps of an editor's last change + +/// The press an editor's last change belonged to, and the frame it was seen in +#[derive(Clone, Copy)] +pub(crate) struct PressEdit { + pub(crate) press: u64, + pub(crate) frame: u64, +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b09f71d2..743f7fbe 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -5,6 +5,7 @@ use egui::{Color32, CornerRadius, Rect, Response, RichText, Sense, Stroke, Strok use crate::drawn_icon::DrawnIcon; use crate::i18n::tr; +use crate::press_edit::PressEdit; use crate::theme::Tokens; /// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike @@ -52,13 +53,6 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { }) } -/// The press an editor's last change belonged to, and the frame it was seen in -#[derive(Clone, Copy)] -struct PressEdit { - press: u64, - frame: u64, -} - /// [`slider`] for a value re-read from the document every frame: `Some(merge)` on every frame /// that changes `value` (live while dragging, a click on the track, a typed value). `merge` is /// true for the later changes of one drag, so the edit that applies them (with the command's diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index faf87c78..398e93b8 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -165,8 +165,8 @@ fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_st let mut harness = harness(64); change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); - // Held still well past the settle time, as a hand pausing mid-drag - let corner = egui::pos2(1590.0, 990.0); + // Held still well past the settle time, as a hand pausing mid-drag, in the window's corner where no control takes the press + let corner = harness.ctx.content_rect().right_bottom() - egui::vec2(10.0, 10.0); harness.drag_at(corner); harness.run_steps(120); assert!(harness.state().bake.is_none(), "the edit is not over while the press lasts"); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 972dc919..ad8fbe24 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -734,7 +734,8 @@ fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); harness.run_steps(3); - harness.get_by_label("Out of date: Position"); + let description = harness.get_by_label("Out of date: Position").accesskit_node().description(); + assert!(description.is_some_and(|reasons| !reasons.is_empty()), "what changed is read without hovering"); assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 29099a64..f52fe624 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -1,7 +1,7 @@ //! The Baking Log panel: the latest bake, map by map use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; @@ -56,6 +56,20 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } +#[test] +fn a_failed_rows_reason_is_read_without_hovering() { + let mut harness = harness(); + + bake_with_set_1_failing(&mut harness, &[BakedMap::Id]); + + let app = harness.state(); + let row = app.session.bake_log.maps.iter().find(|row| row.texture_set == 1).unwrap(); + let BakeMapState::Failed(reason) = &row.state else { panic!("set 1's bake failed: {:?}", row.state) }; + let label = format!("{} ID, Not baked", row.set_name); + let node = harness.get_by_label(&label); + assert_eq!(node.accesskit_node().description().as_deref(), Some(reason.as_str()), "the row's node carries its tooltip's reason"); +} + #[test] fn a_one_map_bake_lists_only_that_map() { let mut harness = harness(); @@ -174,10 +188,13 @@ fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() { harness.run_steps(3); let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); harness.get_by_label("ball_high.obj, Loaded"); + let set_row = format!("{set_name}, High poly files"); + assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(true)); - harness.get_by_label(&format!("{set_name}, High poly files")).click(); + harness.get_by_label(&set_row).click(); harness.run_steps(3); assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a folded set hides its files"); + assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(false), "the row says it is folded"); } #[test] diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index aa049fdc..6c879100 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -1,7 +1,7 @@ //! The generator's note when a mesh map it reads is not baked or out of date, and its Bake button use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::core::{BakedMap, LayerId}; use texturecraft_engine::geom::primitives; @@ -40,7 +40,8 @@ fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { #[test] fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() { let mut harness = harness(); - harness.get_by_label("Curvature map not baked"); + let description = harness.get_by_label("Curvature map not baked").accesskit_node().description(); + assert!(description.is_some_and(|reasons| !reasons.is_empty()), "why the note shows is read without hovering"); execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["curvature"] })).unwrap(); harness.run_steps(3); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b68a5c77..5c8c38a1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -335,8 +335,8 @@ own). Imported maps, and maps saved before this record existed, never show: (the active one by default), replacing its previous one, or turns it off with `null`; it is saved with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the -background, alone (with every checked map when the output size changed), once what it is baked from has stopped changing for half a second; a change during -that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that +background, alone (with every checked map when the output size changed), once what it is baked +from has stopped changing for half a second; a change during that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV box, keeping the rest; maps scaled by their whole range (curvature, height, thickness) are baked whole. The first `bake.skew.paint` stroke of a set (no skew map yet) turns Auto-rebake on for its From e3c299963bea5af7298d2ac38fe8caabd56a5f18 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:26:39 +0000 Subject: [PATCH 103/190] List the Baking Log, out-of-date mesh maps and Auto-rebake in the features --- docs/features.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/features.md b/docs/features.md index 2826868c..d2992ba1 100644 --- a/docs/features.md +++ b/docs/features.md @@ -164,6 +164,16 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel with the summary and the message for each failed set. - **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is finished; the bake bar follows the newest map, pins a finished one or shows the material. +- **Baking Log** at the bottom of Bake mode: the latest bake map by map (Baking Process), the high + poly files each set loads (High Poly Parameters) and how parts paired by name (Matching by Name), + with an issues filter; a failed or canceled map opens its settings. `bake.log` returns the same rows. +- **Out-of-date mesh maps:** each bake records what every map was baked from; a map whose mesh, high + poly, cage or settings changed since shows a clock in Mesh Map Bakers (`outOfDate` in + `project.inspect`), and a generator reading a missing or out-of-date map shows one line with a + Bake button. +- **Auto-rebake:** one map per texture set (`bake.autoRebake`, a row icon in Mesh Map Bakers) is + baked again in the background in Bake mode once what it is baked from stops changing; a skew or + cage stroke rebakes only the stroke's box. The first skew stroke turns it on for the Normal map. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in From 67c8ec6470a4bfe9cf168b59cccb0f62c2a084d0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 104/190] Mask and restore a region bake's texels row by row instead of dividing per sample --- crates/bake/src/lib.rs | 15 ++++++++------- crates/bake/src/texel_box.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 73847b5b..d67c684c 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -273,10 +273,8 @@ fn bake_prepared( if let Some(region) = region { for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() { let y = (sample_start_y + row_index) / samples_per_axis; - for (sample_x, triangle) in row.iter_mut().enumerate() { - if !region.texels.contains(sample_x / samples_per_axis, y) { - *triangle = NO_TRI; - } + for outside in region.texels.outside_row(y, samples_per_axis, row.len()) { + row.get_mut(outside).unwrap_or_default().fill(NO_TRI); } } } @@ -329,9 +327,12 @@ fn bake_prepared( let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len()); let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?; let components = map.components(); - for (index, (pixel, kept)) in pixels.chunks_exact_mut(components).zip(previous.chunks_exact(components)).enumerate() { - if !region.texels.contains(index % width, index / width) { - pixel.copy_from_slice(kept); + let row_len = (width * components).max(1); + for (y, (row, kept)) in pixels.chunks_exact_mut(row_len).zip(previous.chunks_exact(row_len)).enumerate() { + for outside in region.texels.outside_row(y, components, row_len) { + if let (Some(row), Some(kept)) = (row.get_mut(outside.clone()), kept.get(outside)) { + row.copy_from_slice(kept); + } } } } diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs index 3dc062cf..306dd04b 100644 --- a/crates/bake/src/texel_box.rs +++ b/crates/bake/src/texel_box.rs @@ -1,3 +1,5 @@ +use std::ops::Range; + /// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TexelBox { @@ -11,6 +13,15 @@ impl TexelBox { (self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y) } + /// The items of texel row `y` outside the box, in a row of `len` items with `scale` items per texel: those before the box and those after it + pub fn outside_row(&self, y: usize, scale: usize, len: usize) -> [Range; 2] { + let (start, end) = match (self.min.1 as usize..self.max.1 as usize).contains(&y) { + true => ((self.min.0 as usize * scale).min(len), (self.max.0 as usize * scale).min(len)), + false => (len, len), + }; + [0..start, end.max(start)..len] + } + /// The box grown by `texels` on every side, kept inside a `width` x `height` image pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox { TexelBox { @@ -19,3 +30,28 @@ impl TexelBox { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_items_outside_a_row_are_the_ones_contains_leaves_out() { + let (width, scale) = (6, 2); + let boxes = [ + TexelBox { min: (1, 1), max: (4, 3) }, + TexelBox { min: (0, 0), max: (6, 4) }, + TexelBox { min: (3, 1), max: (9, 2) }, + TexelBox { min: (4, 1), max: (2, 3) }, + ]; + for texels in boxes { + for y in 0..4 { + let outside = texels.outside_row(y, scale, width * scale); + for item in 0..width * scale { + let is_outside = outside.iter().any(|range| range.contains(&item)); + assert_eq!(is_outside, !texels.contains(item / scale, y), "{texels:?} row {y} item {item}"); + } + } + } + } +} From 6399d008223af6b970efb5944ac7cd67abe6fccd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 105/190] Take a set's shared bake fingerprints once for all its maps, once per Mesh Map Bakers frame --- crates/engine/src/bake/bake_sources.rs | 22 ++++++++++++------- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 11 +++++----- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs index e835c97c..4235f5f8 100644 --- a/crates/engine/src/bake/bake_sources.rs +++ b/crates/engine/src/bake/bake_sources.rs @@ -9,6 +9,12 @@ use crate::{Result, Session}; impl Session { /// What a bake of `map` on texture set `texture_set` would read now pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result { + let map_settings = self.doc.project.texture_set(texture_set)?.map_settings_fingerprint(map); + Ok(BakeSource { map_settings, ..self.set_bake_source(texture_set)? }) + } + + /// What a bake of any map of texture set `texture_set` would read now, without the map's own settings (0) + fn set_bake_source(&self, texture_set: usize) -> Result { let set = self.doc.project.texture_set(texture_set)?; let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); let high_poly = match from_high { @@ -18,13 +24,7 @@ impl Session { let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile; let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint); - Ok(BakeSource { - low_poly: self.low_poly_fingerprint(), - high_poly, - cage, - settings: set.bake_settings_fingerprint(), - map_settings: set.map_settings_fingerprint(map), - }) + Ok(BakeSource { low_poly: self.low_poly_fingerprint(), high_poly, cage, settings: set.bake_settings_fingerprint(), map_settings: 0 }) } /// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record @@ -37,7 +37,13 @@ impl Session { /// The out-of-date maps of texture set `texture_set`, each with what changed pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap> { - BakedMap::ALL.into_iter().map(|map| (map, self.bake_changes(texture_set, map))).filter(|(_, changes)| !changes.is_empty()).collect() + let Ok(set) = self.doc.project.texture_set(texture_set) else { return BTreeMap::new() }; + let mut records = set.bake_sources.iter().filter(|(map, _)| set.baked.contains(map)).peekable(); + + // The fingerprints every map of the set shares are taken once + let Some(shared) = records.peek().and_then(|_| self.set_bake_source(texture_set).ok()) else { return BTreeMap::new() }; + let changes = records.map(|(map, record)| (*map, record.changes(&BakeSource { map_settings: set.map_settings_fingerprint(*map), ..shared }))); + changes.filter(|(_, changes)| !changes.is_empty()).collect() } /// Fingerprint of the low poly's own geometry (computed once per loaded mesh) diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index fd58b9a4..d2442917 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -94,8 +94,10 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); let texture_set = app.session.ts(); + let out_of_date = app.session.out_of_date_maps(texture_set); for map in BakedMap::ALL { - match ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); + match ui.push_id(map, |ui| row(app, ui, (map, changes), settings, map == selected, &mut check_drag, drag_from)).inner { Some(RowClick::Row) => { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); @@ -255,11 +257,11 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check +/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock naming its `changes` (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check fn row( app: &mut TextureCraftApp, ui: &mut Ui, - map: BakedMap, + (map, changes): (BakedMap, &[BakeChange]), settings: &mut BakeSettings, is_selected: bool, check_drag: &mut Option, @@ -296,9 +298,8 @@ fn row( thumbnail(ui, thumbnail_rect, texture.as_ref()); let texture_set = app.session.ts(); - let changes = app.session.bake_changes(texture_set, map); if !changes.is_empty() { - out_of_date_mark(ui, thumbnail_rect, name, &changes); + out_of_date_mark(ui, thumbnail_rect, name, changes); } // From the right: sync (with several sets), Auto-rebake, bolt, eye; Auto-rebake alone stays while on From 1ab2f153497c59e40290d25a0c311be12310d055 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 106/190] Read each auto-rebake map's bake source once per poll and compare it with its record directly --- crates/engine/src/bake/auto_rebake.rs | 2 +- crates/engine/src/bake/painted_region.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index 3f50f672..8f5704a2 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -47,7 +47,7 @@ impl Session { let map = set.auto_rebake?; let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?; let current = self.bake_source(index, map).ok()?; - (!record.changes(¤t).is_empty()).then_some((index, map, current)) + (*record != current).then_some((index, map, current)) }) .collect() } diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs index c19db7a3..0747cf0a 100644 --- a/crates/engine/src/bake/painted_region.rs +++ b/crates/engine/src/bake/painted_region.rs @@ -47,8 +47,12 @@ impl Session { let set = self.doc.project.texture_sets.get(*index)?; let map = set.auto_rebake.filter(|map| set.baked.contains(map))?; let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); - (from_high && self.bake_changes(*index, map).is_empty()).then_some(())?; - Some((*index, map, self.bake_source(*index, map).ok()?, region.stroke)) + from_high.then_some(())?; + let current = self.bake_source(*index, map).ok()?; + + // Only painting changed it: a map without a record is never out of date + let up_to_date = set.bake_sources.get(&map).is_none_or(|record| *record == current); + up_to_date.then_some((*index, map, current, region.stroke)) }) .collect() } From 8d8993aae4588a97b6f6a6d484f617d2c0b71bb0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:45:33 +0000 Subject: [PATCH 107/190] Forget the press records of earlier presses, so editors dragged once no longer stay in memory --- crates/ui-egui/src/property_sheet/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 6 ++++++ 2 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index d7d45b32..28b126c4 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1042,6 +1042,26 @@ fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { assert_eq!(edit(Some(owner), true), Some(false), "a separate press starts an undo step after reopening"); } +/// Editing one editor after another, a press at a time, keeps the record of the latest press only (it kept one per editor ever dragged) +#[test] +fn the_editors_of_earlier_presses_are_forgotten() { + const EDITOR_COUNT: usize = 12; + let context = egui::Context::default(); + let button = + |pressed| egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + + for editor in 0..EDITOR_COUNT { + let owner = egui::Id::unique(("distinct editor", editor)); + for pressed in [true, false] { + let input = egui::RawInput { events: vec![button(pressed)], ..Default::default() }; + context.run_ui(input, |ui| _ = crate::widgets::press_edit(ui, owner, pressed)).textures_delta.clear(); + } + } + + let kept = context.data(|data| data.count::()); + assert!(kept < 2, "{kept} editor records kept after {EDITOR_COUNT} presses"); +} + /// A floating panel in its own OS window runs a pass of its own between two frames of the main window: the drag stays one undo step #[test] fn a_drag_stays_one_undo_step_while_another_window_draws() { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 743f7fbe..abba3370 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -41,6 +41,12 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { Some(start) => { let continuing = previous.is_some_and(|previous| previous.press == start); if changed || continuing { + // Only the latest press's editors can merge, so its first change forgets every editor of the older ones + let latest_press = egui::Id::unique("pointer edit press"); + if data.get_temp::(latest_press) != Some(start) { + data.remove_by_type::(); + data.insert_temp(latest_press, start); + } data.insert_temp(id, PressEdit { press: start, frame }); } continuing From 82e3e72201fbc269d64f82bf3674fcd298299b83 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:25:57 +0000 Subject: [PATCH 108/190] Texture set UV padding: across seams (3D) or from island edges (2D), set by command and followed by the viewport and export textureSet.settings takes uvPadding (3d or 2d) as one undo step and textureSet.inspect reports it. Padding from island edges (2D) is the padding we always had: each texel outside the UV islands repeats the nearest covered texel. Padding across seams (3D) continues the surface across UV seams: a texel just outside a seam takes the texel as far inside the seam's other island (UvSeam finds the edges two triangles share in 3D but not in UV space), up to 32 texels out, and falls back to the nearest covered texel elsewhere. Tangent-space normals always pad in 2D, since they turn with their island. New texture sets pad across seams; projects without the field keep 2D, so they open and export as before. --- crates/compose/src/eval.rs | 17 +-- crates/compose/src/lib.rs | 2 + crates/compose/src/seam_padding.rs | 160 +++++++++++++++++++++++++++++ crates/core/src/lib.rs | 2 + crates/core/src/project.rs | 5 + crates/core/src/uv_padding_mode.rs | 29 ++++++ crates/engine/src/file_cmds.rs | 2 + crates/engine/src/inspect.rs | 4 + crates/engine/src/session.rs | 40 ++++++-- crates/engine/src/set_cmds.rs | 30 +++++- crates/engine/src/solo.rs | 2 +- crates/formats/src/export/mod.rs | 46 ++++++--- crates/formats/src/export/tests.rs | 35 ++++++- crates/geom/src/lib.rs | 4 + crates/geom/src/uv_seam.rs | 79 ++++++++++++++ crates/geom/src/uv_seam_side.rs | 11 ++ 16 files changed, 429 insertions(+), 39 deletions(-) create mode 100644 crates/compose/src/seam_padding.rs create mode 100644 crates/core/src/uv_padding_mode.rs create mode 100644 crates/geom/src/uv_seam.rs create mode 100644 crates/geom/src/uv_seam_side.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 52184129..db448b28 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -21,7 +21,7 @@ use texturecraft_core::{ }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; -use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; +use texturecraft_texel::{TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; @@ -4874,12 +4874,12 @@ fn store_below(cache: &mut [f32], lanes: &[Lane], stride: usize, o: usize, acc: } } -/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from their -/// nearest covered texel. Returns the tiles it wrote. -pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { +/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from the +/// covered texel `padding` gives each channel. Returns the tiles it wrote. +pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { let mut written = std::collections::BTreeSet::new(); let (w, h) = (out.resolution, out.height); - if (dmap.width, dmap.height) != (w, h) { + if (padding.all.width, padding.all.height) != (w, h) { return written; } @@ -4896,9 +4896,10 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) } } let set: Vec<(u32, u32)> = set.into_iter().collect(); - for img in out.channels.values_mut() { + for (channel, img) in out.channels.iter_mut() { let comps = img.comps(); let src: &TileImage = img; + let dmap = padding.for_channel(*channel); // Each tile pads from the original image, so parallel writes stay independent let padded: Vec<((u32, u32), Vec)> = set @@ -6417,8 +6418,8 @@ soft {soft:?}" out.channels.get_mut(&Channel::Roughness).unwrap().set(10, 10, &[to_u16(0.9)]); let mut covered = vec![false; 64 * 64]; covered[10 * 64 + 10] = true; - let dmap = DilationMap::new(&covered, 64, 64, Some(4)); - pad_tiles(&mut out, &dmap, &[(0, 0)]); + let padding = crate::PaddingMaps { all: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), flat: None }; + pad_tiles(&mut out, &padding, &[(0, 0)]); assert!((out.value(Channel::Roughness, 12, 12)[0] - 0.9).abs() < 1e-3); assert!(out.value(Channel::Roughness, 30, 30)[0] < 0.1 || !out.channels[&Channel::Roughness].is_allocated(0, 0)); } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 32b480e0..75615ba0 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -44,6 +44,7 @@ pub mod projector_depth; mod projector_depth_cache; pub mod projector_view; mod sampled_map; +pub mod seam_padding; mod sections; mod shape_distance; mod slope_texel; @@ -79,6 +80,7 @@ pub use eval::{ pub use mask_gray::MaskGray; pub use pattern_context::PatternContext; pub use projector_depth_cache::ProjectorDepthCache; +pub use seam_padding::PaddingMaps; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/seam_padding.rs b/crates/compose/src/seam_padding.rs new file mode 100644 index 00000000..d0f49b26 --- /dev/null +++ b/crates/compose/src/seam_padding.rs @@ -0,0 +1,160 @@ +//! 3D Space Neighbor UV padding: texels past a UV seam continue the surface from the seam's other side + +use texturecraft_core::{Channel, ChannelKind, UvPaddingMode}; +use texturecraft_geom::{UvSeam, UvSeamSide, glam::Vec2}; +use texturecraft_texel::dilate::{DilationMap, NONE}; + +/// Farthest a padding texel reaches across a seam, in texels; farther ones keep their nearest covered texel +pub const SEAM_REACH: u32 = 32; + +/// A texture set's padding maps: `all` for its channels, `flat` for tangent-space normals +#[derive(Clone, Debug, PartialEq)] +pub struct PaddingMaps { + pub all: DilationMap, + /// 2D Space Neighbor always: a tangent-space normal turns with its island, so it can't continue across a seam + pub flat: Option, +} + +impl PaddingMaps { + /// The maps for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block` + pub fn new(mode: UvPaddingMode, covered: &[bool], (width, height): (u32, u32), max_dist: Option, block: (u32, u32), seams: &[UvSeam]) -> PaddingMaps { + let flat = DilationMap::in_rectangular_blocks(covered, width, height, max_dist, block); + match mode { + UvPaddingMode::Space2d => PaddingMaps { all: flat, flat: None }, + UvPaddingMode::Space3d => { + let mut all = flat.clone(); + cross_seams(&mut all, covered, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams); + PaddingMaps { all, flat: Some(flat) } + } + } + } + + /// The map padding tangent-space normals + pub fn flat(&self) -> &DilationMap { + self.flat.as_ref().unwrap_or(&self.all) + } + + /// The map padding `channel` + pub fn for_channel(&self, channel: Channel) -> &DilationMap { + if channel.kind() == ChannelKind::NormalMap { self.flat() } else { &self.all } + } +} + +/// Point every padding texel just outside a seam at the texel as far inside the seam's other side +fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, block: (u32, u32), seams: &[UvSeam]) { + let (width, height) = (map.width, map.height); + let size = Vec2::new(width as f32, height as f32); + let block_of = |x: u32, y: u32| (x.checked_div(block.0).unwrap_or(0), y.checked_div(block.1).unwrap_or(0)); + let is_covered = |x: u32, y: u32| covered.get((y * width + x) as usize).copied().unwrap_or(false); + let mut crossed_at = vec![f32::INFINITY; map.src.len()]; + for seam in seams { + for (near, far) in [(seam.sides[0], seam.sides[1]), (seam.sides[1], seam.sides[0])] { + let (Some(near_edge), Some(far_edge)) = (TexelEdge::new(near, size), TexelEdge::new(far, size)) else { + continue; + }; + + let reach = reach as f32; + let low = near_edge.start.min(near_edge.end) - Vec2::splat(reach); + let high = near_edge.start.max(near_edge.end) + Vec2::splat(reach); + let (x0, y0) = (low.x.floor().max(0.0) as u32, low.y.floor().max(0.0) as u32); + let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32); + for y in y0..y1 { + for x in x0..x1 { + let index = (y * width + x) as usize; + let Some(&source) = map.src.get(index) else { continue }; + if source == NONE || source == index as u32 { + continue; + } + + let point = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let Some((along, outside)) = near_edge.outside(point) else { continue }; + if outside > reach || outside >= crossed_at.get(index).copied().unwrap_or(0.0) { + continue; + } + + // Another island's edge nearer than the seam keeps its texel + let (source_x, source_y) = (source % width, source / width); + if (source_x.abs_diff(x).max(source_y.abs_diff(y)) as f32) + 1.0 < outside { + continue; + } + + // Padding stays inside its UV tile, like the 2D padding + let inside = near_edge.start.lerp(near_edge.end, along) + near_edge.inward * 0.5; + if block_of(inside.x.max(0.0) as u32, inside.y.max(0.0) as u32) != block_of(x, y) { + continue; + } + + // As far inside the other side as the texel is outside this one, at least to that side's first texel centres + let target = far_edge.start.lerp(far_edge.end, along) + far_edge.inward * outside.max(0.5); + if target.x < 0.0 || target.y < 0.0 || target.x >= size.x || target.y >= size.y { + continue; + } + + let (target_x, target_y) = (target.x as u32, target.y as u32); + if is_covered(target_x, target_y) + && let (Some(destination), Some(at)) = (map.src.get_mut(index), crossed_at.get_mut(index)) + { + *destination = target_y * width + target_x; + *at = outside; + } + } + } + } + } +} + +/// A seam side in texel space, with its unit normal into the island +struct TexelEdge { + start: Vec2, + end: Vec2, + inward: Vec2, +} + +impl TexelEdge { + fn new(side: UvSeamSide, size: Vec2) -> Option { + let (start, end, interior) = (side.start * size, side.end * size, side.interior * size); + let normal = (end - start).perp().try_normalize()?; + let inward = if normal.dot(interior - start) < 0.0 { -normal } else { normal }; + Some(TexelEdge { start, end, inward }) + } + + /// How far along the edge (0..1) and how far outside the island `point` is, when it is beside the edge on the outside + fn outside(&self, point: Vec2) -> Option<(f32, f32)> { + let direction = self.end - self.start; + let along = (point - self.start).dot(direction) / direction.length_squared(); + let outside = -(point - self.start).dot(self.inward); + ((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Two islands of one 3D edge: the left one's right side is the right one's left side + fn two_islands() -> (Vec, Vec) { + let (width, height) = (32u32, 8u32); + let covered = (0..width * height).map(|i| matches!(i % width, 4..=11 | 20..=27)).collect(); + let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); + let left = UvSeamSide { start: at(12.0, 0.0), end: at(12.0, 8.0), interior: at(4.0, 0.0) }; + let right = UvSeamSide { start: at(20.0, 0.0), end: at(20.0, 8.0), interior: at(28.0, 0.0) }; + (covered, vec![UvSeam { sides: [left, right] }]) + } + + #[test] + fn padding_past_a_seam_continues_from_its_other_side_and_normals_stay_flat() { + let (covered, seams) = two_islands(); + let space_3d = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (32, 8), Some(4), (0, 0), &seams); + let space_2d = PaddingMaps::new(UvPaddingMode::Space2d, &covered, (32, 8), Some(4), (0, 0), &seams); + let island = |map: &DilationMap, x: u32| map.source(x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" }); + + // Just right of the left island, then just left of the right island + assert_eq!((island(&space_3d.all, 13), island(&space_3d.all, 18)), (Some("right"), Some("left"))); + assert_eq!((island(&space_2d.all, 13), island(&space_2d.all, 18)), (Some("left"), Some("right"))); + assert_eq!(space_3d.for_channel(Channel::Normal), &space_2d.all); + assert_eq!(space_3d.for_channel(Channel::BaseColor), &space_3d.all); + + // Away from the seam, both modes pad from the near island + assert_eq!(island(&space_3d.all, 2), Some("left")); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 6c7776c7..c450cff6 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -69,6 +69,7 @@ pub mod target_color_mode; pub mod threshold_mode; pub mod tile_transform; pub mod unit_value; +mod uv_padding_mode; pub mod validation_mode; pub mod warp_blending; pub mod warp_mode; @@ -151,6 +152,7 @@ pub use target_color_mode::TargetColorMode; pub use threshold_mode::ThresholdMode; pub use tile_transform::{FlipMode, RepeatMode, TileTransform}; pub use unit_value::{at_or_above_threshold, finite_unit}; +pub use uv_padding_mode::UvPaddingMode; pub use validation_mode::ValidationMode; pub use warp_blending::WarpBlending; pub use warp_mode::WarpMode; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 03939e3d..fd939909 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::{ BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, HeightToNormalMethod, Layer, LayerId, LayerKind, Result, + UvPaddingMode, }; pub use crate::env_alignment::EnvAlignment; @@ -66,6 +67,9 @@ pub struct TextureSet { /// Height to normal method; projects without it keep Smooth, the filter their exports already used #[serde(default)] pub height_to_normal: HeightToNormalMethod, + /// UV padding; projects without it keep 2D Space Neighbor, the padding they were made with + #[serde(default)] + pub uv_padding: UvPaddingMode, /// Height-to-normal strength. #[serde(default = "one")] pub height_strength: f32, @@ -174,6 +178,7 @@ impl TextureSet { normal_mixing: NormalMixing::Combine, ao_mixing: AoMixing::Multiply, height_to_normal: HeightToNormalMethod::Smooth, + uv_padding: UvPaddingMode::Space3d, height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), diff --git a/crates/core/src/uv_padding_mode.rs b/crates/core/src/uv_padding_mode.rs new file mode 100644 index 00000000..ab5150ec --- /dev/null +++ b/crates/core/src/uv_padding_mode.rs @@ -0,0 +1,29 @@ +//! Where a texture set's UV padding takes its texels from + +use serde::{Deserialize, Serialize}; + +/// UV padding mode: what fills the texels just outside a texture set's UV islands +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum UvPaddingMode { + /// Across seams (3D): past a UV seam, the texels continue the surface from the seam's other side + Space3d, + /// From island edges (2D): every texel repeats the nearest covered texel in the texture + #[default] + Space2d, +} + +impl UvPaddingMode { + pub const ALL: [UvPaddingMode; 2] = [UvPaddingMode::Space3d, UvPaddingMode::Space2d]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + UvPaddingMode::Space3d => "3d", + UvPaddingMode::Space2d => "2d", + } + } + + pub fn parse(id: &str) -> Option { + UvPaddingMode::ALL.into_iter().find(|value| value.id() == id) + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 5c813d46..cafee7a6 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -343,12 +343,14 @@ impl Session { let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; let coverage = cache.gbuf.coverage_mask(); + let seams = self.doc.project.texture_set(set_index).map_or_else(|_| Vec::new(), |set| crate::session::padding_seams(&self.mesh, set)); let input = ExportInput { project: &self.doc.project, ts: set_index, composite: &composite, baked: self.doc.baked.get(&set_index).unwrap_or(&empty), coverage: &coverage, + seams: &seams, mesh_name: &mesh_name, }; out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index ada4d0fe..292bdbf3 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -286,6 +286,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value { texturecraft_core::HeightToNormalMethod::Sharp => "sharp", texturecraft_core::HeightToNormalMethod::Smooth => "smooth", }, + "uvPadding": match texture_set.uv_padding { + texturecraft_core::UvPaddingMode::Space3d => "3d", + texturecraft_core::UvPaddingMode::Space2d => "2d", + }, "active": index == session.ts(), }) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 0864bf7b..1ed8dcbd 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -5,13 +5,12 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use texturecraft_compose::{ - BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours, + BakedMaps, BelowCache, Composite, PaddingMaps, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours, }; -use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; +use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet, UvPaddingMode}; use texturecraft_geom::glam::Vec2; -use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; +use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer, UvSeam}; use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; -use texturecraft_texel::DilationMap; use crate::fill_mode::FillMode; pub use crate::stencil_look::StencilLook; @@ -40,7 +39,9 @@ pub struct SetCache { /// Texels across and down (`TextureSet::size`). pub size: (u32, u32), pub gbuf: Arc, - pub dilation: Arc, + /// The set's UV padding mode and the display padding it gives + pub uv_padding: UvPaddingMode, + pub padding: Arc, pub covered_tiles: Arc>, pub composite: Composite, /// Tiles to recomposite. @@ -62,15 +63,14 @@ impl SetCache { pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache { let (w, h) = ts.size(); let gbuf = UvGBuffer::new(mesh, ts.material, w, h); - - // Padding stays inside each UV tile - let dilation = DilationMap::in_blocks(&gbuf.coverage_mask(), w, h, Some(DISPLAY_PADDING), ts.block_resolution()); + let padding = display_padding(mesh, ts, &gbuf); let covered = covered_tiles(&gbuf); let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect(); SetCache { size: (w, h), gbuf: Arc::new(gbuf), - dilation: Arc::new(dilation), + uv_padding: ts.uv_padding, + padding: Arc::new(padding), covered_tiles: Arc::new(covered), composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), @@ -87,6 +87,20 @@ impl SetCache { } } +/// The seams `ts`'s UV padding crosses: none for 2D Space Neighbor +pub(crate) fn padding_seams(mesh: &Mesh, ts: &TextureSet) -> Vec { + match ts.uv_padding { + UvPaddingMode::Space3d => UvSeam::of_material(mesh, ts.material), + UvPaddingMode::Space2d => Vec::new(), + } +} + +/// The viewport's padding of `ts`, which stays inside each UV tile +fn display_padding(mesh: &Mesh, ts: &TextureSet, gbuf: &UvGBuffer) -> PaddingMaps { + let block = ts.block_resolution(); + PaddingMaps::new(ts.uv_padding, &gbuf.coverage_mask(), (gbuf.width, gbuf.height), Some(DISPLAY_PADDING), (block, block), &padding_seams(mesh, ts)) +} + /// Active tool. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Tool { @@ -911,6 +925,12 @@ impl Session { for (i, ts) in sets.iter().enumerate() { match self.caches.get_mut(i) { Some(c) if c.size == ts.size() => { + if c.uv_padding != ts.uv_padding { + c.uv_padding = ts.uv_padding; + c.padding = Arc::new(display_padding(&self.mesh, ts, &c.gbuf)); + c.invalidate_all(); + } + let (want, scales) = (ts.channel_list(), ts.block_scales()); if c.composite.channels.keys().copied().collect::>() != want || c.composite.block_scales != scales { c.composite = Composite { block_scales: scales, ..Composite::with_size(&want, c.size.0, c.size.1) }; @@ -1130,7 +1150,7 @@ impl Session { ); // The composited tiles and the neighbours their padding reached change - let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); + let padded = pad_tiles(&mut cache.composite, &cache.padding, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); cache.revision = cache.revision.wrapping_add(1); changed = true; diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 4060ba8d..f9302e3c 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -1,7 +1,7 @@ //! Texture set commands (Texture Set List / Texture Set Settings). use serde_json::{Value, json}; -use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, HeightToNormalMethod, NormalMixing}; +use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, HeightToNormalMethod, NormalMixing, UvPaddingMode}; use std::sync::Arc; @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Texture set settings", [], None, - "{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, heightToNormal?: sharp|smooth, normalFormat?: openGl|directX}", + "{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, heightToNormal?: sharp|smooth, uvPadding?: 3d|2d, normalFormat?: openGl|directX}", always, settings ), @@ -308,6 +308,12 @@ fn settings(s: &mut Session, p: &Value) -> Result { Some("smooth") => Some(HeightToNormalMethod::Smooth), Some(other) => return Err(bad("textureSet.settings", format!("unknown height to normal method {other:?} (sharp or smooth)"))), }; + let uv_padding = match strp(p, "uvPadding") { + None => None, + Some("3d") => Some(UvPaddingMode::Space3d), + Some("2d") => Some(UvPaddingMode::Space2d), + Some(other) => return Err(bad("textureSet.settings", format!("unknown UV padding {other:?} (3d or 2d)"))), + }; s.edit("Texture set settings", |s| { if let Some(n) = nf { s.doc.project.normal_format = n; @@ -328,6 +334,9 @@ fn settings(s: &mut Session, p: &Value) -> Result { if let Some(method) = height_to_normal { set.height_to_normal = method; } + if let Some(mode) = uv_padding { + set.uv_padding = mode; + } Ok(()) })?; @@ -387,6 +396,23 @@ mod tests { assert_eq!(method(&s, 0), json!("smooth")); } + #[test] + fn uv_padding_rebuilds_the_viewport_padding_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mode = |s: &Session| crate::inspect::texture_set(s, 0)["uvPadding"].clone(); + let crosses_seams = |s: &Session| s.caches[0].padding.flat.is_some(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); + s.update(); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "uvPadding": "2d"})).unwrap(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("2d"), false)); + assert!(!s.caches[0].dirty.is_empty(), "the set recomposites with its new padding"); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"uvPadding": "4d"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); + } + #[test] fn ao_mixing_resends_the_set_to_the_viewport_and_undoes() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/engine/src/solo.rs b/crates/engine/src/solo.rs index 454a8817..bf8c1b74 100644 --- a/crates/engine/src/solo.rs +++ b/crates/engine/src/solo.rs @@ -81,7 +81,7 @@ impl Session { let set = inputs.project.texture_sets.get(ts)?; let mut output = Composite { block_scales: inputs.block_scales.clone(), ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) }; composite_tiles(inputs, &mut output, tiles); - pad_tiles(&mut output, &cache.dilation, tiles); + pad_tiles(&mut output, &cache.padding, tiles); Some(Cow::Owned(output)) }) } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 404980df..e369aa95 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -18,10 +18,10 @@ use std::io::Cursor; use craft_image_codecs::{ChannelLayout, EncodeOptions, Format as CodecFormat, Image as CodecImage, SampleType}; use rayon::prelude::*; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, Composite}; +use texturecraft_compose::{BakedMaps, Composite, PaddingMaps}; use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, Project, TextureSet}; -use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; +use texturecraft_geom::{UvSeam, glam::Vec3}; +use texturecraft_texel::{ColorSpace, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; @@ -290,6 +290,16 @@ impl SourceRef { self.raw_component().min(2) } + /// Whether the source is a tangent-space normal, which pads in 2D whatever the set's UV padding + fn pads_flat(&self) -> bool { + match self { + SourceRef::Channel { channel, .. } => channel.kind() == ChannelKind::NormalMap, + SourceRef::Virtual { map, .. } => matches!(map, VirtualMap::NormalOpenGl | VirtualMap::NormalDirectX | VirtualMap::HeightNormal), + SourceRef::Baked { map, .. } => *map == BakedMap::Normal, + SourceRef::Constant(_) => false, + } + } + /// Components the source has (1 or 3; constants are 1). pub fn components(&self) -> usize { match self { @@ -480,6 +490,8 @@ pub struct ExportInput<'a> { pub composite: &'a Composite, pub baked: &'a BakedMaps, pub coverage: &'a [bool], + /// The set's UV seams, which 3D Space Neighbor padding crosses + pub seams: &'a [UvSeam], pub mesh_name: &'a str, } @@ -913,12 +925,11 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned } // Padding stays inside each UV tile - let dilation_map = match options.padding { + let padding_maps = |max_dist| PaddingMaps::new(set.uv_padding, input.coverage, (width, height), max_dist, (tile_res, tile_res), input.seams); + let padding = match options.padding { Padding::None => None, - Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { - Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) - } - Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), + Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => Some(padding_maps(Some(d))), + Padding::Infinite => Some(padding_maps(None)), }; let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); let diffuse = matches!(options.padding, Padding::DilationDiffusion(_)); @@ -941,6 +952,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned let channel_layout = layout(set, map); let component_count = channel_layout.len(); let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); + let pads_flat: Vec = channel_layout.iter().map(|(_, source)| source.pads_flat()).collect(); // The texels written: one tile, or the whole set let (x0, y0, w, h) = match (planned_file.tile, grid) { @@ -965,17 +977,23 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { let y = y0 + row_y as u32; for (column, x) in (x0..x0 + w).enumerate() { - let at = if sampler.covered(x, y) { - Some(At::Texel(x, y)) - } else { - match dilation_map.as_ref().and_then(|d| d.source(x, y)) { + let at = |flat: bool| { + if sampler.covered(x, y) { + return Some(At::Texel(x, y)); + } + + let dilation_map = padding.as_ref().map(|padding| if flat { padding.flat() } else { &padding.all }); + match dilation_map.and_then(|d| d.source(x, y)) { Some((sx, sy)) => Some(At::Texel(sx, sy)), None => beyond_default.then_some(At::Default), } }; - let Some(at) = at else { continue }; + + // Only normals use the sample cache, and they all sample the 2D padding + let (at_all, at_flat) = (at(false), at(true)); let mut cache = None; for (component, (_, source)) in channel_layout.iter().enumerate() { + let Some(at) = (if pads_flat.get(component).copied().unwrap_or(false) { at_flat } else { at_all }) else { continue }; if let Some(value) = row.get_mut(column * component_count + component) { let sample = sampler.sample(source, at, &mut cache); *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; @@ -988,7 +1006,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned if diffuse { let known: Vec = (y0..y0 + h) .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) - .map(|(x, y)| sampler.covered(x, y) || dilation_map.as_ref().is_some_and(|d| d.source(x, y).is_some())) + .map(|(x, y)| sampler.covered(x, y) || padding.as_ref().is_some_and(|padding| padding.all.source(x, y).is_some())) .collect(); // Keep diffusion within each UV tile when rendering an atlas diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 71435ae0..24b24b95 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1,7 +1,7 @@ use std::io::Cursor; use image::{DynamicImage, GenericImageView, ImageFormat}; -use texturecraft_core::{ChannelFormat, Project, TextureSet}; +use texturecraft_core::{ChannelFormat, Project, TextureSet, UvPaddingMode}; use texturecraft_texel::{to_u16, to_u16_signed}; use super::*; @@ -50,7 +50,7 @@ impl Fx { } fn input(&self) -> ExportInput<'_> { - ExportInput { project: &self.project, ts: 0, composite: &self.comp, baked: &self.baked, coverage: &self.coverage, mesh_name: "sphere" } + ExportInput { project: &self.project, ts: 0, composite: &self.comp, baked: &self.baked, coverage: &self.coverage, seams: &[], mesh_name: "sphere" } } fn render(&self, opts: &ExportOptions) -> Vec { @@ -654,7 +654,8 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() { } } } - let input = ExportInput { project: &project, ts: 0, composite: &comp, baked: &BakedMaps::default(), coverage: &coverage, mesh_name: "udim_plane" }; + let input = + ExportInput { project: &project, ts: 0, composite: &comp, baked: &BakedMaps::default(), coverage: &coverage, seams: &[], mesh_name: "udim_plane" }; let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { @@ -705,7 +706,7 @@ fn small_export_size_keeps_each_nonempty_udim_tile_one_pixel_or_larger() { project.texture_sets.push(set); let composite = Composite::with_size(&[Channel::Roughness], 1024, 512); let coverage = vec![true; 1024 * 512]; - let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &BakedMaps::default(), coverage: &coverage, mesh_name: "m" }; + let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &BakedMaps::default(), coverage: &coverage, seams: &[], mesh_name: "m" }; for format in [FileFormat::Png, FileFormat::Psd] { let opts = ExportOptions { size: Some(2), padding: Padding::None, ..one_map(format, 8, roughness()) }; @@ -1319,6 +1320,32 @@ fn dithering_is_ordered_and_keeps_the_average() { assert!(list_outputs(&fx.project, 0, "sphere", &wide).unwrap().iter().all(|p| !p.dither)); } +#[test] +fn padding_past_a_seam_takes_the_far_island_except_for_normals() { + // Two islands of one 3D edge: the left one's right side (x = 12) is the right one's left side (x = 20) + let mut fx = Fx::new(&default_channels()); + fx.coverage = (0..RES * RES).map(|i| matches!(i % RES, 4..=11 | 20..=27)).collect(); + fx.set_all(Channel::Roughness, |x, _| [if x < 16 { 0.2 } else { 0.8 }; 3]); + fx.set_all(Channel::Normal, |x, _| if x < 16 { [0.3, 0.5, 0.9] } else { [0.7, 0.5, 0.9] }); + let at = |x: f32, y: f32| texturecraft_geom::glam::Vec2::new(x, y) / RES as f32; + let left = texturecraft_geom::UvSeamSide { start: at(12.0, 0.0), end: at(12.0, 64.0), interior: at(4.0, 0.0) }; + let right = texturecraft_geom::UvSeamSide { start: at(20.0, 0.0), end: at(20.0, 64.0), interior: at(28.0, 0.0) }; + let seams = [UvSeam { sides: [left, right] }]; + let normal_x = SourceRef::Channel { channel: Channel::Normal, component: 0 }; + let mut options = one_map(FileFormat::Png, 16, vec![(Dest::R, roughness()[0].1.clone()), (Dest::G, normal_x), (Dest::B, SourceRef::Constant(0.0))]); + options.padding = Padding::Dilation(4); + let render = |fx: &Fx| decode(&render_maps(&ExportInput { seams: &seams, ..fx.input() }, &options).unwrap()[0]).to_rgb16(); + + // Just right of the left island: roughness continues from the right island, the normal stays the left island's + let space_3d = render(&fx); + let (outside, near, far) = (space_3d.get_pixel(13, 30), space_3d.get_pixel(8, 30), space_3d.get_pixel(24, 30)); + assert_eq!((outside[0], outside[1]), (far[0], near[1])); + + fx.project.texture_sets[0].uv_padding = UvPaddingMode::Space2d; + let space_2d = render(&fx); + assert_eq!(space_2d.get_pixel(13, 30), space_2d.get_pixel(8, 30)); +} + #[test] fn diffusion_padding_fills_beyond_the_dilation_smoothly() { let mut fx = Fx::new(&default_channels()); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index eb71f854..e9720ba7 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -13,6 +13,8 @@ pub mod mesh; pub mod primitives; pub mod triangle_partition; pub mod unwrap; +mod uv_seam; +mod uv_seam_side; pub use bvh::{Bvh, Hit}; pub use camera::{OrbitCamera, Ray}; @@ -20,6 +22,8 @@ pub use gbuffer::{NO_TRI, Surface, UvGBuffer, surface_at}; pub use glam; pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; pub use triangle_partition::TrianglePartition; +pub use uv_seam::UvSeam; +pub use uv_seam_side::UvSeamSide; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum GeomError { diff --git a/crates/geom/src/uv_seam.rs b/crates/geom/src/uv_seam.rs new file mode 100644 index 00000000..f22bc39e --- /dev/null +++ b/crates/geom/src/uv_seam.rs @@ -0,0 +1,79 @@ +//! UV seams: mesh edges two triangles share in 3D but not in UV space + +use std::collections::HashMap; + +use crate::{Mesh, UvSeamSide}; + +/// Edge ends closer than this share a UV position +const SAME_UV: f32 = 1e-5; + +/// A UV seam: the same 3D edge on two UV islands; both sides' starts are the same 3D point +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvSeam { + pub sides: [UvSeamSide; 2], +} + +impl UvSeam { + /// The seams between triangles of `material` + pub fn of_material(mesh: &Mesh, material: usize) -> Vec { + // Corners within a millionth of the mesh size are the same 3D point + let (minimum, maximum) = mesh.bounds(); + let tolerance = (maximum - minimum).length().max(1e-6) * 1e-6; + let position_key = |index: usize| mesh.positions.get(index).map(|position| position.to_array().map(|value| (value / tolerance).round() as i64)); + let mut first_sides = HashMap::new(); + let mut seams = Vec::new(); + for triangle in mesh.triangles_of(material) { + let Some(corners) = mesh.tri(triangle) else { + continue; + }; + + for edge in 0..3 { + let (first, second, third) = (corners[edge], corners[(edge + 1) % 3], corners[(edge + 2) % 3]); + let (Some(first_key), Some(second_key)) = (position_key(first), position_key(second)) else { + continue; + }; + + // A pole's collapsed edges have no length to cross + if first_key == second_key { + continue; + } + + let (Some(&first_uv), Some(&second_uv), Some(&interior)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { + continue; + }; + + // Each side starts at the corner with the smaller key, so both sides run the same way + let (key, side) = if first_key <= second_key { + ((first_key, second_key), UvSeamSide { start: first_uv, end: second_uv, interior }) + } else { + ((second_key, first_key), UvSeamSide { start: second_uv, end: first_uv, interior }) + }; + let Some(other) = first_sides.insert(key, side) else { + continue; + }; + + if side.start.distance(other.start) > SAME_UV || side.end.distance(other.end) > SAME_UV { + seams.push(UvSeam { sides: [other, side] }); + } + } + } + + seams + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_closed_mesh_has_seams_and_a_single_island_has_none() { + let sphere = crate::primitives::sphere(1.0, 16, 8); + let plane = crate::primitives::plane(1.0, 4); + let seams = UvSeam::of_material(&sphere, 0); + + assert!(!seams.is_empty()); + assert!(seams.iter().all(|seam| seam.sides[0].start != seam.sides[1].start || seam.sides[0].end != seam.sides[1].end)); + assert!(UvSeam::of_material(&plane, 0).is_empty()); + } +} diff --git a/crates/geom/src/uv_seam_side.rs b/crates/geom/src/uv_seam_side.rs new file mode 100644 index 00000000..b8b810d4 --- /dev/null +++ b/crates/geom/src/uv_seam_side.rs @@ -0,0 +1,11 @@ +//! One side of a UV seam + +use glam::Vec2; + +/// One side of a [`UvSeam`](crate::UvSeam): an island edge in UV space and the third corner of its triangle (which side the island is on) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvSeamSide { + pub start: Vec2, + pub end: Vec2, + pub interior: Vec2, +} From 138b4da0995726225481b2ec02ca492e21c51cf2 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:46:30 +0000 Subject: [PATCH 109/190] Texture set size: width and height, so a set can be non-square, set by command and followed by the viewport, filters and export textureSet.resolution takes an optional height (default: square). Old projects open square as before; sets whose UV tiles have their own sizes stay square. --- crates/automation/src/render.rs | 9 ++- crates/compose/src/eval.rs | 84 +++++++++++++---------- crates/compose/src/field_cache.rs | 1 + crates/core/src/project.rs | 88 +++++++++++++++++++++++-- crates/engine/src/file_cmds.rs | 8 ++- crates/engine/src/inspect.rs | 1 + crates/engine/src/mask_export.rs | 16 +++-- crates/engine/src/material_lib.rs | 1 + crates/engine/src/session.rs | 3 +- crates/engine/src/set_cmds.rs | 43 ++++++++---- crates/engine/src/uv_tile_cmds.rs | 38 ++++++++++- crates/formats/src/export/mod.rs | 59 ++++++++--------- crates/render/src/displace.rs | 1 + crates/render/src/gpu_trace.rs | 14 +++- crates/render/src/renderer.rs | 5 ++ crates/render/src/shaders/mesh.wgsl | 12 ++-- crates/render/src/shaders/trace.wgsl | 14 ++-- crates/render/src/trace.rs | 69 +++++++++++++++++-- crates/render/tests/headless.rs | 15 +++++ crates/ui-egui/src/bake_mode/mod.rs | 4 +- crates/ui-egui/src/dock.rs | 6 +- crates/ui-egui/src/filter_properties.rs | 2 +- crates/ui-egui/src/lib.rs | 10 ++- crates/ui-egui/src/link_import.rs | 9 +-- crates/ui-egui/src/render_mode.rs | 10 ++- crates/ui-egui/src/viewport.rs | 2 + 26 files changed, 395 insertions(+), 129 deletions(-) diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index bdcf9fe8..f1ea7199 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -168,6 +168,7 @@ fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength(), + height_y_factor: ts.atlas_height_y_factor(), height_in_normal: ts.height_in_normal(), height_to_normal: ts.height_to_normal, }) @@ -205,10 +206,12 @@ pub fn shade(s: &Session) -> Shade { ViewMode::UvChecker => (3, 0), ViewMode::NormalHeightMesh => (4, 0), }; + let active_set = s.doc.project.texture_sets.get(s.ts()); Shade { - height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0), - height_in_normal: s.doc.project.texture_sets.get(s.ts()).is_none_or(|t| t.height_in_normal()), - height_to_normal: s.doc.project.texture_sets.get(s.ts()).map_or_else(Default::default, |t| t.height_to_normal), + height_strength: active_set.map_or(1.0, |t| t.atlas_height_strength()), + height_y_factor: active_set.map_or(1.0, |t| t.atlas_height_y_factor()), + height_in_normal: active_set.is_none_or(|t| t.height_in_normal()), + height_to_normal: active_set.map_or_else(Default::default, |t| t.height_to_normal), view_mode, channel, // Only the 2D view uses this default diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index db448b28..489b00c0 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -171,6 +171,12 @@ impl Inputs<'_> { self.gbuf.width / self.tile_grid().map_or(1, |g| g.cols.max(1)) } + /// Texels across and down an atlas block. + fn block_size(&self) -> [u32; 2] { + let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols.max(1), g.rows.max(1))); + [self.gbuf.width / cols, self.gbuf.height / rows] + } + /// The current UV tile can occupy only part of its atlas block fn tile_res_at(&self, x: u32, y: u32) -> u32 { ((self.tile_res() as f32 * self.block_scales.at(x, y)).round() as u32).max(1) @@ -439,9 +445,9 @@ enum Op { /// The shapes moved by `offset` (whole texels), box blurred and laid under them Shadow { offset: [i32; 2] }, /// Each UV tile's texels read from where `mirror` sends them in their tile (`block` texels across the set's atlas blocks) - Mirror { mirror: Mirror, block: u32 }, + Mirror { mirror: Mirror }, /// Each UV tile's texels read from where `transform` sends them (its `affine`, worked out once), repeating round the tile or empty past it - Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]), block: u32 }, + Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]) }, /// A band along the edge of the shapes past a threshold, from the box blur of the shapes Outline(MaskOutline), /// Drawn from the distance to the shapes' edge (see [`distance_filter`]) @@ -529,10 +535,10 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // A mirror reads anywhere in its UV tile - EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror, block: res })), + EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror })), // A transform reads anywhere in its UV tile; one that changes nothing is skipped EffectKind::Filter(Filter::Transform(transform)) if !transform.is_identity() => { - Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine(), block: res })) + Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine() })) } // Three box passes reach the band's width @@ -771,10 +777,10 @@ fn gather( keep_coverage(&mut acc, comps, center.get(3)); } } - Op::Mirror { mirror, block } => { - mirror_texel(&mirror, (x, y), (block, res), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample) + Op::Mirror { mirror } => { + mirror_texel(&mirror, (x, y), (block_size, tile_size), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample) } - Op::Transform { transform, affine, block } => transform_texel(&transform, affine, (x, y), (block, res), &mut acc, &sample), + Op::Transform { transform, affine } => transform_texel(&transform, affine, (x, y), (block_size, tile_size), &mut acc, &sample), Op::SourceWarp(warp) => warp_texel((&warp, &warp_directions), (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)), Op::SourceSlopeBlur(slope) => slope_texel(&slope, (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)), Op::HeightToNormal(filter) => { @@ -1164,21 +1170,14 @@ fn fxaa_texel((x, y): (f32, f32), comps: usize, center: &[f32], acc: &mut [f32; fn mirror_texel( mirror: &Mirror, (x, y): (f32, f32), - (block, res): (u32, u32), + (block, tile): ([u32; 2], [u32; 2]), comps: usize, alpha: Option<&f32>, acc: &mut [f32; 5], sample: &dyn Fn(f32, f32, &mut [f32; 5]), ) { - let (block, size) = (block.max(1) as f32, res.max(1) as f32); - let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); - let (local_x, local_y) = (x - origin_x, y - origin_y); - if local_x >= size || local_y >= size { - return; - } - - let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; - let line = (Mirror::DEBUG_HALF_WIDTH * size / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size; + let Some(([origin_x, origin_y], uv, size)) = tile_local((x, y), (block, tile)) else { return }; + let line = (Mirror::DEBUG_HALF_WIDTH * size[0] / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size[0]; if mirror.debug && mirror.on_axis(uv, line) { // Content stays premultiplied by its own coverage; masks are one value let cover = if comps == 4 { alpha.copied().unwrap_or(0.0) } else { 1.0 }; @@ -1192,8 +1191,21 @@ fn mirror_texel( let [u, v] = mirror.source(uv); // Whole texels, so an even mirror copies texels exactly - let at = |origin: f32, along: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0); - sample(at(origin_x, u), at(origin_y, v), acc); + let at = |origin: f32, along: f32, size: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0); + sample(at(origin_x, u, size[0]), at(origin_y, v, size[1]), acc); +} + +/// The top left of the UV tile holding texel `(x, y)` (tiles of `tile` texels at the top left of +/// `block`-texel atlas blocks), the texel centre's UV in it and the tile's size, both per axis; +/// None past the tile. +fn tile_local((x, y): (f32, f32), (block, tile): ([u32; 2], [u32; 2])) -> Option<([f32; 2], [f32; 2], [f32; 2])> { + let (block, size) = (block.map(|b| b.max(1) as f32), tile.map(|t| t.max(1) as f32)); + let origin = [(x / block[0]).floor() * block[0], (y / block[1]).floor() * block[1]]; + let local = [x - origin[0], y - origin[1]]; + if local[0] >= size[0] || local[1] >= size[1] { + return None; + } + Some((origin, [(local[0] + 0.5) / size[0], (local[1] + 0.5) / size[1]], size)) } /// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`res` texels from its `block`'s top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty @@ -1201,21 +1213,14 @@ fn transform_texel( transform: &TileTransform, (columns, shift): ([[f32; 2]; 2], [f32; 2]), (x, y): (f32, f32), - (block, res): (u32, u32), + (block, tile): ([u32; 2], [u32; 2]), acc: &mut [f32; 5], sample: &dyn Fn(f32, f32, &mut [f32; 5]), ) { - let (block, size) = (block.max(1) as f32, res.max(1) as f32); - let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); - let (local_x, local_y) = (x - origin_x, y - origin_y); - if local_x >= size || local_y >= size { - return; - } - - let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; + let Some(([origin_x, origin_y], uv, size)) = tile_local((x, y), (block, tile)) else { return }; // Texel space of the tile, centres at whole numbers - let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size - 0.5); + let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size[axis] - 0.5); if !at.iter().all(|a| a.is_finite()) { return; } @@ -1230,7 +1235,7 @@ fn transform_texel( } let (cx, cy) = (base_x + dx, base_y + dy); - let inside = (0.0..size).contains(&cx) && (0.0..size).contains(&cy); + let inside = (0.0..size[0]).contains(&cx) && (0.0..size[1]).contains(&cy); if !repeat && !inside { // Empty: no value, full weight total[4] += k; @@ -1239,7 +1244,7 @@ fn transform_texel( // One whole texel: the sample's own weights, so this matches its bilinear read let mut one = [0.0f32; 5]; - sample(origin_x + cx.rem_euclid(size), origin_y + cy.rem_euclid(size), &mut one); + sample(origin_x + cx.rem_euclid(size[0]), origin_y + cy.rem_euclid(size[1]), &mut one); for (slot, value) in total.iter_mut().zip(one) { *slot += value * k; } @@ -1615,7 +1620,7 @@ fn filter_extent(radius: f32, op: Op, inputs: &Inputs) -> (u32, u32) { _ => None, }; let source_reach = if tiled_source.is_some_and(|source| source.mode != WarpSourceMode::DefaultNoise && source.tiling_factor() != 1.0) { - inputs.tile_grid().map_or(longest_side, |_| inputs.tile_res()) + inputs.tile_grid().map_or(longest_side, |_| inputs.block_size().into_iter().max().unwrap_or(0)) } else { 0 }; @@ -1825,7 +1830,7 @@ fn filter_region( // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let (block_size, tiled) = match inputs.tile_grid() { - Some(_) => ([inputs.tile_res(); 2], true), + Some(_) => (inputs.block_size(), true), None => ([inputs.gbuf.width, inputs.gbuf.height], false), }; let filtered = |scale: f32| -> Vec { @@ -1838,7 +1843,7 @@ fn filter_region( let scaled = neighbourhood_filters(effects, tile_resolution, channel).find(|filter| filter.0 == index); let scaled_radius = scaled.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); if !is_box_blur(op) { - let tile_size = if tiled { [tile_resolution; 2] } else { block_size }; + let tile_size = if tiled { block_size.map(|side| ((side as f32 * scale).round() as u32).max(1)) } else { block_size }; return gather( op, (&stack_values, &cover, &grays), @@ -5525,6 +5530,17 @@ mod tests { run_with_images(f, preview, &ImageStore::default()) } + #[test] + fn a_mirror_on_a_wide_set_reflects_across_its_own_height() { + let mirror = Mirror { mode: texturecraft_core::MirrorMode::AxisY, ..Mirror::LIBRARY }; + let (size, near_bottom) = ([256, 128], 120.0); + let read = std::cell::Cell::new(None); + mirror_texel(&mirror, (10.0, near_bottom), (size, size), 4, None, &mut [0.0; 5], &|x, y, _| read.set(Some((x, y)))); + let (x, y) = read.get().unwrap(); + assert_eq!(x, 10.0); + assert!(y < size[1] as f32 / 2.0, "the bottom half copies the top half: read row {y}"); + } + #[test] fn a_mirrored_fill_culls_against_the_mesh_in_each_copy_view() { let mut fixture = fixture(); diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 0f3b99b2..17aa3544 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -57,6 +57,7 @@ pub(crate) fn field_identity(inputs: &Inputs) -> u64 { mesh.submeshes.iter().for_each(|part| (part.material, part.start, part.count).hash(&mut hash)); set.uv_tiles.hash(&mut hash); set.resolution.hash(&mut hash); + set.resolution_height.hash(&mut hash); set.tile_resolutions.hash(&mut hash); } diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index fd939909..7dec5ca6 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -55,8 +55,12 @@ pub struct TextureSet { pub description: String, /// Material index in the mesh this set paints. pub material: usize, - /// Power of two, 128..=8192. + /// Texels across: a power of two, 128..=8192 (the side of a square set). pub resolution: u32, + /// Texels down when they differ from `resolution` (a non-square set); a power of two, + /// 128..=8192. Sets with per-tile resolutions stay square. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resolution_height: Option, pub channels: Vec<(Channel, ChannelFormat)>, /// Top-level layers, bottom → top. pub stack: Vec, @@ -173,6 +177,7 @@ impl TextureSet { description: String::new(), material, resolution, + resolution_height: None, channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(), stack: Vec::new(), normal_mixing: NormalMixing::Combine, @@ -204,16 +209,42 @@ impl TextureSet { self.height_strength / self.tile_grid().map_or(1.0, |g| g.cols as f32) } + /// Columns over rows of the atlas grid (1 for a classic set): how much more slopes down the texture tilt than across it, as in export per block + pub fn atlas_height_y_factor(&self) -> f32 { + self.tile_grid().map_or(1.0, |g| g.cols as f32 / g.rows.max(1) as f32) + } + /// Whether the height slope joins the shaded normal ([`NormalMixing::Replace`] leaves it out) pub fn height_in_normal(&self) -> bool { self.normal_mixing == NormalMixing::Combine } - /// Texels across and down: [`TextureSet::block_resolution`] per block of the atlas grid. + /// Texels across and down: [`TextureSet::block_size`] per block of the atlas grid. pub fn size(&self) -> (u32, u32) { let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); + let (width, height) = self.block_size(); + (width.saturating_mul(cols), height.saturating_mul(rows)) + } + + /// Texels down of the set's size (`resolution` for a square set). + pub fn height(&self) -> u32 { + self.resolution_height.unwrap_or(self.resolution) + } + + /// Set the size to `width × height` (None when square). + pub fn set_size(&mut self, width: u32, height: u32) { + self.resolution = width; + self.resolution_height = (height != width).then_some(height); + } + + /// Texels across and down of an atlas block: the set's size, or the largest tile + /// resolution square when tiles have their own. + pub fn block_size(&self) -> (u32, u32) { + if self.tile_resolutions.is_empty() { + return (self.resolution, self.height()); + } let block = self.block_resolution(); - (block.saturating_mul(cols), block.saturating_mul(rows)) + (block, block) } /// Texels per side of UV tile `udim` (its override, else `resolution`). @@ -221,8 +252,8 @@ impl TextureSet { self.tile_resolutions.get(&udim).copied().unwrap_or(self.resolution) } - /// Texels per side of an atlas block: the largest tile resolution (`resolution` for a - /// classic set or one without overrides). + /// Texels across an atlas block: the largest tile resolution (`resolution` for a + /// classic set or one without overrides); see [`TextureSet::block_size`] for both sides. pub fn block_resolution(&self) -> u32 { if self.tile_resolutions.is_empty() { return self.resolution; @@ -733,6 +764,12 @@ impl Project { if let Some(t) = self.texture_sets.iter().find(|t| bad_tile_res(t)) { return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tile resolutions {:?}", t.name, t.tile_resolutions))); } + let bad_height = |t: &TextureSet| { + t.resolution_height.is_some_and(|h| !h.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&h) || !t.tile_resolutions.is_empty()) + }; + if let Some(t) = self.texture_sets.iter().find(|t| bad_height(t)) { + return Err(CoreError::Invalid(format!("texture set \"{}\" has an invalid height {:?}", t.name, t.resolution_height))); + } let mut seen = BTreeSet::new(); for ts in 0..self.texture_sets.len() { for (id, depth) in self.walk(ts) { @@ -1065,6 +1102,47 @@ mod tests { } } + #[test] + fn atlas_slopes_along_each_side_match_a_block_in_wide_tall_and_square_grids() { + let mut t = TextureSet::new("a", 0, 256); + t.height_strength = 3.0; + for tiles in [vec![1001, 1002], vec![1001, 1011], vec![1001, 1002, 1011, 1012], vec![1001, 1002, 1003]] { + t.uv_tiles = tiles; + let ((width, height), (block_width, block_height)) = (t.size(), t.block_size()); + + let across = t.atlas_height_strength() * width as f32; + let down = t.atlas_height_strength() * t.atlas_height_y_factor() * height as f32; + + assert_eq!(across, t.height_strength * block_width as f32, "{:?}", t.uv_tiles); + assert_eq!(down, t.height_strength * block_height as f32, "{:?}", t.uv_tiles); + } + } + + #[test] + fn non_square_sets_are_wider_than_tall_per_block_and_stay_square_with_tile_sizes() { + let mut p = project(); + let t = &mut p.texture_sets[0]; + t.set_size(1024, 256); + let (w, h) = t.size(); + assert!(w > h, "{:?}", t.size()); + t.uv_tiles = vec![1001, 1011]; + // Tiles stack down, each block keeping the set's shape + assert_eq!(t.size(), (w, h * 2)); + p.validate().unwrap(); + // A height must be a valid size, and per-tile sizes need a square set + for bad in [Some(100), Some(16384)] { + let mut q = p.clone(); + q.texture_sets[0].resolution_height = bad; + assert!(q.validate().is_err(), "{bad:?}"); + } + let mut q = p.clone(); + q.texture_sets[0].tile_resolutions.insert(1011, 128); + assert!(q.validate().is_err()); + // The same size both ways is stored as square + p.texture_sets[0].set_size(512, 512); + assert_eq!(p.texture_sets[0].resolution_height, None); + } + #[test] fn validate_rejects_newer_formats_and_dangling_ids() { let mut p = project(); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index cafee7a6..4b3ee9b6 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -100,7 +100,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)", + "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size (width), height, sourceSize, sourceHeight, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)", always, plan ), @@ -491,6 +491,10 @@ fn plan(session: &mut Session, params: &Value) -> Result { let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile)); let size = scale_export_side(source_size, block_size, options.size); + // Non-square sets have no tile sizes of their own + let source_height = if set.resolution_height.is_some() { set.height() } else { source_size }; + let height = scale_export_side(source_height, block_size, options.size); + files.push(json!({ "ts": set_index, "map": output.map, @@ -499,7 +503,9 @@ fn plan(session: &mut Session, params: &Value) -> Result { "bitDepth": output.bit_depth, "dithering": output.dither, "size": size, + "height": height, "sourceSize": source_size, + "sourceHeight": source_height, "warnings": output.warnings, })); } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 292bdbf3..34a0c968 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -265,6 +265,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "index": index, "name": texture_set.name, "resolution": texture_set.resolution, + "height": texture_set.height(), "size": texture_set.size(), "blockResolution": texture_set.block_resolution(), "uvTiles": texture_set.uv_tiles, diff --git a/crates/engine/src/mask_export.rs b/crates/engine/src/mask_export.rs index 9156b884..c094a426 100644 --- a/crates/engine/src/mask_export.rs +++ b/crates/engine/src/mask_export.rs @@ -42,20 +42,22 @@ impl Session { let (width, height, values) = atlas; let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?; let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) }; - let block = set.block_resolution(); + let (block_width, block_height) = set.block_size(); set.uv_tiles .iter() .map(|&tile| { let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?; // A tile smaller than its block fills the block's top-left corner - let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block); - let mut tile_values = Vec::with_capacity(side as usize * side as usize); - for row in 0..side { - let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize; - tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[])); + let scale = set.tile_scale(tile); + let tile_width = ((block_width as f32 * scale).round() as u32).clamp(1, block_width); + let tile_height = ((block_height as f32 * scale).round() as u32).clamp(1, block_height); + let mut tile_values = Vec::with_capacity(tile_width as usize * tile_height as usize); + for row in 0..tile_height { + let start = ((block_y * block_height + row) as usize) * width as usize + (block_x * block_width) as usize; + tile_values.extend_from_slice(values.get(start..start + tile_width as usize).unwrap_or(&[])); } - Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values }) + Ok(MaskBitmap { tile: Some(tile), width: tile_width, height: tile_height, values: tile_values }) }) .collect() } diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 758ee3b6..eb98f842 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -66,6 +66,7 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { let mut project = Project::new(name, "builtin:none"); let mut set = TextureSet::new(name, 0, src_set.resolution); + set.resolution_height = src_set.resolution_height; set.uv_tiles = src_set.uv_tiles.clone(); set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 1ed8dcbd..a271356d 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -97,8 +97,7 @@ pub(crate) fn padding_seams(mesh: &Mesh, ts: &TextureSet) -> Vec { /// The viewport's padding of `ts`, which stays inside each UV tile fn display_padding(mesh: &Mesh, ts: &TextureSet, gbuf: &UvGBuffer) -> PaddingMaps { - let block = ts.block_resolution(); - PaddingMaps::new(ts.uv_padding, &gbuf.coverage_mask(), (gbuf.width, gbuf.height), Some(DISPLAY_PADDING), (block, block), &padding_seams(mesh, ts)) + PaddingMaps::new(ts.uv_padding, &gbuf.coverage_mask(), (gbuf.width, gbuf.height), Some(DISPLAY_PADDING), ts.block_size(), &padding_seams(mesh, ts)) } /// Active tool. diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index f9302e3c..a56dc2aa 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -20,11 +20,19 @@ pub fn specs() -> Vec { "Inspect texture set", [], None, - "{ts?} → {index, name, resolution, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, active}", + "{ts?} → {index, name, resolution, height, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, active}", always, |s, p| Ok(crate::inspect::texture_set(s, ts_param(s, p, "textureSet.inspect")?)) ), - cmd!("textureSet.resolution", "Texture set size", [], None, "{ts?, resolution: 128..8192 (power of two)}", always, resolution), + cmd!( + "textureSet.resolution", + "Texture set size", + [], + None, + "{ts?, resolution: 128..8192 (power of two, texels across), height?: 128..8192 (texels down; default = resolution, a square set)}", + always, + resolution + ), cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)), cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)), cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible), @@ -112,7 +120,8 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> { fn resolution(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.resolution")?; let r = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?; - let task = s.resize_task(ts, u32::try_from(r).unwrap_or(0))?; + let height = u64p(p, "height").unwrap_or(r); + let task = s.resize_task_to(ts, u32::try_from(r).unwrap_or(0), u32::try_from(height).unwrap_or(0))?; let out = task.run(&texturecraft_bake::Progress::new())?; s.apply_resize(out) } @@ -123,6 +132,7 @@ fn resolution(s: &mut Session, p: &Value) -> Result { pub struct ResizeTask { ts: usize, resolution: u32, + height: u32, doc: Document, mesh: Arc, /// The session's revision and mesh when the task was made: the result applies only to them. @@ -133,6 +143,7 @@ pub struct ResizeTask { pub struct ResizeOutput { ts: usize, resolution: u32, + height: u32, doc: Document, /// The set's new caches (None when its UV tile layout moved: the session rebuilds them). cache: Option, @@ -144,10 +155,13 @@ impl ResizeTask { /// Resample the set's painted pixels (bilinear; strokes are not replayed) and build its /// caches. Progress goes from 0 to 1. pub fn run(self, progress: &texturecraft_bake::Progress) -> Result { - let ResizeTask { ts, resolution, mut doc, mesh, from } = self; + let ResizeTask { ts, resolution, height, mut doc, mesh, from } = self; let set = doc.project.texture_set_mut(ts)?; let old = set.clone(); - set.resolution = resolution; + set.set_size(resolution, height); + if set.resolution_height.is_some() && !set.tile_resolutions.is_empty() { + return Err(bad("textureSet.resolution", "a texture set whose UV tiles have their own sizes stays square")); + } crate::session::check_size(set)?; let size = set.size(); let mut log = crate::log::SessionLog::new(); @@ -162,7 +176,7 @@ impl ResizeTask { let set = doc.project.texture_set(ts)?; let cache = (crate::session::uv_layout(&old) == crate::session::uv_layout(set)).then(|| SetCache::new(&mesh, set)); progress.done.store(10_000, std::sync::atomic::Ordering::Relaxed); - Ok(ResizeOutput { ts, resolution, doc, cache, log, from }) + Ok(ResizeOutput { ts, resolution, height, doc, cache, log, from }) } } @@ -174,23 +188,28 @@ impl ResizeOutput { } impl Session { - /// Prepare resizing texture set `ts` to `resolution` (a power of two, 128..8192). + /// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192). pub fn resize_task(&mut self, ts: usize, resolution: u32) -> Result { - let resolution = check_resolution(resolution)?; + self.resize_task_to(ts, resolution, resolution) + } + + /// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192). + pub fn resize_task_to(&mut self, ts: usize, width: u32, height: u32) -> Result { + let (resolution, height) = (check_resolution(width)?, check_resolution(height)?); self.doc.project.texture_set(ts)?; self.cancel_stroke(); - Ok(ResizeTask { ts, resolution, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) }) + Ok(ResizeTask { ts, resolution, height, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) }) } /// Apply a finished resize as one undo step. When the document changed while it ran, the /// resize runs again here on the current document. pub fn apply_resize(&mut self, out: ResizeOutput) -> Result { if out.from != (self.revision, self.mesh_id) || self.stroke_active() { - let task = self.resize_task(out.ts, out.resolution)?; + let task = self.resize_task_to(out.ts, out.resolution, out.height)?; return self.apply_resize(task.run(&texturecraft_bake::Progress::new())?); } - let ResizeOutput { ts, resolution, doc, cache, log, .. } = out; + let ResizeOutput { ts, resolution, height, doc, cache, log, .. } = out; let before = std::mem::replace(&mut self.doc, doc); // Install the new caches before adding history to avoid rebuilding them @@ -205,7 +224,7 @@ impl Session { } self.log.append(log); self.push_history("Texture set size", before); - Ok(json!({ "ts": ts, "resolution": resolution })) + Ok(json!({ "ts": ts, "resolution": resolution, "height": height })) } } diff --git a/crates/engine/src/uv_tile_cmds.rs b/crates/engine/src/uv_tile_cmds.rs index 1b6e23fc..ce2481d8 100644 --- a/crates/engine/src/uv_tile_cmds.rs +++ b/crates/engine/src/uv_tile_cmds.rs @@ -50,6 +50,10 @@ fn tile_resolution(session: &mut Session, params: &Value) -> Result { return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles))); } + if texture_set.resolution_height.is_some() && resolution != texture_set.resolution { + return Err(bad(COMMAND, format!("UV tiles of a non-square texture set (\"{}\") can't have their own size", texture_set.name))); + } + let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile); if texture_set.tile_resolution(tile) == resolution && !removes_override { return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() })); @@ -299,6 +303,11 @@ mod tests { } } + /// Width and height of a PNG file, read from its header + fn png_size(bytes: &[u8]) -> (u32, u32) { + image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png).into_dimensions().unwrap() + } + /// Mean painted alpha over the covered texels of the set's current layout. fn painted_fraction(s: &Session) -> f64 { let id = s.doc.project.texture_sets[0].stack[0]; @@ -374,8 +383,6 @@ mod tests { execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap(); let files = s.export_files(&[0], &opts).unwrap(); - // PNG: width and height are the big-endian words after the IHDR tag. - let png_size = |b: &[u8]| (u32::from_be_bytes(b[16..20].try_into().unwrap()), u32::from_be_bytes(b[20..24].try_into().unwrap())); assert!(files.len() >= 4); for f in &files { let want = if f.name.contains("1002") { 128 } else { 256 }; @@ -383,6 +390,33 @@ mod tests { } } + #[test] + fn non_square_sets_keep_their_paint_export_wide_tiles_and_refuse_tile_sizes() { + let mut s = udim_session(); + paint_all(&mut s, 50000); + execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).unwrap(); + s.update(); + let (w, h) = s.doc.project.texture_sets[0].size(); + assert!(w > 2 * h, "two tiles side by side, each wider than tall: {:?}", (w, h)); + assert_eq!((s.caches[0].gbuf.width, s.caches[0].gbuf.height), (w, h)); + assert!(painted_fraction(&s) > 0.97); + let inspect = execute(&mut s, "textureSet.inspect", &json!({})).unwrap(); + assert!(inspect["height"].as_u64() < inspect["resolution"].as_u64()); + + let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap(); + for f in &s.export_files(&[0], &opts).unwrap() { + let (fw, fh) = png_size(&f.bytes); + assert!(fw > fh, "{} is {fw}x{fh}", f.name); + } + + assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).is_err()); + s.undo().unwrap(); + assert_eq!(s.doc.project.texture_sets[0].size(), (512, 256)); + // A set whose tiles have their own sizes stays square + execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + assert!(execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).is_err()); + } + /// Paint channel `c` of the first layer over every covered texel as `f(u)`, `u` the texel's /// position across its own UV tile (0..1), so every tile shows the same pattern in UV space. fn paint_across_tiles(s: &mut Session, c: Channel, f: impl Fn(f32) -> Vec) { diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index e369aa95..ed79cb96 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -612,7 +612,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let mut out = Vec::new(); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; let grid = set.tile_grid(); - let block_resolution = set.block_resolution(); + let (block_resolution, block_size) = (set.block_resolution(), set.block_size()); + let scale = |side| scale_export_side(side, block_resolution, opts.size); for (i, map) in opts.preset.maps.iter().enumerate() { if !map.channels.iter().any(|(_, s)| source_present(set, s)) { continue; @@ -641,19 +642,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export for &tile in &tiles { if let Some(channels) = psd_channels { let size = match (tile, grid) { - (Some(tile), Some(_)) => { + (Some(tile), Some(_)) if !set.tile_resolutions.is_empty() => { let side = tile_side(set, tile, block_resolution); let side = scale_export_side(side, block_resolution, opts.size); (side, side) } - (_, Some(grid)) => { - let side = opts.size.unwrap_or(block_resolution); - (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) - } - (_, None) => { - let side = opts.size.unwrap_or(block_resolution); - (side, side) - } + (Some(_), Some(_)) | (_, None) => (scale(block_size.0), scale(block_size.1)), + (_, Some(grid)) => (scale(block_size.0).saturating_mul(grid.cols), scale(block_size.1).saturating_mul(grid.rows)), }; check_psd_size(size, channels, bit_depth)?; } @@ -774,9 +769,9 @@ struct Sampler<'a> { coverage: &'a [bool], /// Composite width. res: u32, - /// Texels per atlas block (`res` for a classic set): the height slope and the slope window - /// follow the block. - tile_res: u32, + /// Texels across and down an atlas block (the composite for a classic set): the height + /// slope and the slope window follow the block. + block: (u32, u32), /// The share of its block each tile fills: a smaller tile's height slope shrinks with it. scales: BlockScales, /// Normal convention overriding every normal output. @@ -820,16 +815,18 @@ impl Sampler<'_> { fn height_normal(&self, x: u32, y: u32) -> Vec3 { let center = self.channel(Channel::Height, At::Texel(x, y))[0]; // Clamped to the texel's UV tile. - let t = self.tile_res.max(1); - let (x0, y0, last) = ((x / t * t) as i64, (y / t * t) as i64, t as i64 - 1); + let (tw, th) = (self.block.0.max(1), self.block.1.max(1)); + let (x0, y0) = ((x / tw * tw) as i64, (y / th * th) as i64); let h = |dx: i32, dy: i32| { - let (sx, sy) = ((x as i64 + dx as i64).clamp(x0, x0 + last) as u32, (y as i64 + dy as i64).clamp(y0, y0 + last) as u32); + let (sx, sy) = ((x as i64 + dx as i64).clamp(x0, x0 + tw as i64 - 1) as u32, (y as i64 + dy as i64).clamp(y0, y0 + th as i64 - 1) as u32); if self.covered(sx, sy) { self.channel(Channel::Height, At::Texel(sx, sy))[0] } else { center } }; let [gx, gy] = self.set.height_to_normal.slope(h); - let s = self.set.height_strength * self.tile_res as f32 * self.scales.at(x, y) / HEIGHT_SPAN; + // Slopes per texel become slopes across the tile along each side + let s = self.set.height_strength * self.scales.at(x, y) / HEIGHT_SPAN; + let (sx, sy) = (s * tw as f32, s * th as f32); // Image y points down; OpenGL normals have +Y up the image. - Vec3::new(-gx * s, gy * s, 1.0).try_normalize().unwrap_or(Vec3::Z) + Vec3::new(-gx * sx, gy * sy, 1.0).try_normalize().unwrap_or(Vec3::Z) } /// The final tangent-space normal (OpenGL): baked normal ⊕ (height ⊕ normal channel). @@ -911,8 +908,9 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned let set = input.project.texture_set(input.ts)?; let (width, height) = (input.composite.resolution, input.composite.height); let grid = set.tile_grid(); - let tile_res = width / grid.map_or(1, |g| g.cols.max(1)); - if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { + let (cols, rows) = grid.map_or((1, 1), |g| (g.cols.max(1), g.rows.max(1))); + let (tile_res, tile_height) = (width / cols, height / rows); + if tile_res == 0 || tile_height == 0 || tile_res.max(tile_height) > MAX_IMAGE_SIZE || (width, height) != (tile_res * cols, tile_height * rows) { return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); } @@ -925,7 +923,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned } // Padding stays inside each UV tile - let padding_maps = |max_dist| PaddingMaps::new(set.uv_padding, input.coverage, (width, height), max_dist, (tile_res, tile_res), input.seams); + let padding_maps = |max_dist| PaddingMaps::new(set.uv_padding, input.coverage, (width, height), max_dist, (tile_res, tile_height), input.seams); let padding = match options.padding { Padding::None => None, Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => Some(padding_maps(Some(d))), @@ -939,7 +937,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned baked: input.baked, coverage: input.coverage, res: width, - tile_res, + block: (tile_res, tile_height), scales: set.block_scales(), normal_override: options.normal_format, project_normal: input.project.normal_format, @@ -961,7 +959,8 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned // A tile smaller than its block fills the block's top-left corner let side = tile_side(set, t, tile_res); - (bx * tile_res, by * tile_res, side, side) + let tile_size = if set.tile_resolutions.is_empty() { (tile_res, tile_height) } else { (side, side) }; + (bx * tile_res, by * tile_height, tile_size.0, tile_size.1) } _ => (0, 0, width, height), }; @@ -1010,8 +1009,8 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned .collect(); // Keep diffusion within each UV tile when rendering an atlas - let block = if planned_file.tile.is_none() && grid.is_some() { tile_res } else { w.max(h) }; - diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, block as usize); + let block = if planned_file.tile.is_none() && grid.is_some() { (tile_res, tile_height) } else { (w, h) }; + diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, (block.0 as usize, block.1 as usize)); } let mut data = resize(data, (w, h), component_count, size); @@ -1060,16 +1059,16 @@ pub fn scale_export_side(source_side: u32, block_resolution: u32, export_size: O u32::try_from(scaled).unwrap_or(u32::MAX).max(u32::from(source_side > 0)) } -fn diffuse_blocks(data: &mut Vec, (width, height): (usize, usize), channels: usize, known: &[bool], block: usize) { +fn diffuse_blocks(data: &mut Vec, (width, height): (usize, usize), channels: usize, known: &[bool], (block_w, block_h): (usize, usize)) { // A whole image or a separately exported tile already occupies a contiguous buffer - if block >= width.max(height) { + if block_w >= width && block_h >= height { diffuse_fill(data, (width, height), channels, known); return; } - for block_y in (0..height).step_by(block.max(1)) { - for block_x in (0..width).step_by(block.max(1)) { - let (block_width, block_height) = (block.min(width - block_x), block.min(height - block_y)); + for block_y in (0..height).step_by(block_h.max(1)) { + for block_x in (0..width).step_by(block_w.max(1)) { + let (block_width, block_height) = (block_w.min(width - block_x), block_h.min(height - block_y)); let rows = || (block_y..block_y + block_height).map(|y| (y * width + block_x)..(y * width + block_x + block_width)); let mut block_data: Vec = rows().flat_map(|row| data.get(row.start * channels..row.end * channels).unwrap_or_default().iter().copied()).collect(); diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index 001b6feb..78d5b5d2 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -145,6 +145,7 @@ mod tests { material: 0, composite, height_strength: strength, + height_y_factor: 1.0, height_in_normal: true, height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 8b53a605..9f01f130 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -34,8 +34,8 @@ const _: () = assert!(KINDS == 8); /// The placeholder mask word's bit for a set with Smooth (Sobel) height to normal (trace.wgsl reads it) const SMOOTH_HEIGHT_BIT: f32 = (1 << KINDS) as f32; -/// Bytes of the trace uniform: [`Head`] then 256 texture-set entries (`MAX_SETS` in trace.wgsl). -const PARAMS_SIZE: u64 = (size_of::() + 256 * 16) as u64; +/// Bytes of the trace uniform: [`Head`], 256 texture-set entries (`MAX_SETS` in trace.wgsl), then their height slope factors down the texture, four per entry +const PARAMS_SIZE: u64 = (size_of::() + 256 * 16 + 256 * 4) as u64; /// Post uniform slots: resolve and denoise init, then the five à-trous steps. const STEPS: [u32; 6] = [0, 1, 2, 4, 8, 16]; const WORKGROUP: u32 = 8; @@ -103,6 +103,8 @@ struct SceneConst { rotation: f32, env_camera: bool, heights: Vec, + /// Per set: how much more the height slope tilts down the texture than across it + height_y_factors: Vec, /// Per set: Smooth (Sobel) height to normal smooth: Vec, ior: f32, @@ -426,6 +428,7 @@ impl GpuTracer { rotation: scene.env_rotation, env_camera: scene.env_camera, heights: scene.sets.iter().map(crate::trace::TraceSet::normal_height_strength).collect(), + height_y_factors: scene.sets.iter().map(|s| s.height_y_factor).collect(), smooth: scene.sets.iter().map(|s| s.height_to_normal == HeightToNormalMethod::Smooth).collect(), ior: scene.ior, lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]), @@ -627,8 +630,13 @@ impl GpuTracer { let smooth = if sc.smooth.get(i).copied().unwrap_or(false) { SMOOTH_HEIGHT_BIT } else { 0.0 }; *slot = [m[0], m[1], m[2] + smooth, sc.heights.get(i).copied().unwrap_or(0.0)]; } + let mut height_y_factors = [1.0f32; 256]; + for (slot, factor) in height_y_factors.iter_mut().zip(&sc.height_y_factors) { + *slot = *factor; + } let mut bytes = bytemuck::bytes_of(&head).to_vec(); bytes.extend_from_slice(bytemuck::cast_slice(&sets)); + bytes.extend_from_slice(bytemuck::cast_slice(&height_y_factors)); queue.write_buffer(&self.params, 0, &bytes); let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_trace"), timestamp_writes: None }); cpass.set_pipeline(&self.trace_pipe); @@ -853,6 +861,7 @@ mod tests { material: 0, composite, height_strength: 0.0, + height_y_factor: 1.0, height_in_normal: true, height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, }], @@ -1053,6 +1062,7 @@ mod tests { material: 0, composite, height_strength: 0.0, + height_y_factor: 1.0, height_in_normal: true, height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, }], diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 8f3f8fc8..8e474886 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -110,6 +110,7 @@ struct GlobalsRaw { bake_neutral: [f32; 4], bake_bent_normal: [f32; 4], uv_rotation: [f32; 4], + height_slope: [f32; 4], } /// The post pass uniform (see `Post` in post.wgsl). @@ -157,6 +158,8 @@ pub struct Shade { pub env_opacity: f32, pub ao_intensity: f32, pub height_strength: f32, + /// How much more the height slope tilts down the texture than across it ([`texturecraft_core::TextureSet::atlas_height_y_factor`]) + pub height_y_factor: f32, /// The height slope joins the shaded normal (normal mixing Combine; Replace leaves it out) pub height_in_normal: bool, /// How the height becomes normal slopes @@ -299,6 +302,7 @@ impl Default for Shade { env_opacity: 0.0, ao_intensity: 0.75, height_strength: 1.0, + height_y_factor: 1.0, height_in_normal: true, height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, normal_y: 1.0, @@ -2142,6 +2146,7 @@ impl Renderer { scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }], fwd: [fwd.x, fwd.y, fwd.z, 0.0], disp: [disp[0], disp[1], disp[2], if s.height_in_normal { 1.0 } else { 0.0 }], + height_slope: [1.0, s.height_y_factor, 0.0, 0.0], refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data), highlight_shift: highlight_shift(frame.size), diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index cd6a54ee..05b1a620 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -36,6 +36,7 @@ struct Globals { bake_neutral: vec4, // x roughness, y metallic, z AO intensity of the neutral material, w on (1) bake_bent_normal: vec4, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw - uv_rotation: vec4, // UV view: x cos, y sin of the view rotation (counter-clockwise on screen), z view aspect (width / height); w Smooth (Sobel) height to normal (1) or Sharp (0) + height_slope: vec4, // xy height slope factors across and down the texture (y: columns over rows of a UV tile grid), zw - }; @group(0) @binding(0) var g: Globals; @@ -492,11 +493,10 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let hgt = textureSample(t_height, samp, uv); let hc = hgt.r; - // Match export: a unit height over 1/16 of the width tilts 45° - // Combine the height gradient with the tangent-space normal - let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(uv); + // Match export (a unit height over 1/16 of a block's width or height tilts 45°), then combine with the tangent-space normal + let k = g.mode.z * g.disp.w * dims * g.height_slope.xy / 16.0 * tile_scale(uv); let slope = height_slope(uv, ts); - let n_height = normalize(vec3(-slope.x * k, slope.y * k, 1.0)); + let n_height = normalize(vec3(-slope.x * k.x, slope.y * k.y, 1.0)); // The Normal texture holds the signed normal in half floats (flat is exactly +z) var n_detail = clamp(nrm_s, vec3(-1.0), vec3(1.0)); @@ -736,9 +736,9 @@ fn fs_uv(i: VOut) -> @location(0) vec4 { // The tangent-space normal the shading uses: the height slope turned by the normal channel let dims = vec2(textureDimensions(t_height)); let ts = 1.0 / dims; - let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(i.uv); + let k = g.mode.z * g.disp.w * dims * g.height_slope.xy / 16.0 * tile_scale(i.uv); let slope = height_slope(i.uv, ts); - let n_height = normalize(vec3(-slope.x * k, slope.y * k, 1.0)); + let n_height = normalize(vec3(-slope.x * k.x, slope.y * k.y, 1.0)); var n_detail = clamp(textureSample(t_nrm, samp, i.uv).rgb, vec3(-1.0), vec3(1.0)); n_detail.y *= g.mode.w; return raw_out(rnm(n_height, normalize(n_detail)) * 0.5 + 0.5); diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index 2e2ea99a..f25530d1 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -8,6 +8,8 @@ const TAU: f32 = 6.28318530717959; const BIG: f32 = 3.0e38; const WALK_STEPS: u32 = 48u; const MAX_SETS: u32 = 256u; +// MAX_SETS / 4: the height slope factors pack four sets to an entry +const HEIGHT_Y_FACTOR_ENTRIES: u32 = 64u; struct Params { inv_vp: mat4x4, @@ -18,8 +20,10 @@ struct Params { sigma: vec4, // subsurface extinction per color channel eye: vec4, // camera position lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR - // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds (bit 8: Smooth (Sobel) height to normal), height strength. + // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds (bit 8: Smooth (Sobel) height to normal), height strength sets: array, MAX_SETS>, + // Per texture set, four to an entry: how much more the height slope tilts down the texture than across it + height_y_factors: array, HEIGHT_Y_FACTOR_ENTRIES>, }; @group(0) @binding(0) var P: Params; @@ -209,7 +213,6 @@ fn occluded(o: vec3, d: vec3) -> bool { // ---- Materials ---- -// Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy). // The change of height per texel to the right and down: Sobel when smooth, else the neighbours across (as HeightToNormalMethod::slope) fn height_slope(layer: u32, uv: vec2, sobel: bool) -> vec2 { let r = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r; @@ -226,6 +229,7 @@ fn height_slope(layer: u32, uv: vec2, sobel: bool) -> vec2 { return vec2(ru + 2.0 * r + rd - lu - 2.0 * l - ld, ld + 2.0 * d + rd - lu - 2.0 * u - ru) / 8.0; } +// Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy). fn texel(layer: u32, k: u32, uv: vec2, dx: i32, dy: i32) -> vec2 { let info = P.sets[layer]; let small = ((u32(info.z) >> k) & 1u) == 1u; @@ -315,11 +319,11 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { let info = P.sets[layer]; // Extra alpha stores 32 × log2(1 / UV tile scale) - let k = info.w * info.x / 16.0 * exp2(-extra.a * 255.0 / 32.0); + let k = info.w * info.xy * vec2(1.0, P.height_y_factors[layer / 4u][layer % 4u]) / 16.0 * exp2(-extra.a * 255.0 / 32.0); var n_height = vec3(0.0, 0.0, 1.0); - if (k != 0.0) { + if (info.w != 0.0) { let slope = height_slope(layer, uv, ((u32(info.z) >> 8u) & 1u) == 1u); - n_height = normalize_or(vec3(-slope.x * k, slope.y * k, 1.0), vec3(0.0, 0.0, 1.0)); + n_height = normalize_or(vec3(-slope.x * k.x, slope.y * k.y, 1.0), vec3(0.0, 0.0, 1.0)); } // The signed normal in half floats, as in mesh.wgsl (flat is exactly +z) diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index bc458eae..1eae4bb3 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -29,6 +29,9 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera}; use crate::ibl::EnvImage; +/// A unit height over this share of a side tilts the normal 45°, as in export +const HEIGHT_SPAN: f32 = 16.0; + /// One texture set's composited channels. #[derive(Clone)] pub struct TraceSet { @@ -37,6 +40,8 @@ pub struct TraceSet { pub composite: Composite, /// Height displacement and, with `height_in_normal`, height-to-normal strength pub height_strength: f32, + /// How much more the height slope tilts down the texture than across it ([`texturecraft_core::TextureSet::atlas_height_y_factor`]) + pub height_y_factor: f32, pub height_in_normal: bool, pub height_to_normal: HeightToNormalMethod, } @@ -582,14 +587,15 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 s.composite.value(c, x, y) }; let base = Vec3::from(ch(Channel::BaseColor, 0, 0)); - // A UV tile smaller than its atlas block has fewer texels per UV unit: slopes per texel shrink. - let k = set.map_or(0.0, |s| { + // Slopes per texel become slopes across the set along each side (less in a UV tile smaller than its block) + let slope_scale = set.map_or(Vec2::ZERO, |s| { let (x, y) = texel(s, 0, 0); - s.normal_height_strength() * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) + let strength = s.normal_height_strength() / HEIGHT_SPAN * s.composite.block_scales.at(x, y); + Vec2::new(s.composite.resolution as f32, s.composite.height as f32 * s.height_y_factor) * strength }); - let n_height = if k != 0.0 { + let n_height = if slope_scale != Vec2::ZERO { let [gx, gy] = set.map_or(HeightToNormalMethod::Smooth, |s| s.height_to_normal).slope(|dx, dy| ch(Channel::Height, dx, dy)[0]); - Vec3::new(-gx * k, gy * k, 1.0).normalize_or(Vec3::Z) + Vec3::new(-gx * slope_scale.x, gy * slope_scale.y, 1.0).normalize_or(Vec3::Z) } else { Vec3::Z }; @@ -1250,6 +1256,7 @@ mod tests { material: 0, composite, height_strength: 0.0, + height_y_factor: 1.0, height_in_normal: true, height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, }], @@ -1258,6 +1265,58 @@ mod tests { ) } + /// How far the shaded normal of a plane leans from straight up under a height ramp along x or along y over `texture_set`'s atlas + fn ramp_tilt(texture_set: &texturecraft_core::TextureSet, along_x: bool) -> f32 { + let mesh = Arc::new(primitives::plane(2.0, 1)); + let bvh = Arc::new(Bvh::new(&mesh)); + let ((width, height), (block_width, block_height)) = (texture_set.size(), texture_set.block_size()); + let mut composite = Composite::with_size(&[Channel::Height], width, height); + let img = composite.channels.get_mut(&Channel::Height).unwrap(); + for y in 0..height { + for x in 0..width { + // The same rise per block side along either side + let rise = if along_x { x as f32 / block_width as f32 } else { y as f32 / block_height as f32 }; + img.set(x, y, &[texturecraft_texel::to_u16(rise * 0.5)]); + } + } + let set = TraceSet { + material: 0, + composite, + height_strength: texture_set.atlas_height_strength(), + height_y_factor: texture_set.atlas_height_y_factor(), + height_in_normal: true, + height_to_normal: HeightToNormalMethod::Sharp, + }; + let env = Arc::new(EnvImage { width: 8, height: 4, data: vec![[1.0; 3]; 32] }); + let s = TraceScene::new(mesh, bvh, vec![set], env, 0.0); + let (o, d) = (Vec3::new(0.1, 1.0, 0.1), Vec3::NEG_Y); + let hit = s.bvh.closest(o, d, f32::MAX).unwrap(); + let surf = surface(&s, hit.tri, hit.u, hit.v, o, d, hit.t).unwrap(); + surf.n.angle_between(Vec3::Y) + } + + #[test] + fn a_wide_set_tilts_the_normal_alike_for_the_same_rise_along_either_side() { + let mut wide = texturecraft_core::TextureSet::new("wide", 0, 128); + wide.set_size(128, 64); + + let (across, down) = (ramp_tilt(&wide, true), ramp_tilt(&wide, false)); + + assert!(across > 0.05, "the ramp tilts the normal: {across}"); + assert!((across - down).abs() < 0.1 * across, "across {across} down {down}"); + } + + #[test] + fn a_uv_tile_row_tilts_the_normal_alike_for_the_same_rise_along_either_side_of_a_tile() { + let mut row = texturecraft_core::TextureSet::new("row", 0, 64); + row.uv_tiles = vec![1001, 1002]; + + let (across, down) = (ramp_tilt(&row, true), ramp_tilt(&row, false)); + + assert!(across > 0.05, "the ramp tilts the normal: {across}"); + assert!((across - down).abs() < 0.1 * across, "across {across} down {down}"); + } + /// Mean radiance of parallel rays over the whole disc of the sphere (grazing hits included) /// in a uniform white environment. fn furnace(values: &[(Channel, [f32; 3])]) -> Vec3 { diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 62c9aa0a..44e4017e 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -260,6 +260,21 @@ fn the_combined_normal_view_shows_the_shading_normal_unlit() { assert_eq!(a.px, b.px, "a data view ignores exposure"); } +#[test] +fn the_height_y_factor_steepens_slopes_down_the_texture_only() { + let Some((mut h, frame)) = setup() else { return }; + let normal_view = shaded(&frame, |s| s.view_mode = 4); + let doubled = shaded(&normal_view, |s| s.height_y_factor = 2.0); + + upload_height(&mut h, |x, _| [x as f32 / 256.0, 0.0, 0.0, 0.0]); + let (across, across_doubled) = (render(&mut h, &normal_view, "height_across"), render(&mut h, &doubled, "height_across_y_doubled")); + upload_height(&mut h, |_, y| [y as f32 / 256.0, 0.0, 0.0, 0.0]); + let (down, down_doubled) = (render(&mut h, &normal_view, "height_down"), render(&mut h, &doubled, "height_down_y_doubled")); + + assert_same(&across, &across_doubled, "a slope across the texture keeps its tilt"); + assert_ne!(down.px, down_doubled.px, "a slope down the texture tilts more"); +} + #[test] fn post_effects() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 1efb19d3..0c405c06 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -51,7 +51,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; let name = texture_set.name.clone(); - let resolution = texture_set.resolution; + let (resolution, height) = (texture_set.resolution, texture_set.height()); let mut is_enabled = texture_set.bake.common.is_enabled; let visible = texture_set.visible; let tiles: Vec<_> = texture_set @@ -71,7 +71,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { } // The name takes the room the resolution leaves, so it only shortens when the row is too narrow - let resolution_text = format!("{resolution}x{resolution}"); + let resolution_text = format!("{resolution}x{height}"); let name_width = (ui.available_width() - resolution_menu_width(ui, &resolution_text) - ui.spacing().item_spacing.x).max(0.0); let name_size = egui::vec2(name_width, ui.spacing().interact_size.y); let name_button = ui.allocate_ui_with_layout(name_size, egui::Layout::left_to_right(egui::Align::Center), |ui| { diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index a59a5f4d..6394c3b0 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -49,10 +49,10 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { .texture_sets .iter() .map(|t| { - let res = t.resolution; + let (width, height) = (t.resolution, t.height()); let size = match t.uv_tiles.len() { - 0 => format!("{res}x{res}"), - n => format!("{res}x{res}, {n} UDIM"), + 0 => format!("{width}x{height}"), + n => format!("{width}x{height}, {n} UDIM"), }; (t.name.clone(), size, t.visible) }) diff --git a/crates/ui-egui/src/filter_properties.rs b/crates/ui-egui/src/filter_properties.rs index 1de8341b..d962d2c2 100644 --- a/crates/ui-egui/src/filter_properties.rs +++ b/crates/ui-egui/src/filter_properties.rs @@ -86,7 +86,7 @@ fn attributes(app: &TextureCraftApp, sheet: &mut PropertySheet<'_>, def: Option< sheet.attribute(tr("Tags"), &about.tags.iter().map(|tag| tr(tag)).collect::>().join(", ")); } if let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) { - sheet.attribute(tr("Size"), &format!("{0} × {0}", texture_set.resolution)); + sheet.attribute(tr("Size"), &format!("{} × {}", texture_set.resolution, texture_set.height())); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f5eb990d..b39d618f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -938,14 +938,18 @@ impl TextureCraftApp { self.session.bake_preview_end(); } - /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when - /// it is done, as one undo step). + /// Resize texture set `ts` to `resolution` texels across on a worker thread, keeping its + /// shape (the document changes when it is done, as one undo step). pub fn start_resize(&mut self, ts: usize, resolution: u32) { if self.resize.is_some() { return; } - match self.session.resize_task(ts, resolution) { + let height = self.session.doc.project.texture_set(ts).map_or(resolution, |set| { + let scaled = u64::from(set.height()) * u64::from(resolution) / u64::from(set.resolution.max(1)); + u32::try_from(scaled).unwrap_or(u32::MAX).clamp(texturecraft_engine::core::MIN_RESOLUTION, texturecraft_engine::core::MAX_RESOLUTION) + }); + match self.session.resize_task_to(ts, resolution, height) { Ok(task) => { let progress = Arc::new(Progress::new()); let p = progress.clone(); diff --git a/crates/ui-egui/src/link_import.rs b/crates/ui-egui/src/link_import.rs index d245ecc5..063584fe 100644 --- a/crates/ui-egui/src/link_import.rs +++ b/crates/ui-egui/src/link_import.rs @@ -18,7 +18,8 @@ pub(super) struct LinkImport { mesh: u64, canceled: Arc, set: usize, - resolution: u32, + /// The set's size when the import started: a resize cancels it + size: (u32, u32), place: Place, result: Receiver>, } @@ -53,7 +54,7 @@ impl TextureCraftApp { ), explicit => explicit, }; - let resolution = texture_set.resolution; + let (resolution, size) = (texture_set.resolution, texture_set.size()); let baked = self.session.baked(set).cloned(); let path = PathBuf::from(path); let canceled = Arc::new(AtomicBool::new(false)); @@ -65,7 +66,7 @@ impl TextureCraftApp { // A pending installation only needs its source package and cooked outputs Ok((source.package, source.source_ext, cooked)) }); - self.link_imports.push(LinkImport { project: self.session.project_id, mesh: self.session.mesh_id, canceled, set, resolution, place, result: rx }); + self.link_imports.push(LinkImport { project: self.session.project_id, mesh: self.session.mesh_id, canceled, set, size, place, result: rx }); self.toast("Cooking MaterialCraft material", false); Some(json!({"pending":true})) } @@ -83,7 +84,7 @@ impl TextureCraftApp { for mut job in std::mem::take(&mut self.link_imports) { if job.project != self.session.project_id || job.mesh != self.session.mesh_id - || !self.session.doc.project.texture_set(job.set).is_ok_and(|set| set.resolution == job.resolution) + || !self.session.doc.project.texture_set(job.set).is_ok_and(|set| set.size() == job.size) { self.toast("Material import canceled because the target texture set changed", true); continue; diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 743ddbc8..e128d7fa 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -272,6 +272,7 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { material: set.material, composite: cache.composite.clone(), height_strength: set.atlas_height_strength(), + height_y_factor: set.atlas_height_y_factor(), height_in_normal: set.height_in_normal(), height_to_normal: set.height_to_normal, }) @@ -333,8 +334,13 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work { /// revisions bump with every composited chunk, so while textures load this changes every frame). fn scene_key(session: &texturecraft_engine::Session, composites: bool) -> String { let revisions: Vec = if composites { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() }; - let sets: Vec<_> = - session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength(), set.height_in_normal(), set.height_to_normal)).collect(); + let sets: Vec<_> = session + .doc + .project + .texture_sets + .iter() + .map(|set| (set.material, set.atlas_height_strength(), set.atlas_height_y_factor(), set.height_in_normal(), set.height_to_normal)) + .collect(); let display = &session.doc.project.display; let env_image = display.environment_resource().and_then(|name| session.images.get(name)).map(Arc::as_ptr); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 036c2ab7..5f7af9ff 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -383,6 +383,7 @@ fn shade(app: &TextureCraftApp) -> Shade { let set_index = app.session.ts(); let active_set = app.session.doc.project.texture_sets.get(set_index); let height_strength = active_set.map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + let height_y_factor = active_set.map_or(1.0, |texture_set| texture_set.atlas_height_y_factor()); let height_in_normal = active_set.is_none_or(|texture_set| texture_set.height_in_normal()); let height_to_normal = active_set.map_or_else(Default::default, |texture_set| texture_set.height_to_normal); @@ -390,6 +391,7 @@ fn shade(app: &TextureCraftApp) -> Shade { let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, + height_y_factor, height_in_normal, height_to_normal, view_mode, From f2b8c0b2bd0c2650adbf629ea133215905af16b7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:02:01 +0000 Subject: [PATCH 110/190] Channel storage format: set by command, and 8-bit and grey formats change what the composite holds textureSet.channel.format {channel, format} stores a channel in sRGB8, L8, RGB8, L16, RGB16, L16F, RGB16F, L32F or RGB32F, as one undo step. The composite keeps 256 steps for 8-bit formats (sRGB8 spaced for gamma) and one grey value for L formats; 16-bit and float formats keep the tiles' 16 bits, and the command says so for floats. Layer data keeps its precision, so a wider format brings back what was painted. Until a format is set, every channel keeps the 16 bits TextureCraft always stored (shown as RGB16 / L16), so new and saved projects render as before; setting one channel's format keeps the others at 16 bits. --- crates/compose/src/channel_store.rs | 59 ++++++++++++++++ crates/compose/src/eval.rs | 31 ++++---- crates/compose/src/lib.rs | 5 +- crates/compose/src/padding_maps.rs | 75 ++++++++++++++++++++ crates/compose/src/seam_padding.rs | 98 ++------------------------ crates/compose/src/texel_edge.rs | 28 ++++++++ crates/core/src/channel.rs | 41 +++++++++++ crates/core/src/project.rs | 105 ++++++++++++++++++++++++---- crates/engine/src/inspect.rs | 2 +- crates/engine/src/material_lib.rs | 1 + crates/engine/src/session.rs | 12 +++- crates/engine/src/set_cmds.rs | 50 +++++++++++++ crates/ui-egui/src/dock.rs | 2 +- 13 files changed, 381 insertions(+), 128 deletions(-) create mode 100644 crates/compose/src/channel_store.rs create mode 100644 crates/compose/src/padding_maps.rs create mode 100644 crates/compose/src/texel_edge.rs diff --git a/crates/compose/src/channel_store.rs b/crates/compose/src/channel_store.rs new file mode 100644 index 00000000..63d77f85 --- /dev/null +++ b/crates/compose/src/channel_store.rs @@ -0,0 +1,59 @@ +//! What a channel's storage format keeps of a composited value + +use texturecraft_core::{ChannelFormat, lum}; +use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; + +/// What `value` keeps in `format`: 8-bit = 256 steps (sRGB8 gamma-spaced), L = grey, others = the tiles' 16 bits; `signed` = stored offset into 0..1 +pub(crate) fn stored(format: ChannelFormat, signed: bool, mut value: [f32; 3], components: usize) -> [f32; 3] { + if format.is_grey() && components == 3 { + value = [lum(value); 3]; + } + value.map(|component| stored_value(format, signed, component)) +} + +fn stored_value(format: ChannelFormat, signed: bool, component: f32) -> f32 { + let value = if signed { component * 0.5 + 0.5 } else { component }; + let unit = |unit_value: f32| if signed { unit_value * 2.0 - 1.0 } else { unit_value }; + let steps = |unit_value: f32| (unit_value.clamp(0.0, 1.0) * 255.0).round() / 255.0; + match format { + ChannelFormat::Rgb8 | ChannelFormat::L8 => unit(steps(value)), + ChannelFormat::Srgb8 => unit(srgb_to_linear(steps(linear_to_srgb(value.clamp(0.0, 1.0))))), + ChannelFormat::L16 | ChannelFormat::Rgb16 | ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F => component, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn eight_bit_formats_keep_256_steps_and_sixteen_bit_ones_everything() { + let x = 0.3_f32 + 1.0 / 1024.0; + let eight = stored(ChannelFormat::L8, false, [x; 3], 1)[0]; + + assert!((eight * 255.0 - (eight * 255.0).round()).abs() < 1e-4, "on a 1/255 step"); + assert!((eight - x).abs() > 1e-4 && (eight - x).abs() <= 0.5 / 255.0 + 1e-6); + assert_eq!(stored(ChannelFormat::L16, false, [x; 3], 1)[0], x); + assert_eq!(stored(ChannelFormat::Rgb32F, true, [-x; 3], 1)[0], -x); + } + + #[test] + fn srgb8_keeps_more_of_the_darks_than_rgb8() { + let dark = 0.002_f32; + let srgb = stored(ChannelFormat::Srgb8, false, [dark; 3], 3)[0]; + let linear = stored(ChannelFormat::Rgb8, false, [dark; 3], 3)[0]; + + assert!((srgb - dark).abs() < (linear - dark).abs()); + } + + #[test] + fn grey_formats_turn_colours_grey_and_signed_values_keep_their_sign() { + let grey = stored(ChannelFormat::L16, false, [1.0, 0.0, 0.0], 3); + + assert!(grey[0] == grey[1] && grey[1] == grey[2] && grey[0] > 0.0 && grey[0] < 1.0); + assert_eq!(stored(ChannelFormat::Rgb16, false, [1.0, 0.0, 0.0], 3), [1.0, 0.0, 0.0]); + + let low = stored(ChannelFormat::L8, true, [-0.5; 3], 1)[0]; + assert!(low < -0.49 && low > -0.51); + } +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 489b00c0..e290c587 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelFormat, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, @@ -171,7 +171,7 @@ impl Inputs<'_> { self.gbuf.width / self.tile_grid().map_or(1, |g| g.cols.max(1)) } - /// Texels across and down an atlas block. + /// Texels across and down an atlas block fn block_size(&self) -> [u32; 2] { let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols.max(1), g.rows.max(1))); [self.gbuf.width / cols, self.gbuf.height / rows] @@ -444,7 +444,7 @@ enum Op { Halo, /// The shapes moved by `offset` (whole texels), box blurred and laid under them Shadow { offset: [i32; 2] }, - /// Each UV tile's texels read from where `mirror` sends them in their tile (`block` texels across the set's atlas blocks) + /// Each UV tile's texels read from where `mirror` sends them in their tile Mirror { mirror: Mirror }, /// Each UV tile's texels read from where `transform` sends them (its `affine`, worked out once), repeating round the tile or empty past it Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]) }, @@ -1191,13 +1191,11 @@ fn mirror_texel( let [u, v] = mirror.source(uv); // Whole texels, so an even mirror copies texels exactly - let at = |origin: f32, along: f32, size: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0); + let at = |origin: f32, along: f32, extent: f32| origin + (along * extent - 0.5).round().clamp(0.0, extent - 1.0); sample(at(origin_x, u, size[0]), at(origin_y, v, size[1]), acc); } -/// The top left of the UV tile holding texel `(x, y)` (tiles of `tile` texels at the top left of -/// `block`-texel atlas blocks), the texel centre's UV in it and the tile's size, both per axis; -/// None past the tile. +/// The top left of texel `(x, y)`'s UV tile (`tile` texels at its `block`'s top left), the texel centre's UV in it and the tile's size, None past the tile fn tile_local((x, y): (f32, f32), (block, tile): ([u32; 2], [u32; 2])) -> Option<([f32; 2], [f32; 2], [f32; 2])> { let (block, size) = (block.map(|b| b.max(1) as f32), tile.map(|t| t.max(1) as f32)); let origin = [(x / block[0]).floor() * block[0], (y / block[1]).floor() * block[1]]; @@ -1208,7 +1206,7 @@ fn tile_local((x, y): (f32, f32), (block, tile): ([u32; 2], [u32; 2])) -> Option Some((origin, [(local[0] + 0.5) / size[0], (local[1] + 0.5) / size[1]], size)) } -/// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`res` texels from its `block`'s top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty +/// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`tile` texels per axis from its block's top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty fn transform_texel( transform: &TileTransform, (columns, shift): ([[f32; 2]; 2], [f32; 2]), @@ -4677,13 +4675,15 @@ fn composite_block( quota: usize, fields: &Fields, ) -> Vec<((u32, u32), Vec)> { - let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); + let formats: Vec<(Channel, ChannelFormat)> = inp.project.texture_set(inp.ts).map(TextureSet::formats).unwrap_or_default(); + let channels: Vec = formats.iter().map(|(c, _)| *c).collect(); let (w, h) = (out.resolution, out.height); let split = below.map(|(_, l)| l); let cached = |t: (u32, u32)| below.and_then(|(b, _)| b.tile(t)); let fresh: Vec<(u32, u32)> = tiles.iter().copied().filter(|t| cached(*t).is_none()).collect(); let recorded: std::collections::BTreeSet<(u32, u32)> = if split.is_some() { fresh.iter().copied().take(quota).collect() } else { Default::default() }; - let lanes: Vec = channels.iter().map(|c| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed }).collect(); + let lanes: Vec = + formats.iter().map(|(c, f)| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed, format: *f }).collect(); let stride: usize = lanes.iter().map(|l| l.n).sum(); let level_count = split.map_or(0, <[Level]>::len); let defaults: Acc = Channel::ALL.map(Channel::default_value); @@ -4772,7 +4772,7 @@ fn composite_block( anchors.clear(); } for (l, buf) in lanes.iter().zip(&mut channel_buffers) { - let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]); + let v = crate::channel_store::stored(l.format, l.signed, acc.get(l.ch).copied().unwrap_or([0.0; 3]), l.n); for (k, x) in v.iter().take(l.n).enumerate() { let encoded = if l.signed { to_u16_signed(*x) } else { to_u16(*x) }; if let Some(slot) = buf.get_mut(band_offset * l.n + k) { @@ -4850,6 +4850,8 @@ struct Lane { ch: usize, n: usize, signed: bool, + /// What the channel is stored in + format: ChannelFormat, } /// Restore the cached stack value of slot `o` (a texel at one nesting level). Scalars are @@ -4879,8 +4881,7 @@ fn store_below(cache: &mut [f32], lanes: &[Lane], stride: usize, o: usize, acc: } } -/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from the -/// covered texel `padding` gives each channel. Returns the tiles it wrote. +/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from the covered texel `padding` gives each, returning the tiles written pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { let mut written = std::collections::BTreeSet::new(); let (w, h) = (out.resolution, out.height); @@ -4904,7 +4905,7 @@ pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u3 for (channel, img) in out.channels.iter_mut() { let comps = img.comps(); let src: &TileImage = img; - let dmap = padding.for_channel(*channel); + let dilation = padding.for_channel(*channel); // Each tile pads from the original image, so parallel writes stay independent let padded: Vec<((u32, u32), Vec)> = set @@ -4918,7 +4919,7 @@ pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u3 continue; } - let Some((sx, sy)) = dmap.source(x, y) else { continue }; + let Some((sx, sy)) = dilation.source(x, y) else { continue }; if (sx, sy) == (x, y) { continue; } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 75615ba0..ff15ffdb 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -10,6 +10,7 @@ pub mod axis_frame; mod baked_maps; pub mod below; +mod channel_store; mod curvature_size_level; pub mod curvature_sizes; pub mod display; @@ -37,6 +38,7 @@ mod mask_gray; mod micro_detail; pub mod mip_level; mod organic; +mod padding_maps; pub mod pattern; mod pattern_context; pub mod projector_cover; @@ -52,6 +54,7 @@ mod slot_placement; mod soft_box; pub mod solo; pub mod store; +mod texel_edge; mod texture_layer; mod three_d_distance; pub mod thumb; @@ -78,9 +81,9 @@ pub use eval::{ stack_reads_neighbours, }; pub use mask_gray::MaskGray; +pub use padding_maps::PaddingMaps; pub use pattern_context::PatternContext; pub use projector_depth_cache::ProjectorDepthCache; -pub use seam_padding::PaddingMaps; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/padding_maps.rs b/crates/compose/src/padding_maps.rs new file mode 100644 index 00000000..880c24f7 --- /dev/null +++ b/crates/compose/src/padding_maps.rs @@ -0,0 +1,75 @@ +//! A texture set's UV padding maps, one per kind of channel + +use texturecraft_core::{Channel, ChannelKind, UvPaddingMode}; +use texturecraft_geom::UvSeam; +use texturecraft_texel::dilate::DilationMap; + +use crate::seam_padding::{SEAM_REACH, cross_seams}; + +/// A texture set's padding maps: `all` for its channels, `flat` for tangent-space normals +#[derive(Clone, Debug, PartialEq)] +pub struct PaddingMaps { + pub all: DilationMap, + /// Padding from island edges (2D) always: a tangent-space normal turns with its island, so it can't continue across a seam + pub flat: Option, +} + +impl PaddingMaps { + /// The maps for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block` + pub fn new(mode: UvPaddingMode, covered: &[bool], (width, height): (u32, u32), max_dist: Option, block: (u32, u32), seams: &[UvSeam]) -> PaddingMaps { + let flat = DilationMap::in_rectangular_blocks(covered, width, height, max_dist, block); + match mode { + UvPaddingMode::Space2d => PaddingMaps { all: flat, flat: None }, + UvPaddingMode::Space3d => { + let mut all = flat.clone(); + cross_seams(&mut all, covered, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams); + PaddingMaps { all, flat: Some(flat) } + } + } + } + + /// The map padding tangent-space normals + pub fn flat(&self) -> &DilationMap { + self.flat.as_ref().unwrap_or(&self.all) + } + + /// The map padding `channel` + pub fn for_channel(&self, channel: Channel) -> &DilationMap { + if channel.kind() == ChannelKind::NormalMap { self.flat() } else { &self.all } + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::UvSeamSide; + use texturecraft_geom::glam::Vec2; + + use super::*; + + /// Two islands of one 3D edge: the left one's right side is the right one's left side + fn two_islands() -> (Vec, Vec) { + let (width, height) = (32u32, 8u32); + let covered = (0..width * height).map(|i| matches!(i % width, 4..=11 | 20..=27)).collect(); + let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); + let left = UvSeamSide { start: at(12.0, 0.0), end: at(12.0, 8.0), interior: at(4.0, 0.0) }; + let right = UvSeamSide { start: at(20.0, 0.0), end: at(20.0, 8.0), interior: at(28.0, 0.0) }; + (covered, vec![UvSeam { sides: [left, right] }]) + } + + #[test] + fn padding_past_a_seam_continues_from_its_other_side_and_normals_stay_flat() { + let (covered, seams) = two_islands(); + let space_3d = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (32, 8), Some(4), (0, 0), &seams); + let space_2d = PaddingMaps::new(UvPaddingMode::Space2d, &covered, (32, 8), Some(4), (0, 0), &seams); + let island = |map: &DilationMap, x: u32| map.source(x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" }); + + // Just right of the left island, then just left of the right island + assert_eq!((island(&space_3d.all, 13), island(&space_3d.all, 18)), (Some("right"), Some("left"))); + assert_eq!((island(&space_2d.all, 13), island(&space_2d.all, 18)), (Some("left"), Some("right"))); + assert_eq!(space_3d.for_channel(Channel::Normal), &space_2d.all); + assert_eq!(space_3d.for_channel(Channel::BaseColor), &space_3d.all); + + // Away from the seam, both modes pad from the near island + assert_eq!(island(&space_3d.all, 2), Some("left")); + } +} diff --git a/crates/compose/src/seam_padding.rs b/crates/compose/src/seam_padding.rs index d0f49b26..1b170c00 100644 --- a/crates/compose/src/seam_padding.rs +++ b/crates/compose/src/seam_padding.rs @@ -1,47 +1,15 @@ -//! 3D Space Neighbor UV padding: texels past a UV seam continue the surface from the seam's other side +//! UV padding across seams (3D): texels past a UV seam continue the surface from the seam's other side -use texturecraft_core::{Channel, ChannelKind, UvPaddingMode}; -use texturecraft_geom::{UvSeam, UvSeamSide, glam::Vec2}; +use texturecraft_geom::{UvSeam, glam::Vec2}; use texturecraft_texel::dilate::{DilationMap, NONE}; +use crate::texel_edge::TexelEdge; + /// Farthest a padding texel reaches across a seam, in texels; farther ones keep their nearest covered texel pub const SEAM_REACH: u32 = 32; -/// A texture set's padding maps: `all` for its channels, `flat` for tangent-space normals -#[derive(Clone, Debug, PartialEq)] -pub struct PaddingMaps { - pub all: DilationMap, - /// 2D Space Neighbor always: a tangent-space normal turns with its island, so it can't continue across a seam - pub flat: Option, -} - -impl PaddingMaps { - /// The maps for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block` - pub fn new(mode: UvPaddingMode, covered: &[bool], (width, height): (u32, u32), max_dist: Option, block: (u32, u32), seams: &[UvSeam]) -> PaddingMaps { - let flat = DilationMap::in_rectangular_blocks(covered, width, height, max_dist, block); - match mode { - UvPaddingMode::Space2d => PaddingMaps { all: flat, flat: None }, - UvPaddingMode::Space3d => { - let mut all = flat.clone(); - cross_seams(&mut all, covered, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams); - PaddingMaps { all, flat: Some(flat) } - } - } - } - - /// The map padding tangent-space normals - pub fn flat(&self) -> &DilationMap { - self.flat.as_ref().unwrap_or(&self.all) - } - - /// The map padding `channel` - pub fn for_channel(&self, channel: Channel) -> &DilationMap { - if channel.kind() == ChannelKind::NormalMap { self.flat() } else { &self.all } - } -} - /// Point every padding texel just outside a seam at the texel as far inside the seam's other side -fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, block: (u32, u32), seams: &[UvSeam]) { +pub(crate) fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, block: (u32, u32), seams: &[UvSeam]) { let (width, height) = (map.width, map.height); let size = Vec2::new(width as f32, height as f32); let block_of = |x: u32, y: u32| (x.checked_div(block.0).unwrap_or(0), y.checked_div(block.1).unwrap_or(0)); @@ -102,59 +70,3 @@ fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, block: (u32, } } } - -/// A seam side in texel space, with its unit normal into the island -struct TexelEdge { - start: Vec2, - end: Vec2, - inward: Vec2, -} - -impl TexelEdge { - fn new(side: UvSeamSide, size: Vec2) -> Option { - let (start, end, interior) = (side.start * size, side.end * size, side.interior * size); - let normal = (end - start).perp().try_normalize()?; - let inward = if normal.dot(interior - start) < 0.0 { -normal } else { normal }; - Some(TexelEdge { start, end, inward }) - } - - /// How far along the edge (0..1) and how far outside the island `point` is, when it is beside the edge on the outside - fn outside(&self, point: Vec2) -> Option<(f32, f32)> { - let direction = self.end - self.start; - let along = (point - self.start).dot(direction) / direction.length_squared(); - let outside = -(point - self.start).dot(self.inward); - ((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Two islands of one 3D edge: the left one's right side is the right one's left side - fn two_islands() -> (Vec, Vec) { - let (width, height) = (32u32, 8u32); - let covered = (0..width * height).map(|i| matches!(i % width, 4..=11 | 20..=27)).collect(); - let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); - let left = UvSeamSide { start: at(12.0, 0.0), end: at(12.0, 8.0), interior: at(4.0, 0.0) }; - let right = UvSeamSide { start: at(20.0, 0.0), end: at(20.0, 8.0), interior: at(28.0, 0.0) }; - (covered, vec![UvSeam { sides: [left, right] }]) - } - - #[test] - fn padding_past_a_seam_continues_from_its_other_side_and_normals_stay_flat() { - let (covered, seams) = two_islands(); - let space_3d = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (32, 8), Some(4), (0, 0), &seams); - let space_2d = PaddingMaps::new(UvPaddingMode::Space2d, &covered, (32, 8), Some(4), (0, 0), &seams); - let island = |map: &DilationMap, x: u32| map.source(x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" }); - - // Just right of the left island, then just left of the right island - assert_eq!((island(&space_3d.all, 13), island(&space_3d.all, 18)), (Some("right"), Some("left"))); - assert_eq!((island(&space_2d.all, 13), island(&space_2d.all, 18)), (Some("left"), Some("right"))); - assert_eq!(space_3d.for_channel(Channel::Normal), &space_2d.all); - assert_eq!(space_3d.for_channel(Channel::BaseColor), &space_3d.all); - - // Away from the seam, both modes pad from the near island - assert_eq!(island(&space_3d.all, 2), Some("left")); - } -} diff --git a/crates/compose/src/texel_edge.rs b/crates/compose/src/texel_edge.rs new file mode 100644 index 00000000..f6b57d21 --- /dev/null +++ b/crates/compose/src/texel_edge.rs @@ -0,0 +1,28 @@ +//! A UV seam side in texel space + +use texturecraft_geom::UvSeamSide; +use texturecraft_geom::glam::Vec2; + +/// A seam side in texel space, with its unit normal into the island +pub(crate) struct TexelEdge { + pub(crate) start: Vec2, + pub(crate) end: Vec2, + pub(crate) inward: Vec2, +} + +impl TexelEdge { + pub(crate) fn new(side: UvSeamSide, size: Vec2) -> Option { + let (start, end, interior) = (side.start * size, side.end * size, side.interior * size); + let normal = (end - start).perp().try_normalize()?; + let inward = if normal.dot(interior - start) < 0.0 { -normal } else { normal }; + Some(TexelEdge { start, end, inward }) + } + + /// How far along the edge (0..1) and how far outside the island `point` is, when it is beside the edge on the outside + pub(crate) fn outside(&self, point: Vec2) -> Option<(f32, f32)> { + let direction = self.end - self.start; + let along = (point - self.start).dot(direction) / direction.length_squared(); + let outside = -(point - self.start).dot(self.inward); + ((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside)) + } +} diff --git a/crates/core/src/channel.rs b/crates/core/src/channel.rs index eb7b3918..7fea2d38 100644 --- a/crates/core/src/channel.rs +++ b/crates/core/src/channel.rs @@ -253,6 +253,38 @@ impl ChannelFormat { ChannelKind::Signed => ChannelFormat::L16F, } } + /// Every format, in the order the channel settings list them + pub const ALL: [ChannelFormat; 9] = [ + ChannelFormat::Srgb8, + ChannelFormat::L8, + ChannelFormat::Rgb8, + ChannelFormat::L16, + ChannelFormat::Rgb16, + ChannelFormat::L16F, + ChannelFormat::Rgb16F, + ChannelFormat::L32F, + ChannelFormat::Rgb32F, + ]; + + /// A format by its label, ignoring case ("srgb8", "L16F") + pub fn parse(s: &str) -> Option { + ChannelFormat::ALL.into_iter().find(|f| f.label().eq_ignore_ascii_case(s.trim())) + } + + /// Grey formats keep one value per texel: a colour channel stored in one turns grey + pub fn is_grey(self) -> bool { + matches!(self, ChannelFormat::L8 | ChannelFormat::L16 | ChannelFormat::L16F | ChannelFormat::L32F) + } + + /// The 16-bit format holding everything an 8-bit one does (itself for the others) + pub fn at_least_16_bit(self) -> ChannelFormat { + match self { + ChannelFormat::Srgb8 | ChannelFormat::Rgb8 => ChannelFormat::Rgb16, + ChannelFormat::L8 => ChannelFormat::L16, + other => other, + } + } + pub fn label(self) -> &'static str { match self { ChannelFormat::Srgb8 => "sRGB8", @@ -304,6 +336,15 @@ mod tests { assert_eq!(Channel::parse("coatWeight"), Some(Channel::CoatWeight)); } + #[test] + fn formats_parse_by_label() { + for f in ChannelFormat::ALL { + assert_eq!(ChannelFormat::parse(&f.label().to_lowercase()), Some(f)); + assert!(f.at_least_16_bit().is_grey() == f.is_grey()); + } + assert_eq!(ChannelFormat::parse("RGB4"), None); + } + #[test] fn index_matches_all_order() { for (i, c) in Channel::ALL.iter().enumerate() { diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 7dec5ca6..d2372215 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -41,6 +41,22 @@ pub enum NormalMixing { Replace, } +impl NormalMixing { + pub const ALL: [NormalMixing; 2] = [NormalMixing::Combine, NormalMixing::Replace]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + NormalMixing::Combine => "combine", + NormalMixing::Replace => "replace", + } + } + + pub fn parse(id: &str) -> Option { + NormalMixing::ALL.into_iter().find(|mixing| mixing.id() == id) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum AoMixing { #[default] @@ -48,6 +64,22 @@ pub enum AoMixing { None, } +impl AoMixing { + pub const ALL: [AoMixing; 2] = [AoMixing::Multiply, AoMixing::None]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + AoMixing::Multiply => "multiply", + AoMixing::None => "none", + } + } + + pub fn parse(id: &str) -> Option { + AoMixing::ALL.into_iter().find(|mixing| mixing.id() == id) + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TextureSet { pub name: String, @@ -55,13 +87,16 @@ pub struct TextureSet { pub description: String, /// Material index in the mesh this set paints. pub material: usize, - /// Texels across: a power of two, 128..=8192 (the side of a square set). + /// Texels across: a power of two, 128..=8192 (the side of a square set) pub resolution: u32, - /// Texels down when they differ from `resolution` (a non-square set); a power of two, - /// 128..=8192. Sets with per-tile resolutions stay square. + /// Texels down when they differ from `resolution` (a power of two, 128..=8192); sets with per-tile resolutions stay square #[serde(default, skip_serializing_if = "Option::is_none")] pub resolution_height: Option, + /// Channels and their storage formats; see [`TextureSet::formats`] for what they hold pub channels: Vec<(Channel, ChannelFormat)>, + /// Whether channels hold their formats' precision; until a format is set every channel keeps 16 bits, what TextureCraft always stored + #[serde(default)] + pub format_precision: bool, /// Top-level layers, bottom → top. pub stack: Vec, #[serde(default)] @@ -71,7 +106,7 @@ pub struct TextureSet { /// Height to normal method; projects without it keep Smooth, the filter their exports already used #[serde(default)] pub height_to_normal: HeightToNormalMethod, - /// UV padding; projects without it keep 2D Space Neighbor, the padding they were made with + /// UV padding; projects without it keep padding from island edges (2D), the padding they were made with #[serde(default)] pub uv_padding: UvPaddingMode, /// Height-to-normal strength. @@ -179,6 +214,7 @@ impl TextureSet { resolution, resolution_height: None, channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(), + format_precision: false, stack: Vec::new(), normal_mixing: NormalMixing::Combine, ao_mixing: AoMixing::Multiply, @@ -219,26 +255,25 @@ impl TextureSet { self.normal_mixing == NormalMixing::Combine } - /// Texels across and down: [`TextureSet::block_size`] per block of the atlas grid. + /// Texels across and down: [`TextureSet::block_size`] per block of the atlas grid pub fn size(&self) -> (u32, u32) { let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); let (width, height) = self.block_size(); (width.saturating_mul(cols), height.saturating_mul(rows)) } - /// Texels down of the set's size (`resolution` for a square set). + /// Texels down of the set's size (`resolution` for a square set) pub fn height(&self) -> u32 { self.resolution_height.unwrap_or(self.resolution) } - /// Set the size to `width × height` (None when square). + /// Set the size to `width × height` (`height` stored only when it differs) pub fn set_size(&mut self, width: u32, height: u32) { self.resolution = width; self.resolution_height = (height != width).then_some(height); } - /// Texels across and down of an atlas block: the set's size, or the largest tile - /// resolution square when tiles have their own. + /// Texels across and down of an atlas block: the set's size, or the largest tile resolution square when tiles have their own pub fn block_size(&self) -> (u32, u32) { if self.tile_resolutions.is_empty() { return (self.resolution, self.height()); @@ -252,8 +287,7 @@ impl TextureSet { self.tile_resolutions.get(&udim).copied().unwrap_or(self.resolution) } - /// Texels across an atlas block: the largest tile resolution (`resolution` for a - /// classic set or one without overrides); see [`TextureSet::block_size`] for both sides. + /// Texels across an atlas block: the largest tile resolution (`resolution` without overrides); see [`TextureSet::block_size`] pub fn block_resolution(&self) -> u32 { if self.tile_resolutions.is_empty() { return self.resolution; @@ -309,6 +343,28 @@ impl TextureSet { pub fn channel_list(&self) -> Vec { self.channels.iter().map(|(c, _)| *c).collect() } + + /// The channels with the formats they are stored in (8-bit ones read as 16-bit without `format_precision`) + pub fn formats(&self) -> Vec<(Channel, ChannelFormat)> { + let held = |format: ChannelFormat| if self.format_precision { format } else { format.at_least_16_bit() }; + self.channels.iter().map(|(channel, format)| (*channel, held(*format))).collect() + } + + /// Store channel `target` in `format` (false when the set lacks it); the other channels keep what they hold + pub fn set_channel_format(&mut self, target: Channel, format: ChannelFormat) -> bool { + if !self.has_channel(target) { + return false; + } + + self.channels = self.formats(); + self.format_precision = true; + for (channel, stored) in &mut self.channels { + if *channel == target { + *stored = format; + } + } + true + } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -764,11 +820,12 @@ impl Project { if let Some(t) = self.texture_sets.iter().find(|t| bad_tile_res(t)) { return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tile resolutions {:?}", t.name, t.tile_resolutions))); } - let bad_height = |t: &TextureSet| { - t.resolution_height.is_some_and(|h| !h.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&h) || !t.tile_resolutions.is_empty()) + let bad_height = |set: &TextureSet| { + set.resolution_height + .is_some_and(|height| !height.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&height) || !set.tile_resolutions.is_empty()) }; - if let Some(t) = self.texture_sets.iter().find(|t| bad_height(t)) { - return Err(CoreError::Invalid(format!("texture set \"{}\" has an invalid height {:?}", t.name, t.resolution_height))); + if let Some(set) = self.texture_sets.iter().find(|set| bad_height(set)) { + return Err(CoreError::Invalid(format!("texture set \"{}\" has an invalid height {:?}", set.name, set.resolution_height))); } let mut seen = BTreeSet::new(); for ts in 0..self.texture_sets.len() { @@ -870,6 +927,24 @@ mod tests { p } + #[test] + fn sets_keep_16_bits_until_a_format_is_set_also_in_older_files() { + let new = TextureSet::new("a", 0, 128); + let mut v = serde_json::to_value(&new).unwrap(); + v.as_object_mut().unwrap().remove("format_precision"); + let mut old: TextureSet = serde_json::from_value(v).unwrap(); + let format = |t: &TextureSet, c: Channel| t.formats().into_iter().find(|(x, _)| *x == c).map(|(_, f)| f); + + assert_eq!(format(&new, Channel::Roughness), Some(ChannelFormat::L16)); + assert_eq!(format(&old, Channel::Roughness), Some(ChannelFormat::L16)); + assert_eq!(format(&old, Channel::BaseColor), Some(ChannelFormat::Rgb16)); + + assert!(old.set_channel_format(Channel::Metallic, ChannelFormat::L8)); + assert_eq!(format(&old, Channel::Metallic), Some(ChannelFormat::L8)); + assert_eq!(format(&old, Channel::Roughness), Some(ChannelFormat::L16), "the other channels keep their precision"); + assert!(!old.set_channel_format(Channel::Emissive, ChannelFormat::L8), "a channel the set lacks"); + } + #[test] fn a_sync_takes_settings_from_a_staying_member_else_the_active_set_else_the_first() { let group = BakeSyncGroup::Common; diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 34a0c968..18732cf9 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -270,7 +270,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "blockResolution": texture_set.block_resolution(), "uvTiles": texture_set.uv_tiles, "tiles": tiles, - "channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::>(), + "channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::>(), "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index eb98f842..8b20818d 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -70,6 +70,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { set.uv_tiles = src_set.uv_tiles.clone(); set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); + set.format_precision = src_set.format_precision; project.texture_sets.push(set); Document { bake_meshes: Default::default(), diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index a271356d..96379575 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use texturecraft_compose::{ BakedMaps, BelowCache, Composite, PaddingMaps, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours, }; -use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet, UvPaddingMode}; +use texturecraft_core::{Channel, ChannelFormat, Layer, LayerId, LayerKind, Project, TextureSet, UvPaddingMode}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer, UvSeam}; use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; @@ -42,6 +42,8 @@ pub struct SetCache { /// The set's UV padding mode and the display padding it gives pub uv_padding: UvPaddingMode, pub padding: Arc, + /// The channels' storage formats the composite was made with + pub formats: Vec<(Channel, ChannelFormat)>, pub covered_tiles: Arc>, pub composite: Composite, /// Tiles to recomposite. @@ -71,6 +73,7 @@ impl SetCache { gbuf: Arc::new(gbuf), uv_padding: ts.uv_padding, padding: Arc::new(padding), + formats: ts.formats(), covered_tiles: Arc::new(covered), composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), @@ -87,7 +90,7 @@ impl SetCache { } } -/// The seams `ts`'s UV padding crosses: none for 2D Space Neighbor +/// The seams `ts`'s UV padding crosses: none for padding from island edges (2D) pub(crate) fn padding_seams(mesh: &Mesh, ts: &TextureSet) -> Vec { match ts.uv_padding { UvPaddingMode::Space3d => UvSeam::of_material(mesh, ts.material), @@ -929,6 +932,11 @@ impl Session { c.padding = Arc::new(display_padding(&self.mesh, ts, &c.gbuf)); c.invalidate_all(); } + let formats = ts.formats(); + if c.formats != formats { + c.formats = formats; + c.invalidate_all(); + } let (want, scales) = (ts.channel_list(), ts.block_scales()); if c.composite.channels.keys().copied().collect::>() != want || c.composite.block_scales != scales { diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index a56dc2aa..bdf4be87 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -35,6 +35,7 @@ pub fn specs() -> Vec { ), cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)), cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)), + cmd!("textureSet.channel.format", "Set channel format", [], None, "{ts?, channel, format}", always, channel_format), cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible), cmd!( "textureSet.visibility", @@ -244,6 +245,25 @@ fn channel(s: &mut Session, p: &Value, add: bool) -> Result { Ok(Value::Null) } +/// Store a channel in another format; layer data keeps its precision, so a wider format brings back what was painted +fn channel_format(s: &mut Session, p: &Value) -> Result { + let cmd = "textureSet.channel.format"; + let ts = ts_param(s, p, cmd)?; + let c = channel_param(cmd, p, "channel")?.ok_or_else(|| bad(cmd, "`channel` is required"))?; + let name = strp(p, "format").ok_or_else(|| bad(cmd, "`format` is required"))?; + let all = || ChannelFormat::ALL.map(ChannelFormat::label).join(", "); + let format = ChannelFormat::parse(name).ok_or_else(|| bad(cmd, format!("unknown format {name:?} ({})", all())))?; + s.edit("Channel format", |s| { + if s.doc.project.texture_set_mut(ts)?.set_channel_format(c, format) { + Ok(()) + } else { + Err(bad(cmd, format!("the texture set has no {} channel", c.label()))) + } + })?; + let float = matches!(format, ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F); + Ok(if float { json!({"note": "float formats are stored at 16 bits for now, and values stay in the channel's range"}) } else { Value::Null }) +} + /// Add channel `c` to texture set `ts` (no-op when present) and enable it on the set's layers. /// Call inside [`Session::edit`]. pub(crate) fn add_channel(s: &mut Session, ts: usize, c: Channel) -> Result<()> { @@ -432,6 +452,36 @@ mod tests { assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); } + #[test] + fn channel_format_changes_what_the_viewport_holds_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let format = |s: &Session| crate::inspect::texture_set(s, 0)["channels"][2]["format"].clone(); + let roughness = |s: &mut Session| { + s.update(); + let img = &s.caches[0].composite.channels[&Channel::Roughness]; + let tile = s.caches[0].covered_tiles[0]; + img.tile(tile.0, tile.1).map(<[u16]>::to_vec).unwrap_or_default() + }; + crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L16"})).unwrap(); + crate::execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3013})).unwrap(); + let sixteen = roughness(&mut s); + assert_eq!(format(&s), json!("L16")); + + crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "Roughness", "format": "l8"})).unwrap(); + let eight = roughness(&mut s); + assert_eq!(format(&s), json!("L8")); + assert_ne!(eight, sixteen, "the composite holds 8 bits"); + assert!(eight.iter().all(|v| v % 257 == 0), "every texel is on an 8-bit step"); + + let float = crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "height", "format": "L32F"})).unwrap(); + assert!(float["note"].is_string(), "a float format says it holds 16 bits"); + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L4"})).is_err()); + assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "emissive", "format": "L8"})).is_err()); + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!((format(&s), roughness(&mut s)), (json!("L16"), sixteen)); + } + #[test] fn ao_mixing_resends_the_set_to_the_viewport_and_undoes() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 6394c3b0..b1ddf848 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1601,7 +1601,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { }); }); - for (channel, format) in &set.channels { + for (channel, format) in &set.formats() { ui.horizontal(|ui| { ui.label(RichText::new(tr(channel.label())).strong()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { From 17923a711635b02fe501ce91446942e6a67ad36c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:33:19 +0000 Subject: [PATCH 111/190] Channels: 19 more material channels and User0 to User31, stored and exported, with inspect marking the ones the shader ignores --- crates/core/src/channel.rs | 363 +++++++++++++++++- crates/engine/src/inspect.rs | 2 +- crates/engine/src/set_cmds.rs | 24 ++ crates/formats/src/export/mod.rs | 47 +-- crates/formats/src/presets.rs | 4 +- .../ui-egui/src/export_templates/map_lists.rs | 38 +- crates/ui-egui/tests/it/output_templates.rs | 21 +- 7 files changed, 453 insertions(+), 46 deletions(-) diff --git a/crates/core/src/channel.rs b/crates/core/src/channel.rs index 7fea2d38..e6e823e8 100644 --- a/crates/core/src/channel.rs +++ b/crates/core/src/channel.rs @@ -39,6 +39,77 @@ pub enum Channel { Transmission, /// Tangent-space normal of the clear coat (relative to the mesh normal). CoatNormal, + /// How much of the base layer shows (stored and exported: our shader does not read it) + BaseWeight, + /// Roughness of the diffuse base (stored and exported: our shader does not read it) + BaseDiffuseRoughness, + /// Strength of the specular lobe (stored and exported: our shader does not read it) + SpecularWeight, + /// Tint of the specular lobe (stored and exported: our shader does not read it) + SpecularColor, + /// Tint of transmitted light (stored and exported: our shader does not read it) + TransmissionColor, + /// Subsurface scattering color (stored and exported: our shader does not read it) + SubsurfaceColor, + /// Scattering distance per color (stored and exported: our shader does not read it) + SubsurfaceRadiusScale, + /// Clear coat tint (stored and exported: our shader does not read it) + CoatColor, + /// Clear coat anisotropy (stored and exported: our shader does not read it) + CoatAnisotropy, + /// Clear coat reflectance (stored and exported: our shader does not read it) + CoatSpecularLevel, + /// Tangent-space direction of the clear coat anisotropy, packed like a normal (stored and exported: our shader does not read it) + CoatTangent, + /// Thin-film iridescence weight (stored and exported: our shader does not read it) + ThinFilmWeight, + /// Tangent-space anisotropy direction, packed like a normal (stored and exported: our shader does not read it) + Tangent, + /// Mask for blending materials in an engine (stored and exported only) + BlendingMask, + /// Diffuse color of older shaders (stored and exported only) + Diffuse, + /// Signed displacement for render engines (stored and exported only) + Displacement, + /// Index of refraction, 0..1 as the target shader maps it (stored and exported only) + Ior, + /// Reflection amount of older shaders (stored and exported only) + Reflection, + /// Transmissive color of older shaders (stored and exported only) + Transmissive, + /// Free channels for anything a target shader needs (grey, stored and exported) + User0, + User1, + User2, + User3, + User4, + User5, + User6, + User7, + User8, + User9, + User10, + User11, + User12, + User13, + User14, + User15, + User16, + User17, + User18, + User19, + User20, + User21, + User22, + User23, + User24, + User25, + User26, + User27, + User28, + User29, + User30, + User31, } /// How a channel's values are stored and interpreted. @@ -55,7 +126,7 @@ pub enum ChannelKind { } impl Channel { - pub const ALL: [Channel; 21] = [ + pub const ALL: [Channel; 72] = [ Channel::BaseColor, Channel::Metallic, Channel::Roughness, @@ -77,8 +148,62 @@ impl Channel { Channel::ScatterWeight, Channel::Transmission, Channel::CoatNormal, + Channel::BaseWeight, + Channel::BaseDiffuseRoughness, + Channel::SpecularWeight, + Channel::SpecularColor, + Channel::TransmissionColor, + Channel::SubsurfaceColor, + Channel::SubsurfaceRadiusScale, + Channel::CoatColor, + Channel::CoatAnisotropy, + Channel::CoatSpecularLevel, + Channel::CoatTangent, + Channel::ThinFilmWeight, + Channel::Tangent, + Channel::BlendingMask, + Channel::Diffuse, + Channel::Displacement, + Channel::Ior, + Channel::Reflection, + Channel::Transmissive, + Channel::User0, + Channel::User1, + Channel::User2, + Channel::User3, + Channel::User4, + Channel::User5, + Channel::User6, + Channel::User7, + Channel::User8, + Channel::User9, + Channel::User10, + Channel::User11, + Channel::User12, + Channel::User13, + Channel::User14, + Channel::User15, + Channel::User16, + Channel::User17, + Channel::User18, + Channel::User19, + Channel::User20, + Channel::User21, + Channel::User22, + Channel::User23, + Channel::User24, + Channel::User25, + Channel::User26, + Channel::User27, + Channel::User28, + Channel::User29, + Channel::User30, + Channel::User31, ]; + /// How many channels, from the start of [`Channel::ALL`], our shader reads + pub const SHADED_COUNT: usize = 21; + /// The extra shading lobes (clear coat, sheen, anisotropy, subsurface scattering, /// transmission). Their defaults switch the lobes off, so a set without them shades exactly /// as before. @@ -101,8 +226,15 @@ impl Channel { pub fn kind(self) -> ChannelKind { match self { Channel::BaseColor | Channel::Emissive | Channel::Specular | Channel::SheenColor => ChannelKind::Color, - Channel::Normal | Channel::CoatNormal => ChannelKind::NormalMap, - Channel::Height => ChannelKind::Signed, + Channel::SpecularColor + | Channel::TransmissionColor + | Channel::SubsurfaceColor + | Channel::SubsurfaceRadiusScale + | Channel::CoatColor + | Channel::Diffuse + | Channel::Transmissive => ChannelKind::Color, + Channel::Normal | Channel::CoatNormal | Channel::Tangent | Channel::CoatTangent => ChannelKind::NormalMap, + Channel::Height | Channel::Displacement => ChannelKind::Signed, _ => ChannelKind::Scalar, } } @@ -133,8 +265,52 @@ impl Channel { Channel::Normal | Channel::CoatNormal => [0.5, 0.5, 1.0], Channel::Opacity | Channel::AmbientOcclusion => [1.0; 3], Channel::SpecularLevel | Channel::Glossiness => [0.5; 3], - // F0 of a common dielectric (4 %). + // F0 of a common dielectric (4 %) Channel::Specular => [0.04; 3], + Channel::BaseWeight | Channel::SpecularWeight | Channel::SpecularColor | Channel::TransmissionColor | Channel::CoatColor => [1.0; 3], + Channel::BaseDiffuseRoughness + | Channel::CoatAnisotropy + | Channel::ThinFilmWeight + | Channel::BlendingMask + | Channel::Displacement + | Channel::Reflection + | Channel::Transmissive => [0.0; 3], + Channel::SubsurfaceColor => [0.8; 3], + Channel::SubsurfaceRadiusScale => [1.0, 0.5, 0.25], + Channel::CoatSpecularLevel | Channel::Diffuse | Channel::Ior => [0.5; 3], + Channel::CoatTangent | Channel::Tangent => [1.0, 0.5, 0.5], + Channel::User0 + | Channel::User1 + | Channel::User2 + | Channel::User3 + | Channel::User4 + | Channel::User5 + | Channel::User6 + | Channel::User7 + | Channel::User8 + | Channel::User9 + | Channel::User10 + | Channel::User11 + | Channel::User12 + | Channel::User13 + | Channel::User14 + | Channel::User15 + | Channel::User16 + | Channel::User17 + | Channel::User18 + | Channel::User19 + | Channel::User20 + | Channel::User21 + | Channel::User22 + | Channel::User23 + | Channel::User24 + | Channel::User25 + | Channel::User26 + | Channel::User27 + | Channel::User28 + | Channel::User29 + | Channel::User30 + | Channel::User31 => [0.0; 3], } } @@ -161,6 +337,57 @@ impl Channel { Channel::ScatterWeight => "Scattering weight", Channel::Transmission => "Transmission", Channel::CoatNormal => "Coat normal", + Channel::BaseWeight => "Base weight", + Channel::BaseDiffuseRoughness => "Base diffuse roughness", + Channel::SpecularWeight => "Specular weight", + Channel::SpecularColor => "Specular color", + Channel::TransmissionColor => "Transmission color", + Channel::SubsurfaceColor => "Subsurface color", + Channel::SubsurfaceRadiusScale => "Subsurface radius scale", + Channel::CoatColor => "Coat color", + Channel::CoatAnisotropy => "Coat anisotropy", + Channel::CoatSpecularLevel => "Coat specular level", + Channel::CoatTangent => "Coat tangent", + Channel::ThinFilmWeight => "Thin-film weight", + Channel::Tangent => "Tangent", + Channel::BlendingMask => "Blending mask", + Channel::Diffuse => "Diffuse", + Channel::Displacement => "Displacement", + Channel::Ior => "Ior", + Channel::Reflection => "Reflection", + Channel::Transmissive => "Transmissive", + Channel::User0 => "User0", + Channel::User1 => "User1", + Channel::User2 => "User2", + Channel::User3 => "User3", + Channel::User4 => "User4", + Channel::User5 => "User5", + Channel::User6 => "User6", + Channel::User7 => "User7", + Channel::User8 => "User8", + Channel::User9 => "User9", + Channel::User10 => "User10", + Channel::User11 => "User11", + Channel::User12 => "User12", + Channel::User13 => "User13", + Channel::User14 => "User14", + Channel::User15 => "User15", + Channel::User16 => "User16", + Channel::User17 => "User17", + Channel::User18 => "User18", + Channel::User19 => "User19", + Channel::User20 => "User20", + Channel::User21 => "User21", + Channel::User22 => "User22", + Channel::User23 => "User23", + Channel::User24 => "User24", + Channel::User25 => "User25", + Channel::User26 => "User26", + Channel::User27 => "User27", + Channel::User28 => "User28", + Channel::User29 => "User29", + Channel::User30 => "User30", + Channel::User31 => "User31", } } @@ -188,6 +415,57 @@ impl Channel { Channel::ScatterWeight => "scatter", Channel::Transmission => "transm", Channel::CoatNormal => "coat nrm", + Channel::BaseWeight => "base weight", + Channel::BaseDiffuseRoughness => "diffuse rough", + Channel::SpecularWeight => "spec weight", + Channel::SpecularColor => "spec color", + Channel::TransmissionColor => "transm color", + Channel::SubsurfaceColor => "sss color", + Channel::SubsurfaceRadiusScale => "sss radius", + Channel::CoatColor => "coat color", + Channel::CoatAnisotropy => "coat aniso", + Channel::CoatSpecularLevel => "coat spec", + Channel::CoatTangent => "coat tangent", + Channel::ThinFilmWeight => "thin film", + Channel::Tangent => "tangent", + Channel::BlendingMask => "blend mask", + Channel::Diffuse => "diffuse", + Channel::Displacement => "displace", + Channel::Ior => "ior", + Channel::Reflection => "reflection", + Channel::Transmissive => "transmissive", + Channel::User0 => "user0", + Channel::User1 => "user1", + Channel::User2 => "user2", + Channel::User3 => "user3", + Channel::User4 => "user4", + Channel::User5 => "user5", + Channel::User6 => "user6", + Channel::User7 => "user7", + Channel::User8 => "user8", + Channel::User9 => "user9", + Channel::User10 => "user10", + Channel::User11 => "user11", + Channel::User12 => "user12", + Channel::User13 => "user13", + Channel::User14 => "user14", + Channel::User15 => "user15", + Channel::User16 => "user16", + Channel::User17 => "user17", + Channel::User18 => "user18", + Channel::User19 => "user19", + Channel::User20 => "user20", + Channel::User21 => "user21", + Channel::User22 => "user22", + Channel::User23 => "user23", + Channel::User24 => "user24", + Channel::User25 => "user25", + Channel::User26 => "user26", + Channel::User27 => "user27", + Channel::User28 => "user28", + Channel::User29 => "user29", + Channel::User30 => "user30", + Channel::User31 => "user31", } } @@ -215,6 +493,57 @@ impl Channel { Channel::ScatterWeight => "scatterWeight", Channel::Transmission => "transmission", Channel::CoatNormal => "coatNormal", + Channel::BaseWeight => "baseWeight", + Channel::BaseDiffuseRoughness => "baseDiffuseRoughness", + Channel::SpecularWeight => "specularWeight", + Channel::SpecularColor => "specularColor", + Channel::TransmissionColor => "transmissionColor", + Channel::SubsurfaceColor => "subsurfaceColor", + Channel::SubsurfaceRadiusScale => "subsurfaceRadiusScale", + Channel::CoatColor => "coatColor", + Channel::CoatAnisotropy => "coatAnisotropy", + Channel::CoatSpecularLevel => "coatSpecularLevel", + Channel::CoatTangent => "coatTangent", + Channel::ThinFilmWeight => "thinFilmWeight", + Channel::Tangent => "tangent", + Channel::BlendingMask => "blendingMask", + Channel::Diffuse => "diffuse", + Channel::Displacement => "displacement", + Channel::Ior => "ior", + Channel::Reflection => "reflection", + Channel::Transmissive => "transmissive", + Channel::User0 => "user0", + Channel::User1 => "user1", + Channel::User2 => "user2", + Channel::User3 => "user3", + Channel::User4 => "user4", + Channel::User5 => "user5", + Channel::User6 => "user6", + Channel::User7 => "user7", + Channel::User8 => "user8", + Channel::User9 => "user9", + Channel::User10 => "user10", + Channel::User11 => "user11", + Channel::User12 => "user12", + Channel::User13 => "user13", + Channel::User14 => "user14", + Channel::User15 => "user15", + Channel::User16 => "user16", + Channel::User17 => "user17", + Channel::User18 => "user18", + Channel::User19 => "user19", + Channel::User20 => "user20", + Channel::User21 => "user21", + Channel::User22 => "user22", + Channel::User23 => "user23", + Channel::User24 => "user24", + Channel::User25 => "user25", + Channel::User26 => "user26", + Channel::User27 => "user27", + Channel::User28 => "user28", + Channel::User29 => "user29", + Channel::User30 => "user30", + Channel::User31 => "user31", } } @@ -225,8 +554,14 @@ impl Channel { Channel::ALL.into_iter().find(|c| norm(c.id()) == want || norm(c.label()) == want || norm(c.short()) == want || norm(&format!("{c:?}")) == want) } + /// Position in [`Channel::ALL`] (the declaration order) pub fn index(self) -> usize { - Channel::ALL.iter().position(|c| *c == self).unwrap_or(0) + self as usize + } + + /// Whether our shader reads the channel; the others are stored and exported for other shaders + pub fn is_shaded(self) -> bool { + self.index() < Channel::SHADED_COUNT } } @@ -253,6 +588,7 @@ impl ChannelFormat { ChannelKind::Signed => ChannelFormat::L16F, } } + /// Every format, in the order the channel settings list them pub const ALL: [ChannelFormat; 9] = [ ChannelFormat::Srgb8, @@ -267,8 +603,8 @@ impl ChannelFormat { ]; /// A format by its label, ignoring case ("srgb8", "L16F") - pub fn parse(s: &str) -> Option { - ChannelFormat::ALL.into_iter().find(|f| f.label().eq_ignore_ascii_case(s.trim())) + pub fn parse(label: &str) -> Option { + ChannelFormat::ALL.into_iter().find(|format| format.label().eq_ignore_ascii_case(label.trim())) } /// Grey formats keep one value per texel: a colour channel stored in one turns grey @@ -345,6 +681,19 @@ mod tests { assert_eq!(ChannelFormat::parse("RGB4"), None); } + #[test] + fn unshaded_channels_round_trip_through_ids() { + // Project files and commands name channels by id: every added channel must come back as itself + for c in Channel::ALL.into_iter().filter(|c| !c.is_shaded()) { + assert_eq!(Channel::parse(c.id()), Some(c)); + let json = serde_json::to_string(&c).unwrap_or_default(); + assert_eq!(serde_json::from_str::(&json).ok(), Some(c)); + } + assert!(Channel::LOBES.iter().chain(&Channel::DEFAULT_SET).all(|c| c.is_shaded())); + assert_eq!(Channel::parse("User31"), Some(Channel::User31)); + assert_eq!(Channel::parse("thin-film weight"), Some(Channel::ThinFilmWeight)); + } + #[test] fn index_matches_all_order() { for (i, c) in Channel::ALL.iter().enumerate() { diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 18732cf9..1c5f9c7e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -270,7 +270,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "blockResolution": texture_set.block_resolution(), "uvTiles": texture_set.uv_tiles, "tiles": tiles, - "channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::>(), + "channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label(), "shaded": channel.is_shaded() })).collect::>(), "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index bdf4be87..3fe920c9 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -498,4 +498,28 @@ mod tests { assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("multiply")); assert!(!s.take_uploads(0).is_empty(), "undo resends the set too"); } + + #[test] + fn channels_our_shader_ignores_are_added_marked_and_exported() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for channel in ["user3", "Displacement", "coat tangent"] { + crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": channel})).unwrap(); + } + let channels = crate::inspect::texture_set(&s, 0)["channels"].clone(); + let shaded = |id: &str| channels.as_array().and_then(|list| list.iter().find(|c| c["channel"] == id)).map(|c| c["shaded"].clone()); + assert_eq!((shaded("user3"), shaded("displacement"), shaded("coatTangent")), (Some(json!(false)), Some(json!(false)), Some(json!(false)))); + assert_eq!(shaded("baseColor"), Some(json!(true))); + + let plan = crate::execute(&mut s, "export.plan", &json!({"preset": "Separate maps"})).unwrap(); + let files: Vec<(Value, String)> = + plan.as_array().into_iter().flatten().map(|f| (f["ts"].clone(), f["file"].as_str().unwrap_or_default().to_ascii_lowercase())).collect(); + for map in ["user3", "displacement", "coattangent"] { + let from = |ts: usize| files.iter().any(|(t, file)| *t == json!(ts) && file.contains(map)); + assert!(from(0) && !from(1), "{map} exported only from the set that has it: {files:?}"); + } + + s.update(); + let composite = &s.caches[0].composite; + assert!(composite.channels.contains_key(&Channel::User3) && composite.channels.contains_key(&Channel::CoatTangent)); + } } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index ed79cb96..454ab930 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -36,8 +36,8 @@ const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; -/// Preset limits (user presets are untrusted JSON). -const MAX_MAPS: usize = 64; +/// Preset limits (user presets are untrusted JSON); maps leave room for one per channel plus packed maps +const MAX_MAPS: usize = 128; const MAX_TEMPLATE: usize = 256; const MAX_STEM: usize = 200; /// Longest preset name. @@ -490,7 +490,7 @@ pub struct ExportInput<'a> { pub composite: &'a Composite, pub baked: &'a BakedMaps, pub coverage: &'a [bool], - /// The set's UV seams, which 3D Space Neighbor padding crosses + /// The set's UV seams, which padding across seams (3D) crosses pub seams: &'a [UvSeam], pub mesh_name: &'a str, } @@ -769,8 +769,7 @@ struct Sampler<'a> { coverage: &'a [bool], /// Composite width. res: u32, - /// Texels across and down an atlas block (the composite for a classic set): the height - /// slope and the slope window follow the block. + /// Texels across and down an atlas block (the composite for a classic set), which the height slope follows block: (u32, u32), /// The share of its block each tile fills: a smaller tile's height slope shrinks with it. scales: BlockScales, @@ -811,22 +810,24 @@ impl Sampler<'_> { self.coverage.get((y as usize) * self.res as usize + x as usize).copied().unwrap_or(false) } - /// Normal from the height channel (the set's height to normal method; uncovered neighbours repeat the centre). + /// Normal from the height channel (the set's height to normal method; uncovered neighbours repeat the centre) fn height_normal(&self, x: u32, y: u32) -> Vec3 { let center = self.channel(Channel::Height, At::Texel(x, y))[0]; - // Clamped to the texel's UV tile. - let (tw, th) = (self.block.0.max(1), self.block.1.max(1)); - let (x0, y0) = ((x / tw * tw) as i64, (y / th * th) as i64); + // Clamped to the texel's UV tile + let (block_width, block_height) = (self.block.0.max(1), self.block.1.max(1)); + let (x0, y0) = ((x / block_width * block_width) as i64, (y / block_height * block_height) as i64); let h = |dx: i32, dy: i32| { - let (sx, sy) = ((x as i64 + dx as i64).clamp(x0, x0 + tw as i64 - 1) as u32, (y as i64 + dy as i64).clamp(y0, y0 + th as i64 - 1) as u32); + let sx = (x as i64 + dx as i64).clamp(x0, x0 + block_width as i64 - 1) as u32; + let sy = (y as i64 + dy as i64).clamp(y0, y0 + block_height as i64 - 1) as u32; if self.covered(sx, sy) { self.channel(Channel::Height, At::Texel(sx, sy))[0] } else { center } }; let [gx, gy] = self.set.height_to_normal.slope(h); + // Slopes per texel become slopes across the tile along each side - let s = self.set.height_strength * self.scales.at(x, y) / HEIGHT_SPAN; - let (sx, sy) = (s * tw as f32, s * th as f32); - // Image y points down; OpenGL normals have +Y up the image. - Vec3::new(-gx * sx, gy * sy, 1.0).try_normalize().unwrap_or(Vec3::Z) + let strength = self.set.height_strength * self.scales.at(x, y) / HEIGHT_SPAN; + let (scale_x, scale_y) = (strength * block_width as f32, strength * block_height as f32); + // Image y points down; OpenGL normals have +Y up the image + Vec3::new(-gx * scale_x, gy * scale_y, 1.0).try_normalize().unwrap_or(Vec3::Z) } /// The final tangent-space normal (OpenGL): baked normal ⊕ (height ⊕ normal channel). @@ -1059,22 +1060,24 @@ pub fn scale_export_side(source_side: u32, block_resolution: u32, export_size: O u32::try_from(scaled).unwrap_or(u32::MAX).max(u32::from(source_side > 0)) } -fn diffuse_blocks(data: &mut Vec, (width, height): (usize, usize), channels: usize, known: &[bool], (block_w, block_h): (usize, usize)) { +fn diffuse_blocks(data: &mut Vec, (width, height): (usize, usize), channels: usize, known: &[bool], block_size: (usize, usize)) { + let (block_width, block_height) = block_size; + // A whole image or a separately exported tile already occupies a contiguous buffer - if block_w >= width && block_h >= height { + if block_width >= width && block_height >= height { diffuse_fill(data, (width, height), channels, known); return; } - for block_y in (0..height).step_by(block_h.max(1)) { - for block_x in (0..width).step_by(block_w.max(1)) { - let (block_width, block_height) = (block_w.min(width - block_x), block_h.min(height - block_y)); - let rows = || (block_y..block_y + block_height).map(|y| (y * width + block_x)..(y * width + block_x + block_width)); + for block_y in (0..height).step_by(block_height.max(1)) { + for block_x in (0..width).step_by(block_width.max(1)) { + let (clipped_width, clipped_height) = (block_width.min(width - block_x), block_height.min(height - block_y)); + let rows = || (block_y..block_y + clipped_height).map(|y| (y * width + block_x)..(y * width + block_x + clipped_width)); let mut block_data: Vec = rows().flat_map(|row| data.get(row.start * channels..row.end * channels).unwrap_or_default().iter().copied()).collect(); let block_known: Vec = rows().flat_map(|row| known.get(row).unwrap_or_default().iter().copied()).collect(); - diffuse_fill(&mut block_data, (block_width, block_height), channels, &block_known); - for (row, chunk) in rows().zip(block_data.chunks(block_width * channels)) { + diffuse_fill(&mut block_data, (clipped_width, clipped_height), channels, &block_known); + for (row, chunk) in rows().zip(block_data.chunks(clipped_width * channels)) { if let Some(destination) = data.get_mut(row.start * channels..row.end * channels) { destination.copy_from_slice(chunk); } diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 2f2879a4..13beff9e 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -87,9 +87,11 @@ pub fn builtin_presets() -> Vec { vec![ preset(DEFAULT_PRESET, { let mut maps: Vec = - Channel::ALL.into_iter().filter(|c| !matches!(c, Channel::Normal | Channel::AmbientOcclusion)).map(channel_map).collect(); + Channel::ALL.into_iter().filter(|c| c.is_shaded() && !matches!(c, Channel::Normal | Channel::AmbientOcclusion)).map(channel_map).collect(); maps.push(map("normal", 8, rgb(|k| ch(Channel::Normal, k)))); maps.push(map("ambientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0)))); + // Later channels come last, so the maps automation addresses by index keep their place + maps.extend(Channel::ALL.into_iter().filter(|c| !c.is_shaded()).map(channel_map)); maps }), // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs index f190370c..7fd30b1d 100644 --- a/crates/ui-egui/src/export_templates/map_lists.rs +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -28,40 +28,56 @@ fn missing(name: &'static str) -> MapEntry { /// Input maps in the OpenPBR parameter groups, then TextureCraft's channels outside OpenPBR pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ - (n_("Base"), vec![missing(n_("Base weight")), channel(Channel::BaseColor), channel(Channel::Metallic), missing(n_("Base diffuse roughness"))]), + (n_("Base"), vec![channel(Channel::BaseWeight), channel(Channel::BaseColor), channel(Channel::Metallic), channel(Channel::BaseDiffuseRoughness)]), ( n_("Specular"), vec![ - missing(n_("Specular weight")), - missing(n_("Specular color")), + channel(Channel::SpecularWeight), + channel(Channel::SpecularColor), channel(Channel::Roughness), channel(Channel::SpecularLevel), channel(Channel::AnisotropyLevel), channel(Channel::AnisotropyAngle), ], ), - (n_("Transmission"), vec![channel(Channel::Transmission), missing(n_("Transmission color"))]), - (n_("Subsurface"), vec![channel(Channel::ScatterWeight), missing(n_("Subsurface color")), missing(n_("Subsurface radius"))]), + (n_("Transmission"), vec![channel(Channel::Transmission), channel(Channel::TransmissionColor)]), + (n_("Subsurface"), vec![channel(Channel::ScatterWeight), channel(Channel::SubsurfaceColor), channel(Channel::SubsurfaceRadiusScale)]), ( n_("Coat"), vec![ channel(Channel::CoatWeight), - missing(n_("Coat color")), + channel(Channel::CoatColor), channel(Channel::CoatRoughness), - missing(n_("Coat roughness anisotropy")), + channel(Channel::CoatAnisotropy), missing(n_("Coat IOR")), + channel(Channel::CoatSpecularLevel), channel(Channel::CoatNormal), - missing(n_("Coat tangent")), + channel(Channel::CoatTangent), ], ), (n_("Sheen"), vec![channel(Channel::SheenWeight), channel(Channel::SheenColor), channel(Channel::SheenRoughness)]), (n_("Emission"), vec![channel(Channel::Emissive)]), - (n_("Thin film"), vec![missing(n_("Thin film weight")), missing(n_("Thin film thickness"))]), + (n_("Thin film"), vec![channel(Channel::ThinFilmWeight), missing(n_("Thin film thickness"))]), ( n_("Geometry"), - vec![channel(Channel::Opacity), channel(Channel::Height), channel(Channel::Normal), missing(n_("Tangent")), channel(Channel::AmbientOcclusion)], + vec![channel(Channel::Opacity), channel(Channel::Height), channel(Channel::Normal), channel(Channel::Tangent), channel(Channel::AmbientOcclusion)], ), - (n_("Other"), vec![channel(Channel::Glossiness), channel(Channel::Specular)]), + ( + n_("Other"), + [ + Channel::BlendingMask, + Channel::Diffuse, + Channel::Displacement, + Channel::Glossiness, + Channel::Ior, + Channel::Reflection, + Channel::Specular, + Channel::Transmissive, + ] + .map(channel) + .to_vec(), + ), + (n_("User"), Channel::ALL.into_iter().filter(|c| c.id().starts_with("user")).map(channel).collect()), ] }); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index d8033152..ff6f91f7 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -432,15 +432,28 @@ fn the_map_lists_stand_in_three_panes_with_their_groups_and_names() { assert!(mesh.left() > input.right(), "Mesh maps stand in a column right of Input maps"); assert!(converted.top() > mesh.bottom() && (converted.left() - mesh.left()).abs() < 2.0, "Converted maps stand below Mesh maps"); - for group in ["Transmission", "Subsurface", "Sheen", "Thin film", "Other"] { + for group in ["Transmission", "Subsurface", "Sheen", "Thin film", "Other", "User"] { assert!(h.query_all_by_label(group).next().is_some(), "group {group}"); } - for name in ["Specular level", "Sheen weight", "Coat normal", "Emissive", "World Space Normal", "Bent Normals", "Normal DirectX", "F0 from specular level"] - { + for name in [ + "Specular level", + "Sheen weight", + "Coat normal", + "Emissive", + "World Space Normal", + "Bent Normals", + "Normal DirectX", + "F0 from specular level", + "Base weight", + "Coat tangent", + "Thin-film weight", + "Subsurface radius scale", + "User31", + ] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(!entry.accesskit_node().is_disabled(), "{name} can be dragged"); } - for name in ["Base weight", "Coat tangent", "Thin film weight", "Subsurface radius"] { + for name in ["Coat IOR", "Thin film thickness"] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(entry.accesskit_node().is_disabled(), "{name} is listed greyed"); } From 8cb65c3c40e28ef23fce35710ad81061010a391c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:21:24 +0000 Subject: [PATCH 112/190] Manage channels: a dialog listing every channel by group, ticked when the set has it, applied in one undo step to this set or all sets --- crates/core/src/channel_group.rs | 118 ++++++++++ crates/core/src/lib.rs | 2 + crates/engine/src/set_cmds.rs | 61 ++++++ crates/ui-egui/src/channel_manager.rs | 296 ++++++++++++++++++++++++++ crates/ui-egui/src/dock.rs | 13 +- crates/ui-egui/src/lib.rs | 1 + 6 files changed, 483 insertions(+), 8 deletions(-) create mode 100644 crates/core/src/channel_group.rs create mode 100644 crates/ui-egui/src/channel_manager.rs diff --git a/crates/core/src/channel_group.rs b/crates/core/src/channel_group.rs new file mode 100644 index 00000000..a1deaae0 --- /dev/null +++ b/crates/core/src/channel_group.rs @@ -0,0 +1,118 @@ +//! The groups the channel manager lists material channels under + +use crate::Channel; + +/// A group of material channels, in the manager's reading order +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChannelGroup { + Base, + Specular, + Transmission, + Subsurface, + Coat, + Sheen, + Emission, + ThinFilm, + Geometry, + Miscellaneous, + User, +} + +impl ChannelGroup { + pub const ALL: [ChannelGroup; 11] = [ + ChannelGroup::Base, + ChannelGroup::Specular, + ChannelGroup::Transmission, + ChannelGroup::Subsurface, + ChannelGroup::Coat, + ChannelGroup::Sheen, + ChannelGroup::Emission, + ChannelGroup::ThinFilm, + ChannelGroup::Geometry, + ChannelGroup::Miscellaneous, + ChannelGroup::User, + ]; + + pub fn label(self) -> &'static str { + match self { + ChannelGroup::Base => "Base", + ChannelGroup::Specular => "Specular", + ChannelGroup::Transmission => "Transmission", + ChannelGroup::Subsurface => "Subsurface", + ChannelGroup::Coat => "Coat", + ChannelGroup::Sheen => "Fuzz / Sheen", + ChannelGroup::Emission => "Emission", + ChannelGroup::ThinFilm => "Thin-film", + ChannelGroup::Geometry => "Geometry", + ChannelGroup::Miscellaneous => "Miscellaneous", + ChannelGroup::User => "User", + } + } + + /// The group's channels, in the order the manager lists them + pub fn channels(self) -> &'static [Channel] { + use Channel as C; + match self { + ChannelGroup::Base => &[C::BaseWeight, C::BaseColor, C::BaseDiffuseRoughness, C::Metallic], + ChannelGroup::Specular => &[C::SpecularWeight, C::SpecularColor, C::Roughness, C::SpecularLevel, C::AnisotropyLevel, C::AnisotropyAngle], + ChannelGroup::Transmission => &[C::Transmission, C::TransmissionColor], + ChannelGroup::Subsurface => &[C::ScatterWeight, C::SubsurfaceColor, C::SubsurfaceRadiusScale], + ChannelGroup::Coat => &[C::CoatWeight, C::CoatColor, C::CoatRoughness, C::CoatAnisotropy, C::CoatSpecularLevel, C::CoatNormal, C::CoatTangent], + ChannelGroup::Sheen => &[C::SheenWeight, C::SheenColor, C::SheenRoughness], + ChannelGroup::Emission => &[C::Emissive], + ChannelGroup::ThinFilm => &[C::ThinFilmWeight], + ChannelGroup::Geometry => &[C::Opacity, C::Normal, C::Height, C::AmbientOcclusion, C::Tangent], + ChannelGroup::Miscellaneous => &[C::BlendingMask, C::Diffuse, C::Displacement, C::Ior, C::Reflection, C::Specular, C::Glossiness, C::Transmissive], + ChannelGroup::User => &[ + C::User0, + C::User1, + C::User2, + C::User3, + C::User4, + C::User5, + C::User6, + C::User7, + C::User8, + C::User9, + C::User10, + C::User11, + C::User12, + C::User13, + C::User14, + C::User15, + C::User16, + C::User17, + C::User18, + C::User19, + C::User20, + C::User21, + C::User22, + C::User23, + C::User24, + C::User25, + C::User26, + C::User27, + C::User28, + C::User29, + C::User30, + C::User31, + ], + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_channel_is_listed_in_exactly_one_group() { + // A channel added to `Channel` but left out here could never be added from the manager + let mut listed: Vec = ChannelGroup::ALL.iter().flat_map(|group| group.channels().iter().copied()).collect(); + let count = listed.len(); + listed.sort(); + listed.dedup(); + assert_eq!(listed.len(), count, "a channel is listed twice"); + assert_eq!(listed, Channel::ALL.to_vec()); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c450cff6..08516311 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -18,6 +18,7 @@ pub mod bevel_smooth; pub mod blend; mod block_scales; pub mod channel; +pub mod channel_group; pub mod color_match; pub mod color_selection; pub mod compare_source; @@ -95,6 +96,7 @@ pub use bevel_direction::BevelDirection; pub use bevel_smooth::BevelSmooth; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use channel_group::ChannelGroup; pub use color_match::ColorMatch; pub use color_selection::ColorSelection; pub use compare_source::CompareSource; diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 3fe920c9..f74d46fb 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -35,6 +35,7 @@ pub fn specs() -> Vec { ), cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)), cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)), + cmd!("textureSet.channels", "Add or remove channels", [], None, "{ts?, add?: [channel], remove?: [channel], allSets?}", always, channels), cmd!("textureSet.channel.format", "Set channel format", [], None, "{ts?, channel, format}", always, channel_format), cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible), cmd!( @@ -245,6 +246,43 @@ fn channel(s: &mut Session, p: &Value, add: bool) -> Result { Ok(Value::Null) } +/// Add and remove several channels in one undo step, on one texture set or on all of them +fn channels(s: &mut Session, p: &Value) -> Result { + let cmd = "textureSet.channels"; + let list = |key: &str| -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(Vec::new()), + Some(Value::Array(items)) => items + .iter() + .map(|item| { + let name = item.as_str().ok_or_else(|| bad(cmd, format!("`{key}` lists channel names")))?; + Channel::parse(name).ok_or_else(|| bad(cmd, format!("unknown channel `{name}`"))) + }) + .collect(), + Some(_) => Err(bad(cmd, format!("`{key}` must be a list of channels"))), + } + }; + let add = list("add")?; + let remove = list("remove")?; + if remove.contains(&Channel::BaseColor) { + return Err(bad(cmd, "base color can't be removed")); + } + if let Some(both) = add.iter().find(|c| remove.contains(c)) { + return Err(bad(cmd, format!("{} is both added and removed", both.label()))); + } + let sets: Vec = if boolp(p, "allSets").unwrap_or(false) { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] }; + s.edit("Add or remove channels", |s| { + for &ts in &sets { + for &c in &add { + add_channel(s, ts, c)?; + } + s.doc.project.texture_set_mut(ts)?.channels.retain(|(c, _)| !remove.contains(c)); + } + Ok(()) + })?; + Ok(json!({ "ts": sets })) +} + /// Store a channel in another format; layer data keeps its precision, so a wider format brings back what was painted fn channel_format(s: &mut Session, p: &Value) -> Result { let cmd = "textureSet.channel.format"; @@ -392,6 +430,29 @@ fn settings(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + #[test] + fn channels_add_and_remove_together_in_one_undo_step_on_every_set() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let has = |s: &Session, ts: usize, c: Channel| s.doc.project.texture_sets[ts].has_channel(c); + assert!(has(&s, 1, Channel::Height) && !has(&s, 1, Channel::User3)); + let edit = json!({"add": ["emissive", "User3"], "remove": ["height"], "allSets": true}); + crate::execute(&mut s, "textureSet.channels", &edit).unwrap(); + for ts in 0..2 { + assert!(has(&s, ts, Channel::Emissive) && has(&s, ts, Channel::User3) && !has(&s, ts, Channel::Height), "set {ts}"); + } + crate::execute(&mut s, "edit.undo", &json!({})).unwrap(); + for ts in 0..2 { + assert!(!has(&s, ts, Channel::Emissive) && !has(&s, ts, Channel::User3) && has(&s, ts, Channel::Height), "set {ts}"); + } + + // Without allSets only the chosen set changes + crate::execute(&mut s, "textureSet.channels", &json!({"ts": 1, "add": ["ior"]})).unwrap(); + assert!(has(&s, 1, Channel::Ior) && !has(&s, 0, Channel::Ior)); + assert!(crate::execute(&mut s, "textureSet.channels", &json!({"remove": ["baseColor"]})).is_err()); + assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["ior"], "remove": ["ior"]})).is_err()); + assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["nope"]})).is_err()); + } + #[test] fn visibility_shows_hides_inverts_and_solos() { // The material ball has two texture sets. diff --git a/crates/ui-egui/src/channel_manager.rs b/crates/ui-egui/src/channel_manager.rs new file mode 100644 index 00000000..5a094d0e --- /dev/null +++ b/crates/ui-egui/src/channel_manager.rs @@ -0,0 +1,296 @@ +//! The dialog that adds and removes a texture set's channels: every channel by group, ticked when the set has it + +use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as icon; +use serde_json::json; +use texturecraft_engine::core::{Channel, ChannelGroup, TextureSet}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::property_sheet::{CHECK_SIZE, PropertySheet, paint_check, paint_keyboard_focus}; +use crate::theme::{Tokens, semibold}; + +/// The columns, left to right: which groups each lists, and how wide it is; the User group runs on into the last column +const COLUMNS: [(&[ChannelGroup], f32); 4] = [ + (&[ChannelGroup::Base, ChannelGroup::Specular, ChannelGroup::Transmission, ChannelGroup::Subsurface], GROUP_COLUMN_WIDTH), + (&[ChannelGroup::Coat, ChannelGroup::Sheen, ChannelGroup::Emission, ChannelGroup::ThinFilm], GROUP_COLUMN_WIDTH), + (&[ChannelGroup::Geometry, ChannelGroup::Miscellaneous], GROUP_COLUMN_WIDTH), + (&[ChannelGroup::User], USER_COLUMN_WIDTH), +]; +const GROUP_COLUMN_WIDTH: f32 = 230.0; +const USER_COLUMN_WIDTH: f32 = 140.0; +const USER_ROWS_PER_COLUMN: usize = 16; + +/// Width of the dialog, in points +const DIALOG_WIDTH: f32 = GROUP_COLUMN_WIDTH * 3.0 + USER_COLUMN_WIDTH * 2.0; + +/// The channel columns scroll past this share of the window's height +const MAX_HEIGHT_SHARE: f32 = 0.75; + +/// The title bar: its height, the title's left edge and size +const TITLE_BAR_HEIGHT: f32 = 30.0; +const TITLE_TEXT_LEFT: f32 = 12.0; +const TEXT_SIZE: f32 = 12.0; +const SMALL_TEXT_SIZE: f32 = 11.0; + +/// Air under the title bar, above the footer, around the dialog's edge and between the footer's parts +const BODY_AIR: f32 = 8.0; +const FOOTER_AIR: f32 = 10.0; +const EDGE_AIR: f32 = 12.0; +const CHECK_TO_LABEL: f32 = 8.0; +const LEGEND_GAP: f32 = 24.0; +const LEGEND_GLYPH_TO_TEXT: f32 = 4.0; + +/// Cancel and Apply: their size, the air between them, the dialog's corners +const BUTTON_SIZE: egui::Vec2 = vec2(88.0, 24.0); +const BUTTON_GAP: f32 = 8.0; +const DIALOG_RADIUS: u8 = 4; + +/// An open dialog: the set it edits, each channel's tick (indexed like [`Channel::ALL`]), and whether Apply goes to every set +#[derive(Clone, Debug)] +pub(crate) struct ChannelManager { + ts: usize, + ticked: Vec, + all_sets: bool, + mesh_id: u64, + opener: egui::Id, +} + +impl ChannelManager { + fn id() -> egui::Id { + egui::Id::unique("channel_manager") + } + + /// Open the dialog on texture set `ts`, ticked as the set is + pub(crate) fn open(app: &TextureCraftApp, opener: &egui::Response, ts: usize) { + let Some(set) = app.session.doc.project.texture_sets.get(ts) else { return }; + let manager = ChannelManager::new(set, ts, app.session.mesh_id, opener.id); + opener.ctx.data_mut(|data| data.insert_temp(Self::id(), Some(manager))); + } + + fn new(set: &TextureSet, ts: usize, mesh_id: u64, opener: egui::Id) -> Self { + let ticked = Channel::ALL.iter().map(|c| set.has_channel(*c)).collect(); + ChannelManager { ts, ticked, all_sets: false, mesh_id, opener } + } + + /// The open dialog, if any; Apply runs one `textureSet.channels` + pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut manager) = ctx.data(|data| data.get_temp::>(Self::id())).flatten() else { + // The opener can receive focus again once the modal layer has left egui's focus order + if ctx.memory(|memory| memory.top_modal_layer().is_none()) + && let Some(opener) = ctx.data_mut(|data| data.remove_temp::>(Self::id().with("opener")).flatten()) + { + ctx.memory_mut(|memory| memory.request_focus(opener)); + } + return; + }; + + if manager.mesh_id != app.session.mesh_id || manager.ts >= app.session.set_count() { + ctx.data_mut(|data| data.remove::>(Self::id())); + return; + } + + let opening = ctx.memory(|memory| memory.top_modal_layer().is_none()); + let tokens = Tokens::get(ctx); + let frame = egui::Frame::new() + .fill(tokens.panel) + .stroke(Stroke::new(1.0, tokens.button_border)) + .corner_radius(CornerRadius::same(DIALOG_RADIUS)) + .inner_margin(0); + let modal = egui::Modal::new(Self::id().with("modal")).frame(frame).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let closed = title_bar(ui, &tokens, opening); + ui.add_space(BODY_AIR); + egui::ScrollArea::vertical().max_height(ctx.content_rect().height() * MAX_HEIGHT_SHARE).show(ui, |ui| manager.columns(ui)); + ui.add_space(FOOTER_AIR); + let (apply, cancel) = manager.footer(ui, &tokens); + ui.add_space(EDGE_AIR); + (apply, cancel || closed) + }); + + let (apply, cancel) = modal.inner; + if apply && let Some(set) = app.session.doc.project.texture_sets.get(manager.ts) { + let (add, remove) = manager.edits(set); + if !add.is_empty() || !remove.is_empty() { + let ids = |list: Vec| list.into_iter().map(Channel::id).collect::>(); + app.run("textureSet.channels", json!({ "ts": manager.ts, "add": ids(add), "remove": ids(remove), "allSets": manager.all_sets })); + } + } + if apply || cancel || modal.should_close() { + ctx.data_mut(|data| { + data.remove::>(Self::id()); + data.insert_temp(Self::id().with("opener"), Some(manager.opener)); + }); + ctx.request_repaint(); + } else { + ctx.data_mut(|data| data.insert_temp(Self::id(), Some(manager))); + } + } + + /// The channels to add and to remove: against `set` alone, or for every set the whole ticked list + fn edits(&self, set: &TextureSet) -> (Vec, Vec) { + let ticked = |c: &Channel| self.ticked.get(c.index()).copied().unwrap_or(false); + let (on, off): (Vec, Vec) = Channel::ALL.into_iter().partition(ticked); + if self.all_sets { + // Other sets may differ from this one: send the whole list so every set ends up the same + return (on, off.into_iter().filter(|c| *c != Channel::BaseColor).collect()); + } + (on.into_iter().filter(|c| !set.has_channel(*c)).collect(), off.into_iter().filter(|c| set.has_channel(*c)).collect()) + } + + /// The groups side by side, a check per channel; a dim ⊘ marks the material channels our shader doesn't read + fn columns(&mut self, ui: &mut Ui) { + let mut user_rows_top = None; + ui.horizontal_top(|ui| { + for (column, (groups, width)) in COLUMNS.iter().enumerate() { + ui.vertical(|ui| { + ui.set_width(*width); + PropertySheet::show(ui, ("channel_manager", column), |sheet| { + for group in *groups { + sheet.section(tr(group.label()), false); + let channels = group.channels(); + let shown = if *group == ChannelGroup::User { &channels[..USER_ROWS_PER_COLUMN] } else { channels }; + for (row, channel) in shown.iter().enumerate() { + let response = self.check(sheet, *channel); + if *group == ChannelGroup::User && row == 0 { + user_rows_top = Some(response.rect.top()); + } + } + } + }); + }); + } + // The rest of the User group, its rows level with the first half's + ui.vertical(|ui| { + ui.set_width(USER_COLUMN_WIDTH); + if let Some(top) = user_rows_top { + ui.add_space((top - ui.cursor().top()).max(0.0)); + } + PropertySheet::show(ui, ("channel_manager", COLUMNS.len()), |sheet| { + for channel in &ChannelGroup::User.channels()[USER_ROWS_PER_COLUMN..] { + self.check(sheet, *channel); + } + }); + }); + }); + } + + fn check(&mut self, sheet: &mut PropertySheet<'_>, channel: Channel) -> egui::Response { + let Some(on) = self.ticked.get(channel.index()).copied() else { + return sheet.ui.allocate_response(egui::Vec2::ZERO, Sense::hover()); + }; + + // User channels are the user's own data for export: reading them is never the shader's job, so they carry no mark + let user = ChannelGroup::User.channels().contains(&channel); + let note = (!channel.is_shaded() && !user).then_some(icon::PROHIBIT); + // Base color stays: every set has it + let fixed = channel == Channel::BaseColor; + let response = sheet.greyed(!fixed, fixed.then(|| tr("Base color can't be removed")), |sheet| sheet.check_noted(tr(channel.label()), Some(on), note)); + if note.is_some() { + sheet.ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(tr("Not used by the shader"))); + } + if response.clicked() + && let Some(tick) = self.ticked.get_mut(channel.index()) + { + *tick = !on; + } + response + } + + /// "Apply to all Texture Sets", the ⊘ legend, then Cancel and Apply at the right; returns (Apply, Cancel) clicked + fn footer(&mut self, ui: &mut Ui, tokens: &Tokens) -> (bool, bool) { + let (row, _) = ui.allocate_exact_size(vec2(DIALOG_WIDTH, BUTTON_SIZE.y), Sense::hover()); + ui.painter().hline(row.x_range(), row.top() - FOOTER_AIR / 2.0, Stroke::new(1.0, tokens.separator)); + let center_y = row.center().y; + + let label = tr("Apply to all Texture Sets"); + let text = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text); + let check = Rect::from_min_size(pos2(row.left() + EDGE_AIR, center_y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); + let hit = Rect::from_min_max(pos2(check.left(), row.top()), pos2(check.right() + CHECK_TO_LABEL + text.size().x, row.bottom())); + let response = ui.interact(hit, ui.scope_id().with("all_sets"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, self.all_sets, label)); + if response.clicked() { + self.all_sets = !self.all_sets; + } + paint_check(ui.painter(), tokens, check, Some(self.all_sets), response.hovered()); + ui.painter().galley(pos2(check.right() + CHECK_TO_LABEL, center_y - text.size().y / 2.0), text, tokens.text); + paint_keyboard_focus(ui, &response, tokens); + + let legend = hit.right() + LEGEND_GAP; + let glyph = ui.painter().text(pos2(legend, center_y), Align2::LEFT_CENTER, icon::PROHIBIT, FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); + let text_left = glyph.right() + LEGEND_GLYPH_TO_TEXT; + ui.painter().text(pos2(text_left, center_y), Align2::LEFT_CENTER, tr("Not used by the shader"), FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); + + let apply = Rect::from_min_size(pos2(row.right() - EDGE_AIR - BUTTON_SIZE.x, row.top()), BUTTON_SIZE); + let cancel = apply.translate(vec2(-(BUTTON_SIZE.x + BUTTON_GAP), 0.0)); + (dialog_button(ui, tokens, apply, tr("Apply")), dialog_button(ui, tokens, cancel, tr("Cancel"))) + } +} + +/// The title and × at the right; returns whether × was clicked +fn title_bar(ui: &mut Ui, tokens: &Tokens, opening: bool) -> bool { + let (bar, _) = ui.allocate_exact_size(vec2(DIALOG_WIDTH, TITLE_BAR_HEIGHT), Sense::hover()); + let top = CornerRadius { nw: DIALOG_RADIUS, ne: DIALOG_RADIUS, sw: 0, se: 0 }; + ui.painter().rect_filled(bar, top, tokens.chrome); + let center_y = bar.center().y; + let text = Rect::from_min_max(pos2(bar.left() + TITLE_TEXT_LEFT, bar.top()), pos2(bar.right() - TITLE_BAR_HEIGHT, bar.bottom())); + let label = egui::Label::new(RichText::new(tr("Add or remove channels")).font(semibold(TEXT_SIZE)).color(tokens.text_strong)).truncate(); + ui.scope_builder(egui::UiBuilder::new().max_rect(text).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| ui.add(label)); + + let close = Rect::from_center_size(pos2(bar.right() - TITLE_BAR_HEIGHT / 2.0, center_y), vec2(TITLE_BAR_HEIGHT, TITLE_BAR_HEIGHT)); + let response = ui.interact(close, ui.scope_id().with("close"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Close"))); + if opening { + response.request_focus(); + } + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(close.center(), Align2::CENTER_CENTER, icon::X, FontId::proportional(TEXT_SIZE), color); + paint_keyboard_focus(ui, &response, tokens); + response.clicked() +} + +fn dialog_button(ui: &mut Ui, tokens: &Tokens, rect: Rect, text: &str) -> bool { + let response = ui.interact(rect, ui.scope_id().with(text), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; + ui.painter().rect(rect, CornerRadius::same(DIALOG_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, text, FontId::proportional(TEXT_SIZE), tokens.text); + paint_keyboard_focus(ui, &response, tokens); + response.clicked() +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::{Channel, TextureSet}; + + use super::ChannelManager; + + fn set() -> TextureSet { + texturecraft_engine::sample_session(128, 64).map(|s| s.doc.project.texture_sets[0].clone()).unwrap() + } + + #[test] + fn apply_sends_only_what_the_ticks_changed() { + let set = set(); + let mut manager = ChannelManager::new(&set, 0, 0, egui::Id::NULL); + assert_eq!(manager.edits(&set), (vec![], vec![]), "an untouched dialog changes nothing"); + + manager.ticked[Channel::Ior.index()] = true; + manager.ticked[Channel::Height.index()] = false; + assert!(set.has_channel(Channel::Height)); + assert_eq!(manager.edits(&set), (vec![Channel::Ior], vec![Channel::Height])); + } + + #[test] + fn apply_to_all_sets_sends_the_whole_list_but_never_removes_base_color() { + // Another set may lack a channel this one has: only the full list makes every set match + let set = set(); + let mut manager = ChannelManager::new(&set, 0, 0, egui::Id::NULL); + manager.all_sets = true; + let (add, remove) = manager.edits(&set); + assert!(set.channels.iter().all(|(c, _)| add.contains(c))); + assert_eq!(add.len() + remove.len(), Channel::ALL.len(), "every channel is sent one way or the other"); + assert!(!remove.contains(&Channel::BaseColor) && !remove.iter().any(|c| set.has_channel(*c))); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index b1ddf848..73abfd80 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1540,6 +1540,7 @@ const MESH_MAP_FILE_TEXT_SIZE: f32 = 10.5; const MESH_MAP_MENU_ICON_SIZE: f32 = 13.0; pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + crate::channel_manager::ChannelManager::show(app, &ui.ctx().clone()); let tokens = Tokens::get(ui.ctx()); let set_index = app.session.ts(); let Some(set) = app.session.doc.project.texture_sets.get(set_index).cloned() else { return }; @@ -1590,14 +1591,10 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { ui.horizontal(|ui| { ui.label(caption(tr("Channels"))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(tr("Add channel"), |ui| { - for channel in Channel::ALL { - if !set.has_channel(channel) && ui.button(tr(channel.label())).clicked() { - app.run("textureSet.channel.add", json!({"ts": set_index, "channel": channel.id()})); - ui.close(); - } - } - }); + let manage = ui.button(tr("Add or remove channels")); + if manage.clicked() { + crate::channel_manager::ChannelManager::open(app, &manage, set_index); + } }); }); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b39d618f..9b6eb96f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ mod bake_preset; pub mod bake_presets; mod bake_report; mod bake_scene; +mod channel_manager; mod color_management; mod color_picker; mod color_selection_editor; From 3ff32d91ccbc4686b2ac450ccaac186693693141 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:07:19 +0000 Subject: [PATCH 113/190] Texture Set list rows: size and shader dropdowns per row, rename in place, a right-click menu, descriptions, and a UV tile set's tiles under it with their own size --- crates/core/src/project.rs | 12 + crates/engine/src/inspect.rs | 22 +- crates/engine/src/set_cmds.rs | 165 +++-- crates/ui-egui/src/dock.rs | 95 +-- crates/ui-egui/src/docking.rs | 5 +- crates/ui-egui/src/layer_toolbar.rs | 40 +- crates/ui-egui/src/layer_toolbar/add_item.rs | 14 +- crates/ui-egui/src/layer_toolbar/item_icon.rs | 2 +- crates/ui-egui/src/layer_toolbar/menu_icon.rs | 2 +- crates/ui-egui/src/layer_toolbar/pick.rs | 2 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/property_sheet/choice.rs | 44 +- crates/ui-egui/src/property_sheet/mod.rs | 1 + crates/ui-egui/src/texture_set_list.rs | 646 ++++++++++++++++++ .../src/texture_set_list/description_mode.rs | 19 + .../src/texture_set_list/list_state.rs | 29 + .../src/texture_set_list/row_action.rs | 12 + .../ui-egui/src/texture_set_list/row_edit.rs | 6 + .../ui-egui/src/texture_set_list/set_row.rs | 12 + .../src/texture_set_list/tile_action.rs | 5 + crates/ui-egui/tests/it/project_config.rs | 3 +- 21 files changed, 927 insertions(+), 210 deletions(-) create mode 100644 crates/ui-egui/src/texture_set_list.rs create mode 100644 crates/ui-egui/src/texture_set_list/description_mode.rs create mode 100644 crates/ui-egui/src/texture_set_list/list_state.rs create mode 100644 crates/ui-egui/src/texture_set_list/row_action.rs create mode 100644 crates/ui-egui/src/texture_set_list/row_edit.rs create mode 100644 crates/ui-egui/src/texture_set_list/set_row.rs create mode 100644 crates/ui-egui/src/texture_set_list/tile_action.rs diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index d2372215..4fb6f848 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -350,6 +350,18 @@ impl TextureSet { self.channels.iter().map(|(channel, format)| (*channel, held(*format))).collect() } + /// Add channel `c` in its default format (16-bit or more until a format is set, see [`TextureSet::formats`]); false when present + pub fn add_channel(&mut self, c: Channel) -> bool { + if self.has_channel(c) { + return false; + } + + let format = ChannelFormat::default_for(c); + self.channels.push((c, if self.format_precision { format.at_least_16_bit() } else { format })); + self.channels.sort_by_key(|(c, _)| c.index()); + true + } + /// Store channel `target` in `format` (false when the set lacks it); the other channels keep what they hold pub fn set_channel_format(&mut self, target: Channel, format: ChannelFormat) -> bool { if !self.has_channel(target) { diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 1c5f9c7e..82f2cb66 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -264,6 +264,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value { json!({ "index": index, "name": texture_set.name, + "originalName": session.original_set_name(index), + "description": texture_set.description, "resolution": texture_set.resolution, "height": texture_set.height(), "size": texture_set.size(), @@ -275,22 +277,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), "visible": texture_set.visible, - "normalMixing": match texture_set.normal_mixing { - texturecraft_core::NormalMixing::Combine => "combine", - texturecraft_core::NormalMixing::Replace => "replace", - }, - "aoMixing": match texture_set.ao_mixing { - texturecraft_core::AoMixing::Multiply => "multiply", - texturecraft_core::AoMixing::None => "none", - }, - "heightToNormal": match texture_set.height_to_normal { - texturecraft_core::HeightToNormalMethod::Sharp => "sharp", - texturecraft_core::HeightToNormalMethod::Smooth => "smooth", - }, - "uvPadding": match texture_set.uv_padding { - texturecraft_core::UvPaddingMode::Space3d => "3d", - texturecraft_core::UvPaddingMode::Space2d => "2d", - }, + "normalMixing": texture_set.normal_mixing.id(), + "aoMixing": texture_set.ao_mixing.id(), + "heightToNormal": texture_set.height_to_normal.id(), + "uvPadding": texture_set.uv_padding.id(), "active": index == session.ts(), }) } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index f74d46fb..6b438759 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Inspect texture set", [], None, - "{ts?} → {index, name, resolution, height, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, active}", + "{ts?} → {index, name, originalName, description, resolution, height, size: [w, h], blockResolution, uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y], resolution, bakeEnabled}], channels: [{channel, format, shaded}], layers, parts, baked, visible, normalMixing, aoMixing, heightToNormal, uvPadding, active}", always, |s, p| Ok(crate::inspect::texture_set(s, ts_param(s, p, "textureSet.inspect")?)) ), @@ -47,7 +47,15 @@ pub fn specs() -> Vec { always, visibility ), - cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename), + cmd!( + "textureSet.rename", + "Rename texture set", + [], + None, + "{ts?, name} or {ts?, reset: true} (back to the mesh material's name, `originalName` in inspect)", + always, + rename + ), cmd!( "textureSet.settings", "Texture set settings", @@ -121,9 +129,9 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> { fn resolution(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.resolution")?; - let r = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?; - let height = u64p(p, "height").unwrap_or(r); - let task = s.resize_task_to(ts, u32::try_from(r).unwrap_or(0), u32::try_from(height).unwrap_or(0))?; + let width = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?; + let height = u64p(p, "height").unwrap_or(width); + let task = s.resize_task_to(ts, u32::try_from(width).unwrap_or(0), u32::try_from(height).unwrap_or(0))?; let out = task.run(&texturecraft_bake::Progress::new())?; s.apply_resize(out) } @@ -190,12 +198,12 @@ impl ResizeOutput { } impl Session { - /// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192). + /// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192) pub fn resize_task(&mut self, ts: usize, resolution: u32) -> Result { self.resize_task_to(ts, resolution, resolution) } - /// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192). + /// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192) pub fn resize_task_to(&mut self, ts: usize, width: u32, height: u32) -> Result { let (resolution, height) = (check_resolution(width)?, check_resolution(height)?); self.doc.project.texture_set(ts)?; @@ -262,15 +270,19 @@ fn channels(s: &mut Session, p: &Value) -> Result { Some(_) => Err(bad(cmd, format!("`{key}` must be a list of channels"))), } }; + let add = list("add")?; let remove = list("remove")?; + if remove.contains(&Channel::BaseColor) { return Err(bad(cmd, "base color can't be removed")); } if let Some(both) = add.iter().find(|c| remove.contains(c)) { return Err(bad(cmd, format!("{} is both added and removed", both.label()))); } + let sets: Vec = if boolp(p, "allSets").unwrap_or(false) { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] }; + s.edit("Add or remove channels", |s| { for &ts in &sets { for &c in &add { @@ -280,6 +292,7 @@ fn channels(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; + Ok(json!({ "ts": sets })) } @@ -291,6 +304,7 @@ fn channel_format(s: &mut Session, p: &Value) -> Result { let name = strp(p, "format").ok_or_else(|| bad(cmd, "`format` is required"))?; let all = || ChannelFormat::ALL.map(ChannelFormat::label).join(", "); let format = ChannelFormat::parse(name).ok_or_else(|| bad(cmd, format!("unknown format {name:?} ({})", all())))?; + s.edit("Channel format", |s| { if s.doc.project.texture_set_mut(ts)?.set_channel_format(c, format) { Ok(()) @@ -298,6 +312,7 @@ fn channel_format(s: &mut Session, p: &Value) -> Result { Err(bad(cmd, format!("the texture set has no {} channel", c.label()))) } })?; + let float = matches!(format, ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F); Ok(if float { json!({"note": "float formats are stored at 16 bits for now, and values stay in the channel's range"}) } else { Value::Null }) } @@ -305,11 +320,8 @@ fn channel_format(s: &mut Session, p: &Value) -> Result { /// Add channel `c` to texture set `ts` (no-op when present) and enable it on the set's layers. /// Call inside [`Session::edit`]. pub(crate) fn add_channel(s: &mut Session, ts: usize, c: Channel) -> Result<()> { - let set = s.doc.project.texture_set_mut(ts)?; - if !set.has_channel(c) { - set.channels.push((c, ChannelFormat::default_for(c))); - set.channels.sort_by_key(|(c, _)| c.index()); - } + s.doc.project.texture_set_mut(ts)?.add_channel(c); + // Existing layers get the new channel enabled. let ids: Vec<_> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect(); for id in ids { @@ -349,13 +361,23 @@ fn visibility(s: &mut Session, p: &Value) -> Result { Ok(json!({ "visible": s.doc.project.texture_sets.iter().map(|t| t.visible).collect::>() })) } +/// Longest texture set name and description, in characters +const MAX_NAME_CHARS: usize = 128; +const MAX_DESCRIPTION_CHARS: usize = 4096; +/// Highest height strength a set takes +const MAX_HEIGHT_STRENGTH: f32 = 100.0; + fn rename(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.rename")?; - let name = strp(p, "name") - .map(str::trim) - .filter(|n| !n.is_empty() && n.chars().count() <= 128) - .ok_or_else(|| bad("textureSet.rename", "`name` is required"))? - .to_string(); + let name = if boolp(p, "reset") == Some(true) { + s.original_set_name(ts).ok_or_else(|| bad("textureSet.rename", "the mesh has no material name for this set"))?.to_string() + } else { + strp(p, "name") + .map(str::trim) + .filter(|name| !name.is_empty() && name.chars().count() <= MAX_NAME_CHARS) + .ok_or_else(|| bad("textureSet.rename", "`name` or `reset: true` is required"))? + .to_string() + }; s.edit("Rename texture set", |s| { s.doc.project.texture_set_mut(ts)?.name = name; Ok(()) @@ -363,44 +385,32 @@ fn rename(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +impl Session { + /// The name set `ts` had when the mesh loaded: its material's name in the mesh + pub fn original_set_name(&self, ts: usize) -> Option<&str> { + let set = self.doc.project.texture_sets.get(ts)?; + self.mesh.materials.get(set.material).map(String::as_str).filter(|name| !name.trim().is_empty()) + } +} + fn settings(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.settings")?; - let nf = normal_format_param("textureSet.settings", p)?; - let ao_mixing_before = s.doc.project.texture_set(ts)?.ao_mixing; - let normal_mixing = match strp(p, "normalMixing") { - None => None, - Some("combine") => Some(NormalMixing::Combine), - Some("replace") => Some(NormalMixing::Replace), - Some(other) => return Err(bad("textureSet.settings", format!("unknown normal mixing {other:?} (combine or replace)"))), - }; - let ao_mixing = match strp(p, "aoMixing") { - None => None, - Some("multiply") => Some(AoMixing::Multiply), - Some("none") => Some(AoMixing::None), - Some(other) => return Err(bad("textureSet.settings", format!("unknown ambient occlusion mixing {other:?} (multiply or none)"))), - }; - let height_to_normal = match strp(p, "heightToNormal") { - None => None, - Some("sharp") => Some(HeightToNormalMethod::Sharp), - Some("smooth") => Some(HeightToNormalMethod::Smooth), - Some(other) => return Err(bad("textureSet.settings", format!("unknown height to normal method {other:?} (sharp or smooth)"))), - }; - let uv_padding = match strp(p, "uvPadding") { - None => None, - Some("3d") => Some(UvPaddingMode::Space3d), - Some("2d") => Some(UvPaddingMode::Space2d), - Some(other) => return Err(bad("textureSet.settings", format!("unknown UV padding {other:?} (3d or 2d)"))), - }; + let normal_format = normal_format_param("textureSet.settings", p)?; + let normal_mixing = choice_param(p, "normalMixing", "normal mixing", NormalMixing::parse, &NormalMixing::ALL.map(NormalMixing::id))?; + let ao_mixing = choice_param(p, "aoMixing", "ambient occlusion mixing", AoMixing::parse, &AoMixing::ALL.map(AoMixing::id))?; + let height_to_normal = + choice_param(p, "heightToNormal", "height to normal method", HeightToNormalMethod::parse, &HeightToNormalMethod::ALL.map(HeightToNormalMethod::id))?; + let uv_padding = choice_param(p, "uvPadding", "UV padding", UvPaddingMode::parse, &UvPaddingMode::ALL.map(UvPaddingMode::id))?; s.edit("Texture set settings", |s| { - if let Some(n) = nf { - s.doc.project.normal_format = n; + if let Some(format) = normal_format { + s.doc.project.normal_format = format; } let set = s.doc.project.texture_set_mut(ts)?; - if let Some(d) = strp(p, "description") { - set.description = d.chars().take(4096).collect(); + if let Some(description) = strp(p, "description") { + set.description = description.chars().take(MAX_DESCRIPTION_CHARS).collect(); } - if let Some(h) = f32p(p, "heightStrength") { - set.height_strength = h.clamp(0.0, 100.0); + if let Some(strength) = f32p(p, "heightStrength") { + set.height_strength = strength.clamp(0.0, MAX_HEIGHT_STRENGTH); } if let Some(mixing) = normal_mixing { set.normal_mixing = mixing; @@ -416,16 +426,16 @@ fn settings(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - - // The viewport's occlusion texture mixes the baked map in: resend the set - if s.doc.project.texture_set(ts)?.ao_mixing != ao_mixing_before - && let Some(cache) = s.caches.get_mut(ts) - { - cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1)); - } Ok(Value::Null) } +/// The optional setting `key` of `textureSet.settings`, one of `ids` +fn choice_param(p: &Value, key: &str, what: &str, parse: fn(&str) -> Option, ids: &[&str]) -> Result> { + let Some(id) = strp(p, key) else { return Ok(None) }; + + parse(id).map(Some).ok_or_else(|| bad("textureSet.settings", format!("unknown {what} {id:?} ({})", ids.join(" or ")))) +} + #[cfg(test)] mod tests { use super::*; @@ -453,6 +463,18 @@ mod tests { assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["nope"]})).is_err()); } + #[test] + fn rename_reset_restores_the_mesh_material_name() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let original = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"].clone(); + crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "Renamed"})).unwrap(); + let inspect = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap(); + assert_eq!((&inspect["name"], &inspect["originalName"]), (&json!("Renamed"), &original)); + crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "reset": true})).unwrap(); + assert_eq!(crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"], original); + assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1})).is_err()); + } + #[test] fn visibility_shows_hides_inverts_and_solos() { // The material ball has two texture sets. @@ -516,7 +538,10 @@ mod tests { #[test] fn channel_format_changes_what_the_viewport_holds_and_undoes() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); - let format = |s: &Session| crate::inspect::texture_set(s, 0)["channels"][2]["format"].clone(); + let format = |s: &Session| { + let channels = crate::inspect::texture_set(s, 0)["channels"].clone(); + channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == "roughness")).map(|entry| entry["format"].clone()) + }; let roughness = |s: &mut Session| { s.update(); let img = &s.caches[0].composite.channels[&Channel::Roughness]; @@ -524,15 +549,17 @@ mod tests { img.tile(tile.0, tile.1).map(<[u16]>::to_vec).unwrap_or_default() }; crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L16"})).unwrap(); + // A roughness off the 8-bit grid, so 8 bits visibly round it crate::execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3013})).unwrap(); let sixteen = roughness(&mut s); - assert_eq!(format(&s), json!("L16")); + assert_eq!(format(&s), Some(json!("L16"))); crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "Roughness", "format": "l8"})).unwrap(); let eight = roughness(&mut s); - assert_eq!(format(&s), json!("L8")); + assert_eq!(format(&s), Some(json!("L8"))); assert_ne!(eight, sixteen, "the composite holds 8 bits"); - assert!(eight.iter().all(|v| v % 257 == 0), "every texel is on an 8-bit step"); + let eight_bit_step = u16::MAX / u16::from(u8::MAX); + assert!(eight.iter().all(|v| v % eight_bit_step == 0), "every texel is on an 8-bit step"); let float = crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "height", "format": "L32F"})).unwrap(); assert!(float["note"].is_string(), "a float format says it holds 16 bits"); @@ -540,7 +567,23 @@ mod tests { assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L4"})).is_err()); assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "emissive", "format": "L8"})).is_err()); crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert_eq!((format(&s), roughness(&mut s)), (json!("L16"), sixteen)); + assert_eq!((format(&s), roughness(&mut s)), (Some(json!("L16")), sixteen)); + } + + #[test] + fn channels_added_after_a_format_is_set_keep_16_bits() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let format = |s: &Session, id: &str| { + let channels = crate::inspect::texture_set(s, 0)["channels"].clone(); + channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == id)).map(|entry| entry["format"].clone()) + }; + crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 0, "channel": "roughness", "format": "L8"})).unwrap(); + + crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": "user3"})).unwrap(); + crate::execute(&mut s, "textureSet.channels", &json!({"ts": 0, "add": ["user4"]})).unwrap(); + + assert_eq!((format(&s, "user3"), format(&s, "user4")), (Some(json!("L16")), Some(json!("L16")))); + assert_eq!(format(&s, "roughness"), Some(json!("L8")), "the set format stays"); } #[test] diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 73abfd80..b0991d59 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -36,100 +36,7 @@ const TAG_COLORS: [Color32; 8] = [ ]; pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { - // The empty state lists nothing - if !app.session.project_open { - return; - } - - let tk = Tokens::get(ui.ctx()); - let sets: Vec<(String, String, bool)> = app - .session - .doc - .project - .texture_sets - .iter() - .map(|t| { - let (width, height) = (t.resolution, t.height()); - let size = match t.uv_tiles.len() { - 0 => format!("{width}x{height}"), - n => format!("{width}x{height}, {n} UDIM"), - }; - (t.name.clone(), size, t.visible) - }) - .collect(); - let active = app.session.ts(); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - ui.menu_button(RichText::new(ic::EYE).size(14.0), |ui| { - for (label, mode) in [(tr("Show all"), "showAll"), (tr("Hide all"), "hideAll"), (tr("Invert show/hide"), "invert")] { - if ui.button(label).clicked() { - app.run("textureSet.visibility", json!({ "mode": mode })); - ui.close(); - } - } - }) - .response - .on_hover_text(tr("Show or hide texture sets")); - let solo = sets.iter().enumerate().all(|(i, s)| s.2 == (i == active)); - if icon_button(ui, ic::FRAME_CORNERS, tr("Focus: show only the active texture set"), solo && sets.len() > 1, 22.0).clicked() { - app.run("textureSet.visibility", json!({ "mode": "solo" })); - } - }); - egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| { - for (i, (name, size, visible)) in sets.into_iter().enumerate() { - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &name)); - ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(i == active)); - - let p = ui.painter(); - let bg = if i == active { - tk.row_selected - } else if resp.hovered() { - tk.row_hover - } else { - tk.panel - }; - p.rect_filled(rect, 2.0, bg); - if i == active { - p.rect_stroke(rect, 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } - if resp.has_focus() { - p.rect_stroke(rect.shrink(2.0), 2.0, Stroke::new(1.0, tk.text_strong), egui::StrokeKind::Inside); - } - - let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0)); - let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set")); - p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text); - - if ui.is_enabled() && (resp.contains_pointer() || eye_resp.contains_pointer()) { - app.next_hovered_texture_set = Some((app.session.project_id, i)); - } - - // Narrow panels drop the shader label, then the resolution, before cutting the name - let cy = rect.center().y; - let mut right = rect.right() - 6.0; - if rect.width() >= 260.0 { - let g = p.layout_no_wrap(tr("Main shader").into(), egui::FontId::proportional(11.0), tk.text_dim); - right -= g.size().x; - p.galley(pos2(right, cy - g.size().y * 0.5), g, tk.text_dim); - right -= 10.0; - } - if rect.width() >= 170.0 { - let g = p.layout_no_wrap(size, egui::FontId::proportional(11.0), tk.text_dim); - let x = (rect.left() + rect.width() * 0.48).min(right - g.size().x); - p.galley(pos2(x, cy - g.size().y * 0.5), g, tk.text_dim); - right = x - 8.0; - } - let color = if i == active { tk.text_strong } else { tk.text }; - let g = elided(p, name, 12.0, color, right - rect.left() - 26.0); - p.galley(pos2(rect.left() + 26.0, cy - g.size().y * 0.5), g, color); - if eye_resp.clicked() { - app.run("textureSet.visible", json!({"ts": i})); - } else if resp.clicked() { - app.run("textureSet.select", json!({"ts": i})); - } - } - }); + crate::texture_set_list::show(app, ui); } // --------------------------------------------------------------------------------------------- diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 6c4f5f97..7a7afe3f 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -168,10 +168,11 @@ pub fn default_workspace() -> Workspace { // The Assets split keeps four tiles visible at the reference window width const ASSETS_SPLIT_RATIO: f32 = 0.16; const VIEWPORT_SPLIT_RATIO: f32 = 0.80; - const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; + // Three texture set rows show at the default window height + const TEXTURE_SET_SPLIT_RATIO: f32 = 0.2; // Leave room for three layer rows and the fill's channel controls - const LAYERS_SPLIT_RATIO: f32 = 0.31; + const LAYERS_SPLIT_RATIO: f32 = 0.34; let column = split( Axis::Y, diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 83e028db..957293af 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -22,11 +22,11 @@ mod item_icon; mod menu_icon; mod pick; -use add_item::AddItem; +pub(crate) use add_item::AddItem; use bitmap_choice::BitmapChoice; -use item_icon::ItemIcon; -use menu_icon::MenuIcon; -use pick::Pick; +pub(crate) use item_icon::ItemIcon; +pub(crate) use menu_icon::MenuIcon; +pub(crate) use pick::Pick; /// The row's height and its controls' height const BAR_HEIGHT: f32 = 40.0; @@ -64,7 +64,7 @@ const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + 3.0 * BUTTON_GAP; const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH; /// A hanging menu: its caption, rows, icon and text columns and its smallest width -const MENU_PADDING: f32 = 4.0; +pub(crate) const MENU_PADDING: f32 = 4.0; const MENU_CAPTION_HEIGHT: f32 = 22.0; const MENU_CAPTION_X: f32 = 12.0; const MENU_CAPTION_SIZE: f32 = 10.0; @@ -201,7 +201,15 @@ const TAB_SEAM_COVER: f32 = 2.5; const TAB_BORDER_WIDTH: f32 = 1.0; /// A button with its icon and a caret whose menu hangs from it (caption, then the `items` built while it is open); the item picked -fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &str, items: impl FnOnce() -> Vec, tokens: &Tokens) -> Option { +pub(crate) fn menu_button( + ui: &mut Ui, + rect: Rect, + label: &str, + icon: MenuIcon, + caption: &str, + items: impl FnOnce() -> Vec, + tokens: &Tokens, +) -> Option { let response = tip_above(ui.interact(rect, ui.scope_id().with(("layer_toolbar_menu", label)), Sense::click()), label); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); let popup = ui.scope_id().with(("layer_toolbar_menu_popup", label)); @@ -215,11 +223,7 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s // A click opens the menu this frame let items = if open || response.clicked() { items() } else { Vec::new() }; let width = menu_width(ui, &items); - let frame = Frame::NONE - .fill(tokens.chrome) - .stroke(Stroke::new(1.0, tokens.field_border)) - .corner_radius(CornerRadius { nw: 0, ..CornerRadius::same(MENU_ROUNDING) }) - .shadow(Shadow { offset: SHADOW_OFFSET, blur: 0, spread: 0, color: HARD_SHADOW }); + let frame = menu_frame(tokens).corner_radius(CornerRadius { nw: 0, ..CornerRadius::same(MENU_ROUNDING) }); let mut picked = None; let shown = egui::Popup::menu(&response).id(popup).align(egui::RectAlign::BOTTOM_START).gap(MENU_TAB_OVERLAP).frame(frame).width(width).show(|ui| { ui.set_width(width); @@ -256,6 +260,16 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s picked } +/// The toolbar menus' frame: chrome fill, field border, hard shadow +pub(crate) fn menu_frame(tokens: &Tokens) -> Frame { + Frame::NONE.fill(tokens.chrome).stroke(Stroke::new(1.0, tokens.field_border)).corner_radius(CornerRadius::same(MENU_ROUNDING)).shadow(Shadow { + offset: SHADOW_OFFSET, + blur: 0, + spread: 0, + color: HARD_SHADOW, + }) +} + /// A menu button's icon and caret fn button_face(painter: &Painter, rect: Rect, icon: MenuIcon, tokens: &Tokens) { let icon_at = pos2(rect.left() + MENU_ICON_X, rect.center().y); @@ -269,7 +283,7 @@ fn button_face(painter: &Painter, rect: Rect, icon: MenuIcon, tokens: &Tokens) { } /// The menu's width: its longest item, with room for the icons and the right edge -fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 { +pub(crate) fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 { let widest = items .iter() .map(|item| ui.fonts_mut(|fonts| fonts.layout_no_wrap(tr(item.short).to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x)) @@ -278,7 +292,7 @@ fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 { } /// One menu row: hover face, icon, name; dim and unclickable when it can't go where the selection is -fn menu_row(ui: &mut Ui, width: f32, item: &AddItem, tokens: &Tokens) -> Response { +pub(crate) fn menu_row(ui: &mut Ui, width: f32, item: &AddItem, tokens: &Tokens) -> Response { let sense = if item.enabled { Sense::click() } else { Sense::hover() }; let (rect, response) = ui.allocate_exact_size(vec2(width, MENU_ROW), sense); let label = tr(item.short); diff --git a/crates/ui-egui/src/layer_toolbar/add_item.rs b/crates/ui-egui/src/layer_toolbar/add_item.rs index 8e44a94c..004940bb 100644 --- a/crates/ui-egui/src/layer_toolbar/add_item.rs +++ b/crates/ui-egui/src/layer_toolbar/add_item.rs @@ -3,12 +3,12 @@ use serde_json::Value; use super::ItemIcon; /// One item of the Add effect or Add mask menu -pub(super) struct AddItem { - pub(super) icon: ItemIcon, +pub(crate) struct AddItem { + pub(crate) icon: ItemIcon, /// The toolbar menu's name (the button says "Add effect" / "Add mask") and the layer context menu's - pub(super) short: &'static str, - pub(super) long: &'static str, - pub(super) command: &'static str, - pub(super) params: Value, - pub(super) enabled: bool, + pub(crate) short: &'static str, + pub(crate) long: &'static str, + pub(crate) command: &'static str, + pub(crate) params: Value, + pub(crate) enabled: bool, } diff --git a/crates/ui-egui/src/layer_toolbar/item_icon.rs b/crates/ui-egui/src/layer_toolbar/item_icon.rs index b5875428..3a7e301f 100644 --- a/crates/ui-egui/src/layer_toolbar/item_icon.rs +++ b/crates/ui-egui/src/layer_toolbar/item_icon.rs @@ -1,6 +1,6 @@ /// What an Add menu item shows at its left #[derive(Clone, Copy)] -pub(super) enum ItemIcon { +pub(crate) enum ItemIcon { Glyph(&'static str), /// A gray swatch (Add mask's White and Black) Swatch(u8), diff --git a/crates/ui-egui/src/layer_toolbar/menu_icon.rs b/crates/ui-egui/src/layer_toolbar/menu_icon.rs index adfcff01..1ef5b5aa 100644 --- a/crates/ui-egui/src/layer_toolbar/menu_icon.rs +++ b/crates/ui-egui/src/layer_toolbar/menu_icon.rs @@ -1,6 +1,6 @@ /// The icon of a menu button #[derive(Clone, Copy)] -pub(super) enum MenuIcon { +pub(crate) enum MenuIcon { Glyph(&'static str), /// Add mask's square, half of it filled corner to corner Mask, diff --git a/crates/ui-egui/src/layer_toolbar/pick.rs b/crates/ui-egui/src/layer_toolbar/pick.rs index 743293e0..4c5b189c 100644 --- a/crates/ui-egui/src/layer_toolbar/pick.rs +++ b/crates/ui-egui/src/layer_toolbar/pick.rs @@ -1,7 +1,7 @@ use serde_json::Value; /// What a click in one of the row's menus asks for, done once the menu has closed -pub(super) enum Pick { +pub(crate) enum Pick { Run { command: &'static str, params: Value }, Bitmap, } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9b6eb96f..5048a68b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -172,6 +172,7 @@ mod source_slot; pub mod state; mod surface_paint_point; pub mod symmetry; +mod texture_set_list; pub mod theme; pub mod thumbs; mod tile_edits; diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs index 122857cb..91d6e7eb 100644 --- a/crates/ui-egui/src/property_sheet/choice.rs +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -77,6 +77,36 @@ const CHOSEN_BAR_RADIUS: u8 = 1; /// The hovered option's eye glyph size const EYE_SIZE: f32 = 13.0; +/// An option's hover fill, the chosen one's accent bar and its keyboard focus outline +fn paint_option(painter: &Painter, rect: Rect, response: &Response, chosen: bool, tokens: &crate::theme::Tokens) { + if response.hovered() { + let fill = Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP)); + painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button); + } + if chosen { + let bar = Rect::from_min_max( + pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP), + pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM), + ); + painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent); + } + if response.has_focus() { + painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(OPTION_FOCUS_WIDTH, tokens.text_strong), StrokeKind::Inside); + } +} + +/// One option of a list drawn outside a sheet (a menu popup), the full width of `ui`, looking like a sheet dropdown's option +pub(crate) fn option_row(ui: &mut egui::Ui, text: &str, chosen: bool) -> Response { + let tokens = crate::theme::Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), OPTION_HEIGHT), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, text)); + let painter = ui.painter(); + paint_option(painter, rect, &response, chosen, &tokens); + let font = if chosen { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) }; + painter.text(pos2(rect.left() + VALUE_INSET, rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT), Align2::LEFT_CENTER, text, font, tokens.text); + response +} + impl PropertySheet<'_> { /// A set-once choice whose list hangs from its button; returns the picked and the hovered option pub(crate) fn dropdown( @@ -225,20 +255,8 @@ impl PropertySheet<'_> { response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, name(option))); if response.hovered() { hovered = Some(option); - let fill = - Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP)); - painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button); - } - if chosen { - let bar = Rect::from_min_max( - pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP), - pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM), - ); - painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent); - } - if response.has_focus() { - painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(OPTION_FOCUS_WIDTH, tokens.text_strong), StrokeKind::Inside); } + paint_option(painter, rect, &response, chosen, &tokens); // Align the option text and picture with the button despite the list border let button_left = rect.left() - LIST_BORDER; diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 51c6ecfb..1475384e 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -62,6 +62,7 @@ mod tests; pub(crate) use action_row_response::ActionRowResponse; pub(crate) use band_response::BandResponse; pub(crate) use button_icon::ButtonIcon; +pub(crate) use choice::option_row; pub(crate) use compare_row_response::CompareRowResponse; pub(crate) use file_list_add::FileListAdd; pub(crate) use file_list_response::FileListResponse; diff --git a/crates/ui-egui/src/texture_set_list.rs b/crates/ui-egui/src/texture_set_list.rs new file mode 100644 index 00000000..fcf911da --- /dev/null +++ b/crates/ui-egui/src/texture_set_list.rs @@ -0,0 +1,646 @@ +//! The Texture Set list: a toolbar, one row per set with its dropdowns, edits in place, a menu and a UV tile set's tiles + +use egui::{Align2, CornerRadius, FontId, Popup, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::project::{MAX_RESOLUTION, MIN_RESOLUTION}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::layer_toolbar::{AddItem, ItemIcon, MENU_PADDING, MenuIcon, Pick, menu_button, menu_frame, menu_row, menu_width}; +use crate::property_sheet::option_row; +use crate::theme::{Tokens, semibold}; +use crate::widgets::elided; + +mod description_mode; +mod list_state; +mod row_action; +mod row_edit; +mod set_row; +mod tile_action; + +use description_mode::DescriptionMode; +pub(crate) use list_state::ListState; +use row_action::RowAction; +use row_edit::RowEdit; +use set_row::SetRow; +use tile_action::TileAction; + +/// The layer toolbar's height and its menu buttons, so both panels' toolbars line up +const BAR_HEIGHT: f32 = 40.0; +const BAR_PADDING: f32 = 8.0; +const MENU_BUTTON: egui::Vec2 = vec2(32.0, 26.0); +const SOLO_SIZE: f32 = 24.0; +const SOLO_GAP: f32 = 6.0; + +/// Row geometry: a set row, the description line under it and a UV tile row +const ROW_HEIGHT: f32 = 28.0; +const DESCRIPTION_HEIGHT: f32 = 14.0; +const TILE_ROW_HEIGHT: f32 = 24.0; +const ROW_GAP: f32 = 2.0; +const ROW_INSET: f32 = 6.0; +const ROW_ROUNDING: u8 = 4; +const GLYPH_SIZE: f32 = 20.0; +const GLYPH_FONT: f32 = 14.0; +const NAME_GAP: f32 = 8.0; +const FOLD_WIDTH: f32 = 14.0; +const TILE_INDENT: f32 = 34.0; +const TILE_BRANCH: f32 = 12.0; + +const NAME_SIZE: f32 = 12.0; +const DESCRIPTION_SIZE: f32 = 11.0; +const CARET_SIZE: f32 = 11.0; + +/// A row dropdown: its text, the caret after it and the air around both +const DROPDOWN_HEIGHT: f32 = 22.0; +const DROPDOWN_TEXT_X: f32 = 6.0; +const DROPDOWN_CARET_GAP: f32 = 4.0; +const DROPDOWN_RIGHT: f32 = 6.0; +const DROPDOWN_GAP: f32 = 4.0; +const SIZE_LIST_WIDTH: f32 = 72.0; + +/// Narrow panels drop the shader dropdown, then the size, before cutting the name +const SHADER_MIN_ROW_WIDTH: f32 = 240.0; +const SIZE_MIN_ROW_WIDTH: f32 = 160.0; + +/// From an edit field's left edge to its text: the field starts this far left of the drawn text +const EDIT_TEXT_X: f32 = 4.0; +/// The name field's air above and below inside the row +const EDIT_FIELD_INSET: f32 = 3.0; +/// The description line starts this far up into the set row and stops this far above the row's end +const DESCRIPTION_OVERLAP: f32 = 4.0; +const DESCRIPTION_BOTTOM: f32 = 1.0; +/// The description field's air above and below its text +const DESCRIPTION_FIELD_AIR: f32 = 1.0; +/// How far an empty description's placeholder fades from the dim text +const PLACEHOLDER_FADE: f32 = 0.7; +/// Keyboard focus ring: inset from the row's edge +const FOCUS_INSET: f32 = 2.0; +/// Space between a dropdown and its list +const MENU_GAP: f32 = 1.0; + +/// The project's one shader, which every set uses +const SHADER_NAME: &str = "Main shader"; + +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + // The empty state lists nothing + if !app.session.project_open { + return; + } + + let tokens = Tokens::get(ui.ctx()); + let mut state = ListState::load(ui.ctx()); + + let rows: Vec = (0..app.session.doc.project.texture_sets.len()) + .filter_map(|index| { + let set = app.session.doc.project.texture_sets.get(index)?; + Some(SetRow { + name: set.name.clone(), + description: set.description.clone(), + original_name: app.session.original_set_name(index).map(str::to_owned), + width: set.resolution, + height: set.height(), + visible: set.visible, + tiles: set.uv_tiles.iter().map(|tile| (*tile, set.tile_resolution(*tile))).collect(), + }) + }) + .collect(); + + // A picked UV tile only stays picked while its set is the active one + let active = app.session.ts(); + if state.tile.is_some_and(|(set, tile)| set != active || !rows.get(set).is_some_and(|row| row.tiles.iter().any(|(udim, _)| *udim == tile))) { + state.tile = None; + } + + toolbar(app, ui, &mut state, &rows, active, &tokens); + egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| { + ui.spacing_mut().item_spacing = vec2(0.0, ROW_GAP); + for (index, row) in rows.iter().enumerate() { + let action = set_row(app, ui, &mut state, index, row, index == active, &tokens); + if !row.tiles.is_empty() && !state.folded.contains(&index) { + for (udim, resolution) in &row.tiles { + let selected = state.tile == Some((index, *udim)); + match tile_row(ui, index, *udim, *resolution, row.width, selected, &tokens) { + Some(TileAction::Select) => { + app.run("textureSet.select", json!({"ts": index})); + state.tile = Some((index, *udim)); + } + Some(TileAction::Resize(size)) => { + app.run("textureSet.tile.resolution", json!({"ts": index, "tile": udim, "resolution": size})); + } + None => {} + } + } + } + match action { + Some(RowAction::Select) => { + app.run("textureSet.select", json!({"ts": index})); + state.tile = None; + } + Some(RowAction::ToggleVisible) => { + app.run("textureSet.visible", json!({"ts": index})); + } + Some(RowAction::Resize(width)) => { + app.start_resize(index, width); + } + Some(RowAction::Edit(edit)) => { + let text = if edit == RowEdit::Name { row.name.clone() } else { row.description.clone() }; + state.edit = Some((index, edit, text, true)); + } + Some(RowAction::ResetName) => { + app.run("textureSet.rename", json!({"ts": index, "reset": true})); + } + Some(RowAction::ToggleFold) => { + if state.folded.contains(&index) { + state.folded.remove(&index); + } else { + state.folded.insert(index); + } + } + None => {} + } + } + }); + state.store(ui.ctx()); +} + +/// Visibility menu and solo at the left, the descriptions menu at the right +fn toolbar(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, rows: &[SetRow], active: usize, tokens: &Tokens) { + let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), BAR_HEIGHT), Sense::hover()); + let visibility = Rect::from_min_size(pos2(bar.left() + BAR_PADDING, bar.center().y - MENU_BUTTON.y * 0.5), MENU_BUTTON); + let items = || { + [(ic::EYE, "Show All", "showAll"), (ic::EYE_SLASH, "Hide All", "hideAll"), (ic::SWAP, "Invert Show/Hide", "invert")] + .into_iter() + .map(|(glyph, short, mode)| AddItem { + icon: ItemIcon::Glyph(glyph), + short, + long: short, + command: "textureSet.visibility", + params: json!({ "mode": mode }), + enabled: true, + }) + .collect() + }; + if let Some(Pick::Run { command, params }) = + menu_button(ui, visibility, tr("Show or hide texture sets"), MenuIcon::Glyph(ic::EYE), tr("Visibility"), items, tokens) + { + app.run(command, params); + } + + let solo_rect = Rect::from_min_size(pos2(visibility.right() + SOLO_GAP, bar.center().y - SOLO_SIZE * 0.5), vec2(SOLO_SIZE, SOLO_SIZE)); + let solo = rows.len() > 1 && rows.iter().enumerate().all(|(index, row)| row.visible == (index == active)); + if glyph_button(ui, "ts_solo", solo_rect, ic::NUMBER_CIRCLE_ONE, tr("Show only the selected texture set"), solo, tokens).clicked() { + app.run("textureSet.visibility", json!({ "mode": "solo" })); + } + + // The descriptions choice is the list's own look, so it stays in the UI + let menu = Rect::from_min_size(pos2(bar.right() - BAR_PADDING - MENU_BUTTON.x, bar.center().y - MENU_BUTTON.y * 0.5), MENU_BUTTON); + let modes = [ + (DescriptionMode::HideEmpty, "Hide Empty Descriptions"), + (DescriptionMode::ShowAll, "Show All Descriptions"), + (DescriptionMode::HideAll, "Hide All Descriptions"), + ]; + let current = state.descriptions; + let items = || { + modes + .iter() + .enumerate() + .map(|(index, (mode, short))| AddItem { + icon: ItemIcon::Glyph(if *mode == current { ic::CHECK } else { "" }), + short, + long: short, + command: "", + params: json!(index), + enabled: true, + }) + .collect() + }; + if let Some(Pick::Run { params, .. }) = menu_button(ui, menu, tr("Texture set list settings"), MenuIcon::Glyph(ic::LIST), tr("Descriptions"), items, tokens) + && let Some((mode, _)) = params.as_u64().and_then(|index| modes.get(usize::try_from(index).ok()?)) + { + state.descriptions = *mode; + } +} + +/// One texture set: eye, fold caret for UV tiles, name (or its field), size and shader dropdowns, description line +fn set_row(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, index: usize, row: &SetRow, selected: bool, tokens: &Tokens) -> Option { + let editing_description = matches!(state.edit, Some((set, RowEdit::Description, ..)) if set == index); + let description_line = editing_description || state.descriptions.shows(&row.description); + let height = if description_line { ROW_HEIGHT + DESCRIPTION_HEIGHT } else { ROW_HEIGHT }; + let (full, response) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &row.name)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_selected(selected)); + let rect = Rect::from_min_size(full.min, vec2(full.width(), ROW_HEIGHT)); + + let painter = ui.painter(); + if selected { + painter.rect(full, CornerRadius::same(ROW_ROUNDING), tokens.row_selected, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(full, CornerRadius::same(ROW_ROUNDING), tokens.row_hover); + } + if response.has_focus() { + painter.rect_stroke(full.shrink(FOCUS_INSET), CornerRadius::same(ROW_ROUNDING), Stroke::new(1.0, tokens.text_strong), StrokeKind::Inside); + } + + let mut action = None; + let eye = Rect::from_center_size(pos2(rect.left() + ROW_INSET + GLYPH_SIZE * 0.5, rect.center().y), vec2(GLYPH_SIZE, GLYPH_SIZE)); + let eye_label = if row.visible { tr("Hide texture set") } else { tr("Show texture set") }; + let eye_response = glyph_button(ui, ("ts_eye", index), eye, if row.visible { ic::EYE } else { ic::EYE_SLASH }, eye_label, false, tokens); + if eye_response.clicked() { + action = Some(RowAction::ToggleVisible); + } + if ui.is_enabled() && (response.contains_pointer() || eye_response.contains_pointer()) { + app.next_hovered_texture_set = Some((app.session.project_id, index)); + } + + let mut name_x = eye.right() + NAME_GAP; + if !row.tiles.is_empty() { + let folded = state.folded.contains(&index); + let fold = Rect::from_min_size(pos2(name_x - NAME_GAP * 0.5, rect.top()), vec2(FOLD_WIDTH, ROW_HEIGHT)); + let label = if folded { tr("Show UV tiles") } else { tr("Hide UV tiles") }; + if glyph_button(ui, ("ts_fold", index), fold, if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN }, label, false, tokens).clicked() { + action = Some(RowAction::ToggleFold); + } + name_x = fold.right() + NAME_GAP * 0.5; + } + + // Dropdowns from the right edge: shader, then size + let mut right = rect.right() - ROW_INSET; + let name_color = if !row.visible { + tokens.text_dim + } else if selected { + tokens.text_strong + } else { + tokens.text + }; + if rect.width() >= SHADER_MIN_ROW_WIDTH { + let shader = tr(SHADER_NAME); + let name = trf("Shader of {name}", &[("name", &row.name)]); + let dropdown = row_dropdown(ui, ("ts_shader", index), pos2(right, rect.center().y), (shader, &name), true, tokens, |ui| { + let _ = option_row(ui, shader, true); + }); + right = dropdown.left() - DROPDOWN_GAP; + } + if rect.width() >= SIZE_MIN_ROW_WIDTH { + let text = if row.width == row.height { row.width.to_string() } else { format!("{}x{}", row.width, row.height) }; + let mut picked = None; + let name = trf("Size of {name}", &[("name", &row.name)]); + let dropdown = row_dropdown(ui, ("ts_size", index), pos2(right, rect.center().y), (&text, &name), true, tokens, |ui| { + picked = size_list(ui, row.width); + }); + if let Some(size) = picked { + action = Some(RowAction::Resize(size)); + } + right = dropdown.left() - DROPDOWN_GAP; + } + + let editing_name = matches!(state.edit, Some((set, RowEdit::Name, ..)) if set == index); + if editing_name { + let field = Rect::from_min_max(pos2(name_x - EDIT_TEXT_X, rect.top() + EDIT_FIELD_INSET), pos2(right, rect.bottom() - EDIT_FIELD_INSET)); + if let Some(name) = edit_field(ui, state, field, NAME_SIZE) + && name.trim() != row.name + { + app.run("textureSet.rename", json!({"ts": index, "name": name})); + } + } else { + let font = if selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) }; + let mut job = egui::text::LayoutJob::simple_singleline(row.name.clone(), font, name_color); + job.wrap = egui::text::TextWrapping::truncate_at_width((right - name_x).max(0.0)); + let galley = ui.painter().layout_job(job); + ui.painter().galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, name_color); + } + + if description_line { + let line = Rect::from_min_max(pos2(name_x, rect.bottom() - DESCRIPTION_OVERLAP), pos2(full.right() - ROW_INSET, full.bottom() - DESCRIPTION_BOTTOM)); + if editing_description { + if let Some(description) = edit_field(ui, state, line.expand2(vec2(EDIT_TEXT_X, DESCRIPTION_FIELD_AIR)), DESCRIPTION_SIZE) + && description.trim() != row.description + { + app.run("textureSet.settings", json!({"ts": index, "description": description.trim()})); + } + } else { + let (text, color) = if row.description.trim().is_empty() { + (tr("No description").to_owned(), tokens.text_dim.gamma_multiply(PLACEHOLDER_FADE)) + } else { + (row.description.clone(), tokens.text_dim) + }; + let galley = elided(ui.painter(), text, DESCRIPTION_SIZE, color, line.width()); + ui.painter().galley(pos2(line.left(), line.center().y - galley.size().y * 0.5), galley, color); + } + } + + // F2 renames the focused row, as a double click does + let rename_key = response.has_focus() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::F2)); + if response.double_clicked() || rename_key { + action = Some(RowAction::Edit(RowEdit::Name)); + } else if action.is_none() && (response.clicked() || response.secondary_clicked()) { + action = Some(RowAction::Select); + } + context_menu(ui, &response, row, tokens).or(action) +} + +/// The row's right-click menu (Shift+F10 or the Menu key on a focused row), in the toolbar menus' look +fn context_menu(ui: &Ui, response: &Response, row: &SetRow, tokens: &Tokens) -> Option { + let renamed = row.original_name.as_ref().is_some_and(|original| *original != row.name); + let visibility = if row.visible { (ic::EYE_SLASH, "Hide Texture Set") } else { (ic::EYE, "Show Texture Set") }; + let entries = [ + (visibility.0, visibility.1, true, RowAction::ToggleVisible), + (ic::PENCIL_SIMPLE, "Edit Name", true, RowAction::Edit(RowEdit::Name)), + (ic::ARROW_COUNTER_CLOCKWISE, "Reset Name to Original", renamed, RowAction::ResetName), + (ic::NOTE_PENCIL, "Edit Description", true, RowAction::Edit(RowEdit::Description)), + ]; + let items = entries.map(|(glyph, short, enabled, _)| AddItem { + icon: ItemIcon::Glyph(glyph), + short, + long: short, + command: "", + params: serde_json::Value::Null, + enabled, + }); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu)); + let mut popup = Popup::context_menu(response).frame(menu_frame(tokens)); + let return_focus = popup.is_open() && ui.input(|input| input.key_pressed(egui::Key::Escape)); + + // A menu opened from the keyboard has no pointer to open at: it hangs under the row while it stays open + let from_keyboard = response.id.with("ts_menu_from_keyboard"); + let menu_key = + |input: &mut egui::InputState| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu); + if response.has_focus() && ui.input_mut(menu_key) { + ui.data_mut(|data| data.insert_temp(from_keyboard, true)); + popup = popup.open_memory(Some(egui::SetOpenCommand::Bool(true))); + } else if !popup.is_open() { + ui.data_mut(|data| data.remove::(from_keyboard)); + } + if ui.data(|data| data.get_temp::(from_keyboard)).unwrap_or(false) { + popup = popup.anchor(response); + } + + let mut picked = None; + popup.show(|ui| { + let width = menu_width(ui, &items); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + ui.add_space(MENU_PADDING); + for (item, (.., action)) in items.iter().zip(entries) { + if menu_row(ui, width, item, tokens).clicked() { + picked = Some(action); + ui.close(); + } + } + ui.add_space(MENU_PADDING); + }); + if return_focus { + response.request_focus(); + } + picked +} + +/// A UV tile under its set: a branch from the set's fold caret, its UDIM and its own size dropdown +fn tile_row(ui: &mut Ui, set: usize, udim: u32, resolution: u32, set_width: u32, selected: bool, tokens: &Tokens) -> Option { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), TILE_ROW_HEIGHT), Sense::click()); + let label = trf("UV tile {udim}", &[("udim", &udim)]); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &label)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_selected(selected)); + let face = rect.with_min_x(rect.left() + TILE_INDENT - ROW_INSET); + let painter = ui.painter(); + if selected { + painter.rect(face, CornerRadius::same(ROW_ROUNDING), tokens.row_selected, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(face, CornerRadius::same(ROW_ROUNDING), tokens.row_hover); + } + if response.has_focus() { + painter.rect_stroke(face.shrink(FOCUS_INSET), CornerRadius::same(ROW_ROUNDING), Stroke::new(1.0, tokens.text_strong), StrokeKind::Inside); + } + let branch_x = rect.left() + ROW_INSET + GLYPH_SIZE + NAME_GAP * 0.5 + FOLD_WIDTH * 0.5; + painter.vline(branch_x, rect.top() - ROW_GAP..=rect.center().y, Stroke::new(1.0, tokens.separator)); + painter.hline(branch_x..=branch_x + TILE_BRANCH, rect.center().y, Stroke::new(1.0, tokens.separator)); + let color = if selected { tokens.text_strong } else { tokens.text }; + let font = if selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) }; + painter.text(pos2(rect.left() + TILE_INDENT, rect.center().y), Align2::LEFT_CENTER, &label, font, color); + + // An overridden tile shows its size in full text colour, one that follows the set dims it + let mut picked = None; + let text = resolution.to_string(); + let name = trf("Size of UV tile {udim}", &[("udim", &udim)]); + let size_right = rect.right() - ROW_INSET - shader_column_width(ui, rect.width()); + let dim = resolution == set_width; + row_dropdown(ui, ("ts_tile_size", set, udim), pos2(size_right, rect.center().y), (&text, &name), dim, tokens, |ui| { + picked = size_list(ui, resolution); + }); + if let Some(size) = picked { + return Some(TileAction::Resize(size)); + } + (response.clicked() || response.secondary_clicked()).then_some(TileAction::Select) +} + +/// The shader dropdown's width on set rows, so tile sizes line up under set sizes +fn shader_column_width(ui: &Ui, row_width: f32) -> f32 { + if row_width < SHADER_MIN_ROW_WIDTH { + return 0.0; + } + dropdown_width(ui, tr(SHADER_NAME)) + DROPDOWN_GAP +} + +fn dropdown_width(ui: &Ui, text: &str) -> f32 { + let text_width = ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(NAME_SIZE), egui::Color32::WHITE).size().x); + DROPDOWN_TEXT_X + text_width + DROPDOWN_CARET_GAP + CARET_SIZE + DROPDOWN_RIGHT +} + +/// A dropdown drawn as its text (`labels`: shown text, then what it sets) and a small caret, its right end middle at `anchor`: a button face only while hovered or open +fn row_dropdown( + ui: &mut Ui, + id: impl egui::AsIdSalt, + anchor: egui::Pos2, + labels: (&str, &str), + dim: bool, + tokens: &Tokens, + list: impl FnOnce(&mut Ui), +) -> Rect { + let (text, name) = labels; + let width = dropdown_width(ui, text); + let rect = Rect::from_min_size(pos2(anchor.x - width, anchor.y - DROPDOWN_HEIGHT * 0.5), vec2(width, DROPDOWN_HEIGHT)); + let response = ui.interact(rect, ui.scope_id().with(id), Sense::click()).on_hover_text(name); + let accessible = format!("{text}, {name}"); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), &accessible)); + let popup = Popup::menu(&response).frame(menu_frame(tokens)).width(SIZE_LIST_WIDTH.max(width)).gap(MENU_GAP).align(egui::RectAlign::BOTTOM_END); + let open = popup.is_open(); + let painter = ui.painter(); + if open || response.hovered() { + painter.rect(rect, CornerRadius::same(ROW_ROUNDING), tokens.button, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + let color = if dim && !response.hovered() && !open { tokens.text_dim } else { tokens.text }; + painter.text(pos2(rect.left() + DROPDOWN_TEXT_X, rect.center().y), Align2::LEFT_CENTER, text, FontId::proportional(NAME_SIZE), color); + painter.text( + pos2(rect.right() - DROPDOWN_RIGHT - CARET_SIZE * 0.5, rect.center().y), + Align2::CENTER_CENTER, + ic::CARET_DOWN, + FontId::proportional(CARET_SIZE), + tokens.text_dim, + ); + popup.show(|ui| { + ui.set_min_width(SIZE_LIST_WIDTH.max(width)); + ui.add_space(MENU_PADDING); + list(ui); + ui.add_space(MENU_PADDING); + }); + rect +} + +/// The sizes a set or tile can take, the current one ticked; the one picked +fn size_list(ui: &mut Ui, current: u32) -> Option { + let mut picked = None; + let mut size = MIN_RESOLUTION; + while size <= MAX_RESOLUTION { + if option_row(ui, &size.to_string(), size == current).clicked() && size != current { + picked = Some(size); + } + size *= 2; + } + picked +} + +/// The field of the row's text being edited: Enter (or clicking away) gives the text, Esc drops it +fn edit_field(ui: &mut Ui, state: &mut ListState, rect: Rect, size: f32) -> Option { + let (_, _, text, needs_focus) = state.edit.as_mut()?; + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect)); + // The text sits where the drawn name or description sat, centred in the field + let font = FontId::proportional(size); + let text_height = ui.fonts_mut(|fonts| fonts.row_height(&font)); + let margin = vec2(EDIT_TEXT_X, ((rect.height() - text_height) * 0.5).max(0.0)); + let response = child.add_sized(rect.size(), egui::TextEdit::singleline(text).font(font).margin(margin)); + if std::mem::take(needs_focus) { + response.request_focus(); + } + if !response.lost_focus() { + return None; + } + let edit = state.edit.take()?; + (!ui.input(|input| input.key_pressed(egui::Key::Escape))).then_some(edit.2) +} + +/// A glyph button of the list: dim glyph, bright and framed when hovered or lit +fn glyph_button(ui: &mut Ui, id: impl egui::AsIdSalt, rect: Rect, glyph: &str, label: &str, lit: bool, tokens: &Tokens) -> Response { + let response = ui.interact(rect, ui.scope_id().with(id), Sense::click()).on_hover_text(label); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), lit, label)); + if lit || response.hovered() { + ui.painter().rect(rect, CornerRadius::same(ROW_ROUNDING), tokens.button, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + let color = if lit || response.hovered() { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_FONT), color); + response +} + +#[cfg(test)] +mod tests { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable as _; + + use super::*; + + fn harness(mesh: &str) -> Harness<'static, TextureCraftApp> { + let mesh_ref = format!("builtin:{mesh}"); + let geometry = texturecraft_engine::geom::primitives::builtin(mesh).unwrap(); + let session = texturecraft_engine::Session::new_project("Texture set list", geometry, &mesh_ref, None, 128).unwrap(); + let mut harness = Harness::builder() + // Tall enough that every row clears the panel under the list + .with_size(vec2(1600.0, 2400.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + harness + } + + /// Presses and lets go on `label`'s node through the real pointer path, as a person's click lands on a control drawn over its row + fn click(harness: &mut Harness<'static, TextureCraftApp>, role: egui::Role, label: &str, button: egui::PointerButton) { + let rect = harness.get_by_role_and_label(role, label).rect(); + // A row's middle is under its size dropdown in a narrow panel: aim at its name + let at = if role == egui::Role::ListItem { egui::pos2(rect.left() + rect.width() * 0.25, rect.center().y) } else { rect.center() }; + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button, pressed: false, modifiers }); + harness.run_steps(2); + } + + #[test] + fn the_row_size_dropdown_resizes_its_set() { + let mut harness = harness("material_ball"); + let name = harness.state().session.doc.project.texture_sets[1].name.clone(); + + click(&mut harness, egui::Role::ComboBox, &format!("128, Size of {name}"), egui::PointerButton::Primary); + click(&mut harness, egui::Role::ListBoxOption, "512", egui::PointerButton::Primary); + // The resize runs on a worker, as the settings' size does + for _ in 0..200 { + harness.run_steps(1); + if harness.state().resize.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + harness.run_steps(2); + + let sets = &harness.state().session.doc.project.texture_sets; + assert!(sets[1].resolution > 128 && sets[1].height() == sets[1].resolution, "the set grew and stayed square"); + assert_eq!(sets[0].resolution, 128, "the other set kept its size"); + } + + #[test] + fn the_right_click_menu_renames_in_place_and_resets_to_the_material_name() { + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + + click(&mut harness, egui::Role::ListItem, &original, egui::PointerButton::Secondary); + click(&mut harness, egui::Role::Button, "Edit Name", egui::PointerButton::Primary); + harness.run_steps(3); + // The field took focus, so typed text goes to it + harness.event(egui::Event::Text("x".into())); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + let renamed = harness.state().session.doc.project.texture_sets[1].name.clone(); + assert!(renamed != original && renamed.contains('x'), "{renamed}"); + + click(&mut harness, egui::Role::ListItem, &renamed, egui::PointerButton::Secondary); + click(&mut harness, egui::Role::Button, "Reset Name to Original", egui::PointerButton::Primary); + harness.run_steps(3); + assert_eq!(harness.state().session.doc.project.texture_sets[1].name, original); + } + + #[test] + fn a_focused_row_renames_with_f2_and_opens_its_menu_from_the_keyboard() { + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + + harness.get_by_role_and_label(egui::Role::ListItem, &original).focus(); + harness.run_steps(2); + harness.key_press(egui::Key::F2); + harness.run_steps(3); + harness.event(egui::Event::Text("y".into())); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + let renamed = harness.state().session.doc.project.texture_sets[1].name.clone(); + assert!(renamed != original && renamed.contains('y'), "{renamed}"); + + harness.get_by_role_and_label(egui::Role::ListItem, &renamed).focus(); + harness.run_steps(2); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_none()); + harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + harness.run_steps(3); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_some(), "Shift+F10 opens the row's menu"); + } + + #[test] + fn a_uv_tile_row_sizes_its_own_tile() { + let mut harness = harness("udim_plane"); + let tiles = harness.state().session.doc.project.texture_sets[0].uv_tiles.clone(); + assert!(harness.query_by_role_and_label(egui::Role::ListItem, &format!("UV tile {}", tiles[1])).is_some()); + + click(&mut harness, egui::Role::ComboBox, &format!("128, Size of UV tile {}", tiles[1]), egui::PointerButton::Primary); + click(&mut harness, egui::Role::ListBoxOption, "256", egui::PointerButton::Primary); + harness.run_steps(3); + + let set = &harness.state().session.doc.project.texture_sets[0]; + assert!(set.tile_resolution(tiles[1]) > set.tile_resolution(tiles[0]), "only the picked tile grew"); + } +} diff --git a/crates/ui-egui/src/texture_set_list/description_mode.rs b/crates/ui-egui/src/texture_set_list/description_mode.rs new file mode 100644 index 00000000..ff042a2d --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/description_mode.rs @@ -0,0 +1,19 @@ +/// Which rows show their description line under the name (the list menu's choice) +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub(crate) enum DescriptionMode { + #[default] + HideEmpty, + ShowAll, + HideAll, +} + +impl DescriptionMode { + /// Whether a row with `description` shows the line + pub(crate) fn shows(self, description: &str) -> bool { + match self { + Self::HideEmpty => !description.trim().is_empty(), + Self::ShowAll => true, + Self::HideAll => false, + } + } +} diff --git a/crates/ui-egui/src/texture_set_list/list_state.rs b/crates/ui-egui/src/texture_set_list/list_state.rs new file mode 100644 index 00000000..3e2bbaa4 --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/list_state.rs @@ -0,0 +1,29 @@ +use std::collections::BTreeSet; + +use super::{DescriptionMode, RowEdit}; + +/// The list's UI state: the row being edited, which descriptions show, folded UV tile sets and the selected tile +#[derive(Clone, Default)] +pub(crate) struct ListState { + /// Set, what it edits, the text so far, and whether the field still needs focus + pub(crate) edit: Option<(usize, RowEdit, String, bool)>, + pub(crate) descriptions: DescriptionMode, + /// UV tile sets whose tile rows are folded away + pub(crate) folded: BTreeSet, + /// Set and UDIM of the selected UV tile row + pub(crate) tile: Option<(usize, u32)>, +} + +impl ListState { + fn id() -> egui::Id { + egui::Id::unique("texture_set_list_state") + } + + pub(crate) fn load(ctx: &egui::Context) -> Self { + ctx.data(|data| data.get_temp::(Self::id())).unwrap_or_default() + } + + pub(crate) fn store(self, ctx: &egui::Context) { + ctx.data_mut(|data| data.insert_temp(Self::id(), self)); + } +} diff --git a/crates/ui-egui/src/texture_set_list/row_action.rs b/crates/ui-egui/src/texture_set_list/row_action.rs new file mode 100644 index 00000000..a8340f3b --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/row_action.rs @@ -0,0 +1,12 @@ +use super::RowEdit; + +/// What a set row asks for once it has drawn +#[derive(Clone, Copy)] +pub(super) enum RowAction { + Select, + ToggleVisible, + Resize(u32), + Edit(RowEdit), + ResetName, + ToggleFold, +} diff --git a/crates/ui-egui/src/texture_set_list/row_edit.rs b/crates/ui-egui/src/texture_set_list/row_edit.rs new file mode 100644 index 00000000..c595220b --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/row_edit.rs @@ -0,0 +1,6 @@ +/// The text a row is editing in place +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum RowEdit { + Name, + Description, +} diff --git a/crates/ui-egui/src/texture_set_list/set_row.rs b/crates/ui-egui/src/texture_set_list/set_row.rs new file mode 100644 index 00000000..62583f7f --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/set_row.rs @@ -0,0 +1,12 @@ +/// What one texture set row shows, read before drawing so commands can run while the rows draw +pub(crate) struct SetRow { + pub(crate) name: String, + pub(crate) description: String, + /// The mesh material's name, when the set has one to go back to + pub(crate) original_name: Option, + pub(crate) width: u32, + pub(crate) height: u32, + pub(crate) visible: bool, + /// UDIM and resolution of each UV tile, in UDIM order + pub(crate) tiles: Vec<(u32, u32)>, +} diff --git a/crates/ui-egui/src/texture_set_list/tile_action.rs b/crates/ui-egui/src/texture_set_list/tile_action.rs new file mode 100644 index 00000000..f638fef4 --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/tile_action.rs @@ -0,0 +1,5 @@ +/// What a UV tile row asks for +pub(super) enum TileAction { + Select, + Resize(u32), +} diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index a44c4640..60daf4aa 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -570,7 +570,8 @@ fn uv_tiles_are_shown_read_only() { hover_uv_tile_box(&mut h); assert!(h.query_by_label_contains("No UV tiles").is_none()); - assert!(h.query_by_label_contains("1001").is_some(), "the tile list of a UDIM project"); + // The hint's own text, not the Texture Sets list's tile rows + assert!(h.query_all_by_label_contains("1001").any(|node| node.accesskit_node().role() == Role::Label), "the tile list of a UDIM project"); } /// Hover the disabled Use UV Tile workflow box, whose hint lists the project's UV tiles. From 8e0b61fe55fe720bb3a23942d2453c3f17e01d9c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:33:03 +0000 Subject: [PATCH 114/190] Texture Set Settings: sections in the property sheet's controls, size as width, lock and height (or the UV tile picked in the list), a format list per channel, and mesh map slots that open the image picker --- crates/ui-egui/src/dock.rs | 161 +-------- crates/ui-egui/src/lib.rs | 21 +- crates/ui-egui/src/shader_settings.rs | 4 +- crates/ui-egui/src/texture_set_list.rs | 8 +- crates/ui-egui/src/texture_set_settings.rs | 392 +++++++++++++++++++++ crates/ui-egui/tests/it/project_config.rs | 3 +- 6 files changed, 413 insertions(+), 176 deletions(-) create mode 100644 crates/ui-egui/src/texture_set_settings.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index b0991d59..8b7328ae 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1422,167 +1422,8 @@ fn mask_management_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, m // --------------------------------------------------------------------------------------------- // Texture set settings -/// Size of a channel's remove button, and of the room Base color keeps for one -const CHANNEL_REMOVE_SIZE: f32 = 18.0; - -/// The sizes a texture set and each of its UV tiles can take -const TEXTURE_SET_RESOLUTIONS: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192]; - -/// Air between the General properties grid's columns and rows -const GENERAL_GRID_SPACING: egui::Vec2 = vec2(8.0, 6.0); - -/// Air above the Channels and Mesh maps captions -const SECTION_GAP: f32 = 8.0; - -/// Air between the channel list and the height and normal settings -const CHANNEL_SETTINGS_GAP: f32 = 6.0; - -/// Range of the Height to normal strength slider -const HEIGHT_STRENGTH_RANGE: std::ops::RangeInclusive = 0.0..=10.0; - -/// A mesh map row's colour square, its corner radius, the size of its file name and of its menu's dots -const MESH_MAP_SWATCH_SIZE: f32 = 26.0; -const MESH_MAP_SWATCH_RADIUS: f32 = 2.0; -const MESH_MAP_FILE_TEXT_SIZE: f32 = 10.5; -const MESH_MAP_MENU_ICON_SIZE: f32 = 13.0; - pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { - crate::channel_manager::ChannelManager::show(app, &ui.ctx().clone()); - let tokens = Tokens::get(ui.ctx()); - let set_index = app.session.ts(); - let Some(set) = app.session.doc.project.texture_sets.get(set_index).cloned() else { return }; - egui::ScrollArea::vertical().id_salt("tss").show(ui, |ui| { - ui.label(caption(tr("General properties"))); - egui::Grid::new("tss_grid").num_columns(2).spacing(GENERAL_GRID_SPACING).show(ui, |ui| { - ui.label(tr("Name")); - ui.label(RichText::new(&set.name).color(tokens.text_strong)); - ui.end_row(); - - ui.label(tr("Size")); - egui::ComboBox::from_id_salt("ts_size").selected_text(format!("{}", set.resolution)).show_ui(ui, |ui| { - for resolution in TEXTURE_SET_RESOLUTIONS { - if ui.selectable_label(resolution == set.resolution, format!("{resolution}")).clicked() { - app.start_resize(set_index, resolution); - } - } - }); - ui.end_row(); - - ui.label(tr("UV tiles (UDIM)")); - let mut tiled = !set.uv_tiles.is_empty(); - if ui.checkbox(&mut tiled, "").changed() { - app.run("textureSet.uvTiles", json!({"ts": set_index, "enabled": tiled})); - } - ui.end_row(); - - // Each tile's own size - for &udim in &set.uv_tiles { - let tile_resolution = set.tile_resolution(udim); - ui.label(RichText::new(format!(" {udim}")).color(tokens.text_dim)); - egui::ComboBox::from_id_salt(("ts_tile", udim)).selected_text(format!("{tile_resolution}")).show_ui(ui, |ui| { - for resolution in TEXTURE_SET_RESOLUTIONS { - if ui.selectable_label(resolution == tile_resolution, format!("{resolution}")).clicked() { - app.run("textureSet.tile.resolution", json!({"ts": set_index, "tile": udim, "resolution": resolution})); - } - } - }); - ui.end_row(); - } - - ui.label(tr("Shader instance")); - ui.label(tr("Main shader")); - ui.end_row(); - }); - - ui.add_space(SECTION_GAP); - ui.horizontal(|ui| { - ui.label(caption(tr("Channels"))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let manage = ui.button(tr("Add or remove channels")); - if manage.clicked() { - crate::channel_manager::ChannelManager::open(app, &manage, set_index); - } - }); - }); - - for (channel, format) in &set.formats() { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(channel.label())).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Base color can't be removed: its × room stays, so every format ends on one column - if *channel == Channel::BaseColor { - ui.allocate_exact_size(vec2(CHANNEL_REMOVE_SIZE, CHANNEL_REMOVE_SIZE), Sense::hover()); - } else if icon_button(ui, ic::X, tr("Remove channel"), false, CHANNEL_REMOVE_SIZE).clicked() { - app.run("textureSet.channel.remove", json!({"ts": set_index, "channel": channel.id()})); - } - ui.label(RichText::new(format.label()).color(tokens.text_dim)); - }); - }); - } - - ui.add_space(CHANNEL_SETTINGS_GAP); - let mut height_strength = set.height_strength; - if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut height_strength, HEIGHT_STRENGTH_RANGE, 2) { - app.run("textureSet.settings", json!({"ts": set_index, "heightStrength": height_strength, "merge": merge})); - } - - let directx = app.session.doc.project.normal_format == texturecraft_engine::core::NormalFormat::DirectX; - combo(ui, tr("Normal map format"), if directx { "DirectX" } else { "OpenGL" }, |ui| { - for (id, label, on) in [("openGl", "OpenGL", !directx), ("directX", "DirectX", directx)] { - if ui.selectable_label(on, label).clicked() && !on { - app.run("textureSet.settings", json!({"ts": set_index, "normalFormat": id})); - } - } - }) - .on_hover_text(tr( - "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", - )); - - ui.add_space(SECTION_GAP); - ui.horizontal(|ui| { - ui.label(caption(tr("Mesh maps"))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Bake Mesh Maps")).clicked() { - app.ui.mode = crate::state::Mode::Baking; - } - }); - }); - for map in BakedMap::ALL { - let present = app.session.doc.baked.get(&set_index).is_some_and(|baked| baked.maps.contains_key(&map)); - let row = ui.horizontal(|ui| { - let (swatch, _) = ui.allocate_exact_size(vec2(MESH_MAP_SWATCH_SIZE, MESH_MAP_SWATCH_SIZE), Sense::hover()); - ui.painter().rect_filled(swatch, MESH_MAP_SWATCH_RADIUS, if present { mesh_map_color(map) } else { tokens.button }); - ui.vertical(|ui| { - ui.label(RichText::new(tr(crate::i18n::baked_map_label(map))).strong()); - ui.label( - RichText::new(if present { format!("{}_{}", set.name, map.id()) } else { tr("Missing (bake to create)").into() }) - .size(MESH_MAP_FILE_TEXT_SIZE) - .color(tokens.text_dim), - ); - }); - - // An image resource instead of a bake, or no map - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(RichText::new(ic::DOTS_THREE).size(MESH_MAP_MENU_ICON_SIZE), |ui| { - if let Some(name) = image_menu(app, ui) { - app.run("textureSet.meshMap.set", json!({"ts": set_index, "map": map.id(), "image": name})); - } - ui.separator(); - if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() { - app.run("textureSet.meshMap.clear", json!({"ts": set_index, "map": map.id()})); - ui.close(); - } - }); - }); - }); - - // A shelf image dropped on the row becomes this mesh map - let response = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); - if let Some(name) = image_drop(ui, &response) { - app.run("textureSet.meshMap.set", json!({"ts": set_index, "map": map.id(), "image": name})); - } - } - }); + crate::texture_set_settings::show(app, ui); } /// Menu listing the decoded image resources with a name filter and thumbnails, then Import...: the diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5048a68b..3820ca4c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -173,6 +173,7 @@ pub mod state; mod surface_paint_point; pub mod symmetry; mod texture_set_list; +mod texture_set_settings; pub mod theme; pub mod thumbs; mod tile_edits; @@ -940,18 +941,22 @@ impl TextureCraftApp { self.session.bake_preview_end(); } - /// Resize texture set `ts` to `resolution` texels across on a worker thread, keeping its - /// shape (the document changes when it is done, as one undo step). - pub fn start_resize(&mut self, ts: usize, resolution: u32) { + /// Resize texture set `ts` to `width` texels across on a worker thread, keeping its shape: one undo step once done + pub fn start_resize(&mut self, ts: usize, width: u32) { + let height = self.session.doc.project.texture_set(ts).map_or(width, |set| { + let scaled = u64::from(set.height()) * u64::from(width) / u64::from(set.resolution.max(1)); + u32::try_from(scaled).unwrap_or(u32::MAX).clamp(texturecraft_engine::core::MIN_RESOLUTION, texturecraft_engine::core::MAX_RESOLUTION) + }); + self.start_resize_to(ts, width, height); + } + + /// [`Self::start_resize`] to `width` by `height` + pub fn start_resize_to(&mut self, ts: usize, width: u32, height: u32) { if self.resize.is_some() { return; } - let height = self.session.doc.project.texture_set(ts).map_or(resolution, |set| { - let scaled = u64::from(set.height()) * u64::from(resolution) / u64::from(set.resolution.max(1)); - u32::try_from(scaled).unwrap_or(u32::MAX).clamp(texturecraft_engine::core::MIN_RESOLUTION, texturecraft_engine::core::MAX_RESOLUTION) - }); - match self.session.resize_task_to(ts, resolution, height) { + match self.session.resize_task_to(ts, width, height) { Ok(task) => { let progress = Arc::new(Progress::new()); let p = progress.clone(); diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs index 88dd9ae4..09b89285 100644 --- a/crates/ui-egui/src/shader_settings.rs +++ b/crates/ui-egui/src/shader_settings.rs @@ -42,8 +42,8 @@ pub const SHADER_TYPES: [&str; 17] = [ /// The shader choice's search starts as the reference's: shaders only pub const SHADER_QUERY: &str = "u:shader"; -/// The reference's default instance name -const INSTANCE_NAME: &str = "Main shader"; +/// The reference's default instance name: the project's one shader, which every set uses +pub(crate) const INSTANCE_NAME: &str = "Main shader"; /// Wide enough for the longer shader model name const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; diff --git a/crates/ui-egui/src/texture_set_list.rs b/crates/ui-egui/src/texture_set_list.rs index fcf911da..f200f98d 100644 --- a/crates/ui-egui/src/texture_set_list.rs +++ b/crates/ui-egui/src/texture_set_list.rs @@ -9,6 +9,7 @@ use crate::TextureCraftApp; use crate::i18n::{tr, trf}; use crate::layer_toolbar::{AddItem, ItemIcon, MENU_PADDING, MenuIcon, Pick, menu_button, menu_frame, menu_row, menu_width}; use crate::property_sheet::option_row; +use crate::shader_settings::INSTANCE_NAME; use crate::theme::{Tokens, semibold}; use crate::widgets::elided; @@ -79,9 +80,6 @@ const FOCUS_INSET: f32 = 2.0; /// Space between a dropdown and its list const MENU_GAP: f32 = 1.0; -/// The project's one shader, which every set uses -const SHADER_NAME: &str = "Main shader"; - pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { // The empty state lists nothing if !app.session.project_open { @@ -274,7 +272,7 @@ fn set_row(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, index: tokens.text }; if rect.width() >= SHADER_MIN_ROW_WIDTH { - let shader = tr(SHADER_NAME); + let shader = tr(INSTANCE_NAME); let name = trf("Shader of {name}", &[("name", &row.name)]); let dropdown = row_dropdown(ui, ("ts_shader", index), pos2(right, rect.center().y), (shader, &name), true, tokens, |ui| { let _ = option_row(ui, shader, true); @@ -437,7 +435,7 @@ fn shader_column_width(ui: &Ui, row_width: f32) -> f32 { if row_width < SHADER_MIN_ROW_WIDTH { return 0.0; } - dropdown_width(ui, tr(SHADER_NAME)) + DROPDOWN_GAP + dropdown_width(ui, tr(INSTANCE_NAME)) + DROPDOWN_GAP } fn dropdown_width(ui: &Ui, text: &str) -> f32 { diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs new file mode 100644 index 00000000..408315a7 --- /dev/null +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -0,0 +1,392 @@ +//! The Texture Set Settings panel: general properties, the set's channels and their mixing, and its mesh maps + +use egui::{Align2, CornerRadius, FontId, Popup, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{ + AoMixing, BakedMap, Channel, ChannelFormat, HeightToNormalMethod, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, TextureSet, UvPaddingMode, +}; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::layer_toolbar::menu_frame; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{PropertySheet, option_row}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shader_settings::INSTANCE_NAME; +use crate::theme::{Tokens, semibold}; + +/// A channel row's height, and its name and format text sizes +const CHANNEL_ROW_HEIGHT: f32 = 26.0; +const CHANNEL_TEXT_SIZE: f32 = 12.0; + +/// A channel row's gear and × buttons, and the air between them and the format text +const GLYPH_BUTTON: f32 = 20.0; +const GLYPH_SIZE: f32 = 13.0; +const GLYPH_GAP: f32 = 3.0; +const FORMAT_GAP: f32 = 6.0; +const GLYPH_ROUNDING: u8 = 3; + +/// The channel format list's width and its padding +const FORMAT_LIST_WIDTH: f32 = 120.0; +const MENU_PADDING: f32 = 3.0; +/// Space between a channel's gear and its format list +const MENU_GAP: f32 = 1.0; + +/// Height to normal strength's slider range +const HEIGHT_STRENGTH_RANGE: std::ops::RangeInclusive = 0.0..=10.0; + +/// The empty slot's outline width (and inset), and the slot's corner rounding +const EMPTY_MAP_OUTLINE: f32 = 1.0; +const MAP_ROUNDING: u8 = 2; + +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + crate::channel_manager::ChannelManager::show(app, &ui.ctx().clone()); + let set_index = app.session.ts(); + let Some(set) = app.session.doc.project.texture_sets.get(set_index).cloned() else { return }; + let tile = crate::texture_set_list::ListState::load(ui.ctx()).tile.filter(|(set, _)| *set == set_index).map(|(_, udim)| udim); + egui::ScrollArea::vertical().id_salt("tss").show(ui, |ui| { + PropertySheet::show(ui, ("texture_set_settings", set_index), |sheet| { + general(app, sheet, set_index, &set, tile); + channels(app, sheet, set_index, &set); + mesh_maps(app, sheet, set_index, &set); + }); + }); +} + +/// Name, description, size (of the UV tile picked in the list, else of the set), UV tiles and shader +fn general(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, set: &TextureSet, tile: Option) { + sheet.section(tr("General Properties"), false); + sheet.attribute(tr("Name"), &set.name); + + // Typing merges into one undo step until the field loses focus + let mut description = set.description.clone(); + if sheet.text_field_above(tr("Description"), &mut description) { + let typing_id = sheet.ui.scope_id().with(("tss_description_typing", ts)); + let focused = sheet.ui.memory(|memory| memory.focused()); + let merge = sheet.ui.data(|data| data.get_temp::>(typing_id)).flatten().is_some_and(|id| Some(id) == focused); + sheet.ui.data_mut(|data| data.insert_temp(typing_id, focused)); + app.run("textureSet.settings", json!({"ts": ts, "description": description, "merge": merge})); + } + + let sizes = resolutions(); + let size_name = |size: u32| size.to_string(); + if let Some(udim) = tile { + let label = trf("Size of UV tile {udim}", &[("udim", &udim)]); + if let Some(size) = sheet.dropdown_above(&label, set.tile_resolution(udim), &sizes, size_name) { + app.run("textureSet.tile.resolution", json!({"ts": ts, "tile": udim, "resolution": size})); + } + } else { + let lock_id = sheet.ui.scope_id().with(("tss_size_lock", ts)); + let mut locked = sheet.ui.data(|data| data.get_temp::(lock_id)).unwrap_or(set.resolution == set.height()); + let picked = sheet.dropdown_pair_above(tr("Size"), [set.resolution, set.height()], &sizes, size_name, &mut locked, tr("Lock Size")); + sheet.ui.data_mut(|data| data.insert_temp(lock_id, locked)); + let resize = match picked { + Some((0, width)) if locked => Some((width, width)), + Some((0, width)) => Some((width, set.height())), + Some((_, height)) => Some((set.resolution, height)), + None => None, + }; + if let Some((width, height)) = resize { + app.start_resize_to(ts, width, height); + } + } + + let mut tiled = !set.uv_tiles.is_empty(); + if sheet.check(tr("UV tiles (UDIM)"), &mut tiled) { + app.run("textureSet.uvTiles", json!({"ts": ts, "enabled": tiled})); + } + // The project has one shader: the list holds it + sheet.dropdown(tr("Shader Instance"), 0, &[0], |_| tr(INSTANCE_NAME).to_owned(), None); +} + +/// Add or remove channels, a row per channel (name, format and its list, ×), then how they mix +fn channels(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, set: &TextureSet) { + sheet.section(tr("Channels"), false); + let manage = sheet.button(ic::LIST_PLUS, tr("Add or remove channels")); + if manage.clicked() { + crate::channel_manager::ChannelManager::open(app, &manage, ts); + } + for (channel, format) in set.formats() { + let (picked, remove) = channel_row(sheet, channel, format); + if let Some(picked) = picked { + app.run("textureSet.channel.format", json!({"ts": ts, "channel": channel.id(), "format": picked.label()})); + } + if remove { + app.run("textureSet.channel.remove", json!({"ts": ts, "channel": channel.id()})); + } + } + + let mixing = NormalMixing::ALL; + let mixing_name = |mixing| tr(if mixing == NormalMixing::Combine { "Combine" } else { "Replace" }).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Normal mixing"), set.normal_mixing, &mixing, mixing_name, None) { + app.run("textureSet.settings", json!({"ts": ts, "normalMixing": picked.id()})); + } + let methods = HeightToNormalMethod::ALL; + let method_name = |method| tr(if method == HeightToNormalMethod::Sharp { "Sharp" } else { "Smooth (Sobel)" }).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Height to normal method"), set.height_to_normal, &methods, method_name, None) { + app.run("textureSet.settings", json!({"ts": ts, "heightToNormal": picked.id()})); + } + let mut strength = set.height_strength; + if let Some(merge) = sheet.slider(tr("Height to normal strength"), &mut strength, HEIGHT_STRENGTH_RANGE, 2) { + app.run("textureSet.settings", json!({"ts": ts, "heightStrength": strength, "merge": merge})); + } + + // Occlusion mixes a baked or set ambient occlusion map in: greyed until the set has one + let has_occlusion = app.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion)); + let occlusion = AoMixing::ALL; + let occlusion_name = |mixing| tr(if mixing == AoMixing::Multiply { "Multiply" } else { "None" }).to_owned(); + let picked = sheet.greyed(has_occlusion, Some(tr("Needs an Ambient occlusion mesh map")), |sheet| { + sheet.dropdown(tr("Ambient occlusion mixing"), set.ao_mixing, &occlusion, occlusion_name, None).0 + }); + if let Some(picked) = picked { + app.run("textureSet.settings", json!({"ts": ts, "aoMixing": picked.id()})); + } + + let paddings = UvPaddingMode::ALL; + let padding_name = |mode| tr(if mode == UvPaddingMode::Space3d { "Across Seams (3D)" } else { "From Island Edges (2D)" }).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("UV padding"), set.uv_padding, &paddings, padding_name, None) { + app.run("textureSet.settings", json!({"ts": ts, "uvPadding": picked.id()})); + } + + // For the whole project, shown here beside the other normal settings + let formats = [NormalFormat::OpenGl, NormalFormat::DirectX]; + let format_name = |format| if format == NormalFormat::DirectX { "DirectX" } else { "OpenGL" }.to_owned(); + let current = app.session.doc.project.normal_format; + if let (Some(picked), _) = sheet.dropdown(tr("Normal map format"), current, &formats, format_name, None) { + let id = if picked == NormalFormat::DirectX { "directX" } else { "openGl" }; + app.run("textureSet.settings", json!({"ts": ts, "normalFormat": id})); + } +} + +/// A channel: its name, its format with the gear that lists the formats, and × (Base color stays); returns the format picked and whether × was clicked +fn channel_row(sheet: &mut PropertySheet<'_>, channel: Channel, format: ChannelFormat) -> (Option, bool) { + sheet.embed(|ui| { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), CHANNEL_ROW_HEIGHT), Sense::hover()); + let name = tr(channel.label()); + let mut picked = None; + let mut removed = false; + + let remove = Rect::from_center_size(pos2(rect.right() - GLYPH_BUTTON * 0.5, rect.center().y), vec2(GLYPH_BUTTON, GLYPH_BUTTON)); + if channel != Channel::BaseColor + && glyph_button(ui, ("tss_remove", channel.id()), remove, ic::X, &trf("Remove {channel}", &[("channel", &name)]), &tokens).clicked() + { + removed = true; + } + + let gear = remove.translate(vec2(-GLYPH_BUTTON - GLYPH_GAP, 0.0)); + let gear_label = trf("{channel} format", &[("channel", &name)]); + let gear_response = glyph_button(ui, ("tss_format", channel.id()), gear, ic::GEAR_SIX, &gear_label, &tokens); + Popup::menu(&gear_response).frame(menu_frame(&tokens)).width(FORMAT_LIST_WIDTH).gap(MENU_GAP).align(egui::RectAlign::BOTTOM_END).show(|ui| { + ui.set_min_width(FORMAT_LIST_WIDTH); + ui.add_space(MENU_PADDING); + for option in ChannelFormat::ALL { + if option_row(ui, option.label(), option == format).clicked() && option != format { + picked = Some(option); + } + } + ui.add_space(MENU_PADDING); + }); + + let painter = ui.painter().clone(); + let format_at = pos2(gear.left() - FORMAT_GAP, rect.center().y); + let format_rect = painter.text(format_at, Align2::RIGHT_CENTER, format.label(), FontId::proportional(CHANNEL_TEXT_SIZE), tokens.text_dim); + let name_rect = painter.text(pos2(rect.left(), rect.center().y), Align2::LEFT_CENTER, name, semibold(CHANNEL_TEXT_SIZE), tokens.text); + painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); + + // The drawn name and format read as labels + for (salt, text_rect, text) in [("tss_channel_name", name_rect, name), ("tss_channel_format", format_rect, format.label())] { + let label = ui.interact(text_rect, ui.scope_id().with((salt, channel.id())), Sense::hover()); + label.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text)); + } + + (picked, removed) + }) +} + +/// The Bake Mesh Maps button (the bake mode's own icon), then a slot per map: a click lists the images, × clears it +fn mesh_maps(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, set: &TextureSet) { + sheet.section(tr("Mesh Maps"), false); + if sheet.button(ic::ATOM, tr("Bake Mesh Maps")).clicked() { + crate::menus::invoke(app, &sheet.ui.ctx().clone(), "ui.mode.bake"); + } + let empty_outline = Tokens::get(sheet.ui.ctx()).field_border; + for map in BakedMap::ALL { + let present = app.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)); + let color = crate::dock::mesh_map_color(map); + let thumbnail = move |painter: &egui::Painter, rect: Rect| { + if present { + painter.rect_filled(rect, CornerRadius::same(MAP_ROUNDING), color); + } else { + painter.rect_stroke( + rect.shrink(EMPTY_MAP_OUTLINE), + CornerRadius::same(MAP_ROUNDING), + Stroke::new(EMPTY_MAP_OUTLINE, empty_outline), + StrokeKind::Inside, + ); + } + }; + let label = tr(baked_map_label(map)); + let source = if present { format!("{}_{}", set.name, map.id()) } else { trf("Select {map} map", &[("map", &label.to_lowercase())]) }; + let slot = sheet.slot(&thumbnail, label, &source, None, present, false); + sheet.close_card(); + if slot.clear { + app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": map.id()})); + } + let popup = slot.pick.id.with("mesh_map_picker"); + if slot.pick.clicked() { + resource_picker::toggle(&slot.pick.ctx, popup); + } + let tabs = || { + vec![PickerTab { + icon: ic::SQUARES_FOUR, + name: tr("Resources"), + groups: vec![PickerGroup { + header: Some(tr("Textures")), + items: ResourcePickerItem::textures(&app.session, None, |name| Some(name.to_owned())), + }], + }] + }; + let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, None, false, tabs); + // A shelf image dropped on the slot becomes this map too + let dropped = crate::dock::image_drop(sheet.ui, &slot.pick).map(Some); + // The picker's Import... tile is None + match picked.or(dropped) { + Some(None) => crate::menus::invoke(app, &sheet.ui.ctx().clone(), "resource.import"), + Some(Some(name)) => { + app.run("textureSet.meshMap.set", json!({"ts": ts, "map": map.id(), "image": name})); + } + None => {} + } + } +} + +/// Every size a set or tile can take +fn resolutions() -> Vec { + std::iter::successors(Some(MIN_RESOLUTION), |size| size.checked_mul(2)).take_while(|size| *size <= MAX_RESOLUTION).collect() +} + +/// A small square glyph button with its face on hover +fn glyph_button(ui: &mut Ui, id: impl egui::AsIdSalt, rect: Rect, glyph: &str, label: &str, tokens: &Tokens) -> egui::Response { + let response = ui.interact(rect, ui.scope_id().with(id), Sense::click()).on_hover_text(label); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); + if response.hovered() { + ui.painter().rect_filled(rect, CornerRadius::same(GLYPH_ROUNDING), tokens.row_hover); + } + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), color); + response +} + +#[cfg(test)] +mod tests { + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT as _, Queryable as _}; + + use super::*; + + fn harness(mesh: &str) -> Harness<'static, TextureCraftApp> { + let mesh_ref = format!("builtin:{mesh}"); + let geometry = texturecraft_engine::geom::primitives::builtin(mesh).unwrap(); + let session = texturecraft_engine::Session::new_project("Texture set settings", geometry, &mesh_ref, None, 128).unwrap(); + let mut harness = Harness::builder() + // Tall enough that the list's rows and the settings' channels show without scrolling + .with_size(vec2(1600.0, 2400.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + let ctx = harness.ctx.clone(); + crate::menus::invoke(harness.state_mut(), &ctx, "ui.view.textureSetSettings"); + harness.run_steps(4); + harness + } + + /// Presses and lets go at `at` through the real pointer path, as a person's click lands on a control drawn over a row + fn click_at(harness: &mut Harness<'static, TextureCraftApp>, at: egui::Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + } + + fn click(harness: &mut Harness<'static, TextureCraftApp>, role: egui::Role, label: &str) { + let rect = harness.get_by_role_and_label(role, label).rect(); + // A row's middle is under its size dropdown in a narrow panel: aim at its name + let at = if role == egui::Role::ListItem { egui::pos2(rect.left() + rect.width() * 0.25, rect.center().y) } else { rect.center() }; + click_at(harness, at); + } + + /// Steps until the resize worker has handed its result back + fn finish_resize(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..200 { + harness.run_steps(1); + if harness.state().resize.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + harness.run_steps(2); + } + + #[test] + fn a_uv_tile_picked_in_the_list_is_what_size_edits() { + let mut harness = harness("udim_plane"); + let tiles = harness.state().session.doc.project.texture_sets[0].uv_tiles.clone(); + assert!(harness.query_by_role_and_label(egui::Role::ComboBox, &format!("Size of UV tile {}", tiles[1])).is_none()); + + click(&mut harness, egui::Role::ListItem, &format!("UV tile {}", tiles[1])); + click(&mut harness, egui::Role::ComboBox, &format!("Size of UV tile {}", tiles[1])); + click(&mut harness, egui::Role::ListBoxOption, "256"); + harness.run_steps(3); + + let set = &harness.state().session.doc.project.texture_sets[0]; + assert!(set.tile_resolution(tiles[1]) > set.tile_resolution(tiles[0]), "only the picked tile grew"); + } + + #[test] + fn unlocked_size_sets_the_height_alone() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::CheckBox, "Lock Size"); + let height = + harness.get_all_by_role_and_label(egui::Role::ComboBox, "Size").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().rect().center(); + click_at(&mut harness, height); + click(&mut harness, egui::Role::ListBoxOption, "256"); + finish_resize(&mut harness); + + let set = &harness.state().session.doc.project.texture_sets[0]; + assert!(set.height() > set.resolution, "{}x{}", set.resolution, set.height()); + } + + #[test] + fn a_channel_gear_lists_the_formats_and_stores_the_one_picked() { + let mut harness = harness("material_ball"); + let format = |harness: &Harness<'static, TextureCraftApp>| { + let formats = harness.state().session.doc.project.texture_sets[0].formats(); + formats.into_iter().find(|(channel, _)| *channel == Channel::BaseColor).map(|(_, format)| format) + }; + let before = format(&harness); + + click(&mut harness, egui::Role::Button, "Base color format"); + click(&mut harness, egui::Role::ListBoxOption, "RGB32F"); + harness.run_steps(3); + + assert!(format(&harness) != before, "{:?}", format(&harness)); + } + + #[test] + fn the_channel_window_marks_unread_material_channels_but_not_user_channels() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + // The dialog lays itself out over a few frames before its checks are in the tree + harness.run_steps(4); + let marked = |label: &str| harness.get_by_role_and_label(egui::Role::CheckBox, label).accesskit_node().description().is_some(); + + assert!(marked("Base weight"), "a channel the shader ignores is marked"); + assert!(!marked("User0"), "a user channel is not"); + } +} diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 60daf4aa..38513638 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -526,7 +526,8 @@ fn the_normal_map_format_changes_on_ok_and_shows_in_the_texture_set_panel() { h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::TextureSetSettings); h.run_steps(3); - assert!(h.query_all_by_value("DirectX").next().is_some(), "the Texture Set Settings panel shows the project's format"); + // The panel's dropdown shows the project's format (the project window is closed by now) + assert!(h.query_all_by_role_and_label(Role::ComboBox, "DirectX").next().is_some(), "the Texture Set Settings panel shows the project's format"); // One undo step puts it back h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); From b4e9c175754cd1e9ed9f5b2bcc529948be2eb810 Mon Sep 17 00:00:00 2001 From: Kirill M <176898419+JaffarSk24@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:16:23 +0100 Subject: [PATCH 115/190] docs: the CJK and Arabic picks need a font for their script The language picker greys out a language whose script no available font covers, so a web build with catalogs but without craft-fonts cannot pick Japanese, Chinese, Korean or Arabic. --- docs/features.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/features.md b/docs/features.md index 8c2e96d4..76d7ff01 100644 --- a/docs/features.md +++ b/docs/features.md @@ -297,7 +297,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - A **History** panel: click any step to go back to it, or forward again to an undone one. - **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese, Chinese, Korean and Arabic, switchable live. A build without the shared craft-i18n catalogs - offers English only. + offers English only, and Japanese, Chinese, Korean and Arabic can be picked only where a font + for their script is available (craft-fonts or the system's); otherwise they show greyed out. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch navigation and project open, save and download. From 658cc2a168dd3efde4dbdb16e587d9393ca0d696 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:34:17 +0000 Subject: [PATCH 116/190] Refuse a malformed texture set height or setting instead of ignoring it textureSet.resolution took a height that was not a number as absent and resized the set square, and textureSet.settings skipped a normalMixing, aoMixing, heightToNormal or uvPadding value that was not a string and reported success. Both now return an error and leave the set as it was, as normalFormat already did. --- crates/engine/src/set_cmds.rs | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 6b438759..7c47c8d8 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -130,7 +130,10 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> { fn resolution(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.resolution")?; let width = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?; - let height = u64p(p, "height").unwrap_or(width); + let height = match p.get("height") { + None | Some(Value::Null) => width, + Some(_) => u64p(p, "height").ok_or_else(|| bad("textureSet.resolution", "`height` must be a number of texels"))?, + }; let task = s.resize_task_to(ts, u32::try_from(width).unwrap_or(0), u32::try_from(height).unwrap_or(0))?; let out = task.run(&texturecraft_bake::Progress::new())?; s.apply_resize(out) @@ -431,9 +434,12 @@ fn settings(s: &mut Session, p: &Value) -> Result { /// The optional setting `key` of `textureSet.settings`, one of `ids` fn choice_param(p: &Value, key: &str, what: &str, parse: fn(&str) -> Option, ids: &[&str]) -> Result> { - let Some(id) = strp(p, key) else { return Ok(None) }; - - parse(id).map(Some).ok_or_else(|| bad("textureSet.settings", format!("unknown {what} {id:?} ({})", ids.join(" or ")))) + let unknown = |value: &Value| bad("textureSet.settings", format!("unknown {what} {value} ({})", ids.join(" or "))); + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(value @ Value::String(id)) => parse(id).map(Some).ok_or_else(|| unknown(value)), + Some(other) => Err(unknown(other)), + } } #[cfg(test)] @@ -463,6 +469,22 @@ mod tests { assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["nope"]})).is_err()); } + #[test] + fn malformed_size_and_setting_values_are_refused_and_change_nothing() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 0, "resolution": 256, "height": 128})).unwrap(); + let before = s.doc.project.texture_sets[0].clone(); + + assert!(crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 0, "resolution": 512, "height": "256"})).is_err()); + for (key, value) in [("normalMixing", json!(1)), ("aoMixing", json!(true)), ("heightToNormal", json!(["sharp"])), ("uvPadding", json!(2))] { + let mut params = json!({"ts": 0}); + params[key] = value.clone(); + assert!(crate::execute(&mut s, "textureSet.settings", ¶ms).is_err(), "{key}: {value}"); + } + + assert_eq!(s.doc.project.texture_sets[0], before); + } + #[test] fn rename_reset_restores_the_mesh_material_name() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); From 544d7881297f6e1dadf6c1ae60daa7910e38d35f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:34:20 +0000 Subject: [PATCH 117/190] Keep a layer's switched-off channels when Manage channels applies to every set With Apply to all Texture Sets the dialog sends every ticked channel, including the ones a set already has, and textureSet.channels added each again, which switched that channel back on in every layer of the set where it had been turned off. A channel the set already has is now left alone. --- crates/engine/src/set_cmds.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 7c47c8d8..fdbef2be 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -288,8 +288,11 @@ fn channels(s: &mut Session, p: &Value) -> Result { s.edit("Add or remove channels", |s| { for &ts in &sets { + // A channel the set already has keeps its layers' channel switches for &c in &add { - add_channel(s, ts, c)?; + if !s.doc.project.texture_set(ts)?.has_channel(c) { + add_channel(s, ts, c)?; + } } s.doc.project.texture_set_mut(ts)?.channels.retain(|(c, _)| !remove.contains(c)); } @@ -469,6 +472,23 @@ mod tests { assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["nope"]})).is_err()); } + #[test] + fn channels_applied_to_every_set_keep_the_channels_a_layer_switched_off() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + let layer = s.doc.project.texture_sets[0].stack[0]; + crate::execute(&mut s, "layer.blend", &json!({"channel": "roughness", "enabled": false})).unwrap(); + let layer_has_roughness = |s: &Session| s.doc.project.layer(layer).is_ok_and(|l| l.channels.contains_key(&Channel::Roughness)); + assert!(!layer_has_roughness(&s)); + + // Apply to all Texture Sets sends every ticked channel, the ones the sets already have too + let ticked: Vec<&str> = s.doc.project.texture_sets[0].channel_list().iter().map(|c| c.id()).chain(["ior"]).collect(); + crate::execute(&mut s, "textureSet.channels", &json!({"add": ticked, "allSets": true})).unwrap(); + + assert!(s.doc.project.texture_sets.iter().all(|set| set.has_channel(Channel::Ior))); + assert!(!layer_has_roughness(&s), "the layer's roughness stays off"); + } + #[test] fn malformed_size_and_setting_values_are_refused_and_change_nothing() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); From 3031941f2a76512c34f1d145720fbf2b53ba705c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:34:53 +0000 Subject: [PATCH 118/190] Start the Texture Set list's state over when another project or mesh replaces this one The list kept the row being renamed, folded sets and the picked UV tile by set index across a project replacement, so a rename under way when another project opened was applied to the new project's set at the same index, and Texture Set Settings could keep sizing a picked UV tile the new set does not have. The state now belongs to the project and mesh it was made in (the descriptions choice stays), and Settings only follows a picked tile the active set has. --- crates/ui-egui/src/texture_set_list.rs | 23 ++++++++++++++++++- .../src/texture_set_list/list_state.rs | 12 ++++++++-- crates/ui-egui/src/texture_set_settings.rs | 3 ++- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/texture_set_list.rs b/crates/ui-egui/src/texture_set_list.rs index f200f98d..422099ad 100644 --- a/crates/ui-egui/src/texture_set_list.rs +++ b/crates/ui-egui/src/texture_set_list.rs @@ -87,7 +87,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { } let tokens = Tokens::get(ui.ctx()); - let mut state = ListState::load(ui.ctx()); + let mut state = ListState::load(ui.ctx(), (app.session.project_id, app.session.mesh_id)); let rows: Vec = (0..app.session.doc.project.texture_sets.len()) .filter_map(|index| { @@ -628,6 +628,27 @@ mod tests { assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_some(), "Shift+F10 opens the row's menu"); } + #[test] + fn a_rename_under_way_is_dropped_when_another_project_replaces_this_one() { + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + harness.get_by_role_and_label(egui::Role::ListItem, &original).focus(); + harness.run_steps(2); + harness.key_press(egui::Key::F2); + harness.run_steps(3); + harness.event(egui::Event::Text("z".into())); + harness.run_steps(1); + + // Another project with the same texture sets takes this one's place mid-edit + let geometry = texturecraft_engine::geom::primitives::builtin("material_ball").unwrap(); + harness.state_mut().session = texturecraft_engine::Session::new_project("Other", geometry, "builtin:material_ball", None, 128).unwrap(); + harness.run_steps(3); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.texture_sets[1].name, original, "the new project's set keeps its name"); + } + #[test] fn a_uv_tile_row_sizes_its_own_tile() { let mut harness = harness("udim_plane"); diff --git a/crates/ui-egui/src/texture_set_list/list_state.rs b/crates/ui-egui/src/texture_set_list/list_state.rs index 3e2bbaa4..772da31d 100644 --- a/crates/ui-egui/src/texture_set_list/list_state.rs +++ b/crates/ui-egui/src/texture_set_list/list_state.rs @@ -5,6 +5,8 @@ use super::{DescriptionMode, RowEdit}; /// The list's UI state: the row being edited, which descriptions show, folded UV tile sets and the selected tile #[derive(Clone, Default)] pub(crate) struct ListState { + /// Project and mesh ids the rows' set indices belong to + owner: (u64, u64), /// Set, what it edits, the text so far, and whether the field still needs focus pub(crate) edit: Option<(usize, RowEdit, String, bool)>, pub(crate) descriptions: DescriptionMode, @@ -19,8 +21,14 @@ impl ListState { egui::Id::unique("texture_set_list_state") } - pub(crate) fn load(ctx: &egui::Context) -> Self { - ctx.data(|data| data.get_temp::(Self::id())).unwrap_or_default() + /// The state for the project and mesh `owner`; another project or mesh starts over, keeping only the descriptions choice + pub(crate) fn load(ctx: &egui::Context, owner: (u64, u64)) -> Self { + let state: Self = ctx.data(|data| data.get_temp::(Self::id())).unwrap_or_default(); + if state.owner == owner { + return state; + } + + ListState { owner, descriptions: state.descriptions, ..ListState::default() } } pub(crate) fn store(self, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs index 408315a7..b1a68a70 100644 --- a/crates/ui-egui/src/texture_set_settings.rs +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -46,7 +46,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { crate::channel_manager::ChannelManager::show(app, &ui.ctx().clone()); let set_index = app.session.ts(); let Some(set) = app.session.doc.project.texture_sets.get(set_index).cloned() else { return }; - let tile = crate::texture_set_list::ListState::load(ui.ctx()).tile.filter(|(set, _)| *set == set_index).map(|(_, udim)| udim); + let list = crate::texture_set_list::ListState::load(ui.ctx(), (app.session.project_id, app.session.mesh_id)); + let tile = list.tile.filter(|(picked_set, udim)| *picked_set == set_index && set.uv_tiles.contains(udim)).map(|(_, udim)| udim); egui::ScrollArea::vertical().id_salt("tss").show(ui, |ui| { PropertySheet::show(ui, ("texture_set_settings", set_index), |sheet| { general(app, sheet, set_index, &set, tile); From a94e3f87034b24c70a1972a19c4f00211600804d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:34:58 +0000 Subject: [PATCH 119/190] Describe the texture set sizes, channels and settings this branch adds in the feature list docs/features.md still said texture sets are square with 21 channel types. --- docs/features.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/features.md b/docs/features.md index 3b58b176..3e584f7a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -137,8 +137,14 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). -- **Texture sets** from 128 to 8192 px per material, resampled when you change them, with 21 - channel types to add or remove. Show, hide or invert them all at once, or **focus** on the +- **Texture sets** from 128 to 8192 px per material, square or with a height of their own + (`textureSet.resolution {resolution, height}`), resampled when you change them, with 72 channel + types to add or remove: the 21 the shader reads, more material channels that are stored and + exported, and User0 to User31 (*Add or remove channels*, `textureSet.channels`). Each channel + has a storage format (`textureSet.channel.format`), and each set its normal mixing, ambient + occlusion mixing, height to normal method and UV padding, across seams (3D) or from island + edges (2D) (`textureSet.settings`). Rename a set in the list, or reset it to the mesh + material's name. Show, hide or invert them all at once, or **focus** on the active one. The project's **normal map format** (OpenGL or DirectX, in Texture Set Settings) says how a normal map image set as a mesh map is read, and is the default for export. - **Projects** are a single `.tcraft` file: the mesh (with its generated UV layout when *Rebuild mesh UVs* was chosen), every layer (sparse and lossless), baked maps From fd91866c47a9b4504a05aebf3e8963a4702332c2 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:36:50 +0000 Subject: [PATCH 120/190] Keep picked channel formats in a project template A template saved the set's channel formats but not whether they were picked, so a project started from it stored every channel at 16 bits again while showing the formats as 16-bit. Templates now carry format_precision; older template files read it as false and keep 16 bits, as before. --- crates/engine/src/template_cmds.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/engine/src/template_cmds.rs b/crates/engine/src/template_cmds.rs index db283d7e..9d0212a8 100644 --- a/crates/engine/src/template_cmds.rs +++ b/crates/engine/src/template_cmds.rs @@ -32,6 +32,8 @@ pub struct ProjectTemplate { pub normal_format: NormalFormat, /// Channels of every texture set, with their formats. pub channels: Vec<(Channel, ChannelFormat)>, + /// Whether the channels hold their formats' precision ([`texturecraft_core::TextureSet::format_precision`]); older templates keep 16 bits + pub format_precision: bool, /// Shader: PBR specular/glossiness instead of metallic/roughness. pub spec_gloss: bool, pub parallax: bool, @@ -48,6 +50,7 @@ impl Default for ProjectTemplate { resolution: 2048, normal_format: NormalFormat::OpenGl, channels: with_formats(&Channel::DEFAULT_SET), + format_precision: false, spec_gloss: d.spec_gloss, parallax: d.parallax, ior: d.ior, @@ -199,6 +202,7 @@ impl Session { for ts in 0..p.texture_sets.len() { if let Some(set) = p.texture_sets.get_mut(ts) { set.channels = t.channels.clone(); + set.format_precision = t.format_precision; } let wanted: Vec = t.channels.iter().map(|(c, _)| *c).collect(); for (id, _) in p.walk(ts) { @@ -293,6 +297,7 @@ fn save(session: &mut Session, params: &Value) -> Result { resolution: set.resolution, normal_format: project.normal_format, channels: set.channels.clone(), + format_precision: set.format_precision, spec_gloss: display.spec_gloss, parallax: display.parallax, ior: display.ior, @@ -431,6 +436,25 @@ mod tests { assert!(execute(&mut s, "project.new", &json!({"template": "nope"})).is_err()); } + #[test] + fn a_template_keeps_the_channel_formats_picked_in_the_set_it_was_saved_from() { + let dir = std::env::temp_dir().join(format!("tc_template_formats_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + s.load_templates(dir.clone()); + execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L8"})).unwrap(); + execute(&mut s, "project.template.save", &json!({"name": "Eight bit roughness"})).unwrap(); + + let mut fresh = Session::new_project("f", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + fresh.load_templates(dir.clone()); + execute(&mut fresh, "project.new", &json!({"template": "Eight bit roughness"})).unwrap(); + let held = |session: &Session, channel: Channel| session.doc.project.texture_sets[0].formats().into_iter().find(|(c, _)| *c == channel).map(|(_, f)| f); + + assert_eq!(held(&fresh, Channel::Roughness), held(&s, Channel::Roughness)); + assert_eq!(held(&fresh, Channel::Metallic), held(&s, Channel::Metallic), "the other channels keep 16 bits"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn save_current_settings_as_template_and_reload() { let dir = std::env::temp_dir().join(format!("tc_templates_{}", std::process::id())); From 7b370383f282b70b355a81b7a2445571225dfb90 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:40:02 +0000 Subject: [PATCH 121/190] Test that a set's size, formats and settings survive save and reopen, and that older sets open as before Two sets with different sizes, channel formats, added channels, mixing, height to normal, padding and a non-Latin description go through the project file and come back the same; a set without the new fields opens square, with 2D padding and Smooth height to normal. --- crates/core/src/project.rs | 13 +++++++++++++ crates/engine/src/set_cmds.rs | 23 +++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 4fb6f848..e965358b 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -939,6 +939,19 @@ mod tests { p } + #[test] + fn older_sets_without_the_new_fields_open_square_with_2d_padding_and_smooth_normals() { + let mut v = serde_json::to_value(TextureSet::new("a", 0, 256)).unwrap(); + for field in ["resolution_height", "format_precision", "height_to_normal", "uv_padding"] { + v.as_object_mut().unwrap().remove(field); + } + + let old: TextureSet = serde_json::from_value(v).unwrap(); + + assert_eq!(old.size(), (256, 256)); + assert_eq!((old.uv_padding, old.height_to_normal), (UvPaddingMode::Space2d, HeightToNormalMethod::Smooth)); + } + #[test] fn sets_keep_16_bits_until_a_format_is_set_also_in_older_files() { let new = TextureSet::new("a", 0, 128); diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index fdbef2be..24089c24 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -505,6 +505,29 @@ mod tests { assert_eq!(s.doc.project.texture_sets[0], before); } + #[test] + fn a_sets_size_formats_and_settings_survive_save_and_reopen() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 1, "resolution": 256, "height": 128})).unwrap(); + crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 1, "channel": "roughness", "format": "L8"})).unwrap(); + crate::execute(&mut s, "textureSet.channels", &json!({"ts": 1, "add": ["user7", "coatTangent"]})).unwrap(); + let settings = + json!({"ts": 1, "normalMixing": "replace", "aoMixing": "none", "heightToNormal": "sharp", "uvPadding": "2d", "description": "Ünïcode 説明"}); + crate::execute(&mut s, "textureSet.settings", &settings).unwrap(); + let inspect = |s: &mut Session, ts: usize| crate::execute(s, "textureSet.inspect", &json!({"ts": ts})).unwrap(); + let (first, second) = (inspect(&mut s, 0), inspect(&mut s, 1)); + + let mut back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + + for (ts, before) in [(0, first), (1, second)] { + let after = inspect(&mut back, ts); + for key in ["resolution", "height", "size", "channels", "normalMixing", "aoMixing", "heightToNormal", "uvPadding", "description"] { + assert_eq!(after[key], before[key], "set {ts} {key}"); + } + } + assert_ne!(inspect(&mut back, 0)["uvPadding"], inspect(&mut back, 1)["uvPadding"], "each set keeps its own settings"); + } + #[test] fn rename_reset_restores_the_mesh_material_name() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); From 8032697c9938ce704ef5d52256288a178a07b3e9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:41:17 +0000 Subject: [PATCH 122/190] Switch the channel off on the layer the Manage channels test reads The test read the set's bottom layer but switched roughness off on the selected one, so it stopped at its own precondition instead of checking textureSet.channels. --- crates/engine/src/set_cmds.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 24089c24..25fbee83 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -476,8 +476,9 @@ mod tests { fn channels_applied_to_every_set_keep_the_channels_a_layer_switched_off() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); crate::execute(&mut s, "layer.add.fill", &json!({})).unwrap(); - let layer = s.doc.project.texture_sets[0].stack[0]; - crate::execute(&mut s, "layer.blend", &json!({"channel": "roughness", "enabled": false})).unwrap(); + let layer = s.selected_layer().unwrap(); + // Switched off, as layer.blend {enabled: false} leaves it + s.doc.project.layer_mut(layer).unwrap().channels.remove(&Channel::Roughness); let layer_has_roughness = |s: &Session| s.doc.project.layer(layer).is_ok_and(|l| l.channels.contains_key(&Channel::Roughness)); assert!(!layer_has_roughness(&s)); From fcd36447441b720330fa0e2db090ce89c89aa78f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:44:02 +0000 Subject: [PATCH 123/190] Put a blank line after the multi-line early-exit guards in the texture set code Spacing only (CODE_STYLE: a blank line after a multi-line if/let-else guard), in methods this branch adds or changes. --- crates/compose/src/eval.rs | 1 + crates/core/src/project.rs | 5 +++++ crates/engine/src/set_cmds.rs | 2 ++ crates/ui-egui/src/channel_manager.rs | 1 + crates/ui-egui/src/texture_set_list.rs | 4 ++++ crates/ui-egui/src/texture_set_settings.rs | 1 + 6 files changed, 14 insertions(+) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index e290c587..b8d0b614 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1203,6 +1203,7 @@ fn tile_local((x, y): (f32, f32), (block, tile): ([u32; 2], [u32; 2])) -> Option if local[0] >= size[0] || local[1] >= size[1] { return None; } + Some((origin, [(local[0] + 0.5) / size[0], (local[1] + 0.5) / size[1]], size)) } diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index e965358b..209bd3cf 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -278,6 +278,7 @@ impl TextureSet { if self.tile_resolutions.is_empty() { return (self.resolution, self.height()); } + let block = self.block_resolution(); (block, block) } @@ -823,15 +824,18 @@ impl Project { if self.format_version > FORMAT_VERSION { return Err(CoreError::Invalid(format!("project format {} is newer than this TextureCraft supports ({FORMAT_VERSION})", self.format_version))); } + if let Some(t) = self.texture_sets.iter().find(|t| !t.uv_tiles.is_empty() && (t.tile_grid().is_none() || !t.uv_tiles.is_sorted_by(|a, b| a < b))) { return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tiles {:?}", t.name, t.uv_tiles))); } + let bad_tile_res = |t: &TextureSet| { t.tile_resolutions.iter().any(|(u, r)| !t.uv_tiles.contains(u) || !r.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(r)) }; if let Some(t) = self.texture_sets.iter().find(|t| bad_tile_res(t)) { return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tile resolutions {:?}", t.name, t.tile_resolutions))); } + let bad_height = |set: &TextureSet| { set.resolution_height .is_some_and(|height| !height.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&height) || !set.tile_resolutions.is_empty()) @@ -839,6 +843,7 @@ impl Project { if let Some(set) = self.texture_sets.iter().find(|set| bad_height(set)) { return Err(CoreError::Invalid(format!("texture set \"{}\" has an invalid height {:?}", set.name, set.resolution_height))); } + let mut seen = BTreeSet::new(); for ts in 0..self.texture_sets.len() { for (id, depth) in self.walk(ts) { diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 25fbee83..0fc74d57 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -175,6 +175,7 @@ impl ResizeTask { if set.resolution_height.is_some() && !set.tile_resolutions.is_empty() { return Err(bad("textureSet.resolution", "a texture set whose UV tiles have their own sizes stays square")); } + crate::session::check_size(set)?; let size = set.size(); let mut log = crate::log::SessionLog::new(); @@ -280,6 +281,7 @@ fn channels(s: &mut Session, p: &Value) -> Result { if remove.contains(&Channel::BaseColor) { return Err(bad(cmd, "base color can't be removed")); } + if let Some(both) = add.iter().find(|c| remove.contains(c)) { return Err(bad(cmd, format!("{} is both added and removed", both.label()))); } diff --git a/crates/ui-egui/src/channel_manager.rs b/crates/ui-egui/src/channel_manager.rs index 5a094d0e..bdbe7b56 100644 --- a/crates/ui-egui/src/channel_manager.rs +++ b/crates/ui-egui/src/channel_manager.rs @@ -136,6 +136,7 @@ impl ChannelManager { // Other sets may differ from this one: send the whole list so every set ends up the same return (on, off.into_iter().filter(|c| *c != Channel::BaseColor).collect()); } + (on.into_iter().filter(|c| !set.has_channel(*c)).collect(), off.into_iter().filter(|c| set.has_channel(*c)).collect()) } diff --git a/crates/ui-egui/src/texture_set_list.rs b/crates/ui-egui/src/texture_set_list.rs index 422099ad..cd47c652 100644 --- a/crates/ui-egui/src/texture_set_list.rs +++ b/crates/ui-egui/src/texture_set_list.rs @@ -427,6 +427,7 @@ fn tile_row(ui: &mut Ui, set: usize, udim: u32, resolution: u32, set_width: u32, if let Some(size) = picked { return Some(TileAction::Resize(size)); } + (response.clicked() || response.secondary_clicked()).then_some(TileAction::Select) } @@ -435,6 +436,7 @@ fn shader_column_width(ui: &Ui, row_width: f32) -> f32 { if row_width < SHADER_MIN_ROW_WIDTH { return 0.0; } + dropdown_width(ui, tr(INSTANCE_NAME)) + DROPDOWN_GAP } @@ -511,6 +513,7 @@ fn edit_field(ui: &mut Ui, state: &mut ListState, rect: Rect, size: f32) -> Opti if !response.lost_focus() { return None; } + let edit = state.edit.take()?; (!ui.input(|input| input.key_pressed(egui::Key::Escape))).then_some(edit.2) } @@ -573,6 +576,7 @@ mod tests { if harness.state().resize.is_none() { break; } + std::thread::sleep(std::time::Duration::from_millis(10)); } harness.run_steps(2); diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs index b1a68a70..046bd94c 100644 --- a/crates/ui-egui/src/texture_set_settings.rs +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -329,6 +329,7 @@ mod tests { if harness.state().resize.is_none() { break; } + std::thread::sleep(std::time::Duration::from_millis(10)); } harness.run_steps(2); From 8dfe91622497e977d42b5e3340f487548dd538fe Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:33:26 +0000 Subject: [PATCH 124/190] Keep only the texels past a seam beside the island-edge padding, so padding across seams holds one full-size map instead of two --- crates/compose/src/eval.rs | 40 ++++++++-------- crates/compose/src/padding_maps.rs | 74 ++++++++++++++++++------------ crates/compose/src/seam_padding.rs | 32 +++++++------ crates/engine/src/set_cmds.rs | 2 +- crates/formats/src/export/mod.rs | 9 ++-- 5 files changed, 90 insertions(+), 67 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b8d0b614..5fa061d7 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4886,33 +4886,35 @@ fn store_below(cache: &mut [f32], lanes: &[Lane], stride: usize, o: usize, acc: pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { let mut written = std::collections::BTreeSet::new(); let (w, h) = (out.resolution, out.height); - if (padding.all.width, padding.all.height) != (w, h) { + if padding.size() != (w, h) { return written; } - let (nx, ny) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64); - let mut set = std::collections::BTreeSet::new(); + // The tiles and their neighbours, which padding reaches into + let (tiles_across, tiles_down) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64); + let mut near_tiles = std::collections::BTreeSet::new(); for &(tx, ty) in tiles { for dy in -1..=1i64 { for dx in -1..=1i64 { let (x, y) = (tx as i64 + dx, ty as i64 + dy); - if x >= 0 && y >= 0 && x < nx && y < ny { - set.insert((x as u32, y as u32)); + if x >= 0 && y >= 0 && x < tiles_across && y < tiles_down { + near_tiles.insert((x as u32, y as u32)); } } } } - let set: Vec<(u32, u32)> = set.into_iter().collect(); + let near_tiles: Vec<(u32, u32)> = near_tiles.into_iter().collect(); + for (channel, img) in out.channels.iter_mut() { let comps = img.comps(); let src: &TileImage = img; - let dilation = padding.for_channel(*channel); + let across_seams = crate::PaddingMaps::crosses_seams(*channel); // Each tile pads from the original image, so parallel writes stay independent - let padded: Vec<((u32, u32), Vec)> = set + let padded: Vec<((u32, u32), Vec)> = near_tiles .par_iter() .filter_map(|&(tx, ty)| { - let mut data: Option> = None; + let mut padded_tile: Option> = None; for ly in 0..TILE { for lx in 0..TILE { let (x, y) = (tx * TILE + lx, ty * TILE + ly); @@ -4920,24 +4922,24 @@ pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u3 continue; } - let Some((sx, sy)) = dilation.source(x, y) else { continue }; + let Some((sx, sy)) = padding.source(across_seams, x, y) else { continue }; if (sx, sy) == (x, y) { continue; } - let v = src.get(sx, sy); - let d = data.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec)); - let o = (ly * TILE + lx) as usize * comps; - if let Some(px) = d.get_mut(o..o + comps) { - px.copy_from_slice(&v[..comps]); + let source_texel = src.get(sx, sy); + let tile_data = padded_tile.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec)); + let offset = (ly * TILE + lx) as usize * comps; + if let Some(texel) = tile_data.get_mut(offset..offset + comps) { + texel.copy_from_slice(&source_texel[..comps]); } } } - Some(((tx, ty), data?)) + Some(((tx, ty), padded_tile?)) }) .collect(); - for ((tx, ty), d) in padded { - img.set_tile(tx, ty, Some(std::sync::Arc::new(d))); + for ((tx, ty), tile_data) in padded { + img.set_tile(tx, ty, Some(std::sync::Arc::new(tile_data))); written.insert((tx, ty)); } } @@ -6436,7 +6438,7 @@ soft {soft:?}" out.channels.get_mut(&Channel::Roughness).unwrap().set(10, 10, &[to_u16(0.9)]); let mut covered = vec![false; 64 * 64]; covered[10 * 64 + 10] = true; - let padding = crate::PaddingMaps { all: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), flat: None }; + let padding = crate::PaddingMaps { flat: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), crossed: Vec::new() }; pad_tiles(&mut out, &padding, &[(0, 0)]); assert!((out.value(Channel::Roughness, 12, 12)[0] - 0.9).abs() < 1e-3); assert!(out.value(Channel::Roughness, 30, 30)[0] < 0.1 || !out.channels[&Channel::Roughness].is_allocated(0, 0)); diff --git a/crates/compose/src/padding_maps.rs b/crates/compose/src/padding_maps.rs index 880c24f7..bfb7fe41 100644 --- a/crates/compose/src/padding_maps.rs +++ b/crates/compose/src/padding_maps.rs @@ -1,4 +1,4 @@ -//! A texture set's UV padding maps, one per kind of channel +//! A texture set's UV padding: from island edges, and across seams for the texels past one use texturecraft_core::{Channel, ChannelKind, UvPaddingMode}; use texturecraft_geom::UvSeam; @@ -6,36 +6,48 @@ use texturecraft_texel::dilate::DilationMap; use crate::seam_padding::{SEAM_REACH, cross_seams}; -/// A texture set's padding maps: `all` for its channels, `flat` for tangent-space normals +/// A texture set's padding: `flat` for every texel, with the few texels past a seam listed apart in `crossed` #[derive(Clone, Debug, PartialEq)] pub struct PaddingMaps { - pub all: DilationMap, - /// Padding from island edges (2D) always: a tangent-space normal turns with its island, so it can't continue across a seam - pub flat: Option, + /// Padding from island edges (2D), which tangent-space normals always take: a normal turns with its island, so it can't continue across a seam + pub flat: DilationMap, + /// Across seams (3D): (texel, source texel) indices of the padding texels that continue from a seam's other side, sorted by texel + pub crossed: Vec<(u32, u32)>, } impl PaddingMaps { - /// The maps for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block` + /// The padding for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block` pub fn new(mode: UvPaddingMode, covered: &[bool], (width, height): (u32, u32), max_dist: Option, block: (u32, u32), seams: &[UvSeam]) -> PaddingMaps { let flat = DilationMap::in_rectangular_blocks(covered, width, height, max_dist, block); - match mode { - UvPaddingMode::Space2d => PaddingMaps { all: flat, flat: None }, - UvPaddingMode::Space3d => { - let mut all = flat.clone(); - cross_seams(&mut all, covered, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams); - PaddingMaps { all, flat: Some(flat) } - } + let crossed = match mode { + UvPaddingMode::Space2d => Vec::new(), + UvPaddingMode::Space3d => cross_seams(&flat, covered, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams), + }; + PaddingMaps { flat, crossed } + } + + /// Texels across and down + pub fn size(&self) -> (u32, u32) { + (self.flat.width, self.flat.height) + } + + /// Whether `channel` pads across seams; tangent-space normals pad from island edges + pub fn crosses_seams(channel: Channel) -> bool { + channel.kind() != ChannelKind::NormalMap + } + + /// The covered texel padding (x, y), itself when covered; `across_seams` takes the seams' other sides + pub fn source(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> { + let source = self.flat.source(x, y)?; + if !across_seams || source == (x, y) || self.crossed.is_empty() { + return Some(source); } - } - /// The map padding tangent-space normals - pub fn flat(&self) -> &DilationMap { - self.flat.as_ref().unwrap_or(&self.all) - } - - /// The map padding `channel` - pub fn for_channel(&self, channel: Channel) -> &DilationMap { - if channel.kind() == ChannelKind::NormalMap { self.flat() } else { &self.all } + let (texel, width) = (y * self.flat.width + x, self.flat.width); + match self.crossed.binary_search_by_key(&texel, |(crossed_texel, _)| *crossed_texel) { + Ok(found) => self.crossed.get(found).map(|(_, crossed_source)| (crossed_source % width, crossed_source / width)), + Err(_) => Some(source), + } } } @@ -61,15 +73,19 @@ mod tests { let (covered, seams) = two_islands(); let space_3d = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (32, 8), Some(4), (0, 0), &seams); let space_2d = PaddingMaps::new(UvPaddingMode::Space2d, &covered, (32, 8), Some(4), (0, 0), &seams); - let island = |map: &DilationMap, x: u32| map.source(x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" }); + let island = |padding: &PaddingMaps, across_seams: bool, x: u32| { + padding.source(across_seams, x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" }) + }; // Just right of the left island, then just left of the right island - assert_eq!((island(&space_3d.all, 13), island(&space_3d.all, 18)), (Some("right"), Some("left"))); - assert_eq!((island(&space_2d.all, 13), island(&space_2d.all, 18)), (Some("left"), Some("right"))); - assert_eq!(space_3d.for_channel(Channel::Normal), &space_2d.all); - assert_eq!(space_3d.for_channel(Channel::BaseColor), &space_3d.all); + assert_eq!((island(&space_3d, true, 13), island(&space_3d, true, 18)), (Some("right"), Some("left"))); + assert_eq!((island(&space_2d, true, 13), island(&space_2d, true, 18)), (Some("left"), Some("right"))); + assert_eq!((island(&space_3d, false, 13), island(&space_3d, false, 18)), (Some("left"), Some("right"))); + assert!(PaddingMaps::crosses_seams(Channel::BaseColor) && !PaddingMaps::crosses_seams(Channel::Normal)); - // Away from the seam, both modes pad from the near island - assert_eq!(island(&space_3d.all, 2), Some("left")); + // Away from the seam, both modes pad from the near island, and only texels between the islands are kept apart + assert_eq!(island(&space_3d, true, 2), Some("left")); + assert!(!space_3d.crossed.is_empty() && space_2d.crossed.is_empty()); + assert!(space_3d.crossed.iter().all(|(texel, _)| (12..20).contains(&(texel % 32)))); } } diff --git a/crates/compose/src/seam_padding.rs b/crates/compose/src/seam_padding.rs index 1b170c00..e0584224 100644 --- a/crates/compose/src/seam_padding.rs +++ b/crates/compose/src/seam_padding.rs @@ -1,5 +1,7 @@ //! UV padding across seams (3D): texels past a UV seam continue the surface from the seam's other side +use std::collections::HashMap; + use texturecraft_geom::{UvSeam, glam::Vec2}; use texturecraft_texel::dilate::{DilationMap, NONE}; @@ -8,13 +10,15 @@ use crate::texel_edge::TexelEdge; /// Farthest a padding texel reaches across a seam, in texels; farther ones keep their nearest covered texel pub const SEAM_REACH: u32 = 32; -/// Point every padding texel just outside a seam at the texel as far inside the seam's other side -pub(crate) fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, block: (u32, u32), seams: &[UvSeam]) { - let (width, height) = (map.width, map.height); +/// The padding texels of `flat` just outside a seam, each with the texel as far inside the seam's other side: (texel, source) indices sorted by texel +pub(crate) fn cross_seams(flat: &DilationMap, covered: &[bool], reach: u32, block: (u32, u32), seams: &[UvSeam]) -> Vec<(u32, u32)> { + let (width, height) = (flat.width, flat.height); let size = Vec2::new(width as f32, height as f32); let block_of = |x: u32, y: u32| (x.checked_div(block.0).unwrap_or(0), y.checked_div(block.1).unwrap_or(0)); let is_covered = |x: u32, y: u32| covered.get((y * width + x) as usize).copied().unwrap_or(false); - let mut crossed_at = vec![f32::INFINITY; map.src.len()]; + + // Each crossed texel's source and how far outside its seam it is; a nearer seam replaces it + let mut crossed: HashMap = HashMap::new(); for seam in seams { for (near, far) in [(seam.sides[0], seam.sides[1]), (seam.sides[1], seam.sides[0])] { let (Some(near_edge), Some(far_edge)) = (TexelEdge::new(near, size), TexelEdge::new(far, size)) else { @@ -28,15 +32,16 @@ pub(crate) fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, b let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32); for y in y0..y1 { for x in x0..x1 { - let index = (y * width + x) as usize; - let Some(&source) = map.src.get(index) else { continue }; - if source == NONE || source == index as u32 { + let index = y * width + x; + let Some(&flat_source) = flat.src.get(index as usize) else { continue }; + if flat_source == NONE || flat_source == index { continue; } let point = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); let Some((along, outside)) = near_edge.outside(point) else { continue }; - if outside > reach || outside >= crossed_at.get(index).copied().unwrap_or(0.0) { + let (source, crossed_at) = crossed.get(&index).copied().unwrap_or((flat_source, f32::INFINITY)); + if outside > reach || outside >= crossed_at { continue; } @@ -59,14 +64,15 @@ pub(crate) fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, b } let (target_x, target_y) = (target.x as u32, target.y as u32); - if is_covered(target_x, target_y) - && let (Some(destination), Some(at)) = (map.src.get_mut(index), crossed_at.get_mut(index)) - { - *destination = target_y * width + target_x; - *at = outside; + if is_covered(target_x, target_y) { + crossed.insert(index, (target_y * width + target_x, outside)); } } } } } + + let mut sources: Vec<(u32, u32)> = crossed.into_iter().map(|(texel, (source, _))| (texel, source)).collect(); + sources.sort_unstable(); + sources } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 0fc74d57..4d535816 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -590,7 +590,7 @@ mod tests { fn uv_padding_rebuilds_the_viewport_padding_and_undoes() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); let mode = |s: &Session| crate::inspect::texture_set(s, 0)["uvPadding"].clone(); - let crosses_seams = |s: &Session| s.caches[0].padding.flat.is_some(); + let crosses_seams = |s: &Session| !s.caches[0].padding.crossed.is_empty(); assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); s.update(); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 454ab930..786da1a2 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -977,20 +977,19 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { let y = y0 + row_y as u32; for (column, x) in (x0..x0 + w).enumerate() { - let at = |flat: bool| { + let at = |across_seams: bool| { if sampler.covered(x, y) { return Some(At::Texel(x, y)); } - let dilation_map = padding.as_ref().map(|padding| if flat { padding.flat() } else { &padding.all }); - match dilation_map.and_then(|d| d.source(x, y)) { + match padding.as_ref().and_then(|padding| padding.source(across_seams, x, y)) { Some((sx, sy)) => Some(At::Texel(sx, sy)), None => beyond_default.then_some(At::Default), } }; // Only normals use the sample cache, and they all sample the 2D padding - let (at_all, at_flat) = (at(false), at(true)); + let (at_all, at_flat) = (at(true), at(false)); let mut cache = None; for (component, (_, source)) in channel_layout.iter().enumerate() { let Some(at) = (if pads_flat.get(component).copied().unwrap_or(false) { at_flat } else { at_all }) else { continue }; @@ -1006,7 +1005,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned if diffuse { let known: Vec = (y0..y0 + h) .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) - .map(|(x, y)| sampler.covered(x, y) || padding.as_ref().is_some_and(|padding| padding.all.source(x, y).is_some())) + .map(|(x, y)| sampler.covered(x, y) || padding.as_ref().is_some_and(|padding| padding.flat.source(x, y).is_some())) .collect(); // Keep diffusion within each UV tile when rendering an atlas From 7bd600f475ae4089f77b51302b51855484570305 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:33:26 +0000 Subject: [PATCH 125/190] Look up the linear value of each 8-bit sRGB step instead of decoding it for every stored texel --- crates/compose/src/channel_store.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/channel_store.rs b/crates/compose/src/channel_store.rs index 63d77f85..748c930f 100644 --- a/crates/compose/src/channel_store.rs +++ b/crates/compose/src/channel_store.rs @@ -1,5 +1,7 @@ //! What a channel's storage format keeps of a composited value +use std::sync::OnceLock; + use texturecraft_core::{ChannelFormat, lum}; use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; @@ -14,14 +16,20 @@ pub(crate) fn stored(format: ChannelFormat, signed: bool, mut value: [f32; 3], c fn stored_value(format: ChannelFormat, signed: bool, component: f32) -> f32 { let value = if signed { component * 0.5 + 0.5 } else { component }; let unit = |unit_value: f32| if signed { unit_value * 2.0 - 1.0 } else { unit_value }; - let steps = |unit_value: f32| (unit_value.clamp(0.0, 1.0) * 255.0).round() / 255.0; + let step = |unit_value: f32| (unit_value.clamp(0.0, 1.0) * 255.0).round(); match format { - ChannelFormat::Rgb8 | ChannelFormat::L8 => unit(steps(value)), - ChannelFormat::Srgb8 => unit(srgb_to_linear(steps(linear_to_srgb(value.clamp(0.0, 1.0))))), + ChannelFormat::Rgb8 | ChannelFormat::L8 => unit(step(value) / 255.0), + ChannelFormat::Srgb8 => unit(srgb8_linear().get(step(linear_to_srgb(value.clamp(0.0, 1.0))) as usize).copied().unwrap_or(0.0)), ChannelFormat::L16 | ChannelFormat::Rgb16 | ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F => component, } } +/// The linear value of each 8-bit sRGB step, so storing a colour decodes no sRGB per texel +fn srgb8_linear() -> &'static [f32; 256] { + static LINEAR: OnceLock<[f32; 256]> = OnceLock::new(); + LINEAR.get_or_init(|| std::array::from_fn(|step| srgb_to_linear(step as f32 / 255.0))) +} + #[cfg(test)] mod tests { use super::*; From a89626c69714a5bcfc872d8f26fe00345ba7546a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:45:25 +0000 Subject: [PATCH 126/190] Paint the brush preview with the current brush's own stamps The stroke at the top of the paint tool's properties was a flat line that only followed size, flow and opacity. It now lays down the brush's stamps (alpha, hardness, spacing, flow, angle, follow path and the jitters) in the colour the tool paints, or the mask's gray, and the sphere takes the tool's metallic and roughness. The picture is rendered again only when the brush, its colours or the panel size change. --- crates/ui-egui/src/brush_stroke_preview.rs | 160 +++++++++++++++++++++ crates/ui-egui/src/dock.rs | 73 ++++------ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/preview_image.rs | 94 ++++++++---- crates/ui-egui/src/thumbs.rs | 75 ++++++---- crates/ui-egui/tests/ui_snapshots.rs | 37 +++++ 6 files changed, 334 insertions(+), 106 deletions(-) create mode 100644 crates/ui-egui/src/brush_stroke_preview.rs diff --git a/crates/ui-egui/src/brush_stroke_preview.rs b/crates/ui-egui/src/brush_stroke_preview.rs new file mode 100644 index 00000000..4aafb9dd --- /dev/null +++ b/crates/ui-egui/src/brush_stroke_preview.rs @@ -0,0 +1,160 @@ +//! The live stroke at the top of the paint tool's properties: the current brush's own stamps along a hand-drawn gesture + +use std::sync::Arc; + +use egui::{Color32, ColorImage, Context, Id, Painter, Rect, TextureHandle, TextureOptions, pos2, vec2}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::BrushSettings; + +use crate::preview_image::stroke_strip; + +/// The stroke's margin from the edges of its half of the preview, in points +const STROKE_MARGIN: f32 = 6.0; + +/// The gesture the stroke follows, as fractions of its box: a small hook, a dip, a tall arch and a long tail down +const STROKE_PATH: [[f32; 2]; 5] = [[0.0, 0.6], [0.18, 0.3], [0.4, 0.8], [0.65, 0.0], [1.0, 1.0]]; + +/// The gesture's widest width for its height, so a wide preview centres it instead of flattening its arch +const STROKE_ASPECT: f32 = 1.4; + +/// The pen pressure the stroke is drawn with, from its start to its end: it presses harder as it goes, as a hand does +const STROKE_PRESSURE: std::ops::RangeInclusive = 0.35..=1.0; + +/// The stroke's width: [`STROKE_WIDTH_PER_ROOT_SIZE`] points times the root of the brush size, kept inside [`STROKE_WIDTH`]; the root lets small brushes read and big ones still grow +const STROKE_WIDTH_PER_ROOT_SIZE: f32 = 70.0; +const STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=32.0; + +/// The rendered stroke and what it was rendered from, kept in egui's memory so a frame with the same brush reuses it +#[derive(Clone)] +pub(crate) struct BrushStrokePreview { + brush: BrushSettings, + image: Option>, + tints: Vec<[u8; 3]>, + size: [usize; 2], + texture: TextureHandle, +} + +impl BrushStrokePreview { + /// Paint the brush's stroke across `rect`, each pixel column coloured by `tint` of its position 0..1; it renders again only on a new brush, alpha image, colour or size + pub(crate) fn paint(ctx: &Context, painter: &Painter, rect: Rect, brush: &BrushSettings, image: Option<&Arc>, tint: impl Fn(f32) -> [u8; 3]) { + let pixels_per_point = ctx.pixels_per_point(); + let size = [(rect.width() * pixels_per_point).round().max(1.0) as usize, (rect.height() * pixels_per_point).round().max(1.0) as usize]; + let tints: Vec<[u8; 3]> = (0..size[0]).map(|x| tint((x as f32 + 0.5) / size[0] as f32)).collect(); + let id = Id::unique("brush_stroke_preview"); + let cached = ctx.data(|data| data.get_temp::(id)).filter(|preview| { + preview.brush == *brush && preview.size == size && preview.tints == tints && preview.image.as_ref().map(Arc::as_ptr) == image.map(Arc::as_ptr) + }); + let preview = match cached { + Some(preview) => preview, + None => { + let picture = stroke_image(brush, image.map(|image| &**image), size, pixels_per_point, &tints); + let texture = ctx.load_texture("brush-stroke-preview", picture, TextureOptions::LINEAR); + let preview = BrushStrokePreview { brush: brush.clone(), image: image.cloned(), tints, size, texture }; + ctx.data_mut(|data| data.insert_temp(id, preview.clone())); + preview + } + }; + painter.image(preview.texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } +} + +/// The brush's stroke as a `size` image at `pixels_per_point`: a hand-drawn gesture as wide as the brush size, narrowed towards Minimum Size at its light start; column `x` in `tints[x]` +pub(crate) fn stroke_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let (width, height) = (size[0] as f32 / pixels_per_point, size[1] as f32 / pixels_per_point); + let stroke_width = (brush.size.max(0.0).sqrt() * STROKE_WIDTH_PER_ROOT_SIZE).clamp(*STROKE_WIDTH.start(), *STROKE_WIDTH.end()); + let inset = STROKE_MARGIN + stroke_width * 0.5; + let span_y = (height - 2.0 * inset).max(0.0); + let span = vec2((width - 2.0 * inset).clamp(0.0, span_y * STROKE_ASPECT), span_y); + let left = (width - span.x) * 0.5; + let curve = |t: f32| { + let [x, y] = path_point(t); + ((left + x * span.x) * pixels_per_point, (inset + y * span.y) * pixels_per_point) + }; + let radius = |t: f32| { + let pressure = STROKE_PRESSURE.start() + (STROKE_PRESSURE.end() - STROKE_PRESSURE.start()) * t * (2.0 - t); + stroke_width * 0.5 * pixels_per_point * brush.uv_stamp_radius(pressure) / brush.uv_stamp_radius(1.0).max(f32::MIN_POSITIVE) + }; + let tint = |x: usize| tints.get(x).copied().unwrap_or([u8::MAX; 3]); + stroke_strip(brush, image, size, radius, curve, tint) +} + +/// The point at `t` (0..1) along [`STROKE_PATH`], a Catmull-Rom spline through its points +fn path_point(t: f32) -> [f32; 2] { + let last = STROKE_PATH.len() - 1; + let at = t.clamp(0.0, 1.0) * last as f32; + let segment = (at as usize).min(last - 1); + let u = at - segment as f32; + let point = |index: isize| STROKE_PATH[index.clamp(0, last as isize) as usize]; + let [p0, p1, p2, p3] = [-1, 0, 1, 2].map(|offset| point(segment as isize + offset)); + let blend = |axis: usize| { + let (a, b, c, d) = (p0[axis], p1[axis], p2[axis], p3[axis]); + 0.5 * (2.0 * b + (c - a) * u + (2.0 * a - 5.0 * b + 4.0 * c - d) * u * u + (3.0 * b - a - 3.0 * c + d) * u * u * u) + }; + [blend(0), blend(1)] +} + +#[cfg(test)] +mod tests { + use super::*; + + const SIZE: [usize; 2] = [160, 88]; + + fn paint(brush: &BrushSettings) -> ColorImage { + stroke_image(brush, None, SIZE, 1.0, &[[u8::MAX; 3]; SIZE[0]]) + } + + fn painted_pixels(picture: &ColorImage) -> usize { + picture.pixels.iter().filter(|pixel| pixel.a() > 0).count() + } + + fn total_paint(picture: &ColorImage) -> u64 { + picture.pixels.iter().map(|pixel| u64::from(pixel.a())).sum() + } + + #[test] + fn wider_spacing_leaves_gaps_between_dabs() { + let dense = BrushSettings { hardness: 1.0, spacing: 0.1, ..BrushSettings::default() }; + let sparse = BrushSettings { spacing: 3.0, ..dense.clone() }; + + assert!(painted_pixels(&paint(&sparse)) < painted_pixels(&paint(&dense))); + } + + #[test] + fn a_softer_brush_lays_down_less_paint() { + let hard = BrushSettings { hardness: 1.0, ..BrushSettings::default() }; + let soft = BrushSettings { hardness: 0.0, ..hard.clone() }; + + assert!(total_paint(&paint(&soft)) < total_paint(&paint(&hard))); + } + + #[test] + fn a_bigger_brush_paints_a_wider_stroke() { + let small = BrushSettings { size: 0.02, ..BrushSettings::default() }; + let big = BrushSettings { size: 0.1, ..small.clone() }; + + assert!(painted_pixels(&paint(&small)) < painted_pixels(&paint(&big))); + } + + /// Paint in the first and last quarter of the columns the stroke covers + fn paint_at_ends(picture: &ColorImage) -> (u64, u64) { + let [width, _] = picture.size; + let painted = |index: &usize| picture.pixels.iter().skip(*index).step_by(width).any(|pixel| pixel.a() > 0); + let (first, last) = ((0..width).find(painted).unwrap_or(0), (0..width).rfind(painted).unwrap_or(width)); + let quarter = (last - first) / 4; + let paint_in = |columns: std::ops::Range| { + picture.pixels.iter().enumerate().filter(|(index, _)| columns.contains(&(index % width))).map(|(_, pixel)| u64::from(pixel.a())).sum() + }; + (paint_in(first..first + quarter), paint_in(last - quarter..last + 1)) + } + + #[test] + fn the_stroke_starts_light_and_a_lower_minimum_size_thins_its_start() { + let brush = BrushSettings { hardness: 1.0, min_size: 0.05, ..BrushSettings::default() }; + let full = BrushSettings { min_size: 1.0, ..brush.clone() }; + let (start, end) = paint_at_ends(&paint(&brush)); + let (full_start, _) = paint_at_ends(&paint(&full)); + + assert!(start < end, "the stroke widens as the pen presses harder"); + assert!(start < full_start, "Minimum Size bounds how thin the light start gets"); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 4226e057..cf53c9d0 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -10,9 +10,11 @@ use texturecraft_engine::core::{ }; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; +use texturecraft_engine::texel::linear_to_srgb; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; +use crate::brush_stroke_preview::BrushStrokePreview; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; use crate::past_end::PastEnd; @@ -2053,24 +2055,13 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId) { const BRUSH_PREVIEW_HEIGHT: f32 = 88.0; const BRUSH_PREVIEW_CORNER_RADIUS: f32 = 2.0; -/// The preview stroke: its segments, its margin from the preview's left (each side of its half), its wave's phase span in radians and its swing -const PREVIEW_STROKE_STEPS: usize = 40; -const PREVIEW_STROKE_MARGIN: f32 = 14.0; -const PREVIEW_STROKE_WAVE: f32 = 9.0; -const PREVIEW_STROKE_SWING: f32 = 18.0; - -/// The preview stroke's width: [`PREVIEW_STROKE_WIDTH_SCALE`] points for each [`PREVIEW_SIZE_UNIT`] of brush size, kept inside [`PREVIEW_STROKE_WIDTH`] -const PREVIEW_SIZE_UNIT: f32 = 0.25; -const PREVIEW_STROKE_WIDTH_SCALE: f32 = 60.0; -const PREVIEW_STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=30.0; - -/// Faintest the preview stroke draws, so a low flow or opacity still shows -const PREVIEW_STROKE_MIN_ALPHA: u8 = 30; - -/// Radius of the preview's material sphere, and the colour it shows when the tool has no base colour +/// Radius of the preview's material sphere, and the material it shows for channels the tool doesn't paint const PREVIEW_SPHERE_RADIUS: f32 = 36.0; const PREVIEW_FALLBACK_BASE_COLOR: [f32; 3] = [0.8; 3]; +/// Samples an image-backed mask's gray is read at across the preview stroke +const STROKE_GRAY_SAMPLES: u32 = 64; + /// Gap between the brush preview and the tab buttons const BRUSH_PREVIEW_GAP: f32 = 4.0; @@ -2078,47 +2069,33 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let content = targets_content(app); - // Brush preview: a stroke and a sphere with the tool's material + // Brush preview: the brush's own stroke in the colour it paints, and a sphere with the tool's material let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); let painter = ui.painter(); painter.rect_filled(rect, BRUSH_PREVIEW_CORNER_RADIUS, tokens.viewport); let half_width = rect.width() * 0.5; + let stroke_rect = Rect::from_min_size(rect.min, vec2(half_width, rect.height())); let brush = &app.session.tool.brush; - let mut points = Vec::new(); - for step in 0..=PREVIEW_STROKE_STEPS { - let fraction = step as f32 / PREVIEW_STROKE_STEPS as f32; - let x = rect.left() + PREVIEW_STROKE_MARGIN + fraction * (half_width - 2.0 * PREVIEW_STROKE_MARGIN); - points.push(pos2(x, rect.center().y + (fraction * PREVIEW_STROKE_WAVE).sin() * PREVIEW_STROKE_SWING)); - } - - let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end()); - let alpha = (brush.flow * brush.opacity * 255.0) as u8; - - let preview_stroke = |gray: f32| { - let gray = (gray.clamp(0.0, 1.0) * 255.0).round() as u8; - Stroke::new(stroke_width, Color32::from_rgba_unmultiplied(gray, gray, gray, alpha.max(PREVIEW_STROKE_MIN_ALPHA))) - }; - - // Sample image-backed masks along the preview stroke - let gray = if content { texturecraft_engine::compose::MaskGray::Value(1.0) } else { app.session.mask_gray() }; - match gray { - texturecraft_engine::compose::MaskGray::Value(value) => { - painter.add(egui::Shape::line(points, preview_stroke(value))); - } - texturecraft_engine::compose::MaskGray::Image { .. } => { - let size = PREVIEW_STROKE_STEPS as u32; - for (index, segment) in points.windows(2).enumerate() { - let value = gray.at(index as u32, size / 2, (size, size)); - painter.line_segment([segment[0], segment[1]], preview_stroke(value)); - } - } - } - + let image = brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)); + let value = |channel: Channel| app.session.tool.values.get(&channel).copied(); if content { - let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); + let srgb = value(Channel::BaseColor).unwrap_or(PREVIEW_FALLBACK_BASE_COLOR).map(|linear| (linear_to_srgb(linear) * 255.0 + 0.5) as u8); + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, |_| srgb); // The sphere sits in the middle of the preview's right half - crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); + let metallic = value(Channel::Metallic).map_or(crate::thumbs::SPHERE_DEFAULT_METALLIC, |metallic| metallic[0]); + let roughness = value(Channel::Roughness).map_or(crate::thumbs::SPHERE_DEFAULT_ROUGHNESS, |roughness| roughness[0]); + let base_color = value(Channel::BaseColor).unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); + let center = pos2(rect.left() + half_width * 1.5, rect.center().y); + crate::thumbs::paint_material_sphere(painter, center, PREVIEW_SPHERE_RADIUS, base_color, metallic, roughness); + } else { + // A mask paints gray: an image-backed one is read across the stroke + let gray = app.session.mask_gray(); + let mask_tint = |across: f32| { + let gray = (gray.at((across * STROKE_GRAY_SAMPLES as f32) as u32, 0, (STROKE_GRAY_SAMPLES, 1)) * 255.0).round() as u8; + [gray; 3] + }; + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, mask_tint); } ui.add_space(BRUSH_PREVIEW_GAP); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 401581e8..c54e5019 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ mod bake_preset; pub mod bake_presets; mod bake_report; mod bake_scene; +mod brush_stroke_preview; mod color_management; mod color_picker; mod color_selection_editor; diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index b078e520..568e160c 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -158,19 +158,12 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { /// Preview the brush along an S curve in a `size_px` square pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&ImageRes>) -> ColorImage { - // Leave room around the S curve and cap work for a single preview + // Leave room around the S curve const STROKE_RADIUS_FRACTION: f32 = 0.11; - const CURVE_SAMPLE_STEP: f32 = 0.002; - const MIN_STAMP_SPACING_PX: f32 = 0.5; - const MAX_STAMPS: u32 = 2000; const CURVE_HORIZONTAL_INSET: f32 = 0.15; const CURVE_HORIZONTAL_SPAN: f32 = 0.7; const CURVE_WAVE_AMPLITUDE: f32 = 0.22; - let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = size_px as f32 * STROKE_RADIUS_FRACTION; - let shape = Shape { alpha: brush.alpha, image, library, params: brush.alpha_params, level: 0 }.at_radius(radius); - // The horizontal inset and vertical wave keep the S curve inside the swatch let curve = |t: f32| { ( @@ -178,48 +171,89 @@ pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&Imag size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()), ) }; - let mut cover = vec![0f32; size_px * size_px]; + let cover = stamp_coverage(brush, image, [size_px, size_px], |_| size_px as f32 * STROKE_RADIUS_FRACTION, curve); + ColorImage::new([size_px, size_px], cover.into_iter().map(|coverage| Color32::from_gray((coverage * brush.opacity * 255.0 + 0.5) as u8)).collect()) +} + +/// The brush's stroke along `curve` (0..1 to pixels) in a `size` strip, stamps `radius` (0..1 to pixels) wide, columns in `tint`'s colour; missed pixels stay transparent +pub fn stroke_strip( + brush: &BrushSettings, + image: Option<&ImageRes>, + size: [usize; 2], + radius: impl Fn(f32) -> f32, + curve: impl Fn(f32) -> (f32, f32), + tint: impl Fn(usize) -> [u8; 3], +) -> ColorImage { + let cover = stamp_coverage(brush, image, size, radius, curve); + let pixels = cover + .into_iter() + .enumerate() + .map(|(index, coverage)| { + let [r, g, b] = tint(index % size[0]); + Color32::from_rgba_unmultiplied(r, g, b, (coverage * brush.opacity * 255.0 + 0.5) as u8) + }) + .collect(); + ColorImage::new(size, pixels) +} + +/// Paint coverage 0..1 of the brush's stamps (`radius` 0..1 to pixels, its alpha, hardness, spacing, flow, angle and jitters) along `curve` in a `width` × `height` image +fn stamp_coverage( + brush: &BrushSettings, + image: Option<&ImageRes>, + [width, height]: [usize; 2], + radius: impl Fn(f32) -> f32, + curve: impl Fn(f32) -> (f32, f32), +) -> Vec { + // Cap work for a single preview + const CURVE_SAMPLE_STEP: f32 = 0.002; + const MIN_STAMP_SPACING_PX: f32 = 0.5; + const MAX_STAMPS: u32 = 2000; + + let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let shape = Shape { alpha: brush.alpha, image, library, params: brush.alpha_params, level: 0 }.at_radius(radius(1.0)); + let mut cover = vec![0f32; width * height]; // Odd multipliers decorrelate reproducible jitter across stamps and channels let jitter_sample = |stamp_index: u32, channel: u32| { (stamp_index.wrapping_mul(0x9E37_79B9) ^ channel.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32 }; - let step = (brush.spacing * 2.0 * radius).max(MIN_STAMP_SPACING_PX); - let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); + // Spacing follows the stamp's own radius, as on the model + let step = |t: f32| (brush.spacing * 2.0 * radius(t)).max(MIN_STAMP_SPACING_PX); + let (mut t, mut travelled, mut stamp_index) = (0.0f32, step(0.0), 0u32); let mut last = curve(0.0); - while t <= 1.0 && i < MAX_STAMPS { - let p = curve(t); - travelled += (p.0 - last.0).hypot(p.1 - last.1); - last = p; + while t <= 1.0 && stamp_index < MAX_STAMPS { + let point = curve(t); + travelled += (point.0 - last.0).hypot(point.1 - last.1); + last = point; t += CURVE_SAMPLE_STEP; - if travelled < step { + if travelled < step(t) { continue; } travelled = 0.0; - i += 1; - let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1)); - let tangent = if brush.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(i, 2); - let (cx, cy) = ( - p.0 + brush.jitter_position * radius * (jitter_sample(i, 3) * 2.0 - 1.0), - p.1 + brush.jitter_position * radius * (jitter_sample(i, 4) * 2.0 - 1.0), + stamp_index += 1; + let stamp_radius = radius(t) * (1.0 - brush.jitter_size * jitter_sample(stamp_index, 1)); + let tangent = if brush.follow_path { (curve(t).1 - point.1).atan2(curve(t).0 - point.0) } else { 0.0 }; + let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(stamp_index, 2); + let (center_x, center_y) = ( + point.0 + brush.jitter_position * radius(t) * (jitter_sample(stamp_index, 3) * 2.0 - 1.0), + point.1 + brush.jitter_position * radius(t) * (jitter_sample(stamp_index, 4) * 2.0 - 1.0), ); - let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5)); + let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(stamp_index, 5)); let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - stamp_radius).floor().max(0.0) as usize, ((cx + stamp_radius).ceil() as usize).min(size_px)); - let (y0, y1) = ((cy - stamp_radius).floor().max(0.0) as usize, ((cy + stamp_radius).ceil() as usize).min(size_px)); + let (x0, x1) = ((center_x - stamp_radius).floor().max(0.0) as usize, ((center_x + stamp_radius).ceil() as usize).min(width)); + let (y0, y1) = ((center_y - stamp_radius).floor().max(0.0) as usize, ((center_y + stamp_radius).ceil() as usize).min(height)); for y in y0..y1 { for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / stamp_radius, (cy - y as f32 - 0.5) / stamp_radius); - let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, i) * flow; - let coverage = &mut cover[y * size_px + x]; + let (dx, dy) = ((x as f32 + 0.5 - center_x) / stamp_radius, (center_y - y as f32 - 0.5) / stamp_radius); + let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, stamp_index) * flow; + let coverage = &mut cover[y * width + x]; *coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0)); } } } - ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect()) + cover } /// Environment `name`'s panorama across a `size²` swatch, transparent above and below diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 41c20d1f..75777c3c 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -479,41 +479,60 @@ impl Thumbs { } } -/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). -pub fn paint_sphere(p: &Painter, c: Pos2, r: f32, base: [f32; 3]) { - let mut mesh = egui::Mesh::default(); - let rings = 10; - let segs = 28; +/// Metallic and roughness of a sphere drawn without a material's own values +pub(crate) const SPHERE_DEFAULT_METALLIC: f32 = 0.0; +pub(crate) const SPHERE_DEFAULT_ROUGHNESS: f32 = 0.5; + +/// Rings and segments per ring of a drawn sphere's mesh +const SPHERE_RINGS: usize = 10; +const SPHERE_SEGMENTS: usize = 28; + +/// Exposure applied to a drawn sphere's shading before tone mapping +const SPHERE_EXPOSURE: f32 = 1.4; + +/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews) +pub fn paint_sphere(painter: &Painter, center: Pos2, radius: f32, base: [f32; 3]) { + paint_material_sphere(painter, center, radius, base, SPHERE_DEFAULT_METALLIC, SPHERE_DEFAULT_ROUGHNESS); +} + +/// [`paint_sphere`] with the material's `metallic` and `roughness` (0..1) +pub fn paint_material_sphere(painter: &Painter, center: Pos2, radius: f32, base: [f32; 3], metallic: f32, roughness: f32) { let color = |dx: f32, dy: f32| { - let d2 = (dx * dx + dy * dy).min(1.0); - let n = [dx, dy, (1.0 - d2).sqrt()]; - let s = shade(n, base, 0.0, 0.5).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0) as u8); - Color32::from_rgb(s[0], s[1], s[2]) + let distance_squared = (dx * dx + dy * dy).min(1.0); + let normal = [dx, dy, (1.0 - distance_squared).sqrt()]; + let srgb = shade(normal, base, metallic, roughness).map(|linear| (linear_to_srgb(aces(linear * SPHERE_EXPOSURE)) * 255.0) as u8); + Color32::from_rgb(srgb[0], srgb[1], srgb[2]) }; - mesh.colored_vertex(c, color(0.0, 0.0)); - for i in 1..=rings { - let rr = i as f32 / rings as f32; - for j in 0..segs { - let a = j as f32 / segs as f32 * std::f32::consts::TAU; - let (dx, dy) = (a.cos() * rr, a.sin() * rr); - mesh.colored_vertex(Pos2::new(c.x + dx * r, c.y - dy * r), color(dx, dy)); + + // A center vertex, then each ring's vertices outwards + let mut mesh = egui::Mesh::default(); + mesh.colored_vertex(center, color(0.0, 0.0)); + for ring in 1..=SPHERE_RINGS { + let ring_radius = ring as f32 / SPHERE_RINGS as f32; + for segment in 0..SPHERE_SEGMENTS { + let angle = segment as f32 / SPHERE_SEGMENTS as f32 * std::f32::consts::TAU; + let (dx, dy) = (angle.cos() * ring_radius, angle.sin() * ring_radius); + mesh.colored_vertex(Pos2::new(center.x + dx * radius, center.y - dy * radius), color(dx, dy)); } } - for j in 0..segs { - let (a, b) = (1 + j, 1 + (j + 1) % segs); - mesh.add_triangle(0, a as u32, b as u32); + + // A fan from the center to the first ring, then quads between neighbouring rings + for segment in 0..SPHERE_SEGMENTS { + let (first, next) = (1 + segment, 1 + (segment + 1) % SPHERE_SEGMENTS); + mesh.add_triangle(0, first as u32, next as u32); } - for i in 1..rings { - let r0 = 1 + (i - 1) * segs; - let r1 = 1 + i * segs; - for j in 0..segs { - let (a, b) = (r0 + j, r0 + (j + 1) % segs); - let (c2, d) = (r1 + j, r1 + (j + 1) % segs); - mesh.add_triangle(a as u32, c2 as u32, d as u32); - mesh.add_triangle(a as u32, d as u32, b as u32); + for ring in 1..SPHERE_RINGS { + let inner_start = 1 + (ring - 1) * SPHERE_SEGMENTS; + let outer_start = 1 + ring * SPHERE_SEGMENTS; + for segment in 0..SPHERE_SEGMENTS { + let next_segment = (segment + 1) % SPHERE_SEGMENTS; + let (inner, inner_next) = (inner_start + segment, inner_start + next_segment); + let (outer, outer_next) = (outer_start + segment, outer_start + next_segment); + mesh.add_triangle(inner as u32, outer as u32, outer_next as u32); + mesh.add_triangle(inner as u32, outer_next as u32, inner_next as u32); } } - p.add(egui::Shape::mesh(mesh)); + painter.add(egui::Shape::mesh(mesh)); } /// Brush alpha preview drawn as small cells (cheap, no texture). diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 9d7c7a32..542a045e 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3211,7 +3211,9 @@ fn sheet_scroll_end_snapshots() { fn paint_tool_properties_snapshots() { use egui::{Event, Modifiers, PointerButton}; use serde_json::json; + use texturecraft_engine::core::Channel; use texturecraft_engine::execute; + use texturecraft_engine::paint::{BrushAlpha, BrushSettings}; use texturecraft_ui_egui::state::PropsTab; let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; @@ -3236,6 +3238,41 @@ fn paint_tool_properties_snapshots() { harness.run_steps(6); save(&mut harness, &output_dir, "paint-brush"); + // The top preview follows the brush and the paint: one picture per brush + let default_brush = harness.state().session.tool.brush.clone(); + let default_values = harness.state().session.tool.values.clone(); + let brushes = [ + ("dotted-red", BrushSettings { size: 0.06, hardness: 1.0, spacing: 1.6, ..default_brush.clone() }, [0.8, 0.05, 0.04], 0.0, 0.5), + ("soft-blue-metal", BrushSettings { size: 0.12, hardness: 0.0, flow: 0.35, ..default_brush.clone() }, [0.1, 0.3, 0.9], 1.0, 0.2), + ( + "star-jitter-green", + BrushSettings { + size: 0.08, + alpha: BrushAlpha::Star, + spacing: 0.9, + follow_path: true, + jitter_size: 0.5, + jitter_angle: 0.3, + jitter_position: 0.6, + ..default_brush.clone() + }, + [0.1, 0.6, 0.15], + 0.0, + 0.8, + ), + ]; + for (name, brush, base_color, metallic, roughness) in brushes { + let tool = &mut harness.state_mut().session.tool; + tool.brush = brush; + tool.values.insert(Channel::BaseColor, base_color); + tool.values.insert(Channel::Metallic, [metallic; 3]); + tool.values.insert(Channel::Roughness, [roughness; 3]); + save(&mut harness, &output_dir, &format!("paint-preview-{name}")); + } + let tool = &mut harness.state_mut().session.tool; + tool.brush = default_brush; + tool.values = default_values; + // The top bar has a Lazy mouse button too: Properties is the rightmost let in_properties = |harness: &Harness<'_, TextureCraftApp>, label: &str| { harness.get_all_by_label(label).map(|node| node.rect().center()).max_by(|a, b| a.x.total_cmp(&b.x)).unwrap() From 18c7b690ca2f2164de3549cc23feec10dcace72c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:03:03 +0000 Subject: [PATCH 127/190] Lay out the paint tool's Properties as one page under jump tabs The tool's Brush, Alpha and Material (Grayscale on a mask) were three pages behind icon buttons, one shown at a time. They are now sections of one scrolling page, with the same jump tabs on the panel's top strip as a fill's Properties: a tab scrolls to its section, and the section in view lights its tab, in the docked panel and the right-click popup. The Projection tool's stencil moves from above the tabs into its own Stencil section. The rows inside the sections are unchanged for now. --- crates/ui-egui/src/dock.rs | 195 +++++++++--------- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/mask_paint_panel.rs | 96 +++++---- crates/ui-egui/src/paint_section.rs | 50 +++++ crates/ui-egui/src/properties_popup.rs | 2 +- crates/ui-egui/src/state.rs | 10 - crates/ui-egui/tests/it/alpha_parameters.rs | 15 +- crates/ui-egui/tests/it/main.rs | 1 + .../ui-egui/tests/it/mask_paint_grayscale.rs | 4 +- crates/ui-egui/tests/it/paint_tool_tabs.rs | 59 ++++++ crates/ui-egui/tests/it/popup_press_close.rs | 8 +- crates/ui-egui/tests/it/smudge_channels.rs | 22 +- crates/ui-egui/tests/it/stencil.rs | 2 + crates/ui-egui/tests/it/view_mode_picker.rs | 26 ++- crates/ui-egui/tests/ui_snapshots.rs | 25 +-- 15 files changed, 312 insertions(+), 204 deletions(-) create mode 100644 crates/ui-egui/src/paint_section.rs create mode 100644 crates/ui-egui/tests/it/paint_tool_tabs.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index cf53c9d0..7e556fdf 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -17,11 +17,11 @@ use crate::TextureCraftApp; use crate::brush_stroke_preview::BrushStrokePreview; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; +use crate::paint_section::PaintSection; use crate::past_end::PastEnd; use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; use crate::source_choice::SourceChoice; -use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; @@ -1884,7 +1884,7 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); let scope = SectionScope::Docked; - if let Some(tabs) = properties_fill_tabs(app) { + if let Some(tabs) = properties_tabs(app) { crate::property_sheet::section_tabs(ui, scope, 0, &tabs); } @@ -1925,21 +1925,29 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: output.state.clamped_offset().y } -/// The tabs over the panel when it shows a fill layer's or a mask fill effect's sections, which they jump between -pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 3]> { - if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { +/// The tabs over the panel when it shows a fill layer's, a mask fill effect's or a paint tool's sections, which they jump between +pub(crate) fn properties_tabs(app: &TextureCraftApp) -> Option> { + if !app.session.project_open || app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } let project = &app.session.doc.project; - match app.session.target { - StackTarget::Content => { - let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; - matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false)) + let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id)); + let tool_shown = match (layer, app.session.target) { + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => { + return matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false).to_vec()); } - StackTarget::Effect(effect) => mask_fill_of(project, effect).map(|_| crate::fill_panel::fill_tabs(true)), - _ => None, - } + (Some(_), StackTarget::Effect(effect)) => match project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Paint | EffectKind::Path(_)) => true, + _ => return mask_fill_of(project, effect).map(|_| crate::fill_panel::fill_tabs(true).to_vec()), + }, + (Some(layer), StackTarget::Content) => !layer.is_group() && layer.instance_source().is_none(), + _ => true, + }; + + // Everything else shows the tool's sections where the tool can paint + let tool_shown = tool_shown && app.session.tool_usable(app.session.tool.tool); + tool_shown.then(|| tool_sections(app).into_iter().map(|section| (section.icon(), section.title())).collect()) } /// Effect `effect`'s source, projection and sampling when it is a mask fill the Properties panel lays out like a fill (a decal's placed fill keeps its own rows) @@ -1980,10 +1988,6 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { (Some(layer), StackTarget::Effect(effect)) => { let snapshot = layer.clone(); effect_properties(app, ui, &snapshot, effect); - let painted = app.session.doc.project.effect(effect).is_some_and(|(_, effect)| matches!(effect.kind, EffectKind::Paint | EffectKind::Path(_))); - if painted && grayscale_tab_open(app) { - crate::mask_paint_panel::grayscale_sheet(app, ui); - } } (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => { let snapshot = layer.clone(); @@ -1996,35 +2000,26 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { } (Some(layer), StackTarget::Mask) => { let layer_id = layer.id; - legacy_body(ui, |ui| { - // Saved height masks can still be turned off here - let height_shown = app.session.doc.project.content_layer(layer_id).is_some_and(|content| content.height_mask.enabled); - if height_shown { + // Saved height masks can still be turned off here + if app.session.doc.project.content_layer(layer_id).is_some_and(|content| content.height_mask.enabled) { + legacy_body(ui, |ui| { height_mask_section(app, ui, layer_id); - } - if tool_usable { - if height_shown { + if tool_usable { ui.separator(); } - tool_properties(app, ui); - } - }); - if tool_usable && grayscale_tab_open(app) { - crate::mask_paint_panel::grayscale_sheet(app, ui); + }); + } + if tool_usable { + tool_properties(app, ui); } } (None, _) if !tool_usable => legacy_body(ui, |ui| { ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); }), - _ => legacy_body(ui, |ui| tool_properties(app, ui)), + _ => tool_properties(app, ui), } } -/// Whether the tool panel's third tab is open while a mask is painted: its Grayscale tab, drawn under the tool's rows -fn grayscale_tab_open(app: &TextureCraftApp) -> bool { - app.ui.props_tab == PropsTab::Material && !targets_content(app) -} - /// Mask with height: the layer's height shapes its mask transitions. fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId) { let height_mask = app.session.project().content_layer(layer).map(|source| source.height_mask).unwrap_or_default(); @@ -2062,10 +2057,11 @@ const PREVIEW_FALLBACK_BASE_COLOR: [f32; 3] = [0.8; 3]; /// Samples an image-backed mask's gray is read at across the preview stroke const STROKE_GRAY_SAMPLES: u32 = 64; -/// Gap between the brush preview and the tab buttons +/// Gap under the brush preview const BRUSH_PREVIEW_GAP: f32 = 4.0; -fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The brush preview, then what only this tool has +fn tool_header(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let content = targets_content(app); @@ -2099,28 +2095,13 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { } ui.add_space(BRUSH_PREVIEW_GAP); - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - - // Painting a mask, the material tab becomes the Grayscale tab - let material = if content { (ic::SPHERE, tr("Material")) } else { (ic::SQUARE_HALF, tr("Grayscale")) }; - for (tab, icon, tip) in - [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, material.0, material.1)] - { - if icon_button(ui, icon, tip, app.ui.props_tab == tab, button_size).clicked() { - app.ui.props_tab = tab; - } - } - }); - ui.separator(); - if app.session.quick_mask.editing { ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tokens.text_dim)); ui.separator(); } + // The Projection tool's stencil has its own section let tool_section: Option = match app.session.tool.tool { - Tool::Projection => Some(stencil_section), Tool::Clone => Some(clone_section), Tool::Smudge => Some(smudge_section), Tool::Path => Some(path_section), @@ -2131,14 +2112,37 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { section(app, ui); ui.separator(); } +} - match app.ui.props_tab { - PropsTab::Brush => brush_section(app, ui), - PropsTab::Alpha => alpha_section(app, ui), - PropsTab::Material if content => material_section(app, ui), - // A mask's Grayscale tab is a property sheet, drawn by the caller past this panel's margins - PropsTab::Material => {} - } +/// The tool's sections, one page under the panel's jump tabs +fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { + legacy_body(ui, |ui| tool_header(app, ui)); + + // Rows not yet laid out by the sheet keep the spacing they were made with + let item_spacing = ui.spacing().item_spacing; + let legacy = |sheet: &mut PropertySheet<'_>, app: &mut TextureCraftApp, body: fn(&mut TextureCraftApp, &mut Ui)| { + sheet.ui.scope(|ui| { + ui.spacing_mut().item_spacing = item_spacing; + legacy_body(ui, |ui| body(app, ui)); + }); + }; + PropertySheet::show(ui, "tool_sheet", |sheet| { + for section in tool_sections(app) { + sheet.section(section.title(), false); + match section { + PaintSection::Brush => legacy(sheet, app, brush_section), + PaintSection::Alpha => legacy(sheet, app, alpha_section), + PaintSection::Stencil => legacy(sheet, app, stencil_section), + PaintSection::Material => legacy(sheet, app, material_controls), + PaintSection::Grayscale => crate::mask_paint_panel::grayscale_section(app, sheet), + } + } + }); +} + +/// The sections of [`tool_properties`]: only the Projection tool uses a stencil +fn tool_sections(app: &TextureCraftApp) -> Vec { + PaintSection::page(app.session.tool.tool == Tool::Projection, targets_content(app)) } /// How far the Position sliders move the stencil's center from the middle of the view (NDC; -1..1 is the view) @@ -2146,7 +2150,6 @@ const STENCIL_POSITION_RANGE: f32 = 2.0; fn stencil_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Stencil"))); let names: Vec = app.session.doc.resources.keys().cloned().collect(); let current = app.session.tool.stencil.as_ref().map(|s| s.image.clone()).unwrap_or_else(|| tr("None").into()); let row = ui.horizontal(|ui| { @@ -2397,10 +2400,7 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { const HINT_TEXT_SIZE: f32 = 10.5; fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - ui.label(caption(tr("Brush"))); - brush_presets_popover(app, ui); - }); + brush_presets_popover(app, ui); let brush = &mut app.session.tool.brush; let defaults = BrushSettings::default(); @@ -2536,10 +2536,7 @@ fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Pain fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(caption(tr("Alpha"))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| import_button(app, ui)); - }); + import_button(app, ui); let brush = &app.session.tool.brush; let (current, image, hardness) = (brush.alpha, brush.alpha_image.clone(), brush.hardness); let library = if image.is_none() { brush.alpha_library.as_deref().and_then(alphas::find) } else { None }; @@ -2671,12 +2668,6 @@ fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { /// Tooltip of the material channel chips. pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; -/// The tool's material under a "Material" heading -fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(caption(tr("Material"))); - material_controls(app, ui); -} - /// Space between the tool's channel chips and the first channel value const CHIPS_GAP: f32 = 4.0; @@ -3193,42 +3184,46 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe }); } EffectKind::Anchor => crate::anchor_properties::anchor_properties(app, ui, effect_id, &effect.name), - EffectKind::Paint => legacy_body(ui, |ui| { - let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { - tr("Paint on the mesh to edit the layer content.") - } else { - tr("Paint on the mesh to edit this mask.") - }; - ui.label(RichText::new(hint).color(tokens.text_dim)); + EffectKind::Paint => { + legacy_body(ui, |ui| { + let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { + tr("Paint on the mesh to edit the layer content.") + } else { + tr("Paint on the mesh to edit this mask.") + }; + ui.label(RichText::new(hint).color(tokens.text_dim)); + }); if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } - }), - EffectKind::Path(paths) => legacy_body(ui, |ui| { - ui.label( + } + EffectKind::Path(paths) => { + legacy_body(ui, |ui| { + ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) .color(tokens.text_dim), ); - let editing = app.session.tool.path.editing; - for index in 0..paths.len() { - ui.horizontal(|ui| { - let selected = editing == Some((effect_id, index)); - if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { - if selected { - app.run("tool.path", json!({"clear": true})); - } else { - app.run("path.edit", json!({"effect": id, "index": index})); + let editing = app.session.tool.path.editing; + for index in 0..paths.len() { + ui.horizontal(|ui| { + let selected = editing == Some((effect_id, index)); + if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { + if selected { + app.run("tool.path", json!({"clear": true})); + } else { + app.run("path.edit", json!({"effect": id, "index": index})); + } } - } - if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { - app.run("path.remove", json!({"effect": id, "index": index})); - } - }); - } + if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { + app.run("path.remove", json!({"effect": id, "index": index})); + } + }); + } + }); if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } - }), + } EffectKind::Filter(filter) => crate::filter_properties::filter_properties(app, ui, effect_id, filter), EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection), EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c54e5019..327ab90b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -104,6 +104,7 @@ pub mod orb_previews; mod orb_shape; /// The channel's OS identity (app id, window and app names) — see its module docs. pub mod os_window; +mod paint_section; mod pane_split; pub mod parity; mod past_end; diff --git a/crates/ui-egui/src/mask_paint_panel.rs b/crates/ui-egui/src/mask_paint_panel.rs index cf12f191..7ecdfba4 100644 --- a/crates/ui-egui/src/mask_paint_panel.rs +++ b/crates/ui-egui/src/mask_paint_panel.rs @@ -1,6 +1,5 @@ -//! The paint tools' Grayscale tab while a mask is painted: the GRAYSCALE section with the slot of the gray a stroke lays down +//! The paint tools' Grayscale section while a mask is painted: the slot of the gray a stroke lays down -use egui::Ui; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::Session; @@ -20,58 +19,55 @@ use crate::theme::Tokens; use crate::tile_picture::TilePicture; /// The GRAYSCALE section: a slot card for one gray (with its ramp and invert) or an image whose gray is painted -pub(crate) fn grayscale_sheet(app: &mut TextureCraftApp, ui: &mut Ui) { - PropertySheet::show(ui, "mask_paint_sheet", |sheet| { - sheet.section(tr("Grayscale"), false); - let gray = app.session.tool.mask_value; - let source = match &app.session.tool.mask_image { - Some(name) => Source::Image { name: name.clone(), normal_format: NormalFormat::default() }, - None => Source::Uniform([gray; 3]), - }; - let tokens = Tokens::get(sheet.ui.ctx()); - let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source); - let line = source_line(app, &source); - let image = app.session.tool.mask_image.is_some(); - let slot = sheet.slot(&|painter, rect| paint_thumbnail(painter, rect, &picture, &tokens), tr("Grayscale"), &line, None, image, false); +pub(crate) fn grayscale_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let gray = app.session.tool.mask_value; + let source = match &app.session.tool.mask_image { + Some(name) => Source::Image { name: name.clone(), normal_format: NormalFormat::default() }, + None => Source::Uniform([gray; 3]), + }; + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source); + let line = source_line(app, &source); + let image = app.session.tool.mask_image.is_some(); + let slot = sheet.slot(&|painter, rect| paint_thumbnail(painter, rect, &picture, &tokens), tr("Grayscale"), &line, None, image, false); - let popup = sheet.ui.make_persistent_id("mask_paint_source"); - if slot.pick.clicked() { - resource_picker::toggle(sheet.ui.ctx(), popup); - } - let current = match &app.session.tool.mask_image { - Some(name) => MaskSourceChoice::Image(name.clone()), - None => MaskSourceChoice::Uniform, - }; - let ctx = sheet.ui.ctx().clone(); - let tabs = || source_tabs(&app.session, shown_color([gray; 3])); - match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), image, tabs) { - Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), - Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => { - app.run("tool.material", json!({"maskImage": name})); - } - Some(MaskSourceChoice::Uniform) if image => { - app.run("tool.material", json!({"maskImage": null})); - } - _ => {} - } - if slot.clear { - app.run("tool.material", json!({"maskImage": null})); - } - if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + let popup = sheet.ui.make_persistent_id("mask_paint_source"); + if slot.pick.clicked() { + resource_picker::toggle(sheet.ui.ctx(), popup); + } + let current = match &app.session.tool.mask_image { + Some(name) => MaskSourceChoice::Image(name.clone()), + None => MaskSourceChoice::Uniform, + }; + let ctx = sheet.ui.ctx().clone(); + let tabs = || source_tabs(&app.session, shown_color([gray; 3])); + match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), image, tabs) { + Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => { app.run("tool.material", json!({"maskImage": name})); } - - if !image { - let mut value = gray; - let edit = sheet.ramp(tr("Grayscale"), &mut value, 0.0..=1.0); - if edit.invert { - app.run("tool.material", json!({"maskValue": 1.0 - gray})); - } else if edit.changed.is_some() { - app.run("tool.material", json!({"maskValue": value})); - } + Some(MaskSourceChoice::Uniform) if image => { + app.run("tool.material", json!({"maskImage": null})); } - sheet.close_card(); - }); + _ => {} + } + if slot.clear { + app.run("tool.material", json!({"maskImage": null})); + } + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("tool.material", json!({"maskImage": name})); + } + + if !image { + let mut value = gray; + let edit = sheet.ramp(tr("Grayscale"), &mut value, 0.0..=1.0); + if edit.invert { + app.run("tool.material", json!({"maskValue": 1.0 - gray})); + } else if edit.changed.is_some() { + app.run("tool.material", json!({"maskValue": value})); + } + } + sheet.close_card(); } /// The picker's one Resources tab: Textures (Import... first, then the project's images) and Uniform diff --git a/crates/ui-egui/src/paint_section.rs b/crates/ui-egui/src/paint_section.rs new file mode 100644 index 00000000..4648658f --- /dev/null +++ b/crates/ui-egui/src/paint_section.rs @@ -0,0 +1,50 @@ +//! The sections of a paint tool's Properties, each with its jump tab + +use egui_phosphor::regular as ic; + +use crate::i18n::tr; + +/// One section of a paint tool's Properties page +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PaintSection { + Brush, + Alpha, + Stencil, + Material, + /// The Material section's place while a mask is painted + Grayscale, +} + +impl PaintSection { + /// The sections in page order: Stencil only for a tool that `uses_stencil`, Grayscale instead of Material unless `content` is painted + pub(crate) fn page(uses_stencil: bool, content: bool) -> Vec { + let mut sections = vec![PaintSection::Brush, PaintSection::Alpha]; + if uses_stencil { + sections.push(PaintSection::Stencil); + } + sections.push(if content { PaintSection::Material } else { PaintSection::Grayscale }); + sections + } + + /// The section's caption and tab name + pub(crate) fn title(self) -> &'static str { + match self { + PaintSection::Brush => tr("Brush"), + PaintSection::Alpha => tr("Alpha"), + PaintSection::Stencil => tr("Stencil"), + PaintSection::Material => tr("Material"), + PaintSection::Grayscale => tr("Grayscale"), + } + } + + /// The tab's icon + pub(crate) fn icon(self) -> &'static str { + match self { + PaintSection::Brush => ic::PAINT_BRUSH, + PaintSection::Alpha => ic::CIRCLE_HALF, + PaintSection::Stencil => ic::FRAME_CORNERS, + PaintSection::Material => ic::SPHERE, + PaintSection::Grayscale => ic::SQUARE_HALF, + } + } +} diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 291d50d9..742ffc36 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -85,7 +85,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // The docked panel's jump tabs on the top edge stay put while the sections scroll under them let scope = SectionScope::Popup; - if let Some(tabs) = crate::dock::properties_fill_tabs(app) { + if let Some(tabs) = crate::dock::properties_tabs(app) { crate::property_sheet::section_tabs(ui, scope, ui.style().visuals.menu_corner_radius.nw, &tabs); } crate::property_sheet::in_scope(ui, scope, |ui| { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b16d6e66..354b6f14 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -81,14 +81,6 @@ pub enum ViewLayout { Only2D, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum PropsTab { - #[default] - Brush, - Alpha, - Material, -} - #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct Windows { pub export: bool, @@ -595,7 +587,6 @@ pub struct UiState { /// Saved searches' share of the pane column above Filter by path, set by the splitter between them #[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")] pub shelf_panes_split: f32, - pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, /// Layer being renamed and the edit buffer. @@ -787,7 +778,6 @@ impl Default for UiState { shelf_panes: ShelfPanes::default(), shelf_saved_searches: Vec::new(), shelf_panes_split: default_shelf_panes_split(), - props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, new_project: NewProject::default(), diff --git a/crates/ui-egui/tests/it/alpha_parameters.rs b/crates/ui-egui/tests/it/alpha_parameters.rs index acbd588f..cdaa7a53 100644 --- a/crates/ui-egui/tests/it/alpha_parameters.rs +++ b/crates/ui-egui/tests/it/alpha_parameters.rs @@ -4,7 +4,6 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::paint::{AlphaParams, BrushAlpha, BrushSettings}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); const STARTUP_FRAMES: usize = 4; @@ -23,8 +22,9 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.brush = brush; - harness.state_mut().ui.props_tab = PropsTab::Alpha; harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(egui::Role::Tab, "Alpha").click(); + harness.run_steps(SETTLE_FRAMES); harness } @@ -86,10 +86,11 @@ fn the_invert_checkbox_sets_the_brush_parameter() { #[test] fn hardness_left_the_brush_tab_and_its_reset() { - let mut harness = app_with_brush(BrushSettings::default()); - harness.state_mut().ui.props_tab = PropsTab::Brush; - harness.run_steps(SETTLE_FRAMES); + let harness = app_with_brush(BrushSettings::default()); - assert!(harness.query_by_label("Hardness").is_none(), "Hardness is in the Alpha tab now"); - assert!(harness.query_by_label("Flow").is_some()); + // One page: the Brush section comes first, Hardness only in the Alpha section under it + let hardness: Vec<_> = harness.get_all_by_label("Hardness").map(|node| node.rect().top()).collect(); + let flow = harness.get_by_label("Flow").rect().top(); + assert_eq!(hardness.len(), 1, "Hardness is in the Alpha section alone"); + assert!(hardness[0] > flow, "the Alpha section follows the Brush section's Flow"); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0129eb7a..8440b902 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -68,6 +68,7 @@ mod nav_buttons; mod new_project_baked_maps; mod new_project_window; mod output_templates; +mod paint_tool_tabs; mod panel_header; mod path_in_view; mod path_list; diff --git a/crates/ui-egui/tests/it/mask_paint_grayscale.rs b/crates/ui-egui/tests/it/mask_paint_grayscale.rs index 059beb4f..b619ea48 100644 --- a/crates/ui-egui/tests/it/mask_paint_grayscale.rs +++ b/crates/ui-egui/tests/it/mask_paint_grayscale.rs @@ -7,7 +7,6 @@ use serde_json::json; use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; @@ -32,8 +31,9 @@ fn folder_mask_harness() -> (Harness<'static, TextureCraftApp>, String) { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.props_tab = PropsTab::Material; harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(Role::Tab, "Grayscale").click(); + harness.run_steps(SETTLE_FRAMES); (harness, image) } diff --git a/crates/ui-egui/tests/it/paint_tool_tabs.rs b/crates/ui-egui/tests/it/paint_tool_tabs.rs new file mode 100644 index 00000000..b63111cc --- /dev/null +++ b/crates/ui-egui/tests/it/paint_tool_tabs.rs @@ -0,0 +1,59 @@ +//! A paint tool's Properties: one page of sections under jump tabs, Brush · Alpha · (Stencil) · Material + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Short enough that the tool's sections scroll +const WINDOW: egui::Vec2 = egui::vec2(1400.0, 800.0); + +/// A second at 60 frames: a jump scrolls with egui's scroll animation +const SCROLL_FRAMES: usize = 60; + +fn paint_harness(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// egui reports a tab's selection as its toggled state +fn tab_selected(harness: &Harness<'_, TextureCraftApp>, tab: &str) -> bool { + harness.get_by_role_and_label(Role::Tab, tab).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn the_tabs_jump_within_one_page_of_the_tools_sections() { + let mut harness = paint_harness("paint"); + for tab in ["Brush", "Alpha", "Material"] { + assert!(harness.query_by_role_and_label(Role::Tab, tab).is_some(), "the {tab} tab"); + } + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "the Paint tool has no stencil yet"); + assert!(tab_selected(&harness, "Brush"), "the page opens on its first section"); + let flow_before = harness.get_by_label("Flow").rect().top(); + + harness.get_by_role_and_label(Role::Tab, "Material").click(); + harness.run_steps(SCROLL_FRAMES); + + assert!(tab_selected(&harness, "Material"), "the clicked section is the one in view"); + assert!(!tab_selected(&harness, "Brush")); + assert!(harness.get_by_label("Flow").rect().top() < flow_before, "the Brush rows scrolled up out of the way, still on the page"); +} + +#[test] +fn the_projection_tool_has_a_stencil_tab() { + let harness = paint_harness("projection"); + + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_some()); +} diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index 72605f64..aaa8b824 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -91,13 +91,13 @@ fn stroke_on_model(harness: &mut Harness<'_, TextureCraftApp>, modifiers: Modifi drag(harness, view.center(), STROKE, modifiers); } -/// Opens the paint tool's Base color swatch from its Properties' Material tab +/// Opens the paint tool's Base color swatch from its Properties' Material section fn open_tool_color(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(SETTLE_FRAMES); + let header = harness.get_by_role_and_label(egui::Role::Tab, "Properties - Paint").rect(); let in_properties = |rect: egui::Rect| header.x_range().contains(rect.center().x) && rect.top() > header.top(); - let material = harness.get_all_by_label("Material").find(|node| in_properties(node.rect())).unwrap(); - material.click(); - harness.run_steps(SETTLE_FRAMES); let label = harness.get_all_by_value("Base color").find(|node| in_properties(node.rect())).unwrap().rect(); click(harness, label.right_center() + vec2(LABEL_TO_SWATCH, 0.0)); diff --git a/crates/ui-egui/tests/it/smudge_channels.rs b/crates/ui-egui/tests/it/smudge_channels.rs index 024377d6..e7ea6d76 100644 --- a/crates/ui-egui/tests/it/smudge_channels.rs +++ b/crates/ui-egui/tests/it/smudge_channels.rs @@ -8,7 +8,6 @@ use texturecraft_engine::core::Channel; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, Tool, execute}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); @@ -26,11 +25,15 @@ fn run(harness: &mut Harness<'_, TextureCraftApp>, command: &str, params: Value) harness.run_steps(4); } -/// The channel chips drawn in the open Properties panel -fn chip_is_on(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> bool { +/// The Smudge panel's chip for `channel`: the top one, over the Material section's +fn smudge_chip<'a>(harness: &'a Harness<'_, TextureCraftApp>, channel: Channel) -> egui_kittest::Node<'a> { let chips: Vec<_> = harness.get_all_by_role_and_label(Role::Button, channel.short()).collect(); - assert_eq!(chips.len(), 1, "one {} chip is drawn", channel.short()); - chips[0].accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) + assert_eq!(chips.len(), 2, "the Smudge panel and the Material section each draw a {} chip", channel.short()); + chips.into_iter().min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() +} + +fn chip_is_on(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> bool { + smudge_chip(harness, channel).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) } /// Channels whose chip is on, in the order of `Channel::ALL` @@ -67,12 +70,12 @@ fn smudge_panel_shows_the_channels_the_material_has_on() { fn clicking_a_channel_in_the_smudge_panel_turns_it_off_and_on_for_the_material() { let mut harness = harness(); - harness.get_by_role_and_label(Role::Button, Channel::Metallic.short()).click(); + smudge_chip(&harness, Channel::Metallic).click(); harness.run_steps(4); assert!(!harness.state().session.tool.enabled.contains(&Channel::Metallic)); assert!(!chip_is_on(&harness, Channel::Metallic)); - harness.get_by_role_and_label(Role::Button, Channel::Metallic.short()).click(); + smudge_chip(&harness, Channel::Metallic).click(); harness.run_steps(4); assert!(harness.state().session.tool.enabled.contains(&Channel::Metallic)); assert!(chip_is_on(&harness, Channel::Metallic)); @@ -81,10 +84,7 @@ fn clicking_a_channel_in_the_smudge_panel_turns_it_off_and_on_for_the_material() #[test] fn material_tab_and_smudge_panel_stay_in_sync() { let mut harness = harness(); - harness.state_mut().ui.props_tab = PropsTab::Material; - harness.run_steps(4); - - // Both the Smudge panel and the Material tab draw a chip per channel + // Both the Smudge panel and the Material section draw a chip per channel let chips = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).count(); assert_eq!(chips, 2, "Smudge panel and Material tab"); diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index 8ec6b680..f1dec885 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -24,6 +24,8 @@ fn projection_app() -> (Harness<'static, TextureCraftApp>, String) { .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); + harness.get_by_role_and_label(Role::Tab, "Stencil").click(); + harness.run_steps(4); (harness, name) } diff --git a/crates/ui-egui/tests/it/view_mode_picker.rs b/crates/ui-egui/tests/it/view_mode_picker.rs index 56619e08..ff447c16 100644 --- a/crates/ui-egui/tests/it/view_mode_picker.rs +++ b/crates/ui-egui/tests/it/view_mode_picker.rs @@ -22,11 +22,23 @@ fn picker<'a>(h: &'a Harness<'_, TextureCraftApp>, value: &str) -> egui_kittest: h.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(value)).unwrap_or_else(|| panic!("a view picker showing {value}")) } +/// The nodes labelled `label` left of the Properties panel, whose paint tool sections also tile every image as an alpha +fn listed<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> Vec> { + let properties = h.get_by_role_and_label(Role::Tab, "Properties - Paint").rect().left(); + h.get_all_by_label(label).filter(|node| node.rect().center().x < properties).collect() +} + +fn one_listed<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + let mut nodes = listed(h, label); + assert_eq!(nodes.len(), 1, "one {label} listed"); + nodes.remove(0) +} + /// Clicks the entry `label` of the open list (a long list scrolls inside the viewport's height) fn pick(h: &mut Harness<'_, TextureCraftApp>, label: &str) { - h.get_by_label(label).scroll_to_me(); + one_listed(h, label).scroll_to_me(); h.run_steps(12); - h.get_by_label(label).click(); + one_listed(h, label).click(); h.run_steps(3); } @@ -65,7 +77,7 @@ fn other_opens_an_image_picker_and_shows_the_chosen_image() { query_field(&h); h.get_by_label("reset query to default"); - h.get_by_label(&name).click(); + one_listed(&h, &name).click(); h.run_steps(3); assert_eq!(h.state().session.view, ViewMode::Image); @@ -81,19 +93,19 @@ fn the_image_picker_filters_by_name_and_the_reset_button_restores_the_query() { h.run_steps(3); open(&mut h, "Material"); pick(&mut h, "Other..."); - assert!(h.query_by_label(&first).is_some() && h.query_by_label(&second).is_some(), "the default query lists every image"); + assert!(!listed(&h, &first).is_empty() && !listed(&h, &second).is_empty(), "the default query lists every image"); let field = query_field(&h); field.click(); field.type_text(" stone"); h.run_steps(3); - assert!(h.query_by_label(&second).is_none(), "{second} does not match"); - assert!(h.query_by_label(&first).is_some()); + assert!(listed(&h, &second).is_empty(), "{second} does not match"); + assert!(!listed(&h, &first).is_empty()); h.get_by_label("reset query to default").click(); h.run_steps(3); query_field(&h); - assert!(h.query_by_label(&second).is_some(), "the reset lists every image again"); + assert!(!listed(&h, &second).is_empty(), "the reset lists every image again"); } #[test] diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 542a045e..2b737b1a 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -2163,7 +2163,8 @@ fn folder_mask_snapshots() { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.props_tab = texturecraft_ui_egui::state::PropsTab::Material; + harness.run_steps(6); + harness.get_by_role_and_label(egui::Role::Tab, "Grayscale").click(); harness.run_steps(6); save(&mut harness, &output_dir, "foldermask-white"); if std::env::var_os("TC_UI_THEMES").is_some() { @@ -3214,7 +3215,6 @@ fn paint_tool_properties_snapshots() { use texturecraft_engine::core::Channel; use texturecraft_engine::execute; use texturecraft_engine::paint::{BrushAlpha, BrushSettings}; - use texturecraft_ui_egui::state::PropsTab; let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; std::fs::create_dir_all(&output_dir).unwrap(); @@ -3295,8 +3295,9 @@ fn paint_tool_properties_snapshots() { save(&mut harness, &output_dir, "paint-brush-scrolled"); let themes = std::env::var_os("TC_UI_THEMES").is_some(); - let tab = |harness: &mut Harness<'_, TextureCraftApp>, tab: PropsTab, name: &str| { - harness.state_mut().ui.props_tab = tab; + let tab = |harness: &mut Harness<'_, TextureCraftApp>, tab: &str, name: &str| { + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::Tab, tab).click(); harness.run_steps(6); save(harness, &output_dir, name); if themes { @@ -3307,26 +3308,26 @@ fn paint_tool_properties_snapshots() { harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; } }; - tab(&mut harness, PropsTab::Brush, "paint-brush-top"); - tab(&mut harness, PropsTab::Alpha, "paint-alpha"); - tab(&mut harness, PropsTab::Material, "paint-material"); + tab(&mut harness, "Brush", "paint-brush-top"); + tab(&mut harness, "Alpha", "paint-alpha"); + tab(&mut harness, "Material", "paint-material"); execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "eraser"})).unwrap(); - tab(&mut harness, PropsTab::Material, "eraser-material"); + tab(&mut harness, "Material", "eraser-material"); execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "clone"})).unwrap(); - tab(&mut harness, PropsTab::Brush, "clone-brush"); + tab(&mut harness, "Brush", "clone-brush"); execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "projection"})).unwrap(); execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": image})).unwrap(); - tab(&mut harness, PropsTab::Brush, "projection-stencil"); + tab(&mut harness, "Stencil", "projection-stencil"); execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "paint"})).unwrap(); let layer = harness.state().session.selected_layer().map(|id| id.0); execute(&mut harness.state_mut().session, "mask.add.black", &json!({"layer": layer})).unwrap(); execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap(); - tab(&mut harness, PropsTab::Material, "mask-grayscale"); + tab(&mut harness, "Grayscale", "mask-grayscale"); execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": "content"})).unwrap(); - harness.state_mut().ui.props_tab = PropsTab::Brush; + harness.get_by_role_and_label(egui::Role::Tab, "Brush").click(); harness.run_steps(4); let at = harness.state().viewport_rect.center() - egui::vec2(150.0, 250.0); harness.hover_at(at); From 92a9d88d4f9fec81d767ff73b9081e9891287bd5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:09:08 +0000 Subject: [PATCH 128/190] Index the texels past a seam by row, so exports with padding to every texel search one row instead of the whole list --- crates/compose/src/eval.rs | 2 +- crates/compose/src/padding_maps.rs | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 5fa061d7..29b7def6 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -6438,7 +6438,7 @@ soft {soft:?}" out.channels.get_mut(&Channel::Roughness).unwrap().set(10, 10, &[to_u16(0.9)]); let mut covered = vec![false; 64 * 64]; covered[10 * 64 + 10] = true; - let padding = crate::PaddingMaps { flat: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), crossed: Vec::new() }; + let padding = crate::PaddingMaps { flat: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), crossed: Vec::new(), row_starts: Vec::new() }; pad_tiles(&mut out, &padding, &[(0, 0)]); assert!((out.value(Channel::Roughness, 12, 12)[0] - 0.9).abs() < 1e-3); assert!(out.value(Channel::Roughness, 30, 30)[0] < 0.1 || !out.channels[&Channel::Roughness].is_allocated(0, 0)); diff --git a/crates/compose/src/padding_maps.rs b/crates/compose/src/padding_maps.rs index bfb7fe41..eb3edd10 100644 --- a/crates/compose/src/padding_maps.rs +++ b/crates/compose/src/padding_maps.rs @@ -6,13 +6,15 @@ use texturecraft_texel::dilate::DilationMap; use crate::seam_padding::{SEAM_REACH, cross_seams}; -/// A texture set's padding: `flat` for every texel, with the few texels past a seam listed apart in `crossed` +/// A texture set's padding: `flat` for every texel, with the few texels past a seam listed apart in `crossed` by row #[derive(Clone, Debug, PartialEq)] pub struct PaddingMaps { /// Padding from island edges (2D), which tangent-space normals always take: a normal turns with its island, so it can't continue across a seam pub flat: DilationMap, /// Across seams (3D): (texel, source texel) indices of the padding texels that continue from a seam's other side, sorted by texel pub crossed: Vec<(u32, u32)>, + /// Where each row's texels start in `crossed`, one more than the rows (empty without any), so a lookup searches one row + pub(crate) row_starts: Vec, } impl PaddingMaps { @@ -23,7 +25,9 @@ impl PaddingMaps { UvPaddingMode::Space2d => Vec::new(), UvPaddingMode::Space3d => cross_seams(&flat, covered, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams), }; - PaddingMaps { flat, crossed } + let row_starts = + if crossed.is_empty() { Vec::new() } else { (0..=height).map(|y| crossed.partition_point(|(texel, _)| *texel < y * width) as u32).collect() }; + PaddingMaps { flat, crossed, row_starts } } /// Texels across and down @@ -39,13 +43,17 @@ impl PaddingMaps { /// The covered texel padding (x, y), itself when covered; `across_seams` takes the seams' other sides pub fn source(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> { let source = self.flat.source(x, y)?; - if !across_seams || source == (x, y) || self.crossed.is_empty() { + if !across_seams || source == (x, y) { return Some(source); } let (texel, width) = (y * self.flat.width + x, self.flat.width); - match self.crossed.binary_search_by_key(&texel, |(crossed_texel, _)| *crossed_texel) { - Ok(found) => self.crossed.get(found).map(|(_, crossed_source)| (crossed_source % width, crossed_source / width)), + let row = match (self.row_starts.get(y as usize), self.row_starts.get(y as usize + 1)) { + (Some(&start), Some(&end)) => self.crossed.get(start as usize..end as usize).unwrap_or_default(), + _ => &[], + }; + match row.binary_search_by_key(&texel, |(crossed_texel, _)| *crossed_texel) { + Ok(found) => row.get(found).map(|(_, crossed_source)| (crossed_source % width, crossed_source / width)), Err(_) => Some(source), } } From f28be5bd2225dab85dd5ee5585e66a4627a18f7d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:09:08 +0000 Subject: [PATCH 129/190] Test that the 8-bit sRGB table keeps the same steps as decoding each one --- crates/compose/src/channel_store.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/compose/src/channel_store.rs b/crates/compose/src/channel_store.rs index 748c930f..c74282e0 100644 --- a/crates/compose/src/channel_store.rs +++ b/crates/compose/src/channel_store.rs @@ -54,6 +54,15 @@ mod tests { assert!((srgb - dark).abs() < (linear - dark).abs()); } + #[test] + fn srgb8_keeps_the_same_steps_as_decoding_each_one() { + for value in (0..=1000).map(|step| step as f32 / 1000.0) { + let decoded = srgb_to_linear((linear_to_srgb(value) * 255.0).round() / 255.0); + + assert_eq!(stored(ChannelFormat::Srgb8, false, [value; 3], 3)[0], decoded, "at {value}"); + } + } + #[test] fn grey_formats_turn_colours_grey_and_signed_values_keep_their_sign() { let grey = stored(ChannelFormat::L16, false, [1.0, 0.0, 0.0], 3); From 5cfdfcd4adbe735ccb64d5fe31d4c45aa5c9820a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:17:02 +0000 Subject: [PATCH 130/190] Check the viewport padding rebuild on the ball's set that has texels past a seam --- crates/engine/src/set_cmds.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 4d535816..788d140b 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -588,15 +588,16 @@ mod tests { #[test] fn uv_padding_rebuilds_the_viewport_padding_and_undoes() { - let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); - let mode = |s: &Session| crate::inspect::texture_set(s, 0)["uvPadding"].clone(); - let crosses_seams = |s: &Session| !s.caches[0].padding.crossed.is_empty(); + // The ball's second set has texels just past its seams at this size + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 512).unwrap(); + let mode = |s: &Session| crate::inspect::texture_set(s, 1)["uvPadding"].clone(); + let crosses_seams = |s: &Session| !s.caches[1].padding.crossed.is_empty(); assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); s.update(); - crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "uvPadding": "2d"})).unwrap(); + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 1, "uvPadding": "2d"})).unwrap(); assert_eq!((mode(&s), crosses_seams(&s)), (json!("2d"), false)); - assert!(!s.caches[0].dirty.is_empty(), "the set recomposites with its new padding"); + assert!(!s.caches[1].dirty.is_empty(), "the set recomposites with its new padding"); assert!(crate::execute(&mut s, "textureSet.settings", &json!({"uvPadding": "4d"})).is_err()); crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); From e6342a9f2956e9b5f81bbb4b578eb623631cbb7e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:18:14 +0000 Subject: [PATCH 131/190] Lay out the paint tool's Brush section in the reference's bands Size (Size, Minimum Size, Spacing), Opacity (Flow, Stroke opacity), Orientation (the brush's stamp on a dial beside Angle, Follow Path), Jitter (a strip of jittered dabs above the four jitters) and Projection (Alignment with a picture per mode, Backface culling with its Angle fade, Size Space, Stamp depth) as property-sheet bands, each with its own reset. Brush presets open from the Brush caption's menu button. Particles and Lazy mouse stay, folded. --- crates/ui-egui/src/brush_pictures.rs | 149 ++++++++++ crates/ui-egui/src/brush_sheet.rs | 264 ++++++++++++++++++ crates/ui-egui/src/brush_stroke_preview.rs | 19 +- crates/ui-egui/src/dock.rs | 156 +---------- crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/property_sheet/axis_rows.rs | 24 +- .../ui-egui/tests/it/brush_section_reset.rs | 58 ++-- crates/ui-egui/tests/it/export_settings.rs | 5 +- crates/ui-egui/tests/it/properties_lists.rs | 14 + crates/ui-egui/tests/it/properties_popup.rs | 32 ++- .../ui-egui/tests/it/shelf_hover_preview.rs | 6 +- crates/ui-egui/tests/ui_snapshots.rs | 2 +- 12 files changed, 518 insertions(+), 213 deletions(-) create mode 100644 crates/ui-egui/src/brush_pictures.rs create mode 100644 crates/ui-egui/src/brush_sheet.rs diff --git a/crates/ui-egui/src/brush_pictures.rs b/crates/ui-egui/src/brush_pictures.rs new file mode 100644 index 00000000..1f8fbbef --- /dev/null +++ b/crates/ui-egui/src/brush_pictures.rs @@ -0,0 +1,149 @@ +//! Pictures of what the brush settings do: the brush's stamp turned to its Angle, a strip of jittered dabs and the alignment modes + +use egui::{ColorImage, Painter, Pos2, Rect, Shape, Stroke, pos2}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::{Alignment, BrushSettings}; + +use crate::preview_image::stroke_strip; +use crate::theme::Tokens; + +/// The stamp's radius in the Orientation picture, as a share of half its side: room for the dial's ring around it +const STAMP_RADIUS_SHARE: f32 = 0.62; + +/// The dial's ring radius, as a share of half the picture's side +const RING_RADIUS_SHARE: f32 = 0.86; + +/// How far the Angle tick reaches in and out of the ring, in points +const TICK_REACH: f32 = 3.0; + +/// The ring's and the tick's line widths, in points +const RING_WIDTH: f32 = 1.0; +const TICK_WIDTH: f32 = 2.0; + +/// How far a dab may reach from the strip's centre line, as a share of half its height +const STRIP_REACH_SHARE: f32 = 0.85; + +/// The least spacing between the strip's dabs, in stamp diameters, so each dab reads on its own +const STRIP_DAB_SPACING: f32 = 1.4; + +/// The brush's own stamp turned to its Angle, alone in a `size` square: jitter, flow and opacity left out so only the shape and its turn show +pub(crate) fn stamp_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], _pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let still = BrushSettings { + jitter_size: 0.0, + jitter_angle: 0.0, + jitter_flow: 0.0, + jitter_position: 0.0, + follow_path: false, + flow: 1.0, + opacity: 1.0, + ..brush.clone() + }; + let center = (size[0] as f32 * 0.5, size[1] as f32 * 0.5); + let radius = center.0.min(center.1) * STAMP_RADIUS_SHARE; + + // A curve that stays put lays exactly one stamp + stroke_strip(&still, image, size, |_| radius, |_| center, |x| column_tint(tints, x)) +} + +/// A row of the brush's dabs across a `size` strip, scattered by its four jitters; dabs shrink as Position Jitter grows so the scatter stays inside +pub(crate) fn jitter_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], _pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let spaced = BrushSettings { spacing: brush.spacing.max(STRIP_DAB_SPACING), follow_path: false, flow: 1.0, opacity: 1.0, ..brush.clone() }; + let (width, middle) = (size[0] as f32, size[1] as f32 * 0.5); + + // A dab lands up to Position Jitter radii from the line, so its radius and that reach together fill the strip's half height + let radius = middle * STRIP_REACH_SHARE / (1.0 + brush.jitter_position.max(0.0)); + let curve = |t: f32| (radius + t * (width - 2.0 * radius), middle); + stroke_strip(&spaced, image, size, |_| radius, curve, |x| column_tint(tints, x)) +} + +fn column_tint(tints: &[[u8; 3]], x: usize) -> [u8; 3] { + tints.get(x).copied().unwrap_or([u8::MAX; 3]) +} + +/// The dial around the Orientation picture's stamp: a ring and an accent tick at `degrees` (counter-clockwise from the right, as the stamp turns) +pub(crate) fn dial_ring(painter: &Painter, rect: Rect, degrees: f32, tokens: &Tokens) { + let center = rect.center(); + let ring = rect.width().min(rect.height()) * 0.5 * RING_RADIUS_SHARE; + painter.circle_stroke(center, ring, Stroke::new(RING_WIDTH, tokens.button_border)); + + let (sin, cos) = degrees.to_radians().sin_cos(); + let at = |reach: f32| pos2(center.x + reach * cos, center.y - reach * sin); + painter.line_segment([at(ring - TICK_REACH), at(ring + TICK_REACH)], Stroke::new(TICK_WIDTH, tokens.accent)); +} + +/// Points along the Alignment picture's surface +const SURFACE_POINTS: usize = 16; + +/// The surface's bulge and the stamp's height above it, as shares of the picture's height +const SURFACE_BULGE_SHARE: f32 = 0.45; +const STAMP_LIFT_SHARE: f32 = 0.12; + +/// Margin inside the Alignment picture, in points +const ALIGNMENT_INSET: f32 = 2.0; + +/// The middle share of the surface the stamp covers +const STAMP_SPAN_SHARE: f32 = 0.6; + +/// How an Alignment lays the stamp on a curved surface: bent along it (Tangent | Wrap) or flat towards the view (Camera) +pub(crate) fn alignment_picture(painter: &Painter, rect: Rect, alignment: Alignment, tokens: &Tokens) { + let rect = rect.shrink(ALIGNMENT_INSET); + let bulge = rect.height() * SURFACE_BULGE_SHARE; + let surface_y = |across: f32| rect.bottom() - bulge * (1.0 - across * across); + let point = |across: f32, lift: f32| pos2(rect.center().x + across * rect.width() * 0.5, surface_y(across) - lift); + let line = |from: f32, to: f32, lift: f32| -> Vec { + (0..=SURFACE_POINTS).map(|step| point(from + (to - from) * step as f32 / SURFACE_POINTS as f32, lift)).collect() + }; + painter.add(Shape::line(line(-1.0, 1.0, 0.0), Stroke::new(RING_WIDTH, tokens.text_dim))); + + let lift = rect.height() * STAMP_LIFT_SHARE; + let stamp = match alignment { + Alignment::Tangent => line(-STAMP_SPAN_SHARE, STAMP_SPAN_SHARE, lift), + Alignment::Camera => { + let top = surface_y(0.0) - lift; + vec![pos2(point(-STAMP_SPAN_SHARE, 0.0).x, top), pos2(point(STAMP_SPAN_SHARE, 0.0).x, top)] + } + }; + painter.add(Shape::line(stamp, Stroke::new(TICK_WIDTH, tokens.accent))); +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::paint::BrushAlpha; + + use super::*; + + const STAMP_SIZE: [usize; 2] = [48, 48]; + const STRIP_SIZE: [usize; 2] = [240, 40]; + + fn white(width: usize) -> Vec<[u8; 3]> { + vec![[u8::MAX; 3]; width] + } + + #[test] + fn the_stamp_turns_with_angle() { + let upright = BrushSettings { alpha: BrushAlpha::Streaks, angle: 0.0, ..BrushSettings::default() }; + let turned = BrushSettings { angle: 45.0, ..upright.clone() }; + + let picture = |brush: &BrushSettings| stamp_image(brush, None, STAMP_SIZE, 1.0, &white(STAMP_SIZE[0])).pixels; + + assert!(picture(&upright).iter().any(|pixel| pixel.a() > 0), "the stamp shows"); + assert_ne!(picture(&upright), picture(&turned)); + } + + #[test] + fn each_jitter_changes_the_strip() { + let steady = BrushSettings { hardness: 1.0, ..BrushSettings::default() }; + let strip = |brush: &BrushSettings| jitter_image(brush, None, STRIP_SIZE, 1.0, &white(STRIP_SIZE[0])).pixels; + let jittered = [ + BrushSettings { jitter_size: 0.8, ..steady.clone() }, + BrushSettings { jitter_flow: 0.8, ..steady.clone() }, + BrushSettings { jitter_angle: 0.8, alpha: BrushAlpha::Streaks, ..steady.clone() }, + BrushSettings { jitter_position: 1.0, ..steady.clone() }, + ]; + + for brush in &jittered { + let unjittered = BrushSettings { jitter_size: 0.0, jitter_flow: 0.0, jitter_angle: 0.0, jitter_position: 0.0, ..brush.clone() }; + assert_ne!(strip(brush), strip(&unjittered), "{brush:?}"); + } + } +} diff --git a/crates/ui-egui/src/brush_sheet.rs b/crates/ui-egui/src/brush_sheet.rs new file mode 100644 index 00000000..167287ae --- /dev/null +++ b/crates/ui-egui/src/brush_sheet.rs @@ -0,0 +1,264 @@ +//! The Brush section of a paint tool's Properties: the Size, Opacity, Orientation, Jitter and Projection bands, grouped and named as the reference groups them + +use std::ops::RangeInclusive; +use std::sync::Arc; + +use egui::{Painter, Rect, Response, Sense, Stroke, StrokeKind, Ui, vec2}; +use serde_json::json; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::{Alignment, BrushSettings}; + +use crate::TextureCraftApp; +use crate::brush_pictures::{alignment_picture, dial_ring, jitter_image, stamp_image}; +use crate::brush_stroke_preview::BrushStrokePreview; +use crate::fill_pictures::backface_picture; +use crate::i18n::tr; +use crate::property_sheet::{PropertySheet, RowLead, StackSlider}; +use crate::theme::{Tokens, caption}; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; + +/// Height of the Jitter band's strip of dabs, in points +const JITTER_STRIP_HEIGHT: f32 = 40.0; + +/// Corner radius of the Jitter strip's frame +const JITTER_STRIP_ROUNDING: f32 = 2.0; + +/// Width of the Jitter strip's frame, in points; the dabs are drawn inside it +const JITTER_STRIP_OUTLINE_WIDTH: f32 = 1.0; + +/// What Angle and each Angle fade may be, in degrees +const ANGLE_RANGE: RangeInclusive = -180.0..=180.0; +const ANGLE_FADE_RANGE: RangeInclusive = 0.0..=90.0; + +/// Size's slider, in percent of the largest brush +const SIZE_PERCENT_RANGE: RangeInclusive = 0.05..=100.0; + +/// Spacing's slider, in percent of the stamp's width +const SPACING_PERCENT_RANGE: RangeInclusive = 1.0..=1000.0; + +/// Position Jitter's slider, in percent of the stamp's radius +const POSITION_JITTER_PERCENT_RANGE: RangeInclusive = 0.0..=400.0; + +const PERCENT_RANGE: RangeInclusive = 0.0..=100.0; + +/// The ranges of Stamp depth, Gravity, particles per stamp, a particle's lifetime in steps and the lazy mouse distance in pixels +const STAMP_DEPTH_RANGE: RangeInclusive = 0.05..=4.0; +const GRAVITY_RANGE: RangeInclusive = 0.0..=2.0; +const PARTICLE_COUNT_RANGE: RangeInclusive = 1.0..=16.0; +const PARTICLE_LIFETIME_RANGE: RangeInclusive = 1.0..=128.0; +const LAZY_DISTANCE_RANGE: RangeInclusive = 0.0..=200.0; + +/// Width of the brush presets list +const PRESETS_WIDTH: f32 = 230.0; + +/// Height the presets list scrolls past +const PRESETS_MAX_HEIGHT: f32 = 380.0; + +/// The Brush section under its caption, whose ≡ button `menu` opens the brush presets +pub(crate) fn brush_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, menu: Option) { + if let Some(menu) = menu { + brush_presets_popover(app, sheet.ui, menu); + } + sheet.dim_line(tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.")); + sheet.dim_line(tr("Ctrl+Shift+right-drag: size and hardness in fine steps.")); + + let tokens = Tokens::get(sheet.ui.ctx()); + let image = app.session.tool.brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)).cloned(); + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); + + // Each band's reset puts back only the fields it shows + let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.spacing); + let band = sheet.band(tr("Size"), true, Some(size_fields(brush) != size_fields(&defaults)), None); + if band.reset { + (brush.size, brush.min_size, brush.spacing) = size_fields(&defaults); + } + if band.open { + let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; + if sheet.slider(tr("Size"), &mut size_percent, SIZE_PERCENT_RANGE, 1).is_some() { + brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + } + percent_slider(sheet, tr("Minimum Size (%)"), &mut brush.min_size, PERCENT_RANGE); + percent_slider(sheet, tr("Spacing"), &mut brush.spacing, SPACING_PERCENT_RANGE); + } + + let opacity_fields = |settings: &BrushSettings| (settings.flow, settings.opacity); + let band = sheet.band(tr("Opacity"), true, Some(opacity_fields(brush) != opacity_fields(&defaults)), None); + if band.reset { + (brush.flow, brush.opacity) = opacity_fields(&defaults); + } + if band.open { + percent_slider(sheet, tr("Flow"), &mut brush.flow, PERCENT_RANGE); + percent_slider(sheet, tr("Stroke opacity"), &mut brush.opacity, PERCENT_RANGE); + } + + let orientation_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); + let band = sheet.band(tr("Orientation"), true, Some(orientation_fields(brush) != orientation_fields(&defaults)), None); + if band.reset { + (brush.angle, brush.follow_path) = orientation_fields(&defaults); + } + if band.open { + let shown = brush.clone(); + let ctx = sheet.ui.ctx().clone(); + let tint = tokens.text.to_array(); + let dial = |painter: &Painter, rect: Rect| { + BrushStrokePreview::paint_picture( + &ctx, + painter, + rect, + "brush_stamp_picture", + (&shown, image.as_ref()), + |_| [tint[0], tint[1], tint[2]], + stamp_image, + ); + dial_ring(painter, rect, shown.angle, &tokens); + }; + let angle = StackSlider { label: tr("Angle"), value: &mut brush.angle, range: ANGLE_RANGE, typed: ANGLE_RANGE, decimals: 0, suffix: "°", dial: false }; + sheet.picture_sliders(&dial, &mut [angle]); + sheet.toggle(tr("Follow Path"), &mut brush.follow_path); + } + + let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_flow, settings.jitter_angle, settings.jitter_position); + let band = sheet.band(tr("Jitter"), true, Some(jitter_fields(brush) != jitter_fields(&defaults)), None); + if band.reset { + (brush.jitter_size, brush.jitter_flow, brush.jitter_angle, brush.jitter_position) = jitter_fields(&defaults); + } + if band.open { + jitter_strip(sheet, brush, image.as_ref(), &tokens); + percent_slider(sheet, tr("Size Jitter"), &mut brush.jitter_size, PERCENT_RANGE); + percent_slider(sheet, tr("Flow Jitter"), &mut brush.jitter_flow, PERCENT_RANGE); + percent_slider(sheet, tr("Angle Jitter"), &mut brush.jitter_angle, PERCENT_RANGE); + percent_slider(sheet, tr("Position Jitter"), &mut brush.jitter_position, POSITION_JITTER_PERCENT_RANGE); + } + + let projection_fields = + |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.screen_space, settings.depth); + let band = sheet.band(tr("Projection"), true, Some(projection_fields(brush) != projection_fields(&defaults)), None); + if band.reset { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.screen_space, brush.depth) = projection_fields(&defaults); + } + if band.open { + projection_rows(sheet, brush, &tokens); + } + + let particles = &mut brush.particles; + let band = sheet.band(tr("Particles"), false, Some(*particles != defaults.particles), None); + if band.reset { + *particles = defaults.particles; + } + if band.open { + sheet.info(tr("Paint slides down the surface")); + sheet.toggle(tr("Particle brush"), &mut particles.enabled); + whole_slider(sheet, tr("Count per stamp"), &mut particles.count, PARTICLE_COUNT_RANGE); + whole_slider(sheet, tr("Lifetime (steps)"), &mut particles.lifetime, PARTICLE_LIFETIME_RANGE); + sheet.slider(tr("Gravity"), &mut particles.gravity, GRAVITY_RANGE, 2); + } + + let band = sheet.band(tr("Lazy mouse"), false, Some(brush.lazy != defaults.lazy), None); + if band.reset { + brush.lazy = defaults.lazy; + } + if band.open { + sheet.slider(tr("Lazy mouse distance"), &mut brush.lazy, LAZY_DISTANCE_RANGE, 0); + } + + *brush = brush.sanitized(); +} + +/// Alignment, Backface culling with its Angle fade under it, Size Space and Stamp depth +fn projection_rows(sheet: &mut PropertySheet<'_>, brush: &mut BrushSettings, tokens: &Tokens) { + let alignment_name = |alignment: Alignment| { + match alignment { + Alignment::Tangent => tr("Tangent | Wrap"), + Alignment::Camera => tr("Camera"), + } + .to_owned() + }; + let picture = |painter: &Painter, rect: Rect, alignment: Alignment| alignment_picture(painter, rect, alignment, tokens); + let (picked, _) = sheet.dropdown(tr("Alignment"), brush.alignment, &[Alignment::Tangent, Alignment::Camera], alignment_name, Some(&picture)); + if let Some(alignment) = picked { + brush.alignment = alignment; + } + + let culled = brush.backface_culling; + let picture = |painter: &Painter, rect: Rect| backface_picture(painter, rect, culled, tokens); + sheet.picture_toggle(&picture, tr("Backface culling"), &mut brush.backface_culling); + + // Faces only fade towards their edge while backfaces are culled + sheet.greyed(brush.backface_culling, Some(tr("Fades only while Backface culling is on")), |sheet| { + sheet.angle_led(RowLead::Child(tr("Angle fade from")), &mut brush.angle_fade.0, ANGLE_FADE_RANGE); + sheet.angle_led(RowLead::Child(tr("Angle fade to")), &mut brush.angle_fade.1, ANGLE_FADE_RANGE); + }); + + if let Some(space) = sheet.switch(tr("Size Space"), &[tr("Object"), tr("Viewport")], usize::from(brush.screen_space)) { + brush.screen_space = space == 1; + } + sheet.slider(tr("Stamp depth"), &mut brush.depth, STAMP_DEPTH_RANGE, 2); +} + +/// The brush's dabs scattered by its jitters, across the panel above the Jitter sliders +fn jitter_strip(sheet: &mut PropertySheet<'_>, brush: &BrushSettings, image: Option<&Arc>, tokens: &Tokens) { + let tint = tokens.text.to_array(); + sheet.embed(|ui: &mut Ui| { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), JITTER_STRIP_HEIGHT), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Jitter preview"))); + + let painter = ui.painter(); + painter.rect_filled(rect, JITTER_STRIP_ROUNDING, tokens.field); + painter.rect_stroke(rect, JITTER_STRIP_ROUNDING, Stroke::new(JITTER_STRIP_OUTLINE_WIDTH, tokens.field_border), StrokeKind::Inside); + BrushStrokePreview::paint_picture( + ui.ctx(), + painter, + rect.shrink(JITTER_STRIP_OUTLINE_WIDTH), + "brush_jitter_picture", + (brush, image), + |_| [tint[0], tint[1], tint[2]], + jitter_image, + ); + }); +} + +/// A 0..1 setting shown and typed in whole percent +fn percent_slider(sheet: &mut PropertySheet<'_>, label: &str, fraction: &mut f32, percent: RangeInclusive) { + let mut shown = *fraction * 100.0; + if sheet.slider(label, &mut shown, percent, 0).is_some() { + *fraction = shown / 100.0; + } +} + +/// A count on a slider of whole numbers +fn whole_slider(sheet: &mut PropertySheet<'_>, label: &str, count: &mut u32, range: RangeInclusive) { + let mut shown = *count as f32; + if sheet.slider(label, &mut shown, range, 0).is_some() { + *count = shown.round() as u32; + } +} + +/// The brush presets, listed under the Brush caption's ≡ button +fn brush_presets_popover(app: &mut TextureCraftApp, ui: &Ui, menu: Response) { + menu.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Brush presets"))); + let menu = menu.on_hover_text(tr("Brush presets")); + let popup_id = ui.make_persistent_id("brush_presets_popup"); + if menu.clicked() { + egui::Popup::toggle_id(ui.ctx(), popup_id); + } + + egui::Popup::from_response(&menu).id(popup_id).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_min_width(PRESETS_WIDTH); + egui::ScrollArea::vertical().max_height(PRESETS_MAX_HEIGHT).show(ui, |ui| { + let mut category = ""; + for preset in texturecraft_engine::paint::presets::PRESETS.iter() { + if preset.category != category { + category = preset.category; + ui.label(caption(category)); + } + if ui.selectable_label(false, preset.label).on_hover_text(tr("Use this brush (keeps its size)")).clicked() { + app.run("brush.preset.apply", json!({"preset": preset.id})); + } + } + + ui.separator(); + crate::shelf::user_brushes(app, ui, ""); + }); + }); +} diff --git a/crates/ui-egui/src/brush_stroke_preview.rs b/crates/ui-egui/src/brush_stroke_preview.rs index 4aafb9dd..23bc1edd 100644 --- a/crates/ui-egui/src/brush_stroke_preview.rs +++ b/crates/ui-egui/src/brush_stroke_preview.rs @@ -37,18 +37,31 @@ pub(crate) struct BrushStrokePreview { impl BrushStrokePreview { /// Paint the brush's stroke across `rect`, each pixel column coloured by `tint` of its position 0..1; it renders again only on a new brush, alpha image, colour or size pub(crate) fn paint(ctx: &Context, painter: &Painter, rect: Rect, brush: &BrushSettings, image: Option<&Arc>, tint: impl Fn(f32) -> [u8; 3]) { + Self::paint_picture(ctx, painter, rect, "brush_stroke_preview", (brush, image), tint, stroke_image); + } + + /// Paint `render`'s picture of the brush across `rect`, kept under `key` until the brush, alpha image, colour or size change + pub(crate) fn paint_picture( + ctx: &Context, + painter: &Painter, + rect: Rect, + key: &'static str, + (brush, image): (&BrushSettings, Option<&Arc>), + tint: impl Fn(f32) -> [u8; 3], + render: impl FnOnce(&BrushSettings, Option<&ImageRes>, [usize; 2], f32, &[[u8; 3]]) -> ColorImage, + ) { let pixels_per_point = ctx.pixels_per_point(); let size = [(rect.width() * pixels_per_point).round().max(1.0) as usize, (rect.height() * pixels_per_point).round().max(1.0) as usize]; let tints: Vec<[u8; 3]> = (0..size[0]).map(|x| tint((x as f32 + 0.5) / size[0] as f32)).collect(); - let id = Id::unique("brush_stroke_preview"); + let id = Id::unique(key); let cached = ctx.data(|data| data.get_temp::(id)).filter(|preview| { preview.brush == *brush && preview.size == size && preview.tints == tints && preview.image.as_ref().map(Arc::as_ptr) == image.map(Arc::as_ptr) }); let preview = match cached { Some(preview) => preview, None => { - let picture = stroke_image(brush, image.map(|image| &**image), size, pixels_per_point, &tints); - let texture = ctx.load_texture("brush-stroke-preview", picture, TextureOptions::LINEAR); + let picture = render(brush, image.map(|image| &**image), size, pixels_per_point, &tints); + let texture = ctx.load_texture(key, picture, TextureOptions::LINEAR); let preview = BrushStrokePreview { brush: brush.clone(), image: image.cloned(), tints, size, texture }; ctx.data_mut(|data| data.insert_temp(id, preview.clone())); preview diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 7e556fdf..ffe7769b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -23,7 +23,6 @@ use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; use crate::source_choice::SourceChoice; use crate::theme::{Tokens, caption}; -use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ @@ -2128,9 +2127,9 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { }; PropertySheet::show(ui, "tool_sheet", |sheet| { for section in tool_sections(app) { - sheet.section(section.title(), false); + let menu = sheet.section(section.title(), section == PaintSection::Brush); match section { - PaintSection::Brush => legacy(sheet, app, brush_section), + PaintSection::Brush => crate::brush_sheet::brush_section(app, sheet, menu), PaintSection::Alpha => legacy(sheet, app, alpha_section), PaintSection::Stencil => legacy(sheet, app, stencil_section), PaintSection::Material => legacy(sheet, app, material_controls), @@ -2270,34 +2269,6 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } -/// Popover for built-in and saved brush presets -fn brush_presets_popover(app: &mut TextureCraftApp, ui: &mut Ui) { - let response = ui.button(format!("{} {}", ic::PAINT_BRUSH_BROAD, tr("Brush presets"))); - let popup_id = ui.make_persistent_id("brush_presets_popup"); - if response.clicked() { - egui::Popup::toggle_id(ui.ctx(), popup_id); - } - - egui::Popup::from_response(&response).id(popup_id).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_min_width(230.0); - egui::ScrollArea::vertical().max_height(380.0).show(ui, |ui| { - let mut category = ""; - for preset in texturecraft_engine::paint::presets::PRESETS.iter() { - if preset.category != category { - category = preset.category; - ui.label(caption(category)); - } - if ui.selectable_label(false, preset.label).on_hover_text(tr("Use this brush (keeps its size)")).clicked() { - app.run("brush.preset.apply", json!({"preset": preset.id})); - } - } - - ui.separator(); - crate::shelf::user_brushes(app, ui, ""); - }); - }); -} - /// Width of the label column in polygon fill's properties const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0; @@ -2396,129 +2367,6 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { } } -/// Font size of the dim hint line under the Brush caption -const HINT_TEXT_SIZE: f32 = 10.5; - -fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { - brush_presets_popover(app, ui); - - let brush = &mut app.session.tool.brush; - let defaults = BrushSettings::default(); - let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); - ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); - ui.label(RichText::new(tr("Ctrl+Shift+right-drag: size and hardness in fine steps.")).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); - - // Each section's reset puts back only the fields it shows - let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space); - if section_with_reset(ui, "sec_size", tr("Size"), true, size_fields(brush) == size_fields(&defaults), |ui| { - let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; - if slider(ui, tr("Size"), &mut size_percent, 0.05..=100.0, 1).changed() { - brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); - } - - let mut min_size_percent = brush.min_size * 100.0; - if slider(ui, tr("Minimum size (%)"), &mut min_size_percent, 0.0..=100.0, 0).changed() { - brush.min_size = min_size_percent / 100.0; - } - - ui.checkbox(&mut brush.screen_space, tr("Size in screen space")); - }) { - (brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults); - } - - let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing); - if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| { - let mut flow_percent = brush.flow * 100.0; - if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() { - brush.flow = flow_percent / 100.0; - } - - let mut opacity_percent = brush.opacity * 100.0; - if slider(ui, tr("Stroke opacity"), &mut opacity_percent, 0.0..=100.0, 0).changed() { - brush.opacity = opacity_percent / 100.0; - } - - let mut spacing_percent = brush.spacing * 100.0; - if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() { - brush.spacing = spacing_percent / 100.0; - } - }) { - (brush.flow, brush.opacity, brush.spacing) = flow_fields(&defaults); - } - - let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); - if section_with_reset(ui, "sec_angle", tr("Angle"), false, angle_fields(brush) == angle_fields(&defaults), |ui| { - slider(ui, tr("Angle"), &mut brush.angle, -180.0..=180.0, 0); - ui.checkbox(&mut brush.follow_path, tr("Follow path")); - }) { - (brush.angle, brush.follow_path) = angle_fields(&defaults); - } - - let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_angle, settings.jitter_flow, settings.jitter_position); - if section_with_reset(ui, "sec_jitter", tr("Jitters"), false, jitter_fields(brush) == jitter_fields(&defaults), |ui| { - let jitters = [(tr("Size jitter"), &mut brush.jitter_size), (tr("Angle jitter"), &mut brush.jitter_angle), (tr("Flow jitter"), &mut brush.jitter_flow)]; - for (label, jitter) in jitters { - let mut jitter_percent = *jitter * 100.0; - if slider(ui, label, &mut jitter_percent, 0.0..=100.0, 0).changed() { - *jitter = jitter_percent / 100.0; - } - } - - let mut position_jitter_percent = brush.jitter_position * 100.0; - if slider(ui, tr("Position jitter"), &mut position_jitter_percent, 0.0..=400.0, 0).changed() { - brush.jitter_position = position_jitter_percent / 100.0; - } - }) { - (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = jitter_fields(&defaults); - } - - let alignment_fields = |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.depth); - if section_with_reset(ui, "sec_align", tr("Alignment and culling"), false, alignment_fields(brush) == alignment_fields(&defaults), |ui| { - use texturecraft_engine::paint::Alignment; - let alignments = [(Alignment::Tangent, tr("Tangent | Wrap")), (Alignment::Camera, tr("Camera"))]; - let shown = alignments.iter().find(|(alignment, _)| *alignment == brush.alignment).map_or("", |(_, label)| label); - combo(ui, tr("Alignment"), shown, |ui| { - for (alignment, label) in alignments { - ui.selectable_value(&mut brush.alignment, alignment, label); - } - }); - - ui.checkbox(&mut brush.backface_culling, tr("Backface culling")); - slider(ui, tr("Angle fade from"), &mut brush.angle_fade.0, 0.0..=90.0, 0); - slider(ui, tr("Angle fade to"), &mut brush.angle_fade.1, 0.0..=90.0, 0); - slider(ui, tr("Stamp depth"), &mut brush.depth, 0.05..=4.0, 2); - }) { - (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = alignment_fields(&defaults); - } - - if section_with_reset(ui, "sec_particles", tr("Particles"), false, brush.particles == defaults.particles, |ui| { - let particles = &mut brush.particles; - ui.checkbox(&mut particles.enabled, tr("Particle brush (slides down the surface)")); - - let mut count = particles.count as f32; - if slider(ui, tr("Count per stamp"), &mut count, 1.0..=16.0, 0).changed() { - particles.count = count as u32; - } - - let mut lifetime_steps = particles.lifetime as f32; - if slider(ui, tr("Lifetime (steps)"), &mut lifetime_steps, 1.0..=128.0, 0).changed() { - particles.lifetime = lifetime_steps as u32; - } - - slider(ui, tr("Gravity"), &mut particles.gravity, 0.0..=2.0, 2); - }) { - brush.particles = defaults.particles; - } - - if section_with_reset(ui, "sec_lazy", tr("Lazy mouse"), false, brush.lazy == defaults.lazy, |ui| { - slider(ui, tr("Lazy mouse distance"), &mut brush.lazy, 0.0..=200.0, 0); - }) { - brush.lazy = defaults.lazy; - } - - *brush = brush.sanitized(); -} - /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Painter, Rect)) -> egui::Response { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 327ab90b..61f2ae64 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,8 @@ mod bake_preset; pub mod bake_presets; mod bake_report; mod bake_scene; +mod brush_pictures; +mod brush_sheet; mod brush_stroke_preview; mod color_management; mod color_picker; diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index c534afc3..c74a956a 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -2,7 +2,7 @@ use std::ops::RangeInclusive; -use egui::{Align2, Color32, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::row::SECTION_CAPTION_CENTER; use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS}; @@ -45,6 +45,9 @@ const PICTURE_TOP: f32 = 4.0; const PICTURE_SHORTER: f32 = 10.0; const PICTURE_TO_COLUMN: f32 = 6.0; +/// Width of the line around the picture +const PICTURE_OUTLINE_WIDTH: f32 = 1.0; + impl PropertySheet<'_> { /// A section caption with its on/off switch at the right edge pub(crate) fn section_switch(&mut self, title: &str, on: bool) -> Response { @@ -135,32 +138,35 @@ impl PropertySheet<'_> { Self::apply_typed(value, typed, dragged) } - /// Draw a picture beside captioned sliders and report the edit on each slider. + /// Draw a picture beside captioned sliders and report the edit on each slider pub(crate) fn picture_sliders(&mut self, picture: &dyn Fn(&Painter, Rect), sliders: &mut [StackSlider<'_>; N]) -> [Option; N] { let count = sliders.len().max(1) as f32; let height = count * (STACK_CAPTION_LINE + STACK_PART_LINE) + (count - 1.0) * STACK_GAP; self.space(BLOCK_MARGIN); let block = self.take(height); - let x0 = self.column(); - let side = (height - PICTURE_SHORTER).min(x0 - self.left - PICTURE_TO_COLUMN).max(1.0); + + let column_x = self.column(); + let side = (height - PICTURE_SHORTER).min(column_x - self.left - PICTURE_TO_COLUMN).max(1.0); let square = Rect::from_min_size(pos2(self.left, block.top() + PICTURE_TOP), vec2(side, side)); picture(self.ui.painter(), square); - self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + self.ui.painter().rect_stroke(square, CornerRadius::ZERO, Stroke::new(PICTURE_OUTLINE_WIDTH, self.tokens.field_border), StrokeKind::Inside); + let caption_color = self.tokens.text_dim; let mut edits = [None; N]; let mut y = block.top(); for (edit, slider) in edits.iter_mut().zip(sliders) { - let dim = self.tokens.text_dim; - let caption = pos2(x0, y + STACK_CAPTION_LINE / 2.0); - self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), dim); + let caption = pos2(column_x, y + STACK_CAPTION_LINE / 2.0); + self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), caption_color); + let center_y = y + STACK_CAPTION_LINE + STACK_PART_LINE / 2.0; let id = self.next_id(); let dial_x = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - DIAL_AIR - DIAL_RADIUS; let end = if slider.dial { dial_x - DIAL_RADIUS - DIAL_AIR } else { self.track_end() }; - let track = Track { start: x0 + KNOB_RADIUS, end, center_y, zero: None, ramp: false }; + let track = Track { start: column_x + KNOB_RADIUS, end, center_y, zero: (*slider.range.start() < 0.0).then_some(0.0), ramp: false }; if slider.dial { self.paint_dial(pos2(dial_x, center_y), *slider.value); } + let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); *edit = Self::apply_typed(slider.value, typed, dragged); diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index 16270401..2e740ff4 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -1,11 +1,11 @@ -//! Each brush section header has a reset icon that puts only that section's settings back to their defaults +//! Each band of the Brush section has a reset that puts back only that band's settings, grouped as the reference groups them use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::paint::{Alignment, BrushAlpha, BrushSettings, Particles, Symmetry}; use texturecraft_ui_egui::TextureCraftApp; -/// The default window; Properties shows only the top of the brush there, so lower headers are scrolled to +/// The default window; Properties shows only the top of the brush there, so lower bands are scrolled to const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); /// Frames for the first layout and fonts to settle @@ -17,22 +17,18 @@ const SETTLE_FRAMES: usize = 3; /// Puts one section's fields of the first brush back to the second's values type SectionReset = fn(&mut BrushSettings, &BrushSettings); -/// Each brush section's title, a label shown only while it is open, whether it starts open, and its reset +/// Each band's title, a label shown only while it is open, whether it starts open, and its reset const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ - ("Size", "Minimum size (%)", true, |brush, defaults| { - (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space) - }), - ("Flow and opacity", "Stroke opacity", true, |brush, defaults| { - (brush.flow, brush.opacity, brush.spacing) = (defaults.flow, defaults.opacity, defaults.spacing) - }), - ("Angle", "Follow path", false, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), - ("Jitters", "Size jitter", false, |brush, defaults| { + ("Size", "Minimum Size (%)", true, |brush, defaults| (brush.size, brush.min_size, brush.spacing) = (defaults.size, defaults.min_size, defaults.spacing)), + ("Opacity", "Stroke opacity", true, |brush, defaults| (brush.flow, brush.opacity) = (defaults.flow, defaults.opacity)), + ("Orientation", "Follow Path", true, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitter", "Size Jitter", true, |brush, defaults| { (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) }), - ("Alignment and culling", "Backface culling", false, |brush, defaults| { - (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = - (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + ("Projection", "Backface culling", true, |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.screen_space, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.screen_space, defaults.depth) }), ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), ("Lazy mouse", "Lazy mouse distance", false, |brush, defaults| brush.lazy = defaults.lazy), @@ -82,18 +78,27 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { harness } -/// The reset icon on the header row titled `title` -fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { - let label = format!("{title}: Reset to defaults"); +/// The band titled `title` in Properties: the rightmost, as the top bar has a Size and a Lazy mouse too +fn band<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { harness .query_all_by_role(egui::Role::Button) - .find(|node| node.accesskit_node().label().as_deref() == Some(label.as_str())) - .unwrap_or_else(|| panic!("no reset icon on the {title} header")) + .filter(|node| node.accesskit_node().label().as_deref() == Some(title)) + .max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())) + .unwrap_or_else(|| panic!("no {title} band")) } -/// Scrolls the header titled `title` into view and clicks its reset icon +/// The reset on the band titled `title` +fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { + let band = band(harness, title).rect(); + harness + .query_all_by_role(egui::Role::Button) + .find(|node| node.accesskit_node().label().as_deref() == Some("Restore defaults") && node.rect().y_range().intersects(band.y_range())) + .unwrap_or_else(|| panic!("no reset on the {title} band")) +} + +/// Scrolls the band titled `title` into view and clicks its reset fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { - reset_icon(harness, title).scroll_to_me(); + band(harness, title).scroll_to_me(); harness.run_steps(SETTLE_FRAMES); reset_icon(harness, title).click(); @@ -118,13 +123,12 @@ fn each_reset_puts_back_only_its_own_section() { } } -/// Scrolls the header titled `title` into view and clicks the header itself, folding or unfolding it +/// Scrolls the band titled `title` into view and clicks it, folding or unfolding it fn click_header(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { - reset_icon(harness, title).scroll_to_me(); + band(harness, title).scroll_to_me(); harness.run_steps(SETTLE_FRAMES); - let icon = reset_icon(harness, title).rect(); - harness.query_all_by_label(title).find(|label| label.rect().y_range().intersects(icon.y_range())).unwrap_or_else(|| panic!("no {title} header")).click(); + band(harness, title).click(); harness.run_steps(SETTLE_FRAMES); } @@ -157,7 +161,7 @@ fn at_the_defaults_the_reset_icons_are_inert() { click_reset(&mut harness, title); - assert_eq!(harness.query_by_label(body_label).is_some(), starts_open, "the click doesn't reach the {title} header"); + assert_eq!(harness.query_by_label(body_label).is_some(), !starts_open, "an inert reset folds the {title} band like the rest of it"); assert_eq!(harness.state().session.tool.brush, BrushSettings::default(), "the {title} reset is inert"); } } @@ -175,7 +179,7 @@ fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { let defaults = BrushSettings::default(); let mut expected = changed_brush(); - (expected.size, expected.min_size, expected.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space); + (expected.size, expected.min_size, expected.spacing) = (defaults.size, defaults.min_size, defaults.spacing); assert_eq!(harness.state().session.tool.brush, expected, "resetting Size with {key:?}"); } } diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 749bab18..45902714 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -154,8 +154,9 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { click(&mut h, "16"); assert!(h.query_by_label("Dilation (pixels)").is_some()); - // A click on the slider sets the width and leaves the menu open - h.get_by_role(egui::Role::Slider).click(); + // A click on the slider sets the width and leaves the menu open; Properties has sliders too, so take the one under the menu's label + let label = h.get_by_label("Dilation (pixels)").rect().left_bottom(); + h.query_all_by_role(egui::Role::Slider).min_by(|a, b| a.rect().left_top().distance(label).total_cmp(&b.rect().left_top().distance(label))).unwrap().click(); h.run_steps(4); assert_ne!(h.state().ui.export.dilation, 16); assert!(h.query_by_label("Dilation (pixels)").is_some(), "the menu stays open"); diff --git a/crates/ui-egui/tests/it/properties_lists.rs b/crates/ui-egui/tests/it/properties_lists.rs index 3486b719..cb2501c2 100644 --- a/crates/ui-egui/tests/it/properties_lists.rs +++ b/crates/ui-egui/tests/it/properties_lists.rs @@ -22,6 +22,9 @@ const GESTURE: Vec2 = vec2(-60.0, 40.0); /// Where in the view the gestures start, as a share of its width from its left edge const GESTURE_SHARE: f32 = 0.3; +/// Frames for a scroll to a list to finish its animation +const SCROLL_FRAMES: usize = 30; + /// Escapes between lists, so one that stays open can't leave its popup over the next const ESCAPES_TO_CLEAR: usize = 2; @@ -242,6 +245,17 @@ fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_ continue; }; + // A list low in a long panel sits below its visible part until scrolled to + let same_before = lists(&harness).iter().take(index).filter(|(_, other)| *other == shown).count(); + if let Some(node) = harness.query_all_by_role(Role::ComboBox).find(|node| node.rect() == button) { + node.scroll_to_me(); + } + harness.run_steps(SCROLL_FRAMES); + let Some((button, _)) = lists(&harness).into_iter().filter(|(_, other)| *other == shown).nth(same_before) else { + problems.push(format!("{screen}: {shown} is gone after scrolling to it")); + continue; + }; + problems.extend(check_list(&mut harness, button, &format!("{screen}: {shown}"))); for _ in 0..ESCAPES_TO_CLEAR { harness.key_press(egui::Key::Escape); diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 19de942d..cb96b1e3 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -9,7 +9,7 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; use texturecraft_ui_egui::state::{Mode, ViewLayout}; -use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; /// A common laptop window const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); @@ -35,6 +35,9 @@ const SCROLL_FRAMES: usize = 25; /// How far left of the popup a click lands on the model const MODEL_LEFT_OF_POPUP: f32 = 60.0; +/// How far in from the popup's right edge a slider drag ends, still over the slider's band +const DROP_LEFT_OF_POPUP_EDGE: f32 = 30.0; + fn harness() -> Harness<'static, TextureCraftApp> { harness_sized(WINDOW_SIZE) } @@ -156,21 +159,22 @@ fn dragging_its_size_slider_changes_the_brush() { click(&mut harness, PointerButton::Secondary, center); let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); - // The Size section's header sits above its slider of the same name - let slider_label = harness - .query_all_by_label("Size") + // The Size band holds a slider of the same name, its track right of the label + let slider = harness + .query_all_by_role(egui::Role::Slider) + .filter(|node| node.accesskit_node().label().as_deref() == Some("Size")) .map(|node| node.rect()) - .filter(|rect| popup.contains_rect(*rect)) - .max_by(|first, second| first.top().total_cmp(&second.top())) + .find(|rect| popup.contains_rect(*rect)) .unwrap(); - let track_y = slider_label.bottom() + 10.0; + let track_y = slider.center().y; let size = harness.state().session.tool.brush.size; - harness.drag_at(egui::pos2(slider_label.left() + 20.0, track_y)); - harness.run_steps(2); - harness.hover_at(egui::pos2(popup.right() - 30.0, track_y)); - harness.run_steps(2); - harness.drop_at(egui::pos2(popup.right() - 30.0, track_y)); - harness.run_steps(3); + let drop = egui::pos2(popup.right() - DROP_LEFT_OF_POPUP_EDGE, track_y); + harness.drag_at(egui::pos2(slider.left() + SLIDER_END_INSET, track_y)); + harness.run_steps(DRAG_STEP_FRAMES); + harness.hover_at(drop); + harness.run_steps(DRAG_STEP_FRAMES); + harness.drop_at(drop); + harness.run_steps(SETTLE_FRAMES); assert!(harness.state().session.tool.brush.size > size, "{size} -> {}", harness.state().session.tool.brush.size); assert!(is_open(&harness), "editing it keeps it open"); } @@ -194,7 +198,7 @@ fn it_shows_what_the_properties_panel_shows() { let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); let in_popup = |label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); assert!(in_popup("UV projection"), "a selected fill shows its fill settings"); - assert!(!in_popup("Minimum size (%)"), "not the brush's"); + assert!(!in_popup("Minimum Size (%)"), "not the brush's"); } /// Whether the jump tab `name` inside `area` is the lit one diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index c2809684..dcb99d5e 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -39,14 +39,14 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static (harness, unique) } -/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points -fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { +/// Largest drawn texture in pixels, excluding fonts and images below `min_side` points on either side (a wide strip is not a big preview) +fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_side: f32) -> Option<[usize; 2]> { let textures = h.ctx.tex_manager(); let textures = textures.read(); h.output() .shapes .iter() - .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().width() >= min_width) + .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().size().min_elem() >= min_side) .filter_map(|clipped| textures.meta(clipped.shape.texture_id()).map(|meta| meta.size)) .max() } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 2b737b1a..9ea94656 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3277,7 +3277,7 @@ fn paint_tool_properties_snapshots() { let in_properties = |harness: &Harness<'_, TextureCraftApp>, label: &str| { harness.get_all_by_label(label).map(|node| node.rect().center()).max_by(|a, b| a.x.total_cmp(&b.x)).unwrap() }; - for header in ["Angle", "Jitters", "Alignment and culling", "Particles", "Lazy mouse"] { + for header in ["Particles", "Lazy mouse"] { harness.get_all_by_label(header).max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); harness.run_steps(3); let at = in_properties(&harness, header); From 2cf3d2ad67e1e7820395142c441c85e5e7a7f9e8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:45:08 +0000 Subject: [PATCH 132/190] Turn pen pressure on Size on and off from the Size row BrushSettings gains size_pressure (on by default and for brushes saved before it existed, so old projects paint as before). Off, a light pen paints at full size in both views; tool.brush takes and reports sizePressure. The Size band's rows keep a pen button slot, Minimum Size greys while pressure is off, and the brush preview drops its pen taper. --- Cargo.lock | 1 + crates/engine/src/tool_cmds.rs | 24 ++++---- crates/engine/tests/it/uv_strokes.rs | 16 ++++++ crates/paint/Cargo.toml | 1 + crates/paint/src/brush.rs | 36 ++++++++++-- crates/paint/src/stroke.rs | 10 ++-- crates/ui-egui/src/brush_sheet.rs | 22 +++++-- crates/ui-egui/src/brush_stroke_preview.rs | 8 +++ crates/ui-egui/src/property_sheet/mod.rs | 1 + .../src/property_sheet/number_field.rs | 2 +- .../ui-egui/src/property_sheet/pen_slider.rs | 57 +++++++++++++++++++ .../ui-egui/tests/it/brush_section_reset.rs | 8 ++- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/size_pressure.rs | 47 +++++++++++++++ 14 files changed, 208 insertions(+), 26 deletions(-) create mode 100644 crates/ui-egui/src/property_sheet/pen_slider.rs create mode 100644 crates/ui-egui/tests/it/size_pressure.rs diff --git a/Cargo.lock b/Cargo.lock index acafef1d..b2eee4fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5984,6 +5984,7 @@ dependencies = [ "harfrust 0.12.0", "rayon", "serde", + "serde_json", "skrifa 0.44.0", "texturecraft-compose", "texturecraft-core", diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 977f34d6..e9e9dc26 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -132,14 +132,17 @@ fn select(s: &mut Session, p: &Value) -> Result { /// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers fn brush(session: &mut Session, params: &Value) -> Result { let mut settings = session.tool.brush.clone(); - let percent = |key: &str| f32p(params, key).map(|value| value / 100.0); + let percent = |key: &str| f32p(params, key).map(|value| value / PERCENT); if let Some(value) = percent("size") { - settings.size = value * 0.25; + settings.size = value * MAX_BRUSH_SIZE; } if let Some(value) = percent("minSize") { settings.min_size = value; } + if let Some(value) = boolp(params, "sizePressure") { + settings.size_pressure = value; + } if let Some(value) = percent("flow") { settings.flow = value; @@ -174,11 +177,11 @@ fn brush(session: &mut Session, params: &Value) -> Result { for (key, slot) in [("jitterSize", &mut settings.jitter_size), ("jitterAngle", &mut settings.jitter_angle), ("jitterFlow", &mut settings.jitter_flow)] { if let Some(value) = f32p(params, key) { - *slot = value / 100.0; + *slot = value / PERCENT; } } if let Some(value) = f32p(params, "jitterPosition") { - settings.jitter_position = value / 100.0; + settings.jitter_position = value / PERCENT; } let alpha = params.get("alpha"); @@ -282,30 +285,31 @@ fn brush(session: &mut Session, params: &Value) -> Result { } } if let Some(value) = f32p(params, "smudgeStrength") { - session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0); + session.tool.smudge_strength = (value / PERCENT).clamp(0.0, 1.0); } session.revision = session.revision.wrapping_add(1); Ok(brush_json(session)) } +/// The brush settings `tool.brush` reports, on the UI's 0–100 scales pub(crate) fn brush_json(session: &Session) -> Value { let settings = &session.tool.brush; json!({ - "size": settings.size / 0.25 * 100.0, "minSize": settings.min_size * 100.0, "flow": settings.flow * 100.0, "opacity": settings.opacity * 100.0, - "spacing": settings.spacing * 100.0, "hardness": settings.hardness * 100.0, "angle": settings.angle, "followPath": settings.follow_path, + "size": settings.size / MAX_BRUSH_SIZE * PERCENT, "minSize": settings.min_size * PERCENT, "sizePressure": settings.size_pressure, "flow": settings.flow * PERCENT, "opacity": settings.opacity * PERCENT, + "spacing": settings.spacing * PERCENT, "hardness": settings.hardness * PERCENT, "angle": settings.angle, "followPath": settings.follow_path, "alignment": format!("{:?}", settings.alignment).to_lowercase(), "lazy": settings.lazy, "alpha": match (&settings.alpha_image, &settings.alpha_library) { (Some(name), _) => json!({ "image": name }), (None, Some(id)) => json!({ "library": id }), (None, None) => json!(settings.alpha.label()), }, - "alphaSizeX": settings.alpha_params.size_x * 100.0, "alphaSizeY": settings.alpha_params.size_y * 100.0, - "alphaRoundness": settings.alpha_params.roundness * 100.0, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert, + "alphaSizeX": settings.alpha_params.size_x * PERCENT, "alphaSizeY": settings.alpha_params.size_y * PERCENT, + "alphaRoundness": settings.alpha_params.roundness * PERCENT, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert, "backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z], "radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) }, "symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span, - "material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles, + "material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * PERCENT, "particles": settings.particles, "cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, "cloneAligned": session.tool.clone_aligned, }) diff --git a/crates/engine/tests/it/uv_strokes.rs b/crates/engine/tests/it/uv_strokes.rs index 18a33fda..9d8466bc 100644 --- a/crates/engine/tests/it/uv_strokes.rs +++ b/crates/engine/tests/it/uv_strokes.rs @@ -103,3 +103,19 @@ fn decreasing_pressure_does_not_stamp_behind_a_turn() { assert!(red_at(&session, 0.33, 0.55), "the new segment is painted"); assert!(!red_at(&session, 0.33, 0.45), "a smaller step must not stamp behind the turn"); } + +#[test] +fn a_light_pen_paints_at_full_size_with_size_pressure_off() { + let painted_across = |size_pressure: bool| { + let mut session = red_brush_session(json!({"size": 10.0, "minSize": 0.0, "sizePressure": size_pressure, "hardness": 90})); + session.begin_stroke_uv([0.5, 0.5].into(), 0.2).unwrap(); + session.continue_stroke_uv([0.5, 0.5001].into(), 0.2); + session.end_stroke().unwrap(); + session.update(); + (0..RESOLUTION).filter(|x| red_at(&session, *x as f32 / RESOLUTION as f32, 0.5)).count() + }; + + let (pressed, ignored) = (painted_across(true), painted_across(false)); + assert!(pressed > 0, "a light pen still paints"); + assert!(ignored > pressed, "with size pressure off a light pen paints wider ({ignored} vs {pressed} texels)"); +} diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index 0b4bb7af..bff08e96 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -20,3 +20,4 @@ serde = { workspace = true } [dev-dependencies] epaint_default_fonts = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index d1a55036..320185bc 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -296,6 +296,9 @@ pub struct BrushSettings { pub size: f32, /// Pen pressure may shrink the size down to this fraction. pub min_size: f32, + /// Pen pressure shrinks the size towards `min_size`; on for projects saved before it could be turned off + #[serde(default = "pressure_on")] + pub size_pressure: bool, /// Per-stamp alpha 0..1. pub flow: f32, /// Caps a whole stroke 0..1. @@ -343,6 +346,7 @@ impl Default for BrushSettings { BrushSettings { size: 0.02, min_size: 0.05, + size_pressure: true, flow: 1.0, opacity: 1.0, spacing: 0.1, @@ -370,11 +374,15 @@ impl Default for BrushSettings { } impl BrushSettings { - /// Radius of a 2D (UV) stamp as a fraction of the UV square, for pen `pressure` 0..1: twice the - /// brush size, shrunk towards `min_size` by a light pen. Painting and the 2D cursor share it. + /// Radius of a 2D (UV) stamp as a fraction of the UV square at pen `pressure` 0..1: twice the brush size, shrunk towards `min_size` by a light pen (shared by painting and the 2D cursor) pub fn uv_stamp_radius(&self, pressure: f32) -> f32 { - let p = pressure.clamp(0.0, 1.0); - self.size * 2.0 * if p < 1.0 { self.min_size + (1.0 - self.min_size) * p } else { 1.0 } + self.size * 2.0 * self.pressure_size(pressure) + } + + /// The fraction of the size a stamp gets at pen `pressure` 0..1: full when size pressure is off + pub fn pressure_size(&self, pressure: f32) -> f32 { + let pressure = pressure.clamp(0.0, 1.0); + if self.size_pressure && pressure < 1.0 { self.min_size + (1.0 - self.min_size) * pressure } else { 1.0 } } /// Clamp every value into its valid range (input from UI, CLI or agents) @@ -415,8 +423,28 @@ impl BrushSettings { } } +fn pressure_on() -> bool { + true +} + #[cfg(test)] mod tests { + #[test] + fn size_pressure_off_keeps_a_light_pen_at_full_size() { + let pressed = BrushSettings { size: 0.1, min_size: 0.2, ..BrushSettings::default() }; + let mouse = BrushSettings { size_pressure: false, ..pressed.clone() }; + assert!(pressed.uv_stamp_radius(0.3) < mouse.uv_stamp_radius(0.3)); + assert_eq!(mouse.uv_stamp_radius(0.3), mouse.uv_stamp_radius(1.0)); + } + + #[test] + fn settings_saved_before_the_size_pressure_switch_keep_pen_pressure() { + let mut saved = serde_json::to_value(BrushSettings { size_pressure: false, ..BrushSettings::default() }).unwrap(); + saved.as_object_mut().unwrap().remove("size_pressure"); + let loaded: BrushSettings = serde_json::from_value(saved).unwrap(); + assert!(loaded.size_pressure); + } + #[test] fn uv_stamp_radius_follows_pen_pressure() { let b = BrushSettings { size: 0.1, min_size: 0.5, ..BrushSettings::default() }; diff --git a/crates/paint/src/stroke.rs b/crates/paint/src/stroke.rs index fcca6427..5aef41cb 100644 --- a/crates/paint/src/stroke.rs +++ b/crates/paint/src/stroke.rs @@ -125,11 +125,13 @@ impl Stroke { all } + /// The stamp radius at `pos` under `pressure`, scaled by its distance from the camera for a screen-space brush fn radius_at(&self, ctx: &PickCtx, pos: Vec3, pressure: f32) -> f32 { - let p = pressure.clamp(0.0, 1.0); - let scale = self.settings.min_size + (1.0 - self.settings.min_size) * p; - let r = self.radius * if pressure < 1.0 { scale } else { 1.0 }; - if self.settings.screen_space { r * (pos.distance(ctx.camera.eye()) / ctx.camera.distance.max(1e-4)) } else { r } + // Keeps the screen-space scale finite with the camera on its target + const MIN_CAMERA_DISTANCE: f32 = 1e-4; + + let radius = self.radius * self.settings.pressure_size(pressure); + if self.settings.screen_space { radius * (pos.distance(ctx.camera.eye()) / ctx.camera.distance.max(MIN_CAMERA_DISTANCE)) } else { radius } } fn feed(&mut self, ctx: &PickCtx, screen: Vec2, pressure: f32, depth: u32, out: &mut Vec) { diff --git a/crates/ui-egui/src/brush_sheet.rs b/crates/ui-egui/src/brush_sheet.rs index 167287ae..71f49872 100644 --- a/crates/ui-egui/src/brush_sheet.rs +++ b/crates/ui-egui/src/brush_sheet.rs @@ -68,18 +68,22 @@ pub(crate) fn brush_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet let defaults = BrushSettings::default(); // Each band's reset puts back only the fields it shows - let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.spacing); + let size_fields = |settings: &BrushSettings| (settings.size, settings.size_pressure, settings.min_size, settings.spacing); let band = sheet.band(tr("Size"), true, Some(size_fields(brush) != size_fields(&defaults)), None); if band.reset { - (brush.size, brush.min_size, brush.spacing) = size_fields(&defaults); + (brush.size, brush.size_pressure, brush.min_size, brush.spacing) = size_fields(&defaults); } if band.open { + // Every row keeps the pen button's slot, so the three values line up let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; - if sheet.slider(tr("Size"), &mut size_percent, SIZE_PERCENT_RANGE, 1).is_some() { + if sheet.pen_slider(tr("Size"), &mut size_percent, SIZE_PERCENT_RANGE, 1, Some(&mut brush.size_pressure)).0.is_some() { brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - percent_slider(sheet, tr("Minimum Size (%)"), &mut brush.min_size, PERCENT_RANGE); - percent_slider(sheet, tr("Spacing"), &mut brush.spacing, SPACING_PERCENT_RANGE); + let pressure = brush.size_pressure; + sheet.greyed(pressure, Some(tr("Applies only while pen pressure on Size is on")), |sheet| { + pen_percent_slider(sheet, tr("Minimum Size (%)"), &mut brush.min_size, PERCENT_RANGE); + }); + pen_percent_slider(sheet, tr("Spacing"), &mut brush.spacing, SPACING_PERCENT_RANGE); } let opacity_fields = |settings: &BrushSettings| (settings.flow, settings.opacity); @@ -226,6 +230,14 @@ fn percent_slider(sheet: &mut PropertySheet<'_>, label: &str, fraction: &mut f32 } } +/// [`percent_slider`] in a band whose rows keep the pen button's slot +fn pen_percent_slider(sheet: &mut PropertySheet<'_>, label: &str, fraction: &mut f32, percent: RangeInclusive) { + let mut shown = *fraction * 100.0; + if sheet.pen_slider(label, &mut shown, percent, 0, None).0.is_some() { + *fraction = shown / 100.0; + } +} + /// A count on a slider of whole numbers fn whole_slider(sheet: &mut PropertySheet<'_>, label: &str, count: &mut u32, range: RangeInclusive) { let mut shown = *count as f32; diff --git a/crates/ui-egui/src/brush_stroke_preview.rs b/crates/ui-egui/src/brush_stroke_preview.rs index 23bc1edd..245065bb 100644 --- a/crates/ui-egui/src/brush_stroke_preview.rs +++ b/crates/ui-egui/src/brush_stroke_preview.rs @@ -170,4 +170,12 @@ mod tests { assert!(start < end, "the stroke widens as the pen presses harder"); assert!(start < full_start, "Minimum Size bounds how thin the light start gets"); } + + #[test] + fn without_size_pressure_the_stroke_keeps_its_width() { + let brush = BrushSettings { hardness: 1.0, min_size: 0.05, size_pressure: false, ..BrushSettings::default() }; + let full = BrushSettings { min_size: 1.0, size_pressure: true, ..brush.clone() }; + + assert!(paint(&brush) == paint(&full), "a mouse brush draws no taper"); + } } diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 51c6ecfb..837d6437 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -29,6 +29,7 @@ mod material_rows; mod name_field; mod number_field; mod open_card; +mod pen_slider; mod preview_block; mod preview_edit; mod preview_lower; diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 36c484ad..11ed89fd 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -8,7 +8,7 @@ use crate::theme::semibold; const FIELD_GAP: f32 = 4.0; /// Room kept at the row's end for the link button, on every row of a group that has one -const LINK_SLOT: f32 = 26.0; +pub(super) const LINK_SLOT: f32 = 26.0; /// Size of the link button pub(super) const LINK_SIZE: f32 = 18.0; diff --git a/crates/ui-egui/src/property_sheet/pen_slider.rs b/crates/ui-egui/src/property_sheet/pen_slider.rs new file mode 100644 index 00000000..23ce262b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/pen_slider.rs @@ -0,0 +1,57 @@ +//! A slider that keeps the link slot at its end, for a pen-pressure button: the Size band's rows + +use std::ops::RangeInclusive; + +use egui::{Align2, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, vec2}; +use egui_phosphor::regular as ic; + +use super::number_field::{LINK_SIZE, LINK_SLOT}; +use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, ROW_HEIGHT, RowLead}; +use crate::i18n::{tr, trf}; + +/// Width of the pen button's outline, in points +const PEN_BUTTON_OUTLINE_WIDTH: f32 = 1.0; + +impl PropertySheet<'_> { + /// [`Self::slider`] ending one link slot early so a band's rows line up, with the `pen` button in that slot; returns the edit and whether the pen was clicked (it flips `pen`) + pub(crate) fn pen_slider( + &mut self, + label: &str, + value: &mut f32, + range: RangeInclusive, + decimals: usize, + pen: Option<&mut bool>, + ) -> (Option, bool) { + let right = self.right; + self.right -= LINK_SLOT; + let edit = self.slider_led(RowLead::label(label), value, range, decimals, ""); + self.right = right; + let center = Pos2::new(right - LINK_SIZE / 2.0, self.cursor_y() - ROW_HEIGHT / 2.0); + let clicked = pen.is_some_and(|pressed| self.pen_button(center, label, pressed)); + (edit, clicked) + } + + /// The pen button: lit while pen pressure drives row `label`'s value + fn pen_button(&mut self, center: Pos2, label: &str, pressed: &mut bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.named_id("pen_pressure", label); + let response = self.ui.interact(rect, id, Sense::click()); + + let name = trf("{name} pen pressure", &[("name", &label)]); + let enabled = self.ui.is_enabled(); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, enabled, *pressed, &name)); + let response = self.tip(response, tr("Pen pressure")); + if response.clicked() { + *pressed = !*pressed; + } + + let tokens = self.tokens; + let (fill, border) = if *pressed { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(PEN_BUTTON_OUTLINE_WIDTH, border), StrokeKind::Inside); + painter.text(rect.center(), Align2::CENTER_CENTER, ic::PEN, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&response); + + response.clicked() + } +} diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index 2e740ff4..88d15966 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -19,7 +19,9 @@ type SectionReset = fn(&mut BrushSettings, &BrushSettings); /// Each band's title, a label shown only while it is open, whether it starts open, and its reset const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ - ("Size", "Minimum Size (%)", true, |brush, defaults| (brush.size, brush.min_size, brush.spacing) = (defaults.size, defaults.min_size, defaults.spacing)), + ("Size", "Minimum Size (%)", true, |brush, defaults| { + (brush.size, brush.size_pressure, brush.min_size, brush.spacing) = (defaults.size, defaults.size_pressure, defaults.min_size, defaults.spacing) + }), ("Opacity", "Stroke opacity", true, |brush, defaults| (brush.flow, brush.opacity) = (defaults.flow, defaults.opacity)), ("Orientation", "Follow Path", true, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), ("Jitter", "Size Jitter", true, |brush, defaults| { @@ -39,6 +41,7 @@ fn changed_brush() -> BrushSettings { BrushSettings { size: 0.1, min_size: 0.5, + size_pressure: false, screen_space: true, flow: 0.5, opacity: 0.6, @@ -179,7 +182,8 @@ fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { let defaults = BrushSettings::default(); let mut expected = changed_brush(); - (expected.size, expected.min_size, expected.spacing) = (defaults.size, defaults.min_size, defaults.spacing); + (expected.size, expected.size_pressure, expected.min_size, expected.spacing) = + (defaults.size, defaults.size_pressure, defaults.min_size, defaults.spacing); assert_eq!(harness.state().session.tool.brush, expected, "resetting Size with {key:?}"); } } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8440b902..4d9c1b36 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -95,6 +95,7 @@ mod shift_lines_3d; mod shortcut_keys; mod shortcut_list; mod side_panels; +mod size_pressure; mod skew_paint; mod smudge_channels; mod snapped_lines; diff --git a/crates/ui-egui/tests/it/size_pressure.rs b/crates/ui-egui/tests/it/size_pressure.rs new file mode 100644 index 00000000..9d6013c3 --- /dev/null +++ b/crates/ui-egui/tests/it/size_pressure.rs @@ -0,0 +1,47 @@ +//! The pen button on the paint tool's Size row turns pen pressure on Size on and off; Minimum Size only applies while it is on + +use egui::accesskit::{Role, Toggled}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Tall enough that the Size band shows without scrolling +const WINDOW: egui::Vec2 = egui::vec2(1600.0, 960.0); + +fn paint_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +fn pen_toggled(harness: &Harness<'_, TextureCraftApp>) -> Option { + harness.get_by_role_and_label(Role::CheckBox, "Size pen pressure").accesskit_node().toggled() +} + +/// Whether every Minimum Size slider node is greyed +fn minimum_size_greyed(harness: &Harness<'_, TextureCraftApp>) -> bool { + let sliders: Vec<_> = harness.get_all_by_label("Minimum Size (%)").filter(|node| node.accesskit_node().role() == Role::Slider).collect(); + assert!(!sliders.is_empty(), "Minimum Size has a slider"); + sliders.iter().all(|node| node.accesskit_node().is_disabled()) +} + +#[test] +fn the_pen_button_turns_size_pressure_off_and_greys_minimum_size() { + let mut harness = paint_harness(); + assert_eq!(pen_toggled(&harness), Some(Toggled::True), "a new brush follows the pen"); + assert!(!minimum_size_greyed(&harness)); + + harness.get_by_role_and_label(Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(!harness.state().session.tool.brush.size_pressure, "the click reached the brush"); + assert_eq!(pen_toggled(&harness), Some(Toggled::False)); + assert!(minimum_size_greyed(&harness), "Minimum Size does nothing without pen pressure"); +} From 161d09514abc52e50d53641d6ad4dc613c87977c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:57:50 +0000 Subject: [PATCH 133/190] Pick the brush alpha from a slot and shape it beside a picture of it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Alpha section's grid of tiles becomes one slot showing the alpha in use (thumbnail, name, kind). A click opens the resource picker with the built-in shapes, the library's alphas and the project's textures; the × goes back to the Round shape. An alpha or a texture dropped on the slot becomes the alpha. Parameters is a band: Hardness, Roundness (Round shape only), Size X and Size Y stack beside a live picture of the stamp they make, then Contrast and Invert. Text is a folded band in the sheet's rows. --- crates/ui-egui/src/alpha_choice.rs | 12 + crates/ui-egui/src/alpha_sheet.rs | 297 ++++++++++++++++++++ crates/ui-egui/src/brush_pictures.rs | 5 + crates/ui-egui/src/dock.rs | 152 +--------- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/resource_picker.rs | 6 +- crates/ui-egui/src/tile_picture.rs | 3 + crates/ui-egui/tests/it/alpha_parameters.rs | 11 +- crates/ui-egui/tests/it/alpha_slot.rs | 107 +++++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/view_mode_picker.rs | 26 +- 11 files changed, 449 insertions(+), 173 deletions(-) create mode 100644 crates/ui-egui/src/alpha_choice.rs create mode 100644 crates/ui-egui/src/alpha_sheet.rs create mode 100644 crates/ui-egui/tests/it/alpha_slot.rs diff --git a/crates/ui-egui/src/alpha_choice.rs b/crates/ui-egui/src/alpha_choice.rs new file mode 100644 index 00000000..234601d0 --- /dev/null +++ b/crates/ui-egui/src/alpha_choice.rs @@ -0,0 +1,12 @@ +//! What the brush Alpha slot's picker offers + +use texturecraft_engine::paint::BrushAlpha; + +/// One tile of the Alpha slot's picker: a built-in shape, a library alpha, an image resource, or importing one +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum AlphaChoice { + Shape(BrushAlpha), + Library(&'static str), + Image(String), + Import, +} diff --git a/crates/ui-egui/src/alpha_sheet.rs b/crates/ui-egui/src/alpha_sheet.rs new file mode 100644 index 00000000..1123b2b7 --- /dev/null +++ b/crates/ui-egui/src/alpha_sheet.rs @@ -0,0 +1,297 @@ +//! The Alpha section of a paint tool's Properties: the alpha's slot with its picker, its Parameters beside a picture of the shape they make, and the Text band + +use std::ops::RangeInclusive; + +use egui::{Color32, CornerRadius, Painter, Rect, Stroke, Ui, pos2}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::Session; +use texturecraft_engine::core::Channel; +use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; + +use crate::TextureCraftApp; +use crate::alpha_choice::AlphaChoice; +use crate::brush_pictures::alpha_image; +use crate::brush_stroke_preview::BrushStrokePreview; +use crate::i18n::{n_, tr}; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::theme::Tokens; +use crate::tile_picture::TilePicture; + +/// Hardness, Roundness and Size X / Y, in percent +const HARDNESS_PERCENT_RANGE: RangeInclusive = 0.0..=99.9; +const ROUNDNESS_PERCENT_RANGE: RangeInclusive = 0.0..=100.0; +const ALPHA_SIZE_PERCENT_RANGE: RangeInclusive = 5.0..=100.0; + +/// Rows the text box shows before it scrolls +const TEXT_ROWS: usize = 2; + +/// Air inside the text box, around its words +const TEXT_BOX_MARGIN: i8 = 6; + +/// Corner radius of the text box, as the sheet's fields +const TEXT_BOX_ROUNDING: u8 = 3; + +/// Width of the text box's outline +const TEXT_BOX_OUTLINE_WIDTH: f32 = 1.0; + +/// The Alpha section: the alpha's slot, its Parameters band and the Text band +pub(crate) fn alpha_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + alpha_slot(app, sheet); + parameters_band(app, sheet); + + if sheet.band(tr("Text"), false, None, None).open { + text_rows(app, sheet); + } +} + +/// The slot showing the alpha in use; a click opens the picker of shapes, library alphas and images, × goes back to the Round shape +fn alpha_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let ctx = sheet.ui.ctx().clone(); + let current = current_choice(&app.session); + let brush = &app.session.tool.brush; + let hardness = brush.hardness; + let (name, source, texture) = match ¤t { + AlphaChoice::Image(name) => { + let texture = app.session.images.get(name).map(|image| app.thumbs.image(&ctx, name, image)); + (name.clone(), tr("Imported image"), texture) + } + AlphaChoice::Library(id) => { + let alpha = alphas::find(id); + let texture = alpha.and_then(|alpha| app.thumbs.alpha(&ctx, alpha)); + (alpha.map_or_else(|| (*id).to_owned(), |alpha| tr(&alpha.label).to_owned()), tr("Library alpha"), texture) + } + AlphaChoice::Shape(_) | AlphaChoice::Import => (tr(brush.alpha.label()).to_owned(), tr("Built-in shape"), None), + }; + let shape = brush.alpha; + let thumbnail = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, Color32::BLACK); + match &texture { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + None => crate::thumbs::paint_alpha(painter, rect, shape, hardness), + } + }; + + // The default Round shape has nothing to clear back to + let clearable = current != AlphaChoice::Shape(BrushAlpha::default()); + let slot = sheet.slot(&thumbnail, &name, source, None, clearable, false); + + let popup = sheet.ui.make_persistent_id("brush_alpha_source"); + if slot.pick.clicked() { + resource_picker::toggle(&ctx, popup); + } + let tabs = || alpha_tabs(&app.session, hardness); + match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), true, tabs) { + Some(AlphaChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(choice) if choice != current => { + app.run("tool.brush", json!({ "alpha": alpha_value(&choice) })); + } + _ => {} + } + if slot.clear { + app.run("tool.brush", json!({ "alpha": BrushAlpha::default().label() })); + } + + // An alpha from the Assets panel, or an image, dropped on the slot becomes the alpha + crate::shelf::drop_target(app, sheet.ui, &slot.pick, crate::shelf::DropZone::Brush); + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("tool.brush", json!({ "alpha": { "image": name } })); + } + sheet.close_card(); +} + +/// The picker's choice the brush's alpha is +fn current_choice(session: &Session) -> AlphaChoice { + let brush = &session.tool.brush; + match (&brush.alpha_image, brush.alpha_library.as_deref().and_then(alphas::find)) { + (Some(name), _) => AlphaChoice::Image(name.clone()), + (None, Some(alpha)) => AlphaChoice::Library(alpha.id.as_str()), + (None, None) => AlphaChoice::Shape(brush.alpha), + } +} + +/// What `tool.brush` takes as `alpha` for `choice` +fn alpha_value(choice: &AlphaChoice) -> Value { + match choice { + AlphaChoice::Shape(shape) => json!(shape.label()), + AlphaChoice::Library(id) => json!({ "library": id }), + AlphaChoice::Image(name) => json!({ "image": name }), + AlphaChoice::Import => Value::Null, + } +} + +/// The picker's one tab: the built-in Shapes at the brush's `hardness`, the library's Alphas in their shelf groups, then Textures with Import... first +fn alpha_tabs(session: &Session, hardness: f32) -> Vec> { + let shapes = BrushAlpha::ALL + .into_iter() + .map(|shape| ResourcePickerItem { + id: AlphaChoice::Shape(shape), + label: tr(shape.label()).to_owned(), + caption: None, + picture: TilePicture::Shape(shape, hardness), + }) + .collect(); + let library = alphas::library() + .iter() + .map(|alpha| ResourcePickerItem { + id: AlphaChoice::Library(alpha.id.as_str()), + label: tr(&alpha.label).to_owned(), + caption: Some(tr(alpha.category)), + picture: TilePicture::Alpha(alpha), + }) + .collect(); + let textures = ResourcePickerItem::textures(session, AlphaChoice::Import, |name| AlphaChoice::Image(name.to_owned())); + let groups = [(n_("Shapes"), shapes), (n_("Alphas"), library), (n_("Textures"), textures)] + .into_iter() + .map(|(header, items)| PickerGroup { header: Some(tr(header)), items }) + .collect(); + vec![PickerTab { icon: ic::CIRCLE_HALF, name: tr("Alphas"), groups }] +} + +/// Hardness and the parameters every alpha shares beside the shape they make; the band's reset puts them all back +fn parameters_band(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let tokens = Tokens::get(sheet.ui.ctx()); + let image = app.session.tool.brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)).cloned(); + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); + let fields = |settings: &BrushSettings| (settings.hardness, settings.alpha_params); + let band = sheet.band(tr("Parameters"), true, Some(fields(brush) != fields(&defaults)), None); + if band.reset { + (brush.hardness, brush.alpha_params) = fields(&defaults); + } + if !band.open { + return; + } + + let shown = brush.clone(); + let ctx = sheet.ui.ctx().clone(); + let tint = tokens.text.to_array(); + let picture = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + BrushStrokePreview::paint_picture(&ctx, painter, rect, "brush_alpha_picture", (&shown, image.as_ref()), |_| [tint[0], tint[1], tint[2]], alpha_image); + }; + + // Only the procedural Round shape has a roundness + let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none(); + let before = [brush.hardness, brush.alpha_params.roundness, brush.alpha_params.size_x, brush.alpha_params.size_y].map(|fraction| fraction * 100.0); + let [mut hardness, mut roundness, mut size_x, mut size_y] = before; + let percent = |label: &'static str, value, range: RangeInclusive| StackSlider { + label: tr(label), + value, + range: range.clone(), + typed: range, + decimals: 0, + suffix: "", + dial: false, + }; + if round { + sheet.picture_sliders( + &picture, + &mut [ + percent(n_("Hardness"), &mut hardness, HARDNESS_PERCENT_RANGE), + percent(n_("Roundness"), &mut roundness, ROUNDNESS_PERCENT_RANGE), + percent(n_("Size X"), &mut size_x, ALPHA_SIZE_PERCENT_RANGE), + percent(n_("Size Y"), &mut size_y, ALPHA_SIZE_PERCENT_RANGE), + ], + ); + } else { + sheet.picture_sliders( + &picture, + &mut [ + percent(n_("Hardness"), &mut hardness, HARDNESS_PERCENT_RANGE), + percent(n_("Size X"), &mut size_x, ALPHA_SIZE_PERCENT_RANGE), + percent(n_("Size Y"), &mut size_y, ALPHA_SIZE_PERCENT_RANGE), + ], + ); + } + + // Only what moved is written back, so an untouched value keeps its exact fraction + for (after, was, fraction) in [ + (hardness, before[0], &mut brush.hardness), + (roundness, before[1], &mut brush.alpha_params.roundness), + (size_x, before[2], &mut brush.alpha_params.size_x), + (size_y, before[3], &mut brush.alpha_params.size_y), + ] { + if after != was { + *fraction = after / 100.0; + } + } + sheet.slider(tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2); + sheet.toggle(tr("Invert"), &mut brush.alpha_params.invert); + *brush = brush.sanitized(); +} + +/// Text drawn in a font, as the brush alpha or a decal (`resource.text`) +fn text_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + if app.ui.text.fonts.is_empty() + && let Some(fonts) = app.run("text.fonts", Value::Null) + { + let installed = fonts["installed"].as_array().into_iter().flatten().map(|font| { + let styles = font["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + (font["family"].as_str().unwrap_or_default().to_string(), styles) + }); + let built_in = fonts["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|name| (name.to_string(), Vec::new())); + app.ui.text.fonts = installed.chain(built_in).collect(); + } + + // A decal shows the text in the tool's base color; an alpha must stay white + let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]); + let tokens = Tokens::get(sheet.ui.ctx()); + let text = &mut app.ui.text; + sheet.embed(|ui: &mut Ui| { + let frame = egui::Frame::NONE + .fill(tokens.field) + .stroke(Stroke::new(TEXT_BOX_OUTLINE_WIDTH, tokens.field_border)) + .corner_radius(CornerRadius::same(TEXT_BOX_ROUNDING)) + .inner_margin(egui::Margin::same(TEXT_BOX_MARGIN)); + frame.show(ui, |ui| { + let edit = + egui::TextEdit::multiline(&mut text.text).frame(egui::Frame::NONE).desired_rows(TEXT_ROWS).desired_width(f32::INFINITY).hint_text(tr("Text")); + ui.add(edit); + }); + }); + + // Index 0 is the default font, then the families in the order `text.fonts` lists them + let family = text.fonts.iter().position(|(family, _)| *family == text.font).map_or(0, |index| index + 1); + let family_name = |index: usize| if index == 0 { tr("Default").to_owned() } else { text.fonts[index - 1].0.clone() }; + let (picked, _) = sheet.dropdown_built(tr("Font"), family, || 0..=text.fonts.len(), family_name, None); + if let Some(index) = picked { + text.font = if index == 0 { String::new() } else { text.fonts[index - 1].0.clone() }; + text.style = String::new(); + } + + let styles = text.fonts.iter().find(|(family, _)| *family == text.font).map(|(_, styles)| styles.clone()).unwrap_or_default(); + if styles.len() > 1 { + let style = styles.iter().position(|style| *style == text.style).map_or(0, |index| index + 1); + let style_name = |index: usize| if index == 0 { tr("Default").to_owned() } else { styles[index - 1].clone() }; + let (picked, _) = sheet.dropdown_built(tr("Style"), style, || 0..=styles.len(), style_name, None); + if let Some(index) = picked { + text.style = if index == 0 { String::new() } else { styles[index - 1].clone() }; + } + } + + let mut params = + json!({"text": text.text, "font": (!text.font.is_empty()).then_some(&text.font), "style": (!text.style.is_empty()).then_some(&text.style)}); + let ready = !text.text.trim().is_empty(); + let alpha = sheet.button_enabled(ic::CIRCLE_HALF, tr("Use as brush alpha"), false, ready).clicked(); + let decal = sheet.button_enabled(ic::STAMP, tr("Place as decal"), false, ready).clicked(); + if decal { + params["color"] = json!(color); + } + if (alpha || decal) + && let Some(name) = app.run("resource.text", params).and_then(|result| result["name"].as_str().map(str::to_string)) + { + if alpha { + app.run("tool.brush", json!({"alpha": {"image": name}})); + } else { + app.run("layer.add.decal", json!({"image": name})); + } + } +} diff --git a/crates/ui-egui/src/brush_pictures.rs b/crates/ui-egui/src/brush_pictures.rs index 1f8fbbef..a4f09487 100644 --- a/crates/ui-egui/src/brush_pictures.rs +++ b/crates/ui-egui/src/brush_pictures.rs @@ -45,6 +45,11 @@ pub(crate) fn stamp_image(brush: &BrushSettings, image: Option<&ImageRes>, size: stroke_strip(&still, image, size, |_| radius, |_| center, |x| column_tint(tints, x)) } +/// The brush's alpha as its Parameters shape it, upright: the Alpha section's Parameters picture +pub(crate) fn alpha_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + stamp_image(&BrushSettings { angle: 0.0, ..brush.clone() }, image, size, pixels_per_point, tints) +} + /// A row of the brush's dabs across a `size` strip, scattered by its four jitters; dabs shrink as Position Jitter grows so the scatter stays inside pub(crate) fn jitter_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], _pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { let spaced = BrushSettings { spacing: brush.spacing.max(STRIP_DAB_SPACING), follow_path: false, flow: 1.0, opacity: 1.0, ..brush.clone() }; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ffe7769b..20e146e1 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -8,8 +8,6 @@ use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, }; -use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; -use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::texel::linear_to_srgb; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; @@ -23,7 +21,7 @@ use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; use crate::source_choice::SourceChoice; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -2130,7 +2128,7 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let menu = sheet.section(section.title(), section == PaintSection::Brush); match section { PaintSection::Brush => crate::brush_sheet::brush_section(app, sheet, menu), - PaintSection::Alpha => legacy(sheet, app, alpha_section), + PaintSection::Alpha => crate::alpha_sheet::alpha_section(app, sheet), PaintSection::Stencil => legacy(sheet, app, stencil_section), PaintSection::Material => legacy(sheet, app, material_controls), PaintSection::Grayscale => crate::mask_paint_panel::grayscale_section(app, sheet), @@ -2367,152 +2365,6 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { } } -/// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. -fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Painter, Rect)) -> egui::Response { - let tk = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(vec2(52.0, 64.0), Sense::click()); - let p = ui.painter(); - p.rect_filled(rect, 3.0, tk.viewport); - if on { - p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } - paint(p, Rect::from_center_size(rect.center() - vec2(0.0, 7.0), vec2(40.0, 40.0))); - let name = elided(p, label, 9.5, tk.viewport_text, rect.width() - 4.0); - p.galley(rect.center_bottom() - vec2(name.size().x * 0.5, 6.0 + name.size().y * 0.5), name, tk.viewport_text); - resp.on_hover_text(label) -} - -fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - import_button(app, ui); - let brush = &app.session.tool.brush; - let (current, image, hardness) = (brush.alpha, brush.alpha_image.clone(), brush.hardness); - let library = if image.is_none() { brush.alpha_library.as_deref().and_then(alphas::find) } else { None }; - let mut pick = None; - let zone = ui.horizontal_wrapped(|ui| { - for a in BrushAlpha::ALL { - let on = image.is_none() && library.is_none() && current == a; - if alpha_tile(ui, on, tr(a.label()), |p, r| crate::thumbs::paint_alpha(p, r, a, hardness)).clicked() { - pick = Some(json!(a.label())); - } - } - - // The library alpha in use (picked from the shelf's Alphas tab) - if let Some(a) = library { - let tex = app.thumbs.alpha(ui.ctx(), a); - alpha_tile(ui, true, &a.label, |p, r| { - if let Some(t) = tex { - p.image(t.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } - }); - } - - // Imported images, sampled as grayscale - for name in app.session.doc.resources.keys() { - let Some(img) = app.session.images.get(name) else { continue }; - let tex = app.thumbs.image(ui.ctx(), name, img); - let on = image.as_deref() == Some(name.as_str()); - if alpha_tile(ui, on, name, |p, r| { - p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - }) - .clicked() - { - pick = Some(json!({ "image": name })); - } - } - }); - if let Some(alpha) = pick { - app.run("tool.brush", json!({ "alpha": alpha })); - } - ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim)); - crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush); - alpha_parameters(&mut app.session.tool.brush, ui); - section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui)); -} - -/// Hardness and the parameters every alpha shares, under a header whose reset puts them back -fn alpha_parameters(brush: &mut BrushSettings, ui: &mut Ui) { - let defaults = BrushSettings::default(); - let at_defaults = brush.hardness == defaults.hardness && brush.alpha_params == defaults.alpha_params; - let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none(); - let percent_slider = |ui: &mut Ui, label: &str, value: &mut f32, min: f32, max: f32| { - let mut percent = *value * 100.0; - if slider(ui, label, &mut percent, min..=max, 0).changed() { - *value = percent / 100.0; - } - }; - - let reset = section_with_reset(ui, "sec_alpha_params", tr("Parameters"), true, at_defaults, |ui| { - percent_slider(ui, tr("Hardness"), &mut brush.hardness, 0.0, 99.9); - percent_slider(ui, tr("Size X"), &mut brush.alpha_params.size_x, 5.0, 100.0); - percent_slider(ui, tr("Size Y"), &mut brush.alpha_params.size_y, 5.0, 100.0); - - // Only the procedural Round shape has a roundness - ui.add_enabled_ui(round, |ui| percent_slider(ui, tr("Roundness"), &mut brush.alpha_params.roundness, 0.0, 100.0)); - slider(ui, tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2); - ui.checkbox(&mut brush.alpha_params.invert, tr("Invert")); - }); - if reset { - (brush.hardness, brush.alpha_params) = (defaults.hardness, defaults.alpha_params); - } - *brush = brush.sanitized(); -} - -/// Text drawn in a font, as the brush alpha or a decal (`resource.text`). -fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { - if app.ui.text.fonts.is_empty() - && let Some(f) = app.run("text.fonts", Value::Null) - { - let installed = f["installed"].as_array().into_iter().flatten().map(|v| { - let styles = v["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); - (v["family"].as_str().unwrap_or_default().to_string(), styles) - }); - let built_in = f["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), Vec::new())); - app.ui.text.fonts = installed.chain(built_in).collect(); - } - // A decal shows the text in the tool's base color; an alpha must stay white. - let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]); - let t = &mut app.ui.text; - ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(2).desired_width(f32::INFINITY).hint_text(tr("Text"))); - let shown = if t.font.is_empty() { tr("Default").to_string() } else { t.font.clone() }; - combo(ui, tr("Font"), shown, |ui| { - if ui.selectable_label(t.font.is_empty(), tr("Default")).clicked() { - (t.font, t.style) = (String::new(), String::new()); - } - for (family, _) in &t.fonts { - if ui.selectable_label(t.font == *family, family).clicked() { - (t.font, t.style) = (family.clone(), String::new()); - } - } - }); - let styles = t.fonts.iter().find(|(f, _)| *f == t.font).map(|(_, s)| s.clone()).unwrap_or_default(); - if styles.len() > 1 { - let shown = if t.style.is_empty() { tr("Default").to_string() } else { t.style.clone() }; - combo(ui, tr("Style"), shown, |ui| { - for s in styles { - ui.selectable_value(&mut t.style, s.clone(), s); - } - }); - } - let mut params = json!({"text": t.text, "font": (!t.font.is_empty()).then_some(&t.font), "style": (!t.style.is_empty()).then_some(&t.style)}); - let ready = !t.text.trim().is_empty(); - ui.horizontal_wrapped(|ui| { - let alpha = ui.add_enabled(ready, egui::Button::new(tr("Use as brush alpha"))).clicked(); - let decal = ui.add_enabled(ready, egui::Button::new(tr("Place as decal"))).clicked(); - if decal { - params["color"] = json!(color); - } - if (alpha || decal) - && let Some(name) = app.run("resource.text", params).and_then(|r| r["name"].as_str().map(str::to_string)) - { - match alpha { - true => app.run("tool.brush", json!({"alpha": {"image": name}})), - false => app.run("layer.add.decal", json!({"image": name})), - }; - } - }); -} - /// Tooltip of the material channel chips. pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 61f2ae64..bd9817e5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,6 +7,8 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod alpha_choice; +mod alpha_sheet; mod anchor_properties; mod angle_dial; mod ask; diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index 8c970158..85e34e5e 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -395,7 +395,7 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz TilePicture::Image(name, image) => Some(thumbs.image(ui.ctx(), name, image)), TilePicture::Procedural(kind) => thumbs.procedural(ui.ctx(), *kind), TilePicture::Generator(kind) => thumbs.generator(ui.ctx(), *kind), - TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, + TilePicture::Shape(..) | TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, }; match (&item.picture, texture) { @@ -419,6 +419,10 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz tokens.text_dim.gamma_multiply(LOADING_GLYPH_OPACITY), ); } + (TilePicture::Shape(alpha, hardness), None) => { + painter.rect_filled(picture, rounding, Color32::BLACK); + crate::thumbs::paint_alpha(painter, picture, *alpha, *hardness); + } (TilePicture::Swatch(color), None) => { painter.rect_filled(picture, rounding, *color); } diff --git a/crates/ui-egui/src/tile_picture.rs b/crates/ui-egui/src/tile_picture.rs index d031e666..3a0f955e 100644 --- a/crates/ui-egui/src/tile_picture.rs +++ b/crates/ui-egui/src/tile_picture.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use egui::Color32; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; +use texturecraft_engine::paint::BrushAlpha; use texturecraft_engine::paint::alphas::LibraryAlpha; /// A tile's picture source. Previews are requested only when its tile is drawn. @@ -12,6 +13,8 @@ pub(crate) enum TilePicture { Material(&'static str), Filter(&'static str), Alpha(&'static LibraryAlpha), + /// A built-in brush shape at a hardness, drawn as the shape tiles of the old alpha grid were + Shape(BrushAlpha, f32), Image(String, Arc), Procedural(ProceduralKind), /// A mask generator at its defaults on the smart masks' orb, a die in its corner when a seed changes its result diff --git a/crates/ui-egui/tests/it/alpha_parameters.rs b/crates/ui-egui/tests/it/alpha_parameters.rs index cdaa7a53..394a135d 100644 --- a/crates/ui-egui/tests/it/alpha_parameters.rs +++ b/crates/ui-egui/tests/it/alpha_parameters.rs @@ -28,8 +28,13 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { harness } +/// The reset on the Parameters band's row fn restore_defaults<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'tree> { - harness.get_by_role_and_label(egui::Role::Button, "Parameters: Reset to defaults") + let band = harness.get_by_role_and_label(egui::Role::Button, "Parameters").rect(); + harness + .query_all_by_role_and_label(egui::Role::Button, "Restore defaults") + .find(|node| node.rect().y_range().intersects(band.y_range())) + .unwrap_or_else(|| panic!("no reset on the Parameters band")) } fn invert_checkbox<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> Option> { @@ -89,8 +94,8 @@ fn hardness_left_the_brush_tab_and_its_reset() { let harness = app_with_brush(BrushSettings::default()); // One page: the Brush section comes first, Hardness only in the Alpha section under it - let hardness: Vec<_> = harness.get_all_by_label("Hardness").map(|node| node.rect().top()).collect(); - let flow = harness.get_by_label("Flow").rect().top(); + let hardness: Vec<_> = harness.query_all_by_role_and_label(egui::Role::Slider, "Hardness").map(|node| node.rect().top()).collect(); + let flow = harness.get_by_role_and_label(egui::Role::Slider, "Flow").rect().top(); assert_eq!(hardness.len(), 1, "Hardness is in the Alpha section alone"); assert!(hardness[0] > flow, "the Alpha section follows the Brush section's Flow"); } diff --git a/crates/ui-egui/tests/it/alpha_slot.rs b/crates/ui-egui/tests/it/alpha_slot.rs new file mode 100644 index 00000000..0093e077 --- /dev/null +++ b/crates/ui-egui/tests/it/alpha_slot.rs @@ -0,0 +1,107 @@ +//! The Alpha section's slot: its picker sets the brush alpha, × goes back to the Round shape, and Roundness shows only for the Round shape + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_widget}; + +/// Window the Alpha section tests run in +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Frames after a click in the slot, more than the crate's SETTLE_FRAMES to leave the alpha picker's popup time to open or close +const SLOT_CLICK_FRAMES: usize = 6; + +/// Frames for the jump tab's animated scroll to settle +const SCROLL_FRAMES: usize = 60; + +/// The app showing the Alpha section of Properties, with `brush` +fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().session.tool.brush = brush; + harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(Role::Tab, "Alpha").click(); + harness.run_steps(SCROLL_FRAMES); + harness +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + click_widget(harness, role, label); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +/// The × of the slot showing `slot`: the Clear button on its row +fn click_clear(harness: &mut Harness<'_, TextureCraftApp>, slot: &str) { + let row = harness.get_by_role_and_label(Role::ComboBox, slot).rect(); + let clear = harness + .query_all_by_role_and_label(Role::Button, "Clear") + .find(|node| node.rect().y_range().intersects(row.y_range())) + .unwrap_or_else(|| panic!("no Clear on the {slot} slot")) + .rect(); + super::click_at(harness, clear.center()); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +/// Clicks the built-in shape `label`: the Shapes come first, above a library alpha of the same name +fn click_shape(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + let tile = harness + .query_all_by_role_and_label(Role::ListBoxOption, label) + .map(|node| node.rect()) + .min_by(|a, b| a.top().total_cmp(&b.top())) + .unwrap_or_else(|| panic!("no {label} tile")); + super::click_at(harness, tile.center()); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +#[test] +fn the_slot_picks_a_shape_and_its_clear_goes_back_to_round() { + let mut harness = app_with_brush(BrushSettings::default()); + let row = harness.get_by_role_and_label(Role::ComboBox, "Round").rect(); + assert!( + !harness.query_all_by_role_and_label(Role::Button, "Clear").any(|node| node.rect().y_range().intersects(row.y_range())), + "the Round shape has nothing to clear back to" + ); + + click(&mut harness, Role::ComboBox, "Round"); + click_shape(&mut harness, "Star"); + assert_eq!(harness.state().session.tool.brush.alpha, BrushAlpha::Star); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Star").is_some(), "the slot shows the picked shape"); + + click_clear(&mut harness, "Star"); + assert_eq!(harness.state().session.tool.brush.alpha, BrushAlpha::Round); +} + +#[test] +fn the_picker_offers_the_library_alphas() { + // Any library alpha + let alpha = &alphas::library()[0]; + let mut harness = app_with_brush(BrushSettings::default()); + + click(&mut harness, Role::ComboBox, "Round"); + harness.event(egui::Event::Text(alpha.label.clone())); + harness.run_steps(SLOT_CLICK_FRAMES); + click(&mut harness, Role::ListBoxOption, &alpha.label); + + let brush = &harness.state().session.tool.brush; + assert_eq!(brush.alpha_library.as_deref(), Some(alpha.id.as_str())); + assert!(harness.query_by_role_and_label(Role::ComboBox, &alpha.label).is_some(), "the slot shows the library alpha"); +} + +#[test] +fn roundness_shows_only_for_the_round_shape() { + let roundness = |harness: &Harness<'_, TextureCraftApp>| harness.query_all_by_role_and_label(Role::Slider, "Roundness").count(); + + let round = app_with_brush(BrushSettings::default()); + assert_eq!(roundness(&round), 1, "the Round shape has a roundness"); + + let star = app_with_brush(BrushSettings { alpha: BrushAlpha::Star, ..BrushSettings::default() }); + assert_eq!(roundness(&star), 0, "other alphas have none"); + assert_eq!(star.query_all_by_role_and_label(Role::Slider, "Hardness").count(), 1, "the rest of the Parameters stay"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 4d9c1b36..0d68818b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. mod alpha_parameters; +mod alpha_slot; mod anchor_point; mod bake_job_mesh; mod bake_live_preview; diff --git a/crates/ui-egui/tests/it/view_mode_picker.rs b/crates/ui-egui/tests/it/view_mode_picker.rs index ff447c16..56619e08 100644 --- a/crates/ui-egui/tests/it/view_mode_picker.rs +++ b/crates/ui-egui/tests/it/view_mode_picker.rs @@ -22,23 +22,11 @@ fn picker<'a>(h: &'a Harness<'_, TextureCraftApp>, value: &str) -> egui_kittest: h.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(value)).unwrap_or_else(|| panic!("a view picker showing {value}")) } -/// The nodes labelled `label` left of the Properties panel, whose paint tool sections also tile every image as an alpha -fn listed<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> Vec> { - let properties = h.get_by_role_and_label(Role::Tab, "Properties - Paint").rect().left(); - h.get_all_by_label(label).filter(|node| node.rect().center().x < properties).collect() -} - -fn one_listed<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { - let mut nodes = listed(h, label); - assert_eq!(nodes.len(), 1, "one {label} listed"); - nodes.remove(0) -} - /// Clicks the entry `label` of the open list (a long list scrolls inside the viewport's height) fn pick(h: &mut Harness<'_, TextureCraftApp>, label: &str) { - one_listed(h, label).scroll_to_me(); + h.get_by_label(label).scroll_to_me(); h.run_steps(12); - one_listed(h, label).click(); + h.get_by_label(label).click(); h.run_steps(3); } @@ -77,7 +65,7 @@ fn other_opens_an_image_picker_and_shows_the_chosen_image() { query_field(&h); h.get_by_label("reset query to default"); - one_listed(&h, &name).click(); + h.get_by_label(&name).click(); h.run_steps(3); assert_eq!(h.state().session.view, ViewMode::Image); @@ -93,19 +81,19 @@ fn the_image_picker_filters_by_name_and_the_reset_button_restores_the_query() { h.run_steps(3); open(&mut h, "Material"); pick(&mut h, "Other..."); - assert!(!listed(&h, &first).is_empty() && !listed(&h, &second).is_empty(), "the default query lists every image"); + assert!(h.query_by_label(&first).is_some() && h.query_by_label(&second).is_some(), "the default query lists every image"); let field = query_field(&h); field.click(); field.type_text(" stone"); h.run_steps(3); - assert!(listed(&h, &second).is_empty(), "{second} does not match"); - assert!(!listed(&h, &first).is_empty()); + assert!(h.query_by_label(&second).is_none(), "{second} does not match"); + assert!(h.query_by_label(&first).is_some()); h.get_by_label("reset query to default").click(); h.run_steps(3); query_field(&h); - assert!(!listed(&h, &second).is_empty(), "the reset lists every image again"); + assert!(h.query_by_label(&second).is_some(), "the reset lists every image again"); } #[test] From 44dceb6059dcad3e5f8c51fd29534e328ca33950 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:29:16 +0000 Subject: [PATCH 134/190] Paint every brush tool's strokes through the stencil, set in a Stencil tab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The stencil now shapes Paint, Eraser, Smudge and Clone strokes as well as Projection ones: its gray times its alpha masks the stroke, read from the viewport's point of view, and the tool keeps painting its own material. Only the Projection tool paints the image's colors. In the 2D view, where the stencil isn't drawn, only the Projection tool uses it, as before. The viewport shows the stencil and S + drag places it for every brush tool. Every brush tool gets the Stencil tab. Its section is a slot showing the stencil image (a click opens the picker of the project's textures with Import... first, × takes the stencil away, an image dropped on it becomes the stencil; the S-drag keys are its tooltip), a Tiling mode list (No Tiling, H and V Tiling) with a picture per mode, Scale, Rotation and Position X / Y stacked beside a picture of the view with the stencil placed in it, and Overlay opacity. The STENCIL caption's reset puts the stencil back in the middle of the view. The sliders change it through tool.stencil. --- crates/compose/src/eval.rs | 153 +++++++++----- crates/engine/src/painting.rs | 72 ++++--- crates/engine/src/session.rs | 10 +- crates/engine/src/tool_cmds.rs | 10 +- crates/engine/tests/session.rs | 85 ++++++++ crates/paint/src/commit.rs | 33 ++- crates/ui-egui/src/dock.rs | 67 +----- crates/ui-egui/src/keymap.rs | 8 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/stencil_choice.rs | 8 + crates/ui-egui/src/stencil_sheet.rs | 229 +++++++++++++++++++++ crates/ui-egui/src/viewport.rs | 34 +-- crates/ui-egui/tests/it/paint_tool_tabs.rs | 14 +- crates/ui-egui/tests/it/stencil.rs | 66 ++++-- crates/ui-egui/tests/it/user_smart_mask.rs | 8 +- crates/ui-egui/tests/ui_snapshots.rs | 9 + docs/features.md | 4 +- 17 files changed, 595 insertions(+), 217 deletions(-) create mode 100644 crates/ui-egui/src/stencil_choice.rs create mode 100644 crates/ui-egui/src/stencil_sheet.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 52184129..0cbc6e4d 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -82,39 +82,66 @@ pub enum PaintTarget { Mask(LayerId), } -/// A screen-pinned image painted through the camera (projection tool / stencil). +/// Smallest clip w a stencil paints at and smallest half extent it divides by +const STENCIL_EPSILON: f32 = 1e-6; + +/// Rec. 709 red, green and blue weights of a gray's luminance +const REC709_LUMINANCE_WEIGHTS: [f32; 3] = [0.2126, 0.7152, 0.0722]; + +/// A screen-pinned image every brush tool paints through #[derive(Clone, Debug)] pub struct Stencil { pub image: std::sync::Arc, - /// Camera view-projection captured when the stroke started. + /// Camera view-projection captured when the stroke started pub view_proj: texturecraft_geom::glam::Mat4, - /// Image placement in normalized device coordinates: center, half extents, rotation. + /// Image placement in normalized device coordinates: center, half extents, rotation pub center: [f32; 2], pub half: [f32; 2], pub rotation: f32, - /// Repeat the image beyond its bounds (otherwise nothing is painted outside it). + /// Repeat the image beyond its bounds (otherwise nothing is painted outside it) pub tile: bool, + /// The Projection tool paints the image's colors; every other tool paints through its gray + pub colors: bool, } impl Stencil { - /// Linear color and alpha of the stencil at world point `p` (None outside the image). - pub fn sample_world(&self, p: Vec3) -> Option<([f32; 3], f32)> { - let c = self.view_proj * p.extend(1.0); - if c.w <= 1e-6 { + /// Linear color and alpha of the stencil at world point `point` (None outside the image) + pub fn sample_world(&self, point: Vec3) -> Option<([f32; 3], f32)> { + let sample = self.sample_raw(point)?; + let rgb = [sample[0], sample[1], sample[2]]; + let rgb = if self.image.srgb { rgb.map(texturecraft_texel::srgb_to_linear) } else { rgb }; + Some((rgb, sample[3].clamp(0.0, 1.0))) + } + + /// How much paint passes at world point `point` when the stencil masks a stroke: its gray times its alpha, read as stored like a brush alpha image (0 outside the image) + pub fn mask_world(&self, point: Vec3) -> f32 { + let Some([red, green, blue, alpha]) = self.sample_raw(point) else { return 0.0 }; + let [red_weight, green_weight, blue_weight] = REC709_LUMINANCE_WEIGHTS; + ((red_weight * red + green_weight * green + blue_weight * blue) * alpha).clamp(0.0, 1.0) + } + + /// The paint a stroke receives at world point `point`: the stencil's color (Projection only) and the factor scaling the stroke there, None where nothing is painted + pub fn paint_world(&self, point: Vec3) -> Option<(Option<[f32; 3]>, f32)> { + if self.colors { self.sample_world(point).map(|(color, alpha)| (Some(color), alpha)) } else { Some((None, self.mask_world(point))) } + } + + /// The stored image value under world point `point` (None outside the image) + fn sample_raw(&self, point: Vec3) -> Option<[f32; 4]> { + let clip = self.view_proj * point.extend(1.0); + if clip.w <= STENCIL_EPSILON { return None; } - let (dx, dy) = (c.x / c.w - self.center[0], c.y / c.w - self.center[1]); - let (sn, cs) = (-self.rotation).sin_cos(); - let lx = (dx * cs - dy * sn) / self.half[0].max(1e-6); - let ly = (dx * sn + dy * cs) / self.half[1].max(1e-6); - if !self.tile && (lx.abs() > 1.0 || ly.abs() > 1.0) { + let offset_x = clip.x / clip.w - self.center[0]; + let offset_y = clip.y / clip.w - self.center[1]; + let (sine, cosine) = (-self.rotation).sin_cos(); + let local_x = (offset_x * cosine - offset_y * sine) / self.half[0].max(STENCIL_EPSILON); + let local_y = (offset_x * sine + offset_y * cosine) / self.half[1].max(STENCIL_EPSILON); + if !self.tile && (local_x.abs() > 1.0 || local_y.abs() > 1.0) { return None; } - let s = self.image.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5); - let rgb = if self.image.srgb { [s[0], s[1], s[2]].map(texturecraft_texel::srgb_to_linear) } else { [s[0], s[1], s[2]] }; - Some((rgb, s[3].clamp(0.0, 1.0))) + Some(self.image.sample(local_x * 0.5 + 0.5, 0.5 - local_y * 0.5)) } } @@ -3897,7 +3924,7 @@ impl<'a, 'b> Texel<'a, 'b> { self.mask_effects(plan, value, skip, plan.effects.len()) } - /// Mask effects `from..to` of `plan` over `value`, recording the anchors among them. + /// Mask effects `from..to` of `plan` over `value`, recording the anchors among them fn mask_effects(&mut self, plan: &MaskPlan, mut value: f32, from: usize, to: usize) -> f32 { // Avoid amplifying rounding error when unpremultiplying faint paint const MIN_PAINT_COVERAGE: f32 = 1e-5; @@ -3915,10 +3942,19 @@ impl<'a, 'b> Texel<'a, 'b> { Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; + if effect.preview && let Some(preview) = self.inp.preview { - let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + let mut stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + + // The stencil shapes the stroke as the commit does + if let Some(stencil) = preview.stencil.as_ref() + && stroke > 0.0 + { + stroke *= self.world().and_then(|world| stencil.paint_world(world)).map_or(0.0, |(_, factor)| factor); + } + if preview.erase { painted *= 1.0 - stroke; coverage *= 1.0 - stroke; @@ -3932,6 +3968,7 @@ impl<'a, 'b> Texel<'a, 'b> { coverage = stroke + coverage * (1.0 - stroke); } } + if coverage > 0.0 { let layer_value = painted / coverage.max(MIN_PAINT_COVERAGE); value += (blend1(effect.blend, value, layer_value) - value) * coverage * opacity; @@ -4271,62 +4308,66 @@ impl<'a, 'b> Texel<'a, 'b> { (coverage > 0.0).then_some((value, coverage.min(1.0))) } - /// Straight value and coverage of painted data of one channel (premultiplied values plus - /// coverage per texel), with the live stroke when `preview`. - fn painted(&mut self, data: Option<&[u16]>, c: &ChanPlan, preview: bool) -> ([f32; 3], f32) { - let pv = if preview { self.inp.preview } else { None }; - let mut sa = pv.map(|p| (self.stroke * p.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); + /// Straight value and coverage of one channel's painted data (premultiplied values plus coverage per texel), with the live stroke when `preview` + fn painted(&mut self, data: Option<&[u16]>, chan_plan: &ChanPlan, preview: bool) -> ([f32; 3], f32) { + // Coverage floor the premultiplied value is divided by + const MIN_COVERAGE: f32 = 1e-5; - // Projection: the stencil's alpha shapes the stroke and its color is the base color - let stencil = match pv.and_then(|p| p.stencil.as_ref()) { - Some(st) if sa > 0.0 => { - let s = self.world().and_then(|w| st.sample_world(w)); - sa *= s.map(|(_, a)| a).unwrap_or(0.0); - s.map(|(c, _)| c) + let stroke_preview = if preview { self.inp.preview } else { None }; + let mut stroke_alpha = stroke_preview.map(|stroke| (self.stroke * stroke.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); + + // The stencil shapes the stroke; on the Projection tool its color is the base color + let stencil_color = match stroke_preview.and_then(|stroke| stroke.stencil.as_ref()) { + Some(stencil) if stroke_alpha > 0.0 => { + let stencil_paint = self.world().and_then(|world| stencil.paint_world(world)); + stroke_alpha *= stencil_paint.map(|(_, factor)| factor).unwrap_or(0.0); + stencil_paint.and_then(|(color, _)| color) } _ => None, }; - let mut val = [0.0f32; 3]; - let mut cov = 0.0f32; - if let Some(d) = data { - let base = self.o * (c.comps + 1); - for (k, slot) in val.iter_mut().take(c.comps).enumerate() { - *slot = decode(c.kind, d.get(base + k).copied().unwrap_or(0)); + + let mut value = [0.0f32; 3]; + let mut coverage = 0.0f32; + if let Some(texels) = data { + let base = self.o * (chan_plan.comps + 1); + for (component, slot) in value.iter_mut().take(chan_plan.comps).enumerate() { + *slot = decode(chan_plan.kind, texels.get(base + component).copied().unwrap_or(0)); } - cov = from_u16(d.get(base + c.comps).copied().unwrap_or(0)); + coverage = from_u16(texels.get(base + chan_plan.comps).copied().unwrap_or(0)); } - if let Some(p) = pv - && sa > 0.0 + + if let Some(stroke) = stroke_preview + && stroke_alpha > 0.0 { - if p.erase { - val = val.map(|v| v * (1.0 - sa)); - cov *= 1.0 - sa; - } else if let Some(ch) = Channel::ALL.get(c.ch) - && let Some(pval) = p.values.get(ch) + if stroke.erase { + value = value.map(|component| component * (1.0 - stroke_alpha)); + coverage *= 1.0 - stroke_alpha; + } else if let Some(channel) = Channel::ALL.get(chan_plan.ch) + && let Some(stroke_value) = stroke.values.get(channel) { - let pval = match stencil { - Some(col) if *ch == Channel::BaseColor => col, - _ => match p.carried.get(ch) { - Some(img) => { - let raw = img.get(self.x, self.y).map(|v| decode(c.kind, v)); + let stroke_value = match stencil_color { + Some(color) if *channel == Channel::BaseColor => color, + _ => match stroke.carried.get(channel) { + Some(carried) => { + let raw = carried.get(self.x, self.y).map(|stored| decode(chan_plan.kind, stored)); [raw[0], raw[1], raw[2]] } - None => *pval, + None => *stroke_value, }, }; - for k in 0..c.comps { - val[k] = pval[k] * sa + val[k] * (1.0 - sa); + for component in 0..chan_plan.comps { + value[component] = stroke_value[component] * stroke_alpha + value[component] * (1.0 - stroke_alpha); } - cov = sa + cov * (1.0 - sa); + coverage = stroke_alpha + coverage * (1.0 - stroke_alpha); } } - if cov <= 0.0 { + if coverage <= 0.0 { return ([0.0; 3], 0.0); } - let inv = 1.0 / cov.max(1e-5); - let v = if c.comps == 3 { val.map(|x| x * inv) } else { [val[0] * inv; 3] }; - (v, cov.min(1.0)) + let inverse_coverage = 1.0 / coverage.max(MIN_COVERAGE); + let straight = if chan_plan.comps == 3 { value.map(|component| component * inverse_coverage) } else { [value[0] * inverse_coverage; 3] }; + (straight, coverage.min(1.0)) } /// Apply one content effect to a channel's straight value and coverage diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 859a2f64..a2207744 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -217,15 +217,17 @@ impl Session { .collect() } - /// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh - /// (the Clone tool's destination anchor). + /// Common setup of 3D and 2D strokes, `first_uv` being where the stroke starts on the mesh (the Clone tool's destination anchor) fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option) -> Result<()> { + // Texture size a stroke paints at before the texture set has a cache + const FALLBACK_TEXTURE_SIZE: (u32, u32) = (1024, 1024); + self.refuse_while_baking()?; let tool = self.tool.tool; let erase = tool == Tool::Eraser; let quick_mask = self.quick_mask.editing; let ts = self.ts(); - let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); + let size = self.caches.get(ts).map_or(FALLBACK_TEXTURE_SIZE, |cache| cache.size); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; let composite_pickup = tool == Tool::Smudge || (tool == Tool::Clone && self.tool.clone_from == CloneFrom::Composite); if pickup.is_some() && composite_pickup && !self.paints_mask() && self.solo.is_none() { @@ -240,26 +242,30 @@ impl Session { } _ => None, }; + let before = self.doc.clone(); let target = if quick_mask { None } else { match self.paint_target() { - Ok(t) => Some(t), - Err(e) => { + Ok(target) => Some(target), + Err(error) => { self.doc = before; - return Err(e); + return Err(error); } } }; - let values = target.map(|t| self.stroke_values(t)).unwrap_or_default(); + + let values = target.map(|target| self.stroke_values(target)).unwrap_or_default(); // Clone and smudge on a mask read the mask as it was before the stroke let mask_owner = match target { Some(PaintTarget::Mask(effect)) if pickup.is_some() => self.doc.project.effect(effect).map(|(owner, _)| owner), _ => None, }; - let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None }; + + // The 2D view doesn't show the stencil, so there it shapes only the Projection tool + let stencil = if !quick_mask && tool.uses_stencil() && (tool == Tool::Projection || !uv_mode) { self.capture_stencil(viewport) } else { None }; let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) { Some("no channel enabled to paint: enable channels in the tool's material") } else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode { @@ -267,9 +273,10 @@ impl Session { } else { None }; - if let Some(msg) = problem { + + if let Some(message) = problem { self.doc = before; - return Err(EngineError::Other(msg.into())); + return Err(EngineError::Other(message.into())); } let depth = (!uv_mode).then(|| self.eye_depth(viewport)); @@ -278,6 +285,7 @@ impl Session { if !quick_mask { canvas.limit = self.stroke_limit(ts, size); } + if let Some((mode, offset)) = pickup && let Some(cache) = self.caches.get(ts) { @@ -285,7 +293,7 @@ impl Session { PickupMode::Clone { .. } => { PickupMode::Clone { offset: [(offset[0] * size.0 as f32).round() as i64, (offset[1] * size.1 as f32).round() as i64] } } - m => m, + other_mode => other_mode, }; let mut pickup = match (&layer_source, mask_owner) { // On a mask the stroke reads the mask's own values @@ -317,20 +325,23 @@ impl Session { canvas.pickup = Some(pickup); if tool == Tool::Clone && self.tool.clone_aligned - && let Some(src) = self.tool.clone_source.as_mut() + && let Some(clone_source) = self.tool.clone_source.as_mut() { - src.offset.get_or_insert(offset); + clone_source.offset.get_or_insert(offset); } } + if canvas.pickup.is_none() && tool == Tool::Paint && matches!(target, Some(PaintTarget::Layer(_))) { canvas.pickup = self.brush_pattern(&values); } + let label = if quick_mask { QUICK_MASK_STROKE_LABEL.to_string() } else { let on_mask = matches!(target, Some(PaintTarget::Mask(_))); history_label(stroke_template(tool, on_mask), &self.stroke_layer_name()) }; + self.stroke = Some(ActiveStroke { ts, target, @@ -394,13 +405,14 @@ impl Session { } } - /// The stencil placed for the current camera and viewport. + /// The stencil placed for the current camera and viewport fn capture_stencil(&self, viewport: Vec2) -> Option { - let st = self.tool.stencil.as_ref()?; - let image = self.images.get(&st.image)?.clone(); + let stencil_state = self.tool.stencil.as_ref()?; + let image = self.images.get(&stencil_state.image)?.clone(); let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); - let (center, half, rotation) = st.placement(image.width as f32 / image.height.max(1) as f32, aspect); - Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile }) + let (center, half, rotation) = stencil_state.placement(image.width as f32 / image.height.max(1) as f32, aspect); + let colors = self.tool.tool == Tool::Projection; + Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: stencil_state.tile, colors }) } /// Painting is paused while a bake preview shows the baked maps instead of the material. @@ -739,22 +751,22 @@ impl Session { } } -/// Run `f` with stroke `st` as a commit source over `tiles` (the Projection tool's stencil -/// colors and alpha come from the surface under each texel). +/// Run `f` with `stroke` as a commit source over `tiles` (the stencil's alpha and, on the Projection tool, its colors come from the surface under each texel) fn with_commit_source( - st: &ActiveStroke, - gbuf: Option<&texturecraft_geom::UvGBuffer>, + stroke: &ActiveStroke, + gbuffer: Option<&texturecraft_geom::UvGBuffer>, mesh: &texturecraft_geom::Mesh, tiles: &BTreeSet<(u32, u32)>, f: impl FnOnce(CommitSource) -> R, ) -> R { - let stencil_fn = |x: u32, y: u32| -> Option<([f32; 3], f32)> { - let g = gbuf?; - let p = g.surface(mesh, (y * g.width + x) as usize)?.pos; - st.stencil.as_ref()?.sample_world(p) + let stencil_fn = |x: u32, y: u32| -> Option<(Option<[f32; 3]>, f32)> { + let gbuffer = gbuffer?; + let position = gbuffer.surface(mesh, (y * gbuffer.width + x) as usize)?.pos; + stroke.stencil.as_ref()?.paint_world(position) }; - let per_texel: Option = if st.stencil.is_some() { Some(&stencil_fn) } else { None }; - let carried = st.canvas.pickup.as_ref().map(|p| &p.values); - let carried_mask = st.canvas.pickup.as_ref().and_then(|p| p.mask_values()); - f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried, carried_mask }) + let per_texel: Option = if stroke.stencil.is_some() { Some(&stencil_fn) } else { None }; + + let carried = stroke.canvas.pickup.as_ref().map(|pickup| &pickup.values); + let carried_mask = stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values()); + f(CommitSource { alpha: &stroke.canvas.alpha, tiles, opacity: stroke.stroke.settings.opacity, erase: stroke.erase, per_texel, carried, carried_mask }) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index cb69ffb3..31cc5dff 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -107,6 +107,12 @@ pub enum Tool { impl Tool { pub const ALL: [Tool; 9] = [Tool::Paint, Tool::Eraser, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::Path, Tool::GeometryMask]; + + /// The brush tools whose strokes the stencil shapes + pub fn uses_stencil(self) -> bool { + matches!(self, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone) + } + pub fn label(self) -> &'static str { match self { Tool::Paint => "Paint", @@ -178,7 +184,7 @@ impl ViewMode { } } -/// A screen-pinned image for the Projection tool (a stencil). +/// A screen-pinned image the brush tools paint through (a stencil) #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StencilState { /// Image resource name. @@ -249,7 +255,7 @@ pub struct ToolState { /// Polygon fill boxes in the 3D view select only the polygons the camera sees #[serde(default = "default_fill_visible_only")] pub fill_visible_only: bool, - /// Stencil used by the Projection tool. + /// Stencil the brush tools paint through (the Projection tool paints its colors) #[serde(default)] pub stencil: Option, /// Placement the next stencil starts with: the last stencil's, kept when the stencil is diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index e9e9dc26..c924dc96 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -12,6 +12,12 @@ use crate::fill_mode::FillMode; use crate::session::{CloneFrom, CloneSource, StackTarget, Tool}; use crate::{Result, Session, cmd}; +/// Brush size the UI's full size slider stands for +const MAX_BRUSH_SIZE: f32 = 0.25; + +/// Full value of the UI's 0–100 brush scales +const PERCENT: f32 = 100.0; + pub fn specs() -> Vec { vec![ cmd!("tool.paint", "Paint", ["Tools"], Some("1"), "{}", always, |s, _| set_tool(s, Tool::Paint)), @@ -36,7 +42,7 @@ pub fn specs() -> Vec { "Brush settings", [], None, - "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", + "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, sizePressure? (default true: pen pressure shrinks the size towards minSize), smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", always, brush ), @@ -64,7 +70,7 @@ pub fn specs() -> Vec { ), cmd!( "tool.stencil", - "Projection stencil", + "Stencil", [], None, "{image?: resource name, center?: [x,y] NDC, scale?: 0.01..10, rotation?: degrees, tile?, opacity?, clear?: bool}", diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 0fc0b848..1c1a6a68 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -697,6 +697,91 @@ fn projection_tool_paints_the_stencil_colors() { assert!(right[1] > 0.8 && right[0] < 0.2, "right {right:?}"); } +/// The stencil tests' texture size, to turn a picked UV into a texel +const TEXTURE_SIZE: u32 = 256; + +/// Side of the stencil black on its left half and white on its right +const STENCIL_SIZE: u32 = 16; + +/// The view's row over the sphere the stencil tests paint along +const DAB_Y: f32 = 200.0; + +/// A dab behind the stencil's black half +const BLACK_DAB_X: f32 = 150.0; + +/// A dab behind the stencil's white half +const WHITE_DAB_X: f32 = 250.0; + +/// Imports a stencil black on its left half and white on its right, returning its resource name +fn half_black_stencil(session: &mut Session) -> String { + let stencil = image::RgbaImage::from_fn(STENCIL_SIZE, STENCIL_SIZE, |x, _| { + if x < STENCIL_SIZE / 2 { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) } + }); + let mut png = Vec::new(); + stencil.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + + session.import_resource_bytes("half.png", png).unwrap() +} + +/// The composite base color under the view's point at `x` on the dab row +fn base_color_at(session: &Session, x: f32) -> [f32; 3] { + let hit = session.pick(Vec2::new(x, DAB_Y), session.viewport).unwrap(); + let texel = |coordinate: f32| (coordinate * TEXTURE_SIZE as f32) as u32; + + session.caches[0].composite.value(Channel::BaseColor, texel(hit.uv.x), texel(hit.uv.y)) +} + +#[test] +fn the_paint_tool_paints_its_own_color_through_the_stencils_gray() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + let left_before = base_color_at(&session, BLACK_DAB_X); + + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + + let (left, right) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left, left_before, "black stencil blocks the paint"); + assert!(right[0] > 0.8 && right[1] < 0.2 && right[2] < 0.2, "white stencil lets the tool's red through: {right:?}"); +} + +#[test] +fn a_mask_stroke_shows_through_the_stencil_while_painting_as_it_commits() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + + // A red fill under a white mask the stroke paints black + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "mask.add.white", &Value::Null).unwrap(); + session.target = texturecraft_engine::StackTarget::Mask; + session.tool.mask_value = 0.0; + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + session.update(); + let (left_before, right_before) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + + // A stroke from behind the stencil's black half to its white half + let viewport = session.viewport; + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), viewport, 1.0).unwrap(); + session.continue_stroke(Vec2::new(WHITE_DAB_X, DAB_Y), 1.0); + session.update(); + let (left_preview, right_preview) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left_preview, left_before, "black stencil hides the live stroke"); + assert_ne!(right_preview, right_before, "white stencil shows the live stroke"); + + session.end_stroke().unwrap(); + session.update(); + let (left_committed, right_committed) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left_committed, left_before, "black stencil blocks the committed stroke"); + assert_ne!(right_committed, right_before, "white stencil lets the committed stroke through"); +} + #[test] fn smart_materials_save_and_load_with_pixels() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); diff --git a/crates/paint/src/commit.rs b/crates/paint/src/commit.rs index e40548bf..d7d105bf 100644 --- a/crates/paint/src/commit.rs +++ b/crates/paint/src/commit.rs @@ -71,26 +71,34 @@ fn over(img: &mut TileImage, b: &Blend, src: &CommitSource, mut staged: Option) { +/// Blend the stroke's alpha tile `stroke_alpha` into tile `(tile_x, tile_y)` of an image (`dst`, `components` per texel) +fn blend_tile( + dst: &mut [u16], + components: usize, + stroke_alpha: &[u16], + (tile_x, tile_y): (u32, u32), + blend: &Blend, + source: &CommitSource, + carried: Option<&[u16]>, +) { // The last component is the coverage, the ones before it the value let value_count = components.saturating_sub(1); let opacity = source.opacity.clamp(0.0, 1.0); let gray_source = if source.erase || carried.is_some() { None } else { blend.gray }; - for i in 0..TILE_AREA { - let mut weight = from_u16(stroke_alpha.get(i).copied().unwrap_or(0)) * opacity; + for texel_index in 0..TILE_AREA { + let mut weight = from_u16(stroke_alpha.get(texel_index).copied().unwrap_or(0)) * opacity; if weight <= 0.0 { continue; } let mut stencil = None; - let (x, y) = (tx * TILE + i as u32 % TILE, ty * TILE + i as u32 / TILE); + let (x, y) = (tile_x * TILE + texel_index as u32 % TILE, tile_y * TILE + texel_index as u32 / TILE); if let Some(per_texel) = source.per_texel { match per_texel(x, y) { Some((color, alpha_factor)) => { weight *= alpha_factor; - stencil = Some(color); + stencil = color; } None => continue, } @@ -99,13 +107,16 @@ fn blend_tile(dst: &mut [u16], components: usize, stroke_alpha: &[u16], (tx, ty) } } - let Some((coverage_slot, values)) = dst.get_mut(i * components..(i + 1) * components).and_then(<[u16]>::split_last_mut) else { continue }; + let Some((coverage_slot, values)) = dst.get_mut(texel_index * components..(texel_index + 1) * components).and_then(<[u16]>::split_last_mut) else { + continue; + }; + let gray = gray_source.map(|gray| gray.at(x, y, (source.alpha.width(), source.alpha.height()))); let coverage = from_u16(*coverage_slot); for (component, slot) in values.iter_mut().enumerate() { let previous = dec(blend.kind, *slot); let target = match (carried, stencil) { - (Some(carried_tile), _) => dec(blend.kind, carried_tile.get(i * value_count + component).copied().unwrap_or(0)), + (Some(carried_tile), _) => dec(blend.kind, carried_tile.get(texel_index * value_count + component).copied().unwrap_or(0)), (None, _) if let Some(gray) = gray => gray, (None, Some(color)) if blend.stencil_color => color.get(component).copied().unwrap_or(0.0), _ => blend.value.get(component).copied().unwrap_or(0.0), @@ -318,8 +329,8 @@ fn mask_blend<'a>(gray: &'a MaskGray, value: &'a [f32; 1]) -> Blend<'a> { Blend { kind: ChannelKind::Scalar, value, stencil_color: false, carried: None, gray } } -/// Per-texel override of a stroke: `(x, y)` → (base color, alpha factor), None = no paint. -pub type TexelFn<'a> = &'a (dyn Fn(u32, u32) -> Option<([f32; 3], f32)> + Sync); +/// Per-texel override of a stroke: `(x, y)` → (base color, alpha factor), None = no paint; a None color keeps the stroke's own value +pub type TexelFn<'a> = &'a (dyn Fn(u32, u32) -> Option<(Option<[f32; 3]>, f32)> + Sync); /// The stroke being committed: its alpha, touched tiles, opacity cap and mode. #[derive(Clone, Copy)] @@ -328,7 +339,7 @@ pub struct CommitSource<'a> { pub tiles: &'a BTreeSet<(u32, u32)>, pub opacity: f32, pub erase: bool, - /// Projection tool: base color and alpha per texel from a stencil. + /// The stencil: alpha per texel and, on the Projection tool, base color pub per_texel: Option>, /// Clone and smudge: straight values per channel carried by the stroke (replace `values`). pub carried: Option<&'a BTreeMap>, diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 20e146e1..455bda0d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2097,7 +2097,7 @@ fn tool_header(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); } - // The Projection tool's stencil has its own section + // A tool's own settings, above the sections every brush tool shares let tool_section: Option = match app.session.tool.tool { Tool::Clone => Some(clone_section), Tool::Smudge => Some(smudge_section), @@ -2125,11 +2125,12 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { }; PropertySheet::show(ui, "tool_sheet", |sheet| { for section in tool_sections(app) { - let menu = sheet.section(section.title(), section == PaintSection::Brush); + // The Stencil caption carries its own reset + let menu = if section == PaintSection::Stencil { None } else { sheet.section(section.title(), section == PaintSection::Brush) }; match section { PaintSection::Brush => crate::brush_sheet::brush_section(app, sheet, menu), PaintSection::Alpha => crate::alpha_sheet::alpha_section(app, sheet), - PaintSection::Stencil => legacy(sheet, app, stencil_section), + PaintSection::Stencil => crate::stencil_sheet::stencil_section(app, sheet), PaintSection::Material => legacy(sheet, app, material_controls), PaintSection::Grayscale => crate::mask_paint_panel::grayscale_section(app, sheet), } @@ -2137,65 +2138,9 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -/// The sections of [`tool_properties`]: only the Projection tool uses a stencil +/// The sections of [`tool_properties`]: Stencil for the brush tools it shapes fn tool_sections(app: &TextureCraftApp) -> Vec { - PaintSection::page(app.session.tool.tool == Tool::Projection, targets_content(app)) -} - -/// How far the Position sliders move the stencil's center from the middle of the view (NDC; -1..1 is the view) -const STENCIL_POSITION_RANGE: f32 = 2.0; - -fn stencil_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let names: Vec = app.session.doc.resources.keys().cloned().collect(); - let current = app.session.tool.stencil.as_ref().map(|s| s.image.clone()).unwrap_or_else(|| tr("None").into()); - let row = ui.horizontal(|ui| { - egui::ComboBox::from_id_salt("stencil_img").width(170.0).selected_text(current.clone()).show_ui(ui, |ui| { - if ui.selectable_label(app.session.tool.stencil.is_none(), tr("None")).clicked() { - app.run("tool.stencil", json!({"clear": true})); - } - for n in &names { - if ui.selectable_label(*n == current, n).clicked() { - app.run("tool.stencil", json!({"image": n})); - } - } - }); - import_button(app, ui); - }); - - // An image from the Assets panel dropped on the row becomes the stencil - let row_response = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as the stencil")); - if let Some(name) = image_drop(ui, &row_response) { - app.run("tool.stencil", json!({"image": name})); - } - if names.is_empty() { - ui.label(RichText::new(tr("Import an image (File > Import resources) to project it onto the mesh.")).color(tk.text_dim)); - return; - } - - if let Some(st) = app.session.tool.stencil.as_mut() { - slider(ui, tr("Scale"), &mut st.scale, 0.05..=4.0, 2); - slider(ui, tr("Rotation"), &mut st.rotation, 0.0..=360.0, 0); - slider(ui, tr("Position X"), &mut st.center[0], -STENCIL_POSITION_RANGE..=STENCIL_POSITION_RANGE, 2); - slider(ui, tr("Position Y"), &mut st.center[1], -STENCIL_POSITION_RANGE..=STENCIL_POSITION_RANGE, 2); - if ui.button(tr("Reset stencil")).on_hover_text(tr("Put the stencil back in the middle of the view at its starting size and rotation")).clicked() { - st.reset_placement(); - } - slider(ui, tr("Overlay opacity"), &mut st.opacity, 0.0..=1.0, 2); - ui.checkbox(&mut st.tile, tr("Tile")); - ui.label( - RichText::new(tr("S + left-drag rotates (with Shift in 15° steps), S + right-drag scales, S + middle-drag moves; or use Position X / Y.")) - .size(10.5) - .color(tk.text_dim), - ); - } -} - -fn import_button(app: &mut TextureCraftApp, ui: &mut Ui) { - if ui.small_button(tr("Import...")).clicked() { - let ctx = ui.ctx().clone(); - crate::menus::invoke(app, &ctx, "resource.import"); - } + PaintSection::page(app.session.tool.tool.uses_stencil(), targets_content(app)) } fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 47d6548d..6a677ca8 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -661,9 +661,9 @@ pub fn fixed_gestures() -> Vec<(String, String)> { (tr("Ctrl + RMB drag").into(), tr("Brush size (left/right) and hardness (up/down)").into()), (tr("Ctrl + LMB drag").into(), tr("Brush flow (left/right) and angle (up/down)").into()), (tr("Ctrl + Shift + RMB drag").into(), tr("Brush size and hardness in fine steps").into()), - (keyed("{key} + LMB drag"), tr("Projection: rotate the stencil").into()), - (keyed("{key} + RMB drag"), tr("Projection: scale the stencil").into()), - (keyed("{key} + MMB drag"), tr("Projection: move the stencil").into()), + (keyed("{key} + LMB drag"), tr("Rotate the stencil").into()), + (keyed("{key} + RMB drag"), tr("Scale the stencil").into()), + (keyed("{key} + MMB drag"), tr("Move the stencil").into()), (trf("{key} + LMB", &[("key", &clone)]), tr("Clone: pick the point to copy from").into()), (tr("Click (Path tool)").into(), tr("Path: add a point; on the curve it inserts one").into()), (tr("LMB drag on a point (Path tool)").into(), tr("Path: move the point").into()), @@ -696,7 +696,7 @@ mod tests { let rows = fixed_gestures(); let has = |gesture: &str, what: &str| rows.iter().any(|(g, w)| g == gesture && w.contains(what)); let (s, v) = (crate::viewport::STENCIL_KEY.name(), crate::viewport::CLONE_SOURCE_KEY.name()); - assert!(has(&format!("{s} + LMB drag"), "rotate") && has(&format!("{s} + RMB drag"), "scale") && has(&format!("{s} + MMB drag"), "move")); + assert!(has(&format!("{s} + LMB drag"), "Rotate") && has(&format!("{s} + RMB drag"), "Scale") && has(&format!("{s} + MMB drag"), "Move")); assert!(has(&format!("{v} + LMB"), "Clone")); for (gesture, what) in [ ("Shift + LMB", "straight line"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bd9817e5..eef10a5e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -173,6 +173,8 @@ mod soft_box; mod source_choice; mod source_slot; pub mod state; +mod stencil_choice; +mod stencil_sheet; mod surface_paint_point; pub mod symmetry; pub mod theme; diff --git a/crates/ui-egui/src/stencil_choice.rs b/crates/ui-egui/src/stencil_choice.rs new file mode 100644 index 00000000..1414f08e --- /dev/null +++ b/crates/ui-egui/src/stencil_choice.rs @@ -0,0 +1,8 @@ +//! What the Stencil slot's picker offers + +/// One tile of the Stencil slot's picker: an image resource, or importing one +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum StencilChoice { + Image(String), + Import, +} diff --git a/crates/ui-egui/src/stencil_sheet.rs b/crates/ui-egui/src/stencil_sheet.rs new file mode 100644 index 00000000..ebf55fbe --- /dev/null +++ b/crates/ui-egui/src/stencil_sheet.rs @@ -0,0 +1,229 @@ +//! The Stencil section of a brush tool's Properties: the stencil's slot with its picker, its Tiling mode, and its placement beside a picture of where it sits in the view + +use std::f32::consts::SQRT_2; +use std::ops::RangeInclusive; + +use egui::{Color32, CornerRadius, Painter, Pos2, Rect, Stroke, StrokeKind, TextureId, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::session::StencilState; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::stencil_choice::StencilChoice; +use crate::theme::Tokens; + +/// Scale = the image's height as a fraction of the view's +const SCALE_RANGE: RangeInclusive = 0.05..=4.0; + +/// How far the Position sliders move the stencil's center from the middle of the view (NDC; -1..1 is the view) +const POSITION_RANGE: RangeInclusive = -2.0..=2.0; + +/// The Rotation dial's range in degrees +const ROTATION_RANGE: RangeInclusive = 0.0..=360.0; + +/// Copies a tiled stencil's picture draws each way from the middle one at most, so a tiny stencil stays cheap +const MAX_PICTURED_TILES: i32 = 12; + +/// The view's outline in the placement picture +const VIEW_OUTLINE_WIDTH: f32 = 1.0; + +/// Air between the placement picture's edge and the view drawn in it +const VIEW_INSET: f32 = 6.0; + +/// A Tiling mode picture's cell: its share of the picture and the air between two cells +const TILE_CELL_FRACTION: f32 = 0.42; +const TILE_CELL_GAP: f32 = 2.0; + +/// The Stencil section under its caption, whose reset puts the stencil back in the middle of the view +pub(crate) fn stencil_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let moved = app.session.tool.stencil.as_ref().is_some_and(|stencil| placement(stencil) != placement(&StencilState::new(&stencil.image))); + if sheet.section_reset(tr("Stencil"), moved) + && let Some(stencil) = &app.session.tool.stencil + { + let start = StencilState::new(&stencil.image); + app.run("tool.stencil", json!({"center": start.center, "scale": start.scale, "rotation": start.rotation})); + } + + stencil_slot(app, sheet); + let Some(stencil) = app.session.tool.stencil.clone() else { return }; + + let tile_name = |tile: bool| if tile { tr("H and V Tiling") } else { tr("No Tiling") }.to_owned(); + let text = Tokens::get(sheet.ui.ctx()).text; + let tile_picture = |painter: &Painter, rect: Rect, tile: bool| paint_tiling(painter, rect, tile, text); + let (picked, _) = sheet.dropdown(tr("Tiling mode"), stencil.tile, &[false, true], tile_name, Some(&tile_picture)); + if let Some(tile) = picked { + app.run("tool.stencil", json!({ "tile": tile })); + } + + placement_rows(app, sheet, &stencil); + + let mut opacity = stencil.opacity; + if sheet.slider(tr("Overlay opacity"), &mut opacity, 0.0..=1.0, 2).is_some() { + app.run("tool.stencil", json!({ "opacity": opacity })); + } +} + +/// What the section's reset puts back: where the stencil sits, its size and its turn +fn placement(stencil: &StencilState) -> ([f32; 2], f32, f32) { + (stencil.center, stencil.scale, stencil.rotation) +} + +/// The slot showing the stencil's image; a click opens the picker of images, × takes the stencil away +fn stencil_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let ctx = sheet.ui.ctx().clone(); + let current = app.session.tool.stencil.as_ref().map(|stencil| StencilChoice::Image(stencil.image.clone())); + let texture = match ¤t { + Some(StencilChoice::Image(name)) => app.session.images.get(name).map(|image| app.thumbs.image(&ctx, name, image)), + _ => None, + }; + let (name, source) = match ¤t { + Some(StencilChoice::Image(name)) => (name.clone(), tr("Imported image")), + _ => (tr("None").to_owned(), tr("Pick an image to paint through")), + }; + let tokens = Tokens::get(&ctx); + let thumbnail = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + if let Some(texture) = &texture { + painter.image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + }; + let slot = sheet.slot(&thumbnail, &name, source, None, current.is_some(), false); + let slot_pick = + slot.pick.clone().on_hover_text(tr("S + left-drag rotates (with Shift in 15° steps), S + right-drag scales, S + middle-drag moves the stencil")); + + let popup = sheet.ui.make_persistent_id("brush_stencil_source"); + if slot_pick.clicked() { + resource_picker::toggle(&ctx, popup); + } + let tabs = || { + let textures = ResourcePickerItem::textures(&app.session, StencilChoice::Import, |name| StencilChoice::Image(name.to_owned())); + vec![PickerTab { icon: ic::FRAME_CORNERS, name: tr("Stencils"), groups: vec![PickerGroup { header: None, items: textures }] }] + }; + match resource_picker::show(&slot_pick, popup, &mut app.thumbs, current.as_ref(), true, tabs) { + Some(StencilChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(choice) if Some(&choice) != current.as_ref() => { + if let StencilChoice::Image(name) = choice { + app.run("tool.stencil", json!({ "image": name })); + } + } + _ => {} + } + if slot.clear { + app.run("tool.stencil", json!({"clear": true})); + } + + // An image from the Assets panel dropped on the slot becomes the stencil + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot_pick) { + app.run("tool.stencil", json!({ "image": name })); + } + sheet.close_card(); +} + +/// Scale, Rotation and Position X / Y beside a picture of the view with the stencil placed in it +fn placement_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, stencil: &StencilState) { + let ctx = sheet.ui.ctx().clone(); + let tokens = Tokens::get(&ctx); + let image = app.session.images.get(&stencil.image).cloned(); + let texture = image.as_ref().map(|image| app.thumbs.stencil(&ctx, &stencil.image, image)); + let view_aspect = app.session.viewport.x.max(1.0) / app.session.viewport.y.max(1.0); + let image_aspect = image.as_ref().map_or(1.0, |image| image.width as f32 / image.height.max(1) as f32); + let picture = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + let view = fit(rect.shrink(VIEW_INSET), view_aspect); + painter.rect_filled(view, CornerRadius::ZERO, tokens.panel); + if let Some(texture) = &texture { + paint_stencil(&painter.with_clip_rect(view), view, texture.id(), stencil, image_aspect, Color32::WHITE, stencil.tile); + } + painter.rect_stroke(view, CornerRadius::ZERO, Stroke::new(VIEW_OUTLINE_WIDTH, tokens.text_dim), StrokeKind::Inside); + }; + + let (mut scale, mut rotation, [mut x, mut y]) = (stencil.scale, stencil.rotation, stencil.center); + let edits = sheet.picture_sliders( + &picture, + &mut [ + StackSlider { label: tr("Scale"), value: &mut scale, range: SCALE_RANGE, typed: SCALE_RANGE, decimals: 2, suffix: "", dial: false }, + StackSlider { label: tr("Rotation"), value: &mut rotation, range: ROTATION_RANGE, typed: ROTATION_RANGE, decimals: 0, suffix: "°", dial: true }, + StackSlider { label: tr("Position X"), value: &mut x, range: POSITION_RANGE, typed: POSITION_RANGE, decimals: 2, suffix: "", dial: false }, + StackSlider { label: tr("Position Y"), value: &mut y, range: POSITION_RANGE, typed: POSITION_RANGE, decimals: 2, suffix: "", dial: false }, + ], + ); + let [scale_edit, rotation_edit, x_edit, y_edit] = edits.map(|edit| edit.is_some()); + let mut params = serde_json::Map::new(); + if scale_edit { + params.insert("scale".into(), json!(scale)); + } + if rotation_edit { + params.insert("rotation".into(), json!(rotation)); + } + if x_edit || y_edit { + params.insert("center".into(), json!([x, y])); + } + if !params.is_empty() { + app.run("tool.stencil", Value::Object(params)); + } +} + +/// The largest rect of `aspect` (width / height) centred in `outer` +fn fit(outer: Rect, aspect: f32) -> Rect { + let width = outer.width().min(outer.height() * aspect); + Rect::from_center_size(outer.center(), vec2(width, width / aspect.max(f32::EPSILON))) +} + +/// Paints the stencil's image where it sits in the view `rect`, `tint`ed: one copy, or every copy that reaches the view when `tiled`; returns the middle copy's corners (top left, top right, bottom right, bottom left) +pub(crate) fn paint_stencil( + painter: &Painter, + rect: Rect, + texture: TextureId, + stencil: &StencilState, + image_aspect: f32, + tint: Color32, + tiled: bool, +) -> [Pos2; 4] { + let aspect = rect.width() / rect.height().max(1.0); + let (center, half_size, rotation) = stencil.placement(image_aspect, aspect); + let to_screen = |x: f32, y: f32| pos2(rect.left() + (x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - y * 0.5) * rect.height()); + let (sine, cosine) = rotation.sin_cos(); + + // A copy's corner: (x, y) in the image's own -1..1 square, moved `step` whole images along its sides + let corner = |x: f32, y: f32, step: (i32, i32)| { + let (x, y) = ((x + 2.0 * step.0 as f32) * half_size[0], (y + 2.0 * step.1 as f32) * half_size[1]); + to_screen(center[0] + x * cosine - y * sine, center[1] + x * sine + y * cosine) + }; + + // Copies far enough out to cover the view from the stencil's center, at any turn + let reach = |half: f32| ((SQRT_2 + center[0].abs().max(center[1].abs())) / (2.0 * half.max(f32::EPSILON))).ceil() as i32; + let (reach_x, reach_y) = if tiled { (reach(half_size[0]).min(MAX_PICTURED_TILES), reach(half_size[1]).min(MAX_PICTURED_TILES)) } else { (0, 0) }; + let mut mesh = egui::Mesh::with_texture(texture); + for step_x in -reach_x..=reach_x { + for step_y in -reach_y..=reach_y { + let first = mesh.vertices.len() as u32; + for (x, y, u, v) in [(-1.0, 1.0, 0.0, 0.0), (1.0, 1.0, 1.0, 0.0), (1.0, -1.0, 1.0, 1.0), (-1.0, -1.0, 0.0, 1.0)] { + mesh.vertices.push(egui::epaint::Vertex { pos: corner(x, y, (step_x, step_y)), uv: pos2(u, v), color: tint }); + } + mesh.indices.extend([0, 1, 2, 0, 2, 3].map(|index| first + index)); + } + } + painter.add(egui::Shape::mesh(mesh)); + [corner(-1.0, 1.0, (0, 0)), corner(1.0, 1.0, (0, 0)), corner(1.0, -1.0, (0, 0)), corner(-1.0, -1.0, (0, 0))] +} + +/// A Tiling mode's picture: one square for No Tiling, four for H and V Tiling +fn paint_tiling(painter: &Painter, rect: Rect, tile: bool, color: Color32) { + let cell = rect.width() * TILE_CELL_FRACTION; + if !tile { + painter.rect_filled(Rect::from_center_size(rect.center(), vec2(cell, cell)), CornerRadius::ZERO, color); + return; + } + + let half_step = (cell + TILE_CELL_GAP) / 2.0; + for (direction_x, direction_y) in [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] { + let center = rect.center() + vec2(direction_x * half_step, direction_y * half_step); + painter.rect_filled(Rect::from_center_size(center, vec2(cell, cell)), CornerRadius::ZERO, color); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3ae2bfbd..2c2f3d3b 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -23,7 +23,7 @@ use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; -/// Hold this key with the Projection tool to rotate, scale or move the stencil with the mouse +/// Hold this key with a brush tool to rotate, scale or move the stencil with the mouse pub const STENCIL_KEY: egui::Key = egui::Key::S; /// Hold this key with the Clone tool and click to set the source pub const CLONE_SOURCE_KEY: egui::Key = egui::Key::V; @@ -305,7 +305,7 @@ const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; const BAKE_PAINT_CURSOR_STROKE: f32 = 1.0; const BAKE_PAINT_CURSOR_ALPHA: u8 = 200; -/// The projection stencil's dashed outline: width, white alpha, dash and gap, in points +/// The stencil's dashed outline: width, white alpha, dash and gap, in points const STENCIL_OUTLINE_STROKE: f32 = 1.0; const STENCIL_OUTLINE_ALPHA: u8 = 120; const STENCIL_OUTLINE_DASH: f32 = 5.0; @@ -778,13 +778,13 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let holding = crate::move_on_model::holding(app, ui.ctx()); let navigating = !adjusting && !holding && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); - // Navigation; S + drag moves the projection stencil instead, below + // Navigation; S + drag moves the stencil instead, below let delta = ui.input(|input| input.pointer.delta()); let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !crate::framework::widget_has_keyboard(ui.ctx()); - // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise - let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; + // Only an equipped brush tool that can act moves the stencil: it isn't drawn otherwise + let stencil_moves = tool_acts(app) && app.session.tool.tool.uses_stencil(); let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some(); if stencil_drag || adjusting || holding { // The stencil, the brush or the held Move on model button changes instead of the camera @@ -1178,9 +1178,9 @@ fn bake_visualization(app: &TextureCraftApp) -> Option, tab: &str) -> bool { #[test] fn the_tabs_jump_within_one_page_of_the_tools_sections() { let mut harness = paint_harness("paint"); - for tab in ["Brush", "Alpha", "Material"] { + for tab in ["Brush", "Alpha", "Stencil", "Material"] { assert!(harness.query_by_role_and_label(Role::Tab, tab).is_some(), "the {tab} tab"); } - assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "the Paint tool has no stencil yet"); assert!(tab_selected(&harness, "Brush"), "the page opens on its first section"); let flow_before = harness.get_by_label("Flow").rect().top(); @@ -52,8 +51,13 @@ fn the_tabs_jump_within_one_page_of_the_tools_sections() { } #[test] -fn the_projection_tool_has_a_stencil_tab() { - let harness = paint_harness("projection"); +fn every_brush_tool_has_a_stencil_tab_and_polygon_fill_none() { + for tool in ["paint", "eraser", "projection", "smudge", "clone"] { + let harness = paint_harness(tool); - assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_some()); + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_some(), "{tool}"); + } + + let harness = paint_harness("polygonFill"); + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "polygon fill paints no strokes"); } diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index f1dec885..dafd004a 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -1,5 +1,4 @@ -//! The Projection tool's stencil: an Assets image dropped on its slot, position fields and a reset in the tool panel, -//! S + Shift + left-drag to turn it in snapped steps, and the 2D view saying that projection paints in the 3D view +//! The brush tools' stencil: an Assets image dropped on its slot, position fields, Tiling mode and the section reset in the tool panel, S + Shift + left-drag to turn it in snapped steps, and the 2D view saying that projection paints in the 3D view use egui::accesskit::Role; use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; @@ -11,32 +10,50 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; use texturecraft_ui_egui::state::ViewLayout; +use crate::{BAKE_RESOLUTION, REDRAW_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + /// The sample project with the Projection tool equipped, and an imported image's resource name fn projection_app() -> (Harness<'static, TextureCraftApp>, String) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + tool_app(Tool::Projection) +} + +/// Window the stencil tests run in +const WINDOW_SIZE: egui::Vec2 = vec2(1600.0, 960.0); + +/// Side of the plain white image imported for the stencil +const IMAGE_SIZE: u32 = 4; + +/// The sample project with `tool` equipped and its Stencil section in view, and an imported image's resource name +fn tool_app(tool: Tool) -> (Harness<'static, TextureCraftApp>, String) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let white = image::RgbaImage::from_pixel(IMAGE_SIZE, IMAGE_SIZE, image::Rgba([255, 255, 255, 255])); + white.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let name = session.import_resource_bytes("logo.png", png).unwrap(); - session.tool.tool = Tool::Projection; + session.tool.tool = tool; + let mut harness = Harness::builder() - .with_size(egui::vec2(1600.0, 960.0)) + .with_size(WINDOW_SIZE) .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(4); + harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(Role::Tab, "Stencil").click(); - harness.run_steps(4); + harness.run_steps(REDRAW_FRAMES); (harness, name) } -/// The number field beside a uniquely labelled slider +/// The number field a click on a slider's value opens, on the slider's line fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = harness.get_by_label(label).rect().center().y; + let row = harness.get_by_role_and_label(Role::Slider, label).rect().center().y; harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } -/// Type a complete value in the number field beside a uniquely labelled slider +/// Type a complete value in the number field of a uniquely labelled slider fn set_number(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { + harness.get_by_label(&format!("{label} value")).click(); + harness.run_steps(2); let length = number_field(harness, label).value().unwrap().len(); number_field(harness, label).focus(); harness.run_steps(2); @@ -89,7 +106,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { let (mut harness, name) = projection_app(); assert!(harness.state().session.tool.stencil.is_none()); - let slot = harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).unwrap().rect().center(); + let slot = harness.get_by_role_and_label(Role::ComboBox, "None").rect().center(); egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() }); harness.hover_at(slot); harness.run_steps(2); @@ -100,7 +117,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { } #[test] -fn the_position_fields_move_the_stencil_and_reset_puts_it_back() { +fn the_position_fields_move_the_stencil_and_the_section_reset_puts_it_back() { let (mut harness, name) = projection_app(); texturecraft_engine::execute( &mut harness.state_mut().session, @@ -114,20 +131,35 @@ fn the_position_fields_move_the_stencil_and_reset_puts_it_back() { set_number(&mut harness, "Position X", "-0.75"); let moved = harness.state().session.tool.stencil.clone().unwrap(); assert_eq!(moved.center, [-0.75, -0.25], "only X changed"); - harness.get_by_label("Position Y"); + harness.get_by_role_and_label(Role::Slider, "Position Y"); - harness.get_by_label("Reset stencil").scroll_to_me(); + harness.get_by_label("Stencil: Reset to defaults").scroll_to_me(); harness.run_steps(3); - harness.get_by_label("Reset stencil").click(); + harness.get_by_label("Stencil: Reset to defaults").click(); harness.run_steps(3); let reset = harness.state().session.tool.stencil.clone().unwrap(); assert_eq!((reset.center, reset.scale, reset.rotation), ([0.0, 0.0], 0.8, 0.0)); assert_eq!((reset.image.as_str(), reset.opacity, reset.tile), (name.as_str(), 0.3, true), "image, opacity and tiling stay"); } +#[test] +fn the_tiling_mode_list_tiles_the_stencil() { + let (mut harness, name) = tool_app(Tool::Paint); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); + harness.run_steps(3); + + harness.get_by_role_and_label(Role::ComboBox, "No Tiling").click(); + harness.run_steps(3); + harness.get_by_label("H and V Tiling").click(); + harness.run_steps(3); + + assert!(harness.state().session.tool.stencil.as_ref().is_some_and(|stencil| stencil.tile)); +} + +/// The Paint tool's stencil turns like the Projection tool's #[test] fn s_shift_left_drag_turns_the_stencil_in_snapped_steps_without_painting() { - let (mut harness, name) = projection_app(); + let (mut harness, name) = tool_app(Tool::Paint); texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); harness.run_steps(2); let from = harness.state().viewport_rect.center(); diff --git a/crates/ui-egui/tests/it/user_smart_mask.rs b/crates/ui-egui/tests/it/user_smart_mask.rs index 7547e74c..e3b7260e 100644 --- a/crates/ui-egui/tests/it/user_smart_mask.rs +++ b/crates/ui-egui/tests/it/user_smart_mask.rs @@ -65,8 +65,8 @@ fn a_saved_smart_mask_is_listed_with_the_smart_masks_and_applies_to_the_selected let source = add_layer(&mut saved, "Source", true); let dir = std::env::temp_dir().join(format!("tc-ui-smart-mask-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("Stencil.tcmask"); - std::fs::write(&file, saved.smart_mask_bytes(source, "Stencil").unwrap()).unwrap(); + let file = dir.join("Zebra Saved.tcmask"); + std::fs::write(&file, saved.smart_mask_bytes(source, "Zebra Saved").unwrap()).unwrap(); let mut harness = harness(|_| {}); let target = harness.state().session.selected_layer().unwrap(); @@ -75,11 +75,11 @@ fn a_saved_smart_mask_is_listed_with_the_smart_masks_and_applies_to_the_selected harness.state_mut().ui.shelf_path = vec!["user".into()]; harness.state_mut().ui.shelf_tab = SMART_MATERIALS_TYPE; harness.run_steps(3); - assert!(harness.query_by_label_contains("Stencil").is_none(), "it is not a smart material"); + assert!(harness.query_by_label_contains("Zebra Saved").is_none(), "it is not a smart material"); harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE; harness.run_steps(3); - harness.get_by_label_contains("Stencil").click(); + harness.get_by_label_contains("Zebra Saved").click(); harness.run_steps(3); std::fs::remove_dir_all(&dir).unwrap(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 9ea94656..fe164ce6 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3319,6 +3319,15 @@ fn paint_tool_properties_snapshots() { execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "projection"})).unwrap(); execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": image})).unwrap(); tab(&mut harness, "Stencil", "projection-stencil"); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"rotation": 15.0, "center": [0.1, -0.05]})).unwrap(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::ComboBox, "No Tiling").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "projection-stencil-tiling-open"); + harness.get_by_label("H and V Tiling").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "projection-stencil-tiled"); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"clear": true})).unwrap(); execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "paint"})).unwrap(); let layer = harness.state().session.selected_layer().map(|id| id.0); diff --git a/docs/features.md b/docs/features.md index 520ff678..0a1279ce 100644 --- a/docs/features.md +++ b/docs/features.md @@ -16,8 +16,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the stroke and keep the size. The Brush section's **Brush presets** popover (and the shelf) also keeps your own: save the current brush, click to use it, rename, replace or delete it. -- **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the - stencil), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a +- **Tools:** paint, eraser, **projection** (paints an image's colors), a **stencil** every brush tool + paints through (its gray masks the stroke; hold S to move, turn and scale it), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a **particle brush**, **smudge**, **clone** (V + click sets the source, marked in the 3D and 2D views; an Aligned option keeps or restarts the offset per stroke), material picker, Shift+click straight lines (Ctrl+Shift+click snaps them to 15 degree steps), and painting directly in the **2D UV view**. From d627b8c004a4a28d93f786c2efc96054a3386d8d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:47:05 +0000 Subject: [PATCH 135/190] Set the brush's channel values in cards under the fill layer's pills The Material section of a brush tool's Properties now looks like a fill layer's: the channel strip uses the fill's pills (Color, Metal, Rough, Normal, Height; a click turns a channel on or off, Alt+click keeps it alone), and each channel that is on gets a card with its swatch, name and "Uniform" under it. Base color has the colour bar with its eyedropper, Metallic, Roughness and Height a gray ramp with its value and invert glyph, and Normal reads "Flat" with no value row (the brush paints the flat normal). Each card's reset puts the channel back to its default value. Every change goes through tool.material. The eraser shows only the strip: it removes paint from the channels that are on and has no values to set. The hint lines under the old chips are gone. Polygon fill keeps its own material rows. A slot card whose source can't be swapped (these uniform channels) answers no clicks on its row and reads as a label, not a list. --- crates/ui-egui/src/dock.rs | 20 +--- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/material_sheet.rs | 71 +++++++++++++++ crates/ui-egui/src/property_sheet/mod.rs | 1 + crates/ui-egui/src/property_sheet/slot.rs | 54 +++++++---- .../ui-egui/src/property_sheet/slot_ends.rs | 16 ++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/popup_press_close.rs | 31 +++---- crates/ui-egui/tests/it/smudge_channels.rs | 33 ++++--- crates/ui-egui/tests/it/tool_material.rs | 91 +++++++++++++++++++ 10 files changed, 250 insertions(+), 69 deletions(-) create mode 100644 crates/ui-egui/src/material_sheet.rs create mode 100644 crates/ui-egui/src/property_sheet/slot_ends.rs create mode 100644 crates/ui-egui/tests/it/tool_material.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 455bda0d..11c004ce 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2114,15 +2114,6 @@ fn tool_header(app: &mut TextureCraftApp, ui: &mut Ui) { /// The tool's sections, one page under the panel's jump tabs fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { legacy_body(ui, |ui| tool_header(app, ui)); - - // Rows not yet laid out by the sheet keep the spacing they were made with - let item_spacing = ui.spacing().item_spacing; - let legacy = |sheet: &mut PropertySheet<'_>, app: &mut TextureCraftApp, body: fn(&mut TextureCraftApp, &mut Ui)| { - sheet.ui.scope(|ui| { - ui.spacing_mut().item_spacing = item_spacing; - legacy_body(ui, |ui| body(app, ui)); - }); - }; PropertySheet::show(ui, "tool_sheet", |sheet| { for section in tool_sections(app) { // The Stencil caption carries its own reset @@ -2131,7 +2122,7 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { PaintSection::Brush => crate::brush_sheet::brush_section(app, sheet, menu), PaintSection::Alpha => crate::alpha_sheet::alpha_section(app, sheet), PaintSection::Stencil => crate::stencil_sheet::stencil_section(app, sheet), - PaintSection::Material => legacy(sheet, app, material_controls), + PaintSection::Material => crate::material_sheet::material_section(app, sheet), PaintSection::Grayscale => crate::mask_paint_panel::grayscale_section(app, sheet), } } @@ -2319,8 +2310,7 @@ const CHIPS_GAP: f32 = 4.0; /// Room right of the tool's colour swatch, like a linked material's const TOOL_SWATCH_RIGHT_MARGIN: f32 = LINK_SWATCH_RIGHT_MARGIN; -/// One chip per channel of the texture set, on while the tool's material has it enabled; returns the channels. -/// The Material tab and the Smudge panel both draw these, so they share one set of flags. +/// One chip per channel of the texture set, on while the tool's material has it enabled (the flags the Material section's pills show); returns the channels fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec { let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { @@ -2335,7 +2325,7 @@ fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec) { + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); + let names: Vec<&str> = channels.iter().map(|channel| tr(pill_name(*channel))).collect(); + let enabled: Vec = channels.iter().map(|channel| app.session.tool.enabled.contains(channel)).collect(); + if let Some((index, solo)) = sheet.channel_pills(&names, &enabled) + && let Some(channel) = channels.get(index) + { + let enable = solo || !enabled.get(index).copied().unwrap_or(false); + app.run("tool.material", json!({"channel": channel.id(), "enabled": enable, "solo": solo})); + } + if app.session.tool.tool == Tool::Eraser { + return; + } + + let shown: Vec = channels.into_iter().filter(|channel| app.session.tool.enabled.contains(channel)).collect(); + for channel in shown { + channel_card(app, sheet, channel); + } +} + +/// One channel's card: its swatch, name and source, the ⟲ back to the channel's default, then its colour bar or gray ramp (a normal paints flat and has none) +fn channel_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, channel: Channel) { + let slot_of = SourceSlot::Channel(channel); + let kind = channel.kind(); + let default = channel.default_value(); + let value = if kind == ChannelKind::NormalMap { default } else { app.session.tool.values.get(&channel).copied().unwrap_or(default) }; + + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = thumbnail(app, &sheet.ui.ctx().clone(), &Source::Uniform(value)); + let thumb = |painter: &egui::Painter, rect: egui::Rect| paint_thumbnail(painter, rect, &picture, &tokens); + let line = if kind == ChannelKind::NormalMap { tr("Flat") } else { tr("Uniform") }; + if sheet.slot_fixed(&thumb, slot_of.name(), line, value != default).reset { + app.run("tool.material", json!({"channel": channel.id(), "value": default})); + } + + match kind { + ChannelKind::Color => { + let pick = sheet.color_bar(slot_of.name(), value, app.picking_color, &app.session.doc.project.swatches); + if let Some(color) = take_color_pick(app, pick) { + app.run("tool.material", json!({"channel": channel.id(), "color": color})); + } + } + ChannelKind::Scalar | ChannelKind::Signed => { + let mut gray = value[0]; + let edit = sheet.ramp(slot_of.name(), &mut gray, slot_of.range()); + if edit.invert { + let inverted = if kind == ChannelKind::Signed { -gray } else { 1.0 - gray }; + app.run("tool.material", json!({"channel": channel.id(), "value": inverted})); + } else if edit.changed.is_some() { + app.run("tool.material", json!({"channel": channel.id(), "value": gray})); + } + } + ChannelKind::NormalMap => {} + } + sheet.close_card(); +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 837d6437..78394df0 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -47,6 +47,7 @@ mod size_columns; mod size_columns_response; mod slider; mod slot; +mod slot_ends; mod slot_response; mod source_card; mod stack_slider; diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 90d2111b..c1d7b6de 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -1,6 +1,7 @@ use egui::{Align2, CornerRadius, FontId, Painter, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; use egui_phosphor::regular as ic; +use super::slot_ends::SlotEnds; use super::switch_control::PILL_SIZE; use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, SlotResponse, TEXT_SIZE}; use crate::theme::semibold; @@ -14,6 +15,9 @@ const SLOT_HEIGHT: f32 = 36.0; /// Size of a slot's thumbnail pub(super) const THUMB_SIZE: f32 = 26.0; +/// Width of the thumbnail's frame, lit while the row is hovered, in points +const THUMB_OUTLINE_WIDTH: f32 = 1.0; + /// Air between the thumbnail and the slot's name const THUMB_TO_NAME: f32 = 10.0; @@ -73,31 +77,32 @@ impl PropertySheet<'_> { self.open_card(); self.scope = self.named_id("slot", name); self.space(SLOT_CARD_TOP); - self.slot_row(thumbnail, name, source, on, clear, reset.then_some(true)) + self.slot_row(thumbnail, name, source, SlotEnds { on, clear, reset: reset.then_some(true), pickable: true }) } /// [`Self::slot`] whose ⟲ always shows beside the ×, faint and inert while what it restores is at its defaults (`changed` false) pub(crate) fn slot_restorable(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, changed: bool) -> SlotResponse { self.open_card(); self.space(SLOT_CARD_TOP); - self.slot_row(thumbnail, name, source, None, true, Some(changed)) + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear: true, reset: Some(changed), pickable: true }) + } + + /// A slot card whose one source can't be swapped (a brush's uniform channel): the row picks nothing, its ⟲ is faint and inert while at the defaults (`changed` false) + pub(crate) fn slot_fixed(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, changed: bool) -> SlotResponse { + self.open_card(); + self.scope = self.named_id("slot", name); + self.space(SLOT_CARD_TOP); + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear: false, reset: Some(changed), pickable: false }) } /// [`Self::slot`]'s row inside the card open now (an input a mode adds, under that mode), not a card of its own pub(crate) fn slot_in_card(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, clear: bool) -> SlotResponse { - self.slot_row(thumbnail, name, source, None, clear, None) + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear, reset: None, pickable: true }) } - /// A slot row: thumbnail, name over source, then ⟲ (`Some(changed)`), × and the toggle on the right; the row opens the source list - fn slot_row( - &mut self, - thumbnail: &dyn Fn(&Painter, Rect), - name: &str, - source: &str, - on: Option<&mut bool>, - clear: bool, - reset: Option, - ) -> SlotResponse { + /// A slot row: thumbnail, name over source, then ⟲ (`Some(changed)`), × and the toggle on the right; the row opens the source list when `pickable` + fn slot_row(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, ends: SlotEnds<'_>) -> SlotResponse { + let SlotEnds { on, clear, reset, pickable } = ends; let rect = self.take(SLOT_HEIGHT); let center_y = rect.top() + SLOT_HEIGHT / 2.0; let enabled = on.as_deref().copied().unwrap_or(true); @@ -109,8 +114,16 @@ impl PropertySheet<'_> { // The picker spans the card while the trailing glyphs keep their own hit areas let row = self.bled_row(rect); let pick_id = self.next_id(); - let pick = self.ui.interact(row, pick_id, Sense::click()); - pick.widget_info(|| egui::WidgetInfo { current_text_value: Some(source.to_owned()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name) }); + let pick = self.ui.interact(row, pick_id, if pickable { Sense::click() } else { Sense::hover() }); + if pickable { + pick.widget_info(|| egui::WidgetInfo { + current_text_value: Some(source.to_owned()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name) + }); + } else { + // A label's words are its value, so the name and source read as one + pick.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, false, format!("{name}: {source}"))); + } let mut result = SlotResponse { pick, clear: false, reset: false, toggled: false }; let tokens = self.tokens; @@ -119,15 +132,16 @@ impl PropertySheet<'_> { painter.rect_stroke( thumb, CornerRadius::ZERO, - Stroke::new(1.0, if result.pick.hovered() { tokens.accent } else { tokens.field_border }), + Stroke::new(THUMB_OUTLINE_WIDTH, if pickable && result.pick.hovered() { tokens.accent } else { tokens.field_border }), StrokeKind::Inside, ); let text_x = thumb.right() + THUMB_TO_NAME; + let (name_font, name_color) = if enabled { (semibold(TEXT_SIZE), tokens.text) } else { (FontId::proportional(TEXT_SIZE), tokens.text_dim) }; painter.text(pos2(text_x, center_y - NAME_ABOVE_CENTER), Align2::LEFT_CENTER, name, name_font, name_color); painter.text(pos2(text_x, center_y + SOURCE_BELOW_CENTER), Align2::LEFT_CENTER, source, FontId::proportional(SOURCE_TEXT_SIZE), tokens.text_dim); - for (shown, live, x, glyph, tip, slot) in [ + for (shown, live, x, glyph, tip, clicked) in [ (clear, true, clear_x, ic::X, crate::i18n::n_("Clear"), &mut result.clear), (reset.is_some(), reset.unwrap_or(false), reset_x, ic::CLOCK_COUNTER_CLOCKWISE, crate::i18n::n_("Restore defaults"), &mut result.reset), ] { @@ -138,14 +152,15 @@ impl PropertySheet<'_> { let glyph_rect = Rect::from_center_size(pos2(x, center_y), Vec2::splat(SLOT_GLYPH_BOX)); let id = self.next_id(); - // At the defaults the ⟲ is faint and inert, as on a band: a click there picks the source like the rest of the row + // At the defaults the ⟲ is faint and inert, as on a band: on a pickable row a click there picks the source like the rest of the row let response = if live { self.tip(self.ui.interact(glyph_rect, id, Sense::click()), crate::i18n::tr(tip)) } else { self.ui.interact(glyph_rect, id, Sense::hover()) }; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, live, crate::i18n::tr(tip))); - *slot = live && response.clicked(); + *clicked = live && response.clicked(); + let color = self.reset_glyph_color(live, response.hovered(), tokens.text); painter.text(glyph_rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(SLOT_ICON_SIZE), color); } @@ -161,6 +176,7 @@ impl PropertySheet<'_> { response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *on, name)); self.pill(pill.center(), *on, true); } + self.drawn(thumb.bottom()); result } diff --git a/crates/ui-egui/src/property_sheet/slot_ends.rs b/crates/ui-egui/src/property_sheet/slot_ends.rs new file mode 100644 index 00000000..cfc42cda --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slot_ends.rs @@ -0,0 +1,16 @@ +//! What a slot row offers besides its picture and words + +/// A slot row's toggle, ×, ⟲ and whether the row opens the source list +pub(super) struct SlotEnds<'a> { + /// The on/off pill at the right end, when the slot has one + pub(super) on: Option<&'a mut bool>, + + /// The × back to a uniform source shows + pub(super) clear: bool, + + /// The ⟲ shows: `Some(changed)`, faint and inert while unchanged + pub(super) reset: Option, + + /// A click on the row opens the source list + pub(super) pickable: bool, +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0d68818b..f5671628 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -106,6 +106,7 @@ mod temp_dir; mod template_invert; mod templates_681; mod tool_availability; +mod tool_material; mod tool_settings_saved; mod toolbar; mod user_smart_mask; diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index aaa8b824..42393fa3 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -1,4 +1,4 @@ -//! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the tool's colour, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart +//! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the brush presets, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart use eframe::App as _; use egui::accesskit::Role; @@ -18,9 +18,6 @@ const DRAG_MOVES: usize = 6; /// A short stroke on the model const STROKE: Vec2 = vec2(-60.0, 40.0); -/// From the tool's Base color label to inside its swatch -const LABEL_TO_SWATCH: f32 = 60.0; - /// The app started on `storage` (its saved arrangement, if any) with the paint tool's Properties showing fn app(storage: &MemoryStorage) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); @@ -91,23 +88,17 @@ fn stroke_on_model(harness: &mut Harness<'_, TextureCraftApp>, modifiers: Modifi drag(harness, view.center(), STROKE, modifiers); } -/// Opens the paint tool's Base color swatch from its Properties' Material section -fn open_tool_color(harness: &mut Harness<'_, TextureCraftApp>) { - harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); - harness.run_steps(SETTLE_FRAMES); - - let header = harness.get_by_role_and_label(egui::Role::Tab, "Properties - Paint").rect(); - let in_properties = |rect: egui::Rect| header.x_range().contains(rect.center().x) && rect.top() > header.top(); - - let label = harness.get_all_by_value("Base color").find(|node| in_properties(node.rect())).unwrap().rect(); - click(harness, label.right_center() + vec2(LABEL_TO_SWATCH, 0.0)); - assert!(egui::Popup::is_any_open(&harness.ctx), "the swatch opens its colour popup"); +/// Opens the brush presets from the ≡ on the paint tool's Brush caption +fn open_brush_presets(harness: &mut Harness<'_, TextureCraftApp>) { + let menu = harness.get_by_role_and_label(Role::Button, "Brush presets").rect(); + click(harness, menu.center()); + assert!(egui::Popup::is_any_open(&harness.ctx), "the ≡ opens the brush presets"); } #[test] -fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_restored_rearranged_layout() { +fn a_stroke_on_the_model_closes_the_brush_presets_in_the_default_and_a_restored_rearranged_layout() { let check_stroke = |mut harness: Harness<'_, TextureCraftApp>, layout: &str| { - open_tool_color(&mut harness); + open_brush_presets(&mut harness); let history = harness.state().session.history_labels().len(); stroke_on_model(&mut harness, Modifiers::NONE); @@ -121,9 +112,9 @@ fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_resto } #[test] -fn an_alt_orbit_keeps_the_tool_colour_popup_open() { +fn an_alt_orbit_keeps_the_brush_presets_open() { let mut harness = app(&MemoryStorage::default()); - open_tool_color(&mut harness); + open_brush_presets(&mut harness); stroke_on_model(&mut harness, Modifiers::ALT); @@ -147,7 +138,7 @@ fn a_stroke_on_the_model_closes_the_add_effect_menu() { fn outside_drag_dismissal_handles_motion_batched_with_release() { for (modifiers, stays_open) in [(Modifiers::ALT, true), (Modifiers::NONE, false)] { let mut harness = app(&MemoryStorage::default()); - open_tool_color(&mut harness); + open_brush_presets(&mut harness); let origin = harness.state().viewport_rect.center(); harness.event(Event::ModifiersChanged(modifiers)); harness.hover_at(origin); diff --git a/crates/ui-egui/tests/it/smudge_channels.rs b/crates/ui-egui/tests/it/smudge_channels.rs index e7ea6d76..083ce503 100644 --- a/crates/ui-egui/tests/it/smudge_channels.rs +++ b/crates/ui-egui/tests/it/smudge_channels.rs @@ -9,6 +9,9 @@ use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, Tool, execute}; use texturecraft_ui_egui::TextureCraftApp; +/// Frames egui's scroll animation takes to bring a row into view +const SCROLL_FRAMES: usize = 30; + fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); let mut harness = Harness::builder() @@ -25,11 +28,9 @@ fn run(harness: &mut Harness<'_, TextureCraftApp>, command: &str, params: Value) harness.run_steps(4); } -/// The Smudge panel's chip for `channel`: the top one, over the Material section's +/// The Smudge panel's chip for `channel` (the Material section's pill below it is a checkbox) fn smudge_chip<'a>(harness: &'a Harness<'_, TextureCraftApp>, channel: Channel) -> egui_kittest::Node<'a> { - let chips: Vec<_> = harness.get_all_by_role_and_label(Role::Button, channel.short()).collect(); - assert_eq!(chips.len(), 2, "the Smudge panel and the Material section each draw a {} chip", channel.short()); - chips.into_iter().min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() + harness.get_by_role_and_label(Role::Button, channel.short()) } fn chip_is_on(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> bool { @@ -84,16 +85,22 @@ fn clicking_a_channel_in_the_smudge_panel_turns_it_off_and_on_for_the_material() #[test] fn material_tab_and_smudge_panel_stay_in_sync() { let mut harness = harness(); - // Both the Smudge panel and the Material section draw a chip per channel - let chips = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).count(); - assert_eq!(chips, 2, "Smudge panel and Material tab"); - - let first = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).next().unwrap(); - first.click(); + // The Smudge panel draws a chip per channel, the Material section a pill + harness.get_by_role_and_label(Role::CheckBox, "Height").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + harness.get_by_role_and_label(Role::CheckBox, "Height").click(); harness.run_steps(4); assert!(!harness.state().session.tool.enabled.contains(&Channel::Height)); - for chip in harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()) { - assert_ne!(chip.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "both chips show height off"); - } + assert!(!chip_is_on(&harness, Channel::Height), "the Smudge panel's chip shows height off"); + let pill = harness.get_by_role_and_label(Role::CheckBox, "Height"); + assert_ne!(pill.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "so does the Material section's pill"); + + smudge_chip(&harness, Channel::Height).scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + smudge_chip(&harness, Channel::Height).click(); + harness.run_steps(4); + + let pill = harness.get_by_role_and_label(Role::CheckBox, "Height"); + assert_eq!(pill.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the chip turns the pill back on") } diff --git a/crates/ui-egui/tests/it/tool_material.rs b/crates/ui-egui/tests/it/tool_material.rs new file mode 100644 index 00000000..15fe5c3e --- /dev/null +++ b/crates/ui-egui/tests/it/tool_material.rs @@ -0,0 +1,91 @@ +//! A brush tool's Material section: the fill layer's channel pills, then a card per channel that is on with the value the brush paints + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::drag; +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, click_widget}; + +/// A second at 60 frames: the Material tab's jump scrolls with egui's scroll animation +const SCROLL_FRAMES: usize = 60; + +/// `tool`'s Properties scrolled to its Material section +fn material_section(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + click_widget(&mut harness, Role::Tab, "Material"); + harness.run_steps(SCROLL_FRAMES); + harness +} + +fn tool_value(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> [f32; 3] { + harness.state().session.tool.values.get(&channel).copied().unwrap_or(channel.default_value()) +} + +/// The top row of the card named `card` ("Metallic: Uniform"), if it shows +fn card_row(harness: &Harness<'_, TextureCraftApp>, card: &str) -> Option { + let named = |node: &egui_kittest::Node<'_>| node.accesskit_node().value().is_some_and(|value| value.starts_with(&format!("{card}: "))); + harness.query_all_by_role(Role::Label).find(named).map(|node| node.rect()) +} + +/// Clicks the widget with `role` and `label` on the top row of the card named `card` +fn click_in_card(harness: &mut Harness<'_, TextureCraftApp>, card: &str, role: Role, label: &str) { + let row = card_row(harness, card).unwrap(); + let at = harness.get_all_by_role_and_label(role, label).map(|node| node.rect().center()).find(|at| row.contains(*at)).unwrap(); + click_at(harness, at); +} + +#[test] +fn each_channel_that_is_on_gets_a_card_whose_reset_returns_the_channels_default() { + let mut harness = material_section("paint"); + assert!(harness.query_by_role_and_label(Role::Button, "Base color").is_some(), "Base color is a colour bar"); + for gray in ["Metallic", "Roughness", "Height"] { + assert!(harness.query_by_role_and_label(Role::Slider, gray).is_some(), "{gray} is a gray ramp"); + } + assert!(card_row(&harness, "Normal").is_some(), "Normal has a card"); + assert!(harness.query_by_role_and_label(Role::Slider, "Normal").is_none(), "the normal paints flat: no value to set"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "metallic", "value": 0.8})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + click_in_card(&mut harness, "Metallic", Role::Button, "Restore defaults"); + + assert_eq!(tool_value(&harness, Channel::Metallic), Channel::Metallic.default_value(), "⟲ goes back to the channel's default"); + + click_widget(&mut harness, Role::CheckBox, "Metal"); + + assert!(!harness.state().session.tool.enabled.contains(&Channel::Metallic), "off in the strip, the brush stops painting Metallic"); + assert!(card_row(&harness, "Metallic").is_none(), "a channel that is off has no card"); +} + +#[test] +fn a_click_on_a_ramp_sets_the_value_the_brush_paints() { + let mut harness = material_section("paint"); + let before = tool_value(&harness, Channel::Roughness); + harness.get_by_role_and_label(Role::Slider, "Roughness").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + let track = harness.get_by_role_and_label(Role::Slider, "Roughness").rect(); + + drag(&mut harness, track.center(), egui::pos2(track.right() - SLIDER_END_INSET, track.center().y)); + + assert!(tool_value(&harness, Channel::Roughness)[0] > before[0], "dragged toward the ramp's white end the brush paints rougher"); +} + +#[test] +fn the_eraser_picks_its_channels_without_value_cards() { + let harness = material_section("eraser"); + assert!(harness.query_by_role_and_label(Role::CheckBox, "Color").is_some(), "the channel strip"); + assert!(harness.query_by_role_and_label(Role::Button, "Base color").is_none(), "the eraser paints no colour"); + assert!(harness.query_by_role_and_label(Role::Slider, "Roughness").is_none()); +} From bec8934c807e24ed355de36d06c5cdf260653ff4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:05:09 +0000 Subject: [PATCH 136/190] Leave the brush tools' Properties without hint lines The Brush section's two Ctrl+drag lines go (the shortcuts stay in the keymap), the Smudge section's two lines become the tooltips of Strength and Channels dragged, and the Clone section's lines become the tooltip of its source row, which reads Source: none until one is set. --- crates/ui-egui/src/brush_sheet.rs | 2 - crates/ui-egui/src/dock.rs | 46 ++++++++++-------- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/paint_hint_lines.rs | 53 +++++++++++++++++++++ 4 files changed, 81 insertions(+), 21 deletions(-) create mode 100644 crates/ui-egui/tests/it/paint_hint_lines.rs diff --git a/crates/ui-egui/src/brush_sheet.rs b/crates/ui-egui/src/brush_sheet.rs index 71f49872..1f08fd32 100644 --- a/crates/ui-egui/src/brush_sheet.rs +++ b/crates/ui-egui/src/brush_sheet.rs @@ -59,8 +59,6 @@ pub(crate) fn brush_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet if let Some(menu) = menu { brush_presets_popover(app, sheet.ui, menu); } - sheet.dim_line(tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.")); - sheet.dim_line(tr("Ctrl+Shift+right-drag: size and hardness in fine steps.")); let tokens = Tokens::get(sheet.ui.ctx()); let image = app.session.tool.brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)).cloned(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 11c004ce..27b12c33 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2135,7 +2135,6 @@ fn tool_sections(app: &TextureCraftApp) -> Vec { } fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Clone"))); ui.horizontal(|ui| { ui.label(tr("Copy from")); @@ -2148,6 +2147,7 @@ fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { } } }); + let mut aligned = app.session.tool.clone_aligned; if ui .checkbox(&mut aligned, tr("Aligned")) @@ -2156,39 +2156,47 @@ fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { { app.run("tool.brush", json!({"cloneAligned": aligned})); } - let Some(src) = app.session.tool.clone_source else { - ui.label(RichText::new(tr("Hold V and click the mesh to set the source, then paint elsewhere to copy it.")).color(tk.text_dim)); + + let Some(source) = app.session.tool.clone_source else { + ui.label(tr("Source: none")).on_hover_text(tr("Hold V and click the mesh to set the source, then paint elsewhere to copy it.")); return; }; - ui.horizontal(|ui| { - ui.label(trf("Source U {u} V {v}", &[("u", &format!("{:.3}", src.uv[0])), ("v", &format!("{:.3}", src.uv[1]))])); - if ui.small_button(tr("Clear")).clicked() { - app.run("tool.cloneSource", json!({"clear": true})); - } - }); let hint = if !app.session.tool.clone_aligned { tr("Not aligned: every stroke starts at the source. V + click sets a new source.") - } else if src.offset.is_some() { + } else if source.offset.is_some() { tr("Aligned: the offset set by the first stroke is kept. V + click sets a new source.") } else { tr("The first stroke sets the offset from the source.") }; - ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); + ui.horizontal(|ui| { + ui.label(trf("Source U {u} V {v}", &[("u", &format!("{:.3}", source.uv[0])), ("v", &format!("{:.3}", source.uv[1]))])).on_hover_text(hint); + if ui.small_button(tr("Clear")).clicked() { + app.run("tool.cloneSource", json!({"clear": true})); + } + }); } +/// Space between the smudge strength and the channels it drags +const SMUDGE_CHANNELS_GAP: f32 = 4.0; + +/// Full value of the smudge strength slider, the 0..100 scale `tool.brush` takes +const SMUDGE_STRENGTH_PERCENT: f32 = 100.0; + fn smudge_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Smudge"))); - let mut v = app.session.tool.smudge_strength * 100.0; - if slider(ui, tr("Strength"), &mut v, 0.0..=100.0, 0).changed() { - app.session.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0); + + let mut strength_percent = app.session.tool.smudge_strength * SMUDGE_STRENGTH_PERCENT; + let strength = slider(ui, tr("Strength"), &mut strength_percent, 0.0..=SMUDGE_STRENGTH_PERCENT, 0); + if strength.on_hover_text(tr("Drags the layer stack's values along the stroke into the selected layer.")).changed() { + app.run("tool.brush", json!({"smudgeStrength": strength_percent})); } - ui.label(RichText::new(tr("Drags the layer stack's values along the stroke into the selected layer.")).size(10.5).color(tk.text_dim)); - ui.add_space(4.0); - ui.label(tr("Channels dragged")); + + ui.add_space(SMUDGE_CHANNELS_GAP); + ui.label(tr("Channels dragged")).on_hover_text(tr( + "These are the brush's material channels, the same ones Paint writes and the Material tab shows. A channel the selected layer does not have is skipped.", + )); material_channel_chips(app, ui); - ui.label(RichText::new(tr("These are the brush's material channels, the same ones Paint writes and the Material tab shows. A channel the selected layer does not have is skipped.")).size(10.5).color(tk.text_dim)); } fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index f5671628..ed1fd104 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -69,6 +69,7 @@ mod nav_buttons; mod new_project_baked_maps; mod new_project_window; mod output_templates; +mod paint_hint_lines; mod paint_tool_tabs; mod panel_header; mod path_in_view; diff --git a/crates/ui-egui/tests/it/paint_hint_lines.rs b/crates/ui-egui/tests/it/paint_hint_lines.rs new file mode 100644 index 00000000..c4759186 --- /dev/null +++ b/crates/ui-egui/tests/it/paint_hint_lines.rs @@ -0,0 +1,53 @@ +//! A brush tool's Properties explain themselves in tooltips: no line of instructions under the controls + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +fn with_tool(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// The words of every label in the app +fn labels(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.query_all_by_role(Role::Label).filter_map(|node| node.accesskit_node().value().map(|value| value.to_string())).collect() +} + +#[test] +fn the_brush_section_has_no_shortcut_lines() { + let harness = with_tool("paint"); + assert!(harness.query_by_role_and_label(Role::Slider, "Size").is_some(), "the Brush section is on screen"); + let labels = labels(&harness); + let shortcut = labels.iter().find(|label| label.contains("drag")); + assert!(shortcut.is_none(), "the view shortcuts are in the keymap, not under the brush: {shortcut:?}"); +} + +#[test] +fn the_smudge_section_has_no_explanation_lines() { + let labels = labels(&with_tool("smudge")); + assert!(labels.iter().any(|label| label == "Channels dragged"), "the Smudge section is on screen"); + let sentence = labels.iter().find(|label| label.ends_with('.')); + assert!(sentence.is_none(), "what Smudge does is in its tooltips: {sentence:?}"); +} + +#[test] +fn the_clone_section_shows_its_source_state_without_instructions() { + let labels = labels(&with_tool("clone")); + assert!(labels.iter().any(|label| label == "Source: none"), "no source set yet reads as state"); + let sentence = labels.iter().find(|label| label.ends_with('.')); + assert!(sentence.is_none(), "how to set the source is in the tooltip: {sentence:?}"); +} From a82b9312fd8ee4cd7f2feb03fb18815a3a21b974 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:17:59 +0000 Subject: [PATCH 137/190] Keep the right-click popup's brush pictures apart from the docked panel's The popup and the docked panel draw the brush preview, stamp dial and jitter strip at their own widths through one cache entry per picture, so each frame one replaced the other's texture: the popup's pictures came out blank and both were rendered again every frame. The cache now keeps one entry per drawing layer. --- crates/ui-egui/src/brush_stroke_preview.rs | 3 ++- crates/ui-egui/tests/it/properties_popup.rs | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/brush_stroke_preview.rs b/crates/ui-egui/src/brush_stroke_preview.rs index 245065bb..52b8b9b3 100644 --- a/crates/ui-egui/src/brush_stroke_preview.rs +++ b/crates/ui-egui/src/brush_stroke_preview.rs @@ -53,7 +53,8 @@ impl BrushStrokePreview { let pixels_per_point = ctx.pixels_per_point(); let size = [(rect.width() * pixels_per_point).round().max(1.0) as usize, (rect.height() * pixels_per_point).round().max(1.0) as usize]; let tints: Vec<[u8; 3]> = (0..size[0]).map(|x| tint((x as f32 + 0.5) / size[0] as f32)).collect(); - let id = Id::unique(key); + // The docked panel and the right-click popup draw the same picture at their own widths: one cache each + let id = Id::unique(key).with(painter.layer_id()); let cached = ctx.data(|data| data.get_temp::(id)).filter(|preview| { preview.brush == *brush && preview.size == size && preview.tints == tints && preview.image.as_ref().map(Arc::as_ptr) == image.map(Arc::as_ptr) }); diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index cb96b1e3..80403926 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -201,6 +201,27 @@ fn it_shows_what_the_properties_panel_shows() { assert!(!in_popup("Minimum Size (%)"), "not the brush's"); } +#[test] +fn its_brush_pictures_and_the_docked_panels_keep_their_own_textures() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + + assert!(is_open(&harness)); + + let previews = |harness: &Harness<'_, TextureCraftApp>| { + let mut ids: Vec<_> = + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name == "brush_stroke_preview").map(|(id, _)| *id).collect(); + ids.sort_unstable_by_key(|id| format!("{id:?}")); + ids + }; + let before = previews(&harness); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(before.len(), 2, "one stroke preview for the docked panel and one for the popup"); + assert_eq!(previews(&harness), before, "neither is drawn again while the brush stays the same"); +} + /// Whether the jump tab `name` inside `area` is the lit one fn tab_lit(harness: &Harness<'_, TextureCraftApp>, area: egui::Rect, name: &str) -> bool { let tab = harness.get_all_by_role_and_label(Role::Tab, name).find(|tab| area.contains_rect(tab.rect())); From 1ace4f12e9ad628d792fbbae3f28830015bb4224 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:19:29 +0000 Subject: [PATCH 138/190] Set the lazy mouse in the top bar only, and give its Spacing the Properties range The Brush section's folded Lazy mouse band repeated the top bar's button and distance; it goes, as the reference keeps the lazy mouse in the top bar. The top bar's Spacing slider stopped at 200 % while Properties' goes to 1000 %; both now reach 1000 %. Saved values are unchanged. --- crates/ui-egui/src/brush_sheet.rs | 11 +----- crates/ui-egui/src/toolbar.rs | 2 +- .../ui-egui/tests/it/brush_section_reset.rs | 12 ++++-- crates/ui-egui/tests/it/toolbar.rs | 37 ++++++++++++++++++- crates/ui-egui/tests/ui_snapshots.rs | 6 +-- 5 files changed, 50 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/brush_sheet.rs b/crates/ui-egui/src/brush_sheet.rs index 1f08fd32..cf4a7022 100644 --- a/crates/ui-egui/src/brush_sheet.rs +++ b/crates/ui-egui/src/brush_sheet.rs @@ -41,12 +41,11 @@ const POSITION_JITTER_PERCENT_RANGE: RangeInclusive = 0.0..=400.0; const PERCENT_RANGE: RangeInclusive = 0.0..=100.0; -/// The ranges of Stamp depth, Gravity, particles per stamp, a particle's lifetime in steps and the lazy mouse distance in pixels +/// The ranges of Stamp depth, Gravity, particles per stamp, and a particle's lifetime in steps const STAMP_DEPTH_RANGE: RangeInclusive = 0.05..=4.0; const GRAVITY_RANGE: RangeInclusive = 0.0..=2.0; const PARTICLE_COUNT_RANGE: RangeInclusive = 1.0..=16.0; const PARTICLE_LIFETIME_RANGE: RangeInclusive = 1.0..=128.0; -const LAZY_DISTANCE_RANGE: RangeInclusive = 0.0..=200.0; /// Width of the brush presets list const PRESETS_WIDTH: f32 = 230.0; @@ -156,14 +155,6 @@ pub(crate) fn brush_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet sheet.slider(tr("Gravity"), &mut particles.gravity, GRAVITY_RANGE, 2); } - let band = sheet.band(tr("Lazy mouse"), false, Some(brush.lazy != defaults.lazy), None); - if band.reset { - brush.lazy = defaults.lazy; - } - if band.open { - sheet.slider(tr("Lazy mouse distance"), &mut brush.lazy, LAZY_DISTANCE_RANGE, 0); - } - *brush = brush.sanitized(); } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 21cf3c93..842f4dc7 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -283,7 +283,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) const SIZE_PERCENT_RANGE: std::ops::RangeInclusive = 0.05..=100.0; /// Spacing's track, in percent of the brush's diameter - const SPACING_PERCENT_RANGE: std::ops::RangeInclusive = 1.0..=200.0; + const SPACING_PERCENT_RANGE: std::ops::RangeInclusive = 1.0..=1000.0; /// Lazy mouse Distance's track, in pixels const LAZY_DISTANCE_RANGE_PX: std::ops::RangeInclusive = 1.0..=200.0; diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index 88d15966..3bf18f0a 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -18,7 +18,7 @@ const SETTLE_FRAMES: usize = 3; type SectionReset = fn(&mut BrushSettings, &BrushSettings); /// Each band's title, a label shown only while it is open, whether it starts open, and its reset -const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ +const SECTIONS: [(&str, &str, bool, SectionReset); 6] = [ ("Size", "Minimum Size (%)", true, |brush, defaults| { (brush.size, brush.size_pressure, brush.min_size, brush.spacing) = (defaults.size, defaults.size_pressure, defaults.min_size, defaults.spacing) }), @@ -33,7 +33,6 @@ const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.screen_space, defaults.depth) }), ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), - ("Lazy mouse", "Lazy mouse distance", false, |brush, defaults| brush.lazy = defaults.lazy), ]; /// A valid brush with every section field changed and a custom alpha that resets must preserve @@ -81,7 +80,7 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { harness } -/// The band titled `title` in Properties: the rightmost, as the top bar has a Size and a Lazy mouse too +/// The band titled `title` in Properties: the rightmost, as the top bar has a Size too fn band<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { harness .query_all_by_role(egui::Role::Button) @@ -108,6 +107,13 @@ fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { harness.run_steps(SETTLE_FRAMES); } +#[test] +fn the_lazy_mouse_is_set_only_in_the_top_bar() { + let harness = app_with_brush(BrushSettings::default()); + + assert_eq!(harness.query_all_by_label("Lazy mouse").count(), 1, "the top bar's button, no band in Properties"); +} + #[test] fn each_reset_puts_back_only_its_own_section() { let defaults = BrushSettings::default(); diff --git a/crates/ui-egui/tests/it/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs index c9271888..9c1b1adf 100644 --- a/crates/ui-egui/tests/it/toolbar.rs +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -6,6 +6,8 @@ use texturecraft_engine::{Session, Tool}; use texturecraft_ui_egui::state::{Mode, ViewLayout}; use texturecraft_ui_egui::{TextureCraftApp, theme, toolbar}; +use crate::DRAG_STEP_FRAMES; + fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> { let session = Session::new_project("Toolbar", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let context = eframe::CreationContext::_new_kittest(egui::Context::default()); @@ -24,12 +26,17 @@ fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> } fn size_label(harness: &Harness<'_, TextureCraftApp>) -> (egui::Pos2, egui::Rect) { + bar_label(harness, "Size") +} + +/// Where the top bar paints the slider label `label`, and that text's clip +fn bar_label(harness: &Harness<'_, TextureCraftApp>, label: &str) -> (egui::Pos2, egui::Rect) { harness .output() .shapes .iter() .find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == "Size" => Some((text.pos, shape.clip_rect)), + egui::Shape::Text(text) if text.galley.text() == label => Some((text.pos, shape.clip_rect)), _ => None, }) .unwrap() @@ -88,6 +95,34 @@ fn arrows_and_wheel_scroll_without_changing_the_brush() { assert_eq!(harness.state().session.tool.brush, brush); } +#[test] +fn the_spacing_slider_reaches_as_far_as_the_properties_one() { + // Wide enough that the bar shows Spacing without scrolling + const BAR_WIDTH: f32 = 1600.0; + // From the label's top left onto its text, which drags the value + const LABEL_GRAB_OFFSET: egui::Vec2 = egui::vec2(4.0, 8.0); + // Far enough right to pass the slider's end + const DRAG_PAST_END: f32 = 400.0; + // The top bar's old Spacing limit: 200 % of the diameter + const OLD_SPACING_LIMIT: f32 = 2.0; + + let mut harness = toolbar_harness(BAR_WIDTH, Tool::Paint); + let (label, _) = bar_label(&harness, "Spacing"); + let from = label + LABEL_GRAB_OFFSET; + let past_the_end = from + egui::vec2(DRAG_PAST_END, 0.0); + + harness.hover_at(from); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(DRAG_STEP_FRAMES); + harness.hover_at(past_the_end); + harness.run_steps(DRAG_STEP_FRAMES); + harness.event(egui::Event::PointerButton { pos: past_the_end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(DRAG_STEP_FRAMES); + + // Properties' Spacing goes to 1000 % of the diameter + assert!(harness.state().session.tool.brush.spacing > OLD_SPACING_LIMIT, "past the 200 % the top bar used to stop at"); +} + #[test] fn shorter_tools_and_wider_windows_remove_the_arrows() { let mut harness = toolbar_harness(700.0, Tool::Path); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index fe164ce6..4e275b7c 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3273,11 +3273,11 @@ fn paint_tool_properties_snapshots() { tool.brush = default_brush; tool.values = default_values; - // The top bar has a Lazy mouse button too: Properties is the rightmost + // The top bar has labels of the same names: Properties is the rightmost let in_properties = |harness: &Harness<'_, TextureCraftApp>, label: &str| { harness.get_all_by_label(label).map(|node| node.rect().center()).max_by(|a, b| a.x.total_cmp(&b.x)).unwrap() }; - for header in ["Particles", "Lazy mouse"] { + for header in ["Particles"] { harness.get_all_by_label(header).max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); harness.run_steps(3); let at = in_properties(&harness, header); @@ -3290,7 +3290,7 @@ fn paint_tool_properties_snapshots() { harness.get_by_label_contains("Brush presets").scroll_to_me(); harness.run_steps(3); save(&mut harness, &output_dir, "paint-brush-open"); - harness.get_all_by_label("Lazy mouse").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); + harness.get_all_by_label("Particles").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); harness.run_steps(6); save(&mut harness, &output_dir, "paint-brush-scrolled"); From 896cd220c8da0d51c21ca5d905b65668111c055a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:25:49 +0000 Subject: [PATCH 139/190] Keep the brush preview in view under the paint tool's tabs while its sections scroll --- crates/ui-egui/src/dock.rs | 38 +++++++--- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/properties_popup.rs | 1 + crates/ui-egui/src/tabbed_page.rs | 8 +++ crates/ui-egui/tests/it/paint_tool_tabs.rs | 16 ++++- crates/ui-egui/tests/ui_snapshots.rs | 84 ++++++++++++++++------ 6 files changed, 115 insertions(+), 33 deletions(-) create mode 100644 crates/ui-egui/src/tabbed_page.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 27b12c33..369eba60 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -20,6 +20,7 @@ use crate::past_end::PastEnd; use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; use crate::source_choice::SourceChoice; +use crate::tabbed_page::TabbedPage; use crate::theme::{Tokens, caption}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, slider, slider_edit}; @@ -1884,6 +1885,7 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(tabs) = properties_tabs(app) { crate::property_sheet::section_tabs(ui, scope, 0, &tabs); } + pinned_brush_preview(app, ui); let selection = properties_selection(app); crate::property_sheet::in_scope(ui, scope, |ui| { @@ -1924,6 +1926,14 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: /// The tabs over the panel when it shows a fill layer's, a mask fill effect's or a paint tool's sections, which they jump between pub(crate) fn properties_tabs(app: &TextureCraftApp) -> Option> { + Some(match tabbed_page(app)? { + TabbedPage::Fill { mask } => crate::fill_panel::fill_tabs(mask).to_vec(), + TabbedPage::Tool => tool_sections(app).into_iter().map(|section| (section.icon(), section.title())).collect(), + }) +} + +/// The page under the panel's jump tabs, if it shows one +fn tabbed_page(app: &TextureCraftApp) -> Option { if !app.session.project_open || app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } @@ -1932,19 +1942,25 @@ pub(crate) fn properties_tabs(app: &TextureCraftApp) -> Option { - return matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false).to_vec()); + return matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then_some(TabbedPage::Fill { mask: false }); } (Some(_), StackTarget::Effect(effect)) => match project.effect(effect).map(|(_, effect)| &effect.kind) { Some(EffectKind::Paint | EffectKind::Path(_)) => true, - _ => return mask_fill_of(project, effect).map(|_| crate::fill_panel::fill_tabs(true).to_vec()), + _ => return mask_fill_of(project, effect).map(|_| TabbedPage::Fill { mask: true }), }, (Some(layer), StackTarget::Content) => !layer.is_group() && layer.instance_source().is_none(), _ => true, }; // Everything else shows the tool's sections where the tool can paint - let tool_shown = tool_shown && app.session.tool_usable(app.session.tool.tool); - tool_shown.then(|| tool_sections(app).into_iter().map(|section| (section.icon(), section.title())).collect()) + (tool_shown && app.session.tool_usable(app.session.tool.tool)).then_some(TabbedPage::Tool) +} + +/// The brush preview under the tool's jump tabs: it stays in view while the sections scroll under it +pub(crate) fn pinned_brush_preview(app: &TextureCraftApp, ui: &mut Ui) { + if tabbed_page(app) == Some(TabbedPage::Tool) { + legacy_body(ui, |ui| brush_preview(app, ui)); + } } /// Effect `effect`'s source, projection and sampling when it is a mask fill the Properties panel lays out like a fill (a decal's placed fill keeps its own rows) @@ -2057,13 +2073,12 @@ const STROKE_GRAY_SAMPLES: u32 = 64; /// Gap under the brush preview const BRUSH_PREVIEW_GAP: f32 = 4.0; -/// The brush preview, then what only this tool has -fn tool_header(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The brush's own stroke in the colour it paints, and a sphere with the tool's material +fn brush_preview(app: &TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let content = targets_content(app); - - // Brush preview: the brush's own stroke in the colour it paints, and a sphere with the tool's material - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Brush preview"))); let painter = ui.painter(); painter.rect_filled(rect, BRUSH_PREVIEW_CORNER_RADIUS, tokens.viewport); let half_width = rect.width() * 0.5; @@ -2091,13 +2106,16 @@ fn tool_header(app: &mut TextureCraftApp, ui: &mut Ui) { BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, mask_tint); } ui.add_space(BRUSH_PREVIEW_GAP); +} +/// What only this tool has, above the sections every brush tool shares +fn tool_header(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); if app.session.quick_mask.editing { ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tokens.text_dim)); ui.separator(); } - // A tool's own settings, above the sections every brush tool shares let tool_section: Option = match app.session.tool.tool { Tool::Clone => Some(clone_section), Tool::Smudge => Some(smudge_section), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c508cf33..b2203133 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -178,6 +178,7 @@ mod stencil_choice; mod stencil_sheet; mod surface_paint_point; pub mod symmetry; +mod tabbed_page; pub mod theme; pub mod thumbs; mod tile_edits; diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 742ffc36..1d59fdc1 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -88,6 +88,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if let Some(tabs) = crate::dock::properties_tabs(app) { crate::property_sheet::section_tabs(ui, scope, ui.style().visuals.menu_corner_radius.nw, &tabs); } + crate::dock::pinned_brush_preview(app, ui); crate::property_sheet::in_scope(ui, scope, |ui| { // A popup that fits its rows keeps its size; one that scrolls goes on until its last section's top let area = egui::ScrollArea::vertical().id_salt("properties_popup_scroll"); diff --git a/crates/ui-egui/src/tabbed_page.rs b/crates/ui-egui/src/tabbed_page.rs new file mode 100644 index 00000000..815af5eb --- /dev/null +++ b/crates/ui-egui/src/tabbed_page.rs @@ -0,0 +1,8 @@ +//! Which page under jump tabs the Properties panel shows + +/// A fill's sections (`mask` for a mask fill effect) or the paint tool's +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum TabbedPage { + Fill { mask: bool }, + Tool, +} diff --git a/crates/ui-egui/tests/it/paint_tool_tabs.rs b/crates/ui-egui/tests/it/paint_tool_tabs.rs index 169dcc82..a51dfb26 100644 --- a/crates/ui-egui/tests/it/paint_tool_tabs.rs +++ b/crates/ui-egui/tests/it/paint_tool_tabs.rs @@ -1,4 +1,4 @@ -//! A paint tool's Properties: one page of sections under jump tabs, Brush · Alpha · (Stencil) · Material +//! A paint tool's Properties: one page of sections under jump tabs, Brush · Alpha · (Stencil) · Material, below a brush preview that stays put use egui::accesskit::Role; use egui_kittest::Harness; @@ -61,3 +61,17 @@ fn every_brush_tool_has_a_stencil_tab_and_polygon_fill_none() { let harness = paint_harness("polygonFill"); assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "polygon fill paints no strokes"); } + +#[test] +fn the_brush_preview_stays_under_the_tabs_while_the_sections_scroll() { + let mut harness = paint_harness("paint"); + let preview_before = harness.get_by_label("Brush preview").rect(); + let flow_before = harness.get_by_label("Flow").rect().top(); + + harness.get_by_role_and_label(Role::Tab, "Material").click(); + harness.run_steps(SCROLL_FRAMES); + + assert!(harness.get_by_label("Flow").rect().top() < flow_before, "the sections scrolled"); + assert_eq!(harness.get_by_label("Brush preview").rect(), preview_before, "the preview stayed where it was"); + assert!(preview_before.top() >= harness.get_by_role_and_label(Role::Tab, "Material").rect().bottom(), "under the tabs"); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 4e275b7c..fe111e01 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3206,7 +3206,7 @@ fn sheet_scroll_end_snapshots() { save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); } -/// The paint tool's Properties: the Brush tab with every section open and scrolled down, the Alpha and Material tabs, a stencil on the Projection tool, a mask's Grayscale tab, the right-click popup, and the Clone and Eraser tools' tabs; `TC_UI_THEMES` set adds the dark and light themes +/// The paint tool's Properties: the Brush tab with every section open and scrolled down, its presets, pen button and Alignment list mid-use, the Alpha tab with its picker open, the Material tab with a pill hovered, a stencil on the Projection tool, a mask's Grayscale tab, the right-click popup, and the Clone and Eraser tools' tabs; `TC_UI_THEMES` set adds the dark and light themes #[test] #[ignore] fn paint_tool_properties_snapshots() { @@ -3277,28 +3277,18 @@ fn paint_tool_properties_snapshots() { let in_properties = |harness: &Harness<'_, TextureCraftApp>, label: &str| { harness.get_all_by_label(label).map(|node| node.rect().center()).max_by(|a, b| a.x.total_cmp(&b.x)).unwrap() }; - for header in ["Particles"] { - harness.get_all_by_label(header).max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); - harness.run_steps(3); - let at = in_properties(&harness, header); - harness.hover_at(at); - for pressed in [true, false] { - harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - harness.run_steps(2); - } - } - harness.get_by_label_contains("Brush presets").scroll_to_me(); - harness.run_steps(3); - save(&mut harness, &output_dir, "paint-brush-open"); + // Open the Particles section harness.get_all_by_label("Particles").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); - harness.run_steps(6); - save(&mut harness, &output_dir, "paint-brush-scrolled"); + harness.run_steps(3); + let at = in_properties(&harness, "Particles"); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } let themes = std::env::var_os("TC_UI_THEMES").is_some(); - let tab = |harness: &mut Harness<'_, TextureCraftApp>, tab: &str, name: &str| { - harness.run_steps(2); - harness.get_by_role_and_label(egui::Role::Tab, tab).click(); - harness.run_steps(6); + let shoot = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { save(harness, &output_dir, name); if themes { for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { @@ -3308,9 +3298,59 @@ fn paint_tool_properties_snapshots() { harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; } }; + let hover = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + let at = harness.get_by_role_and_label(role, label).rect().center(); + harness.hover_at(at); + harness.run_steps(40); + }; + let open = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(6); + harness.get_by_role_and_label(role, label).click(); + harness.run_steps(6); + }; + let close = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + }; + harness.get_by_label_contains("Brush presets").scroll_to_me(); + harness.run_steps(3); + shoot(&mut harness, "paint-brush-open"); + open(&mut harness, egui::Role::Button, "Brush presets"); + shoot(&mut harness, "paint-presets-open"); + close(&mut harness); + hover(&mut harness, egui::Role::CheckBox, "Size pen pressure"); + shoot(&mut harness, "paint-size-pen-hover"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(6); + shoot(&mut harness, "paint-size-pen-off"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(4); + open(&mut harness, egui::Role::ComboBox, "Tangent | Wrap"); + shoot(&mut harness, "paint-alignment-open"); + close(&mut harness); + harness.get_all_by_label("Particles").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); + harness.run_steps(6); + shoot(&mut harness, "paint-brush-scrolled"); + + let tab = |harness: &mut Harness<'_, TextureCraftApp>, tab: &str, name: &str| { + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::Tab, tab).click(); + harness.run_steps(6); + shoot(harness, name); + }; tab(&mut harness, "Brush", "paint-brush-top"); tab(&mut harness, "Alpha", "paint-alpha"); + open(&mut harness, egui::Role::ComboBox, "Round"); + let star = + harness.query_all_by_role_and_label(egui::Role::ListBoxOption, "Star").map(|node| node.rect()).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap(); + harness.hover_at(star.center()); + harness.run_steps(6); + shoot(&mut harness, "paint-alpha-picker"); + close(&mut harness); tab(&mut harness, "Material", "paint-material"); + hover(&mut harness, egui::Role::CheckBox, "Height"); + shoot(&mut harness, "paint-material-pill-hover"); execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "eraser"})).unwrap(); tab(&mut harness, "Material", "eraser-material"); @@ -3323,7 +3363,7 @@ fn paint_tool_properties_snapshots() { harness.run_steps(3); harness.get_by_role_and_label(egui::Role::ComboBox, "No Tiling").click(); harness.run_steps(4); - save(&mut harness, &output_dir, "projection-stencil-tiling-open"); + shoot(&mut harness, "projection-stencil-tiling-open"); harness.get_by_label("H and V Tiling").click(); harness.run_steps(4); save(&mut harness, &output_dir, "projection-stencil-tiled"); @@ -3345,5 +3385,5 @@ fn paint_tool_properties_snapshots() { harness.run_steps(2); } harness.run_steps(6); - save(&mut harness, &output_dir, "paint-popup"); + shoot(&mut harness, "paint-popup"); } From 13deee13b46f32e611b1caec8a5a8f2d101d2f03 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:17:56 +0000 Subject: [PATCH 140/190] Draw the panel tabs and frames in TextureCraft's colours again craft-ui's dock has drawn every panel's tab strip and body in the suite's default grey since the move to craft-libs: the app gave craft-ui no theme. Hand it one built from the app's tokens (the strip on the window chrome, the shown tab and body on the panel card, the tab names in the app's text colours), kept while the tokens stay the same. --- crates/ui-egui/src/framework.rs | 3 ++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/library_theme.rs | 51 ++++++++++++++++++++++++ crates/ui-egui/tests/it/library_theme.rs | 38 ++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 5 files changed, 94 insertions(+) create mode 100644 crates/ui-egui/src/library_theme.rs create mode 100644 crates/ui-egui/tests/it/library_theme.rs diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs index 187d0de6..4cd127bb 100644 --- a/crates/ui-egui/src/framework.rs +++ b/crates/ui-egui/src/framework.rs @@ -121,6 +121,9 @@ impl TextureCraftApp { Brightness::Dark | Brightness::MediumDark => craft_theme::Mode::Dark, }; let mut root = RootEnv::new().mode(mode).scale(Scale::new(scale)); + if let Some(theme) = crate::library_theme::library_theme(ctx, &crate::theme::Tokens::get(ctx)) { + root = root.library_theme(theme); + } // Hide UI on another key leaves Tab to focus traversal and the shortcuts root.tab_toggles_chrome = crate::keymap::shortcut_of(&self.ui.keymap, "ui.hideUi") == Some("Tab"); let app_modal = crate::docking::input_blocked(self, ctx).then_some(ViewportId::ROOT); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b2203133..e0d1231a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -80,6 +80,7 @@ mod levels_display; mod levels_editor; mod levels_handle; mod levels_properties; +mod library_theme; mod line_snap; mod list_action; pub mod log_panel; diff --git a/crates/ui-egui/src/library_theme.rs b/crates/ui-egui/src/library_theme.rs new file mode 100644 index 00000000..9a120861 --- /dev/null +++ b/crates/ui-egui/src/library_theme.rs @@ -0,0 +1,51 @@ +//! TextureCraft's colours handed to craft-ui, so the dock's frames, tab strips and splitters draw in our theme instead of the suite's default grey + +use std::sync::Arc; + +use craft_theme::{ColorToken, ModePins, Pins, Rgba, SUITE_DEFAULT, ThemeDef, ThemeId, builtins}; +use egui::{Color32, Context, Id}; + +use crate::theme::Tokens; + +/// The id of TextureCraft's theme, apart from every built-in one +const THEME_ID: &str = "texturecraft.app"; + +/// The theme craft-ui resolves its tokens from (`RootEnv::library_theme`), kept while the tokens stay the same so it resolves once per theme change +pub(crate) fn library_theme(ctx: &Context, tokens: &Tokens) -> Option> { + let pins = app_pins(tokens); + let memory_id = Id::unique(THEME_ID); + let kept: Option> = ctx.data(|data| data.get_temp(memory_id)); + if let Some(def) = kept.filter(|def| def.pins.dark == pins) { + return Some(def); + } + let def = Arc::new(app_def(pins)?); + ctx.data_mut(|data| data.insert_temp(memory_id, Arc::clone(&def))); + Some(def) +} + +/// The suite default with TextureCraft's colours pinned in both modes (the root's mode picks one); `None` if the suite default is missing +fn app_def(pins: Pins) -> Option { + let mut def = builtins().iter().find(|theme| theme.id.as_str() == SUITE_DEFAULT)?.clone(); + def.id = ThemeId::parse(THEME_ID).ok()?; + def.pins = ModePins { light: pins.clone(), dark: pins }; + Some(def) +} + +fn app_pins(tokens: &Tokens) -> Pins { + [ + (ColorToken::SurfaceBackground, rgba(tokens.chrome)), + (ColorToken::SurfacePanel, rgba(tokens.panel)), + (ColorToken::LineBorder, rgba(tokens.separator)), + (ColorToken::AccentSolid, rgba(tokens.accent)), + // The shown tab's name is brighter than the others, as on the panel headers + (ColorToken::TextNormal, rgba(tokens.text_strong)), + (ColorToken::TextMuted, rgba(tokens.text_dim)), + ] + .into_iter() + .collect() +} + +fn rgba(color: Color32) -> Rgba { + let [r, g, b, a] = color.to_srgba_unmultiplied(); + Rgba([r, g, b, a]) +} diff --git a/crates/ui-egui/tests/it/library_theme.rs b/crates/ui-egui/tests/it/library_theme.rs new file mode 100644 index 00000000..3afe5219 --- /dev/null +++ b/crates/ui-egui/tests/it/library_theme.rs @@ -0,0 +1,38 @@ +//! craft-ui's parts (the dock's frames and tab strips) draw in TextureCraft's colours, not the suite's default grey + +use craft_ui::style::StyleCx; +use egui::Color32; +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::theme::{Brightness, Tokens}; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, TEXTURE_RESOLUTION}; + +/// A window wide enough for the dock's groups, strips and splitters +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1200.0, 800.0); + +fn srgba(color: craft_theme::Rgba) -> Color32 { + let [r, g, b, a] = color.0; + Color32::from_rgba_unmultiplied(r, g, b, a) +} + +#[test] +fn the_dock_strips_and_panel_bodies_take_the_app_theme_colours() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + for brightness in [Brightness::Dark, Brightness::MediumDark, Brightness::MediumLight, Brightness::Light] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(SETTLE_FRAMES); + let tokens = Tokens::get(&harness.ctx); + let (strip, body, frame) = StyleCx::with_root(&harness.ctx, |cx| { + let color = &cx.tokens.color; + (color.surface.background, color.surface.panel, color.line.border) + }); + assert_eq!(srgba(strip), tokens.chrome, "{brightness:?}: the tab strips lie on the window chrome"); + assert_eq!(srgba(body), tokens.panel, "{brightness:?}: the shown tab and the panel body are the panel card"); + assert_eq!(srgba(frame), tokens.separator, "{brightness:?}: the group frames are the cards' hairline"); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index ed1fd104..6ddf698a 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -59,6 +59,7 @@ mod layer_rename; mod layer_toolbar; mod layers_panel; mod levels_editor; +mod library_theme; mod log_panel_680; mod mask_export; mod mask_fill_rows; From 3c559657551320d817b6787b354fccddea86dfb8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:34:42 +0000 Subject: [PATCH 141/190] Set and report the Brush section's Projection settings through tool.brush The Projection band's Angle fade from / to and Stamp depth rows had no command behind them, and tool.brush took Size Space (screenSpace) without reporting it, so an agent could neither set nor read what the panel shows. tool.brush now takes angleFade [from, to] and stampDepth, refuses a malformed angleFade before changing anything, and returns all three. --- crates/engine/src/tool_cmds.rs | 12 ++++++++++-- crates/engine/tests/it/tool_settings.rs | 23 +++++++++++++++++++++++ docs/control-protocol.md | 7 ++++++- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index c924dc96..a890113d 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Brush settings", [], None, - "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, sizePressure? (default true: pen pressure shrinks the size towards minSize), smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", + "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, angleFade?: [from, to] degrees 0..90 (culled faces fade out between them), screenSpace? (the size follows the view), stampDepth?: 0.05..4, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, sizePressure? (default true: pen pressure shrinks the size towards minSize), smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", always, brush ), @@ -224,6 +224,13 @@ fn brush(session: &mut Session, params: &Value) -> Result { if let Some(value) = boolp(params, "backfaceCulling") { settings.backface_culling = value; } + if params.get("angleFade").is_some() { + let [from, to] = pair(params, "angleFade").ok_or_else(|| bad("tool.brush", "`angleFade` must be [from, to] in degrees"))?; + settings.angle_fade = (from, to); + } + if let Some(value) = f32p(params, "stampDepth") { + settings.depth = value; + } if let Some(value) = boolp(params, "symmetryOn") { settings.symmetry.enabled = value; @@ -312,7 +319,8 @@ pub(crate) fn brush_json(session: &Session) -> Value { }, "alphaSizeX": settings.alpha_params.size_x * PERCENT, "alphaSizeY": settings.alpha_params.size_y * PERCENT, "alphaRoundness": settings.alpha_params.roundness * PERCENT, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert, - "backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z], + "backfaceCulling": settings.backface_culling, "angleFade": [settings.angle_fade.0, settings.angle_fade.1], "screenSpace": settings.screen_space, + "stampDepth": settings.depth, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z], "radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) }, "symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span, "material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * PERCENT, "particles": settings.particles, diff --git a/crates/engine/tests/it/tool_settings.rs b/crates/engine/tests/it/tool_settings.rs index 281e28a0..ef5a921b 100644 --- a/crates/engine/tests/it/tool_settings.rs +++ b/crates/engine/tests/it/tool_settings.rs @@ -148,3 +148,26 @@ fn restored_stencil_and_smudge_settings_use_the_tool_limits() { let look = session.tool.stencil_look; assert_eq!((look.center, look.scale, look.opacity, look.rotation), ([-4.0, 4.0], 0.01, 0.0, 345.0)); } + +#[test] +fn tool_brush_sets_and_reports_the_projection_bands_settings() { + let mut session = another_project(); + let defaults = session.tool.brush.clone(); + let reported = execute(&mut session, "tool.brush", &json!({"angleFade": [20, 40], "stampDepth": 2.5, "screenSpace": !defaults.screen_space})).unwrap(); + + let brush = &session.tool.brush; + assert_ne!(brush.angle_fade, defaults.angle_fade, "Angle fade from / to changes through the command"); + assert_ne!(brush.depth, defaults.depth, "Stamp depth changes through the command"); + assert_eq!(reported["angleFade"], json!([brush.angle_fade.0, brush.angle_fade.1])); + assert_eq!(reported["stampDepth"], json!(brush.depth)); + assert_eq!(reported["screenSpace"], json!(brush.screen_space)); +} + +#[test] +fn a_malformed_angle_fade_leaves_the_brush_unchanged() { + let mut session = another_project(); + let before = session.tool.brush.clone(); + + assert!(execute(&mut session, "tool.brush", &json!({"size": 50, "angleFade": "steep"})).is_err()); + assert_eq!(session.tool.brush, before); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 184c1e75..5b8e0710 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -133,7 +133,12 @@ sampling at the source point. Changing `cloneAligned` forgets the offset of earl procedural Round alpha: 100 is a circle, 0 a square), `alphaContrast` (1..8, 1 leaves the values alone) and `alphaInvert` (swaps paint and no paint inside the stamp square). They apply to procedural, library and imported alphas alike and are returned by `tool.brush` with the other -values. The alpha's rotation is the brush `angle`. +values. The alpha's rotation is the brush `angle`. The Projection settings of the Brush section go +through `tool.brush` too and come back with it: `angleFade` (`[from, to]` in degrees, 0..90: with +`backfaceCulling` on, faces turned further than `from` from the view fade out until `to`), +`screenSpace` (Size Space Viewport: the size follows the view instead of the object) and +`stampDepth` (0.05..4). `sizePressure` (default `true`) lets pen pressure shrink the size towards +`minSize`; `false` keeps every stamp at full size. Bake mode applies an edit in Common Settings or Mesh Map Settings to the texture sets sharing that group's settings: Common Settings, and each map's settings, are shared by any set of texture sets From 9a871c0c064c6dc9ab4540f67245906bfc482072 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:34:42 +0000 Subject: [PATCH 142/190] Test that the eraser erases only through the stencil's gray The stencil now shapes every brush tool's strokes, but only the Paint tool's and a mask stroke had a headless test. --- crates/engine/tests/session.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 1c1a6a68..d91422fe 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -750,6 +750,28 @@ fn the_paint_tool_paints_its_own_color_through_the_stencils_gray() { assert!(right[0] > 0.8 && right[1] < 0.2 && right[2] < 0.2, "white stencil lets the tool's red through: {right:?}"); } +#[test] +fn the_eraser_erases_only_through_the_stencils_gray() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + let (left_painted, right_painted) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + + execute(&mut session, "tool.eraser", &Value::Null).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + + assert_eq!(base_color_at(&session, BLACK_DAB_X), left_painted, "black stencil keeps the paint from the eraser"); + assert_ne!(base_color_at(&session, WHITE_DAB_X), right_painted, "white stencil lets the eraser through"); +} + #[test] fn a_mask_stroke_shows_through_the_stencil_while_painting_as_it_commits() { let mut session = session_at(TEXTURE_SIZE); From 8f50db09f63510d14b0831f2f14ab79bf497d2f5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:39:51 +0000 Subject: [PATCH 143/190] Keep a brush channel card's name from reading as unavailable The Material section's channel cards mark their top row as a disabled label, so a screen reader announced "Metallic: Uniform" as unavailable although the card's reset and its value row answer. The row is a label that picks nothing, not a disabled control. --- crates/ui-egui/src/property_sheet/slot.rs | 2 +- crates/ui-egui/tests/it/tool_material.rs | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index c1d7b6de..623b6126 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -122,7 +122,7 @@ impl PropertySheet<'_> { }); } else { // A label's words are its value, so the name and source read as one - pick.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, false, format!("{name}: {source}"))); + pick.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{name}: {source}"))); } let mut result = SlotResponse { pick, clear: false, reset: false, toggled: false }; diff --git a/crates/ui-egui/tests/it/tool_material.rs b/crates/ui-egui/tests/it/tool_material.rs index 15fe5c3e..691edec0 100644 --- a/crates/ui-egui/tests/it/tool_material.rs +++ b/crates/ui-egui/tests/it/tool_material.rs @@ -89,3 +89,12 @@ fn the_eraser_picks_its_channels_without_value_cards() { assert!(harness.query_by_role_and_label(Role::Button, "Base color").is_none(), "the eraser paints no colour"); assert!(harness.query_by_role_and_label(Role::Slider, "Roughness").is_none()); } + +#[test] +fn a_channel_cards_name_is_not_read_as_unavailable() { + let harness = material_section("paint"); + let named = |node: &egui_kittest::Node<'_>| node.accesskit_node().value().is_some_and(|value| value.starts_with("Metallic: ")); + let card = harness.query_all_by_role(Role::Label).find(named).unwrap(); + + assert!(!card.accesskit_node().is_disabled(), "the card's reset and value row answer, so its name must not read as unavailable"); +} From 15bfc6f90ec5c2f4b537a8e54a9f4951e3162159 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:44:30 +0000 Subject: [PATCH 144/190] Hide the stencil while the quick mask is painted, as its strokes skip it The Stencil tab, the viewport overlay and S + drag now follow the same rule as the stroke: a brush tool painting the quick mask does not use the stencil. --- crates/ui-egui/src/dock.rs | 4 ++-- crates/ui-egui/src/viewport.rs | 9 +++++++-- crates/ui-egui/tests/it/stencil.rs | 21 ++++++++++++++++++++- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 369eba60..7f44e287 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2147,9 +2147,9 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -/// The sections of [`tool_properties`]: Stencil for the brush tools it shapes +/// The sections of [`tool_properties`]: Stencil for the brush tools it shapes, except while they paint the quick mask fn tool_sections(app: &TextureCraftApp) -> Vec { - PaintSection::page(app.session.tool.tool.uses_stencil(), targets_content(app)) + PaintSection::page(crate::viewport::stencil_applies(app), targets_content(app)) } fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 2c2f3d3b..ba9785ae 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -784,7 +784,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !crate::framework::widget_has_keyboard(ui.ctx()); // Only an equipped brush tool that can act moves the stencil: it isn't drawn otherwise - let stencil_moves = tool_acts(app) && app.session.tool.tool.uses_stencil(); + let stencil_moves = tool_acts(app) && stencil_applies(app); let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some(); if stencil_drag || adjusting || holding { // The stencil, the brush or the held Move on model button changes instead of the camera @@ -1180,7 +1180,7 @@ fn bake_visualization(app: &TextureCraftApp) -> Option bool { + app.session.tool.tool.uses_stencil() && !app.session.quick_mask.editing +} + /// Whether the active tool can act on the selection now: a greyed tool ignores clicks, keys and drags in the views fn tool_acts(app: &TextureCraftApp) -> bool { app.ui.mode == crate::state::Mode::Painting && app.session.tool_usable(app.session.tool.tool) diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index dafd004a..5691c0ae 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -1,4 +1,4 @@ -//! The brush tools' stencil: an Assets image dropped on its slot, position fields, Tiling mode and the section reset in the tool panel, S + Shift + left-drag to turn it in snapped steps, and the 2D view saying that projection paints in the 3D view +//! The brush tools' stencil: an Assets image dropped on its slot, position fields, Tiling mode and the section reset in the tool panel, S + Shift + left-drag to turn it in snapped steps, the 2D view saying that projection paints in the 3D view, and no stencil while the quick mask is painted use egui::accesskit::Role; use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; @@ -182,6 +182,25 @@ fn s_shift_left_drag_turns_the_stencil_in_snapped_steps_without_painting() { assert_eq!(history(&harness), steps); } +#[test] +fn the_stencil_hides_and_stays_put_while_the_quick_mask_is_painted() { + let (mut harness, name) = tool_app(Tool::Paint); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + harness.run_steps(REDRAW_FRAMES); + let from = harness.state().viewport_rect.center(); + let before = harness.state().session.tool.stencil.clone().unwrap(); + + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "quick mask strokes skip the stencil, so it has no tab"); + drag_holding(&mut harness, &[Key::S], Modifiers::SHIFT, from, vec2(100.0, -40.0)); + assert_eq!(harness.state().session.tool.stencil.clone().unwrap().rotation, before.rotation, "S + drag leaves it alone"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); + harness.run_steps(REDRAW_FRAMES); + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_some(), "back when the quick mask is done"); +} + #[test] fn the_2d_view_says_projection_paints_in_3d_and_paints_nothing() { let (mut harness, name) = projection_app(); From c2431e8fe0861f89d1550eff6dc1bd31d74bf6b9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:50:23 +0000 Subject: [PATCH 145/190] Sample the live stroke's stencil once per texel for all the channels it paints --- crates/compose/src/eval.rs | 44 +++++++++++++++++++++++++++++++--- crates/engine/tests/session.rs | 29 ++++++++++++++++++++++ 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 0cbc6e4d..07936750 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -67,6 +67,9 @@ const MIN_BOUNDS_EXTENT: f32 = 1e-6; /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; +/// What the live stroke's stencil lets through at a texel ([`Stencil::paint_world`]) +type StencilPaint = Option<(Option<[f32; 3]>, f32)>; + /// How tall a baked height of 1 stands, as a fraction of a UV tile, when Baked Lighting Stylized tilts normals by its slope const HEIGHT_RELIEF: f32 = 1.0 / 32.0; @@ -3042,6 +3045,8 @@ struct Texel<'a, 'b> { tape: Tape<'b>, /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip copy: Option<(usize, FillCopy)>, + /// The live stroke's stencil sampled here once for every channel (None until a channel reads it) + stencil_paint: Option, } /// What a layer contributes (its mask, its content value and coverage per channel): evaluated @@ -3077,7 +3082,22 @@ type ChannelContents = [Option<([f32; 3], f32)>; NCH]; impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { - Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, lit: None, tape: Tape::Off, copy: None } + Texel { + inp, + x, + y, + o, + res: inp.gbuf.width, + coords: None, + stroke, + stop: None, + anchors: Vec::new(), + below: None, + lit: None, + tape: Tape::Off, + copy: None, + stencil_paint: None, + } } /// Run `f` with `tape` as this texel's tape. @@ -3220,6 +3240,24 @@ impl<'a, 'b> Texel<'a, 'b> { self.surface((self.y * self.inp.gbuf.width + self.x) as usize).map(|s| s.pos) } + /// What the live stroke's `stencil` lets through here, sampled once for all of the texel's channels + fn stencil_paint(&mut self, stencil: &Stencil) -> StencilPaint { + let sample = |texel: &Self| texel.world().and_then(|world| stencil.paint_world(world)); + + // A symmetric fill's copy sees another surface point, so only the texel's own sample is kept + if self.copy.is_some() { + return sample(self); + } + + if let Some(paint) = self.stencil_paint { + return paint; + } + + let paint = sample(self); + self.stencil_paint = Some(paint); + paint + } + /// The surface at G-buffer index `i`, as the fill copy being sampled sees it #[inline(always)] fn surface(&self, i: usize) -> Option { @@ -3952,7 +3990,7 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(stencil) = preview.stencil.as_ref() && stroke > 0.0 { - stroke *= self.world().and_then(|world| stencil.paint_world(world)).map_or(0.0, |(_, factor)| factor); + stroke *= self.stencil_paint(stencil).map_or(0.0, |(_, factor)| factor); } if preview.erase { @@ -4319,7 +4357,7 @@ impl<'a, 'b> Texel<'a, 'b> { // The stencil shapes the stroke; on the Projection tool its color is the base color let stencil_color = match stroke_preview.and_then(|stroke| stroke.stencil.as_ref()) { Some(stencil) if stroke_alpha > 0.0 => { - let stencil_paint = self.world().and_then(|world| stencil.paint_world(world)); + let stencil_paint = self.stencil_paint(stencil); stroke_alpha *= stencil_paint.map(|(_, factor)| factor).unwrap_or(0.0); stencil_paint.and_then(|(color, _)| color) } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index d91422fe..5e9afd43 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -804,6 +804,35 @@ fn a_mask_stroke_shows_through_the_stencil_while_painting_as_it_commits() { assert_ne!(right_committed, right_before, "white stencil lets the committed stroke through"); } +#[test] +fn a_live_paint_stroke_shows_through_the_stencil_on_every_channel_it_paints() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "roughness", "value": 0.0})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + let channel_at = |session: &Session, channel: Channel, x: f32| { + let hit = session.pick(Vec2::new(x, DAB_Y), session.viewport).unwrap(); + let texel = |coordinate: f32| (coordinate * TEXTURE_SIZE as f32) as u32; + session.caches[0].composite.value(channel, texel(hit.uv.x), texel(hit.uv.y)) + }; + let before = + [Channel::BaseColor, Channel::Roughness].map(|channel| (channel_at(&session, channel, BLACK_DAB_X), channel_at(&session, channel, WHITE_DAB_X))); + + // A stroke from behind the stencil's black half to its white half, shown before it commits + let viewport = session.viewport; + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), viewport, 1.0).unwrap(); + session.continue_stroke(Vec2::new(WHITE_DAB_X, DAB_Y), 1.0); + session.update(); + + for (channel, (left_before, right_before)) in [Channel::BaseColor, Channel::Roughness].into_iter().zip(before) { + assert_eq!(channel_at(&session, channel, BLACK_DAB_X), left_before, "black stencil hides the live {channel:?}"); + assert_ne!(channel_at(&session, channel, WHITE_DAB_X), right_before, "white stencil shows the live {channel:?}"); + } +} + #[test] fn smart_materials_save_and_load_with_pixels() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); From 5fe48173249c7fea396d7e6caa784bd69a5a689d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:51:56 +0000 Subject: [PATCH 146/190] Reuse the brush pictures each frame without copying their cache entries --- crates/ui-egui/src/brush_stroke_preview.rs | 26 +++++++++++++--------- crates/ui-egui/tests/it/paint_tool_tabs.rs | 18 +++++++++++++++ 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/brush_stroke_preview.rs b/crates/ui-egui/src/brush_stroke_preview.rs index 52b8b9b3..bd7d58c9 100644 --- a/crates/ui-egui/src/brush_stroke_preview.rs +++ b/crates/ui-egui/src/brush_stroke_preview.rs @@ -24,8 +24,7 @@ const STROKE_PRESSURE: std::ops::RangeInclusive = 0.35..=1.0; const STROKE_WIDTH_PER_ROOT_SIZE: f32 = 70.0; const STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=32.0; -/// The rendered stroke and what it was rendered from, kept in egui's memory so a frame with the same brush reuses it -#[derive(Clone)] +/// The rendered stroke and what it was rendered from, kept in egui's memory behind an `Arc` so a frame with the same brush reuses it without copying it pub(crate) struct BrushStrokePreview { brush: BrushSettings, image: Option>, @@ -52,23 +51,30 @@ impl BrushStrokePreview { ) { let pixels_per_point = ctx.pixels_per_point(); let size = [(rect.width() * pixels_per_point).round().max(1.0) as usize, (rect.height() * pixels_per_point).round().max(1.0) as usize]; - let tints: Vec<[u8; 3]> = (0..size[0]).map(|x| tint((x as f32 + 0.5) / size[0] as f32)).collect(); + let column_tint = |x: usize| tint((x as f32 + 0.5) / size[0] as f32); + // The docked panel and the right-click popup draw the same picture at their own widths: one cache each let id = Id::unique(key).with(painter.layer_id()); - let cached = ctx.data(|data| data.get_temp::(id)).filter(|preview| { - preview.brush == *brush && preview.size == size && preview.tints == tints && preview.image.as_ref().map(Arc::as_ptr) == image.map(Arc::as_ptr) + let cached = ctx.data(|data| data.get_temp::>(id)).filter(|preview| { + preview.brush == *brush + && preview.size == size + && preview.image.as_ref().map(Arc::as_ptr) == image.map(Arc::as_ptr) + && preview.tints.iter().enumerate().all(|(x, shown)| *shown == column_tint(x)) }); - let preview = match cached { - Some(preview) => preview, + + let texture = match cached { + Some(preview) => preview.texture.id(), None => { + let tints: Vec<[u8; 3]> = (0..size[0]).map(column_tint).collect(); let picture = render(brush, image.map(|image| &**image), size, pixels_per_point, &tints); let texture = ctx.load_texture(key, picture, TextureOptions::LINEAR); + let texture_id = texture.id(); let preview = BrushStrokePreview { brush: brush.clone(), image: image.cloned(), tints, size, texture }; - ctx.data_mut(|data| data.insert_temp(id, preview.clone())); - preview + ctx.data_mut(|data| data.insert_temp(id, Arc::new(preview))); + texture_id } }; - painter.image(preview.texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + painter.image(texture, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } } diff --git a/crates/ui-egui/tests/it/paint_tool_tabs.rs b/crates/ui-egui/tests/it/paint_tool_tabs.rs index a51dfb26..a2094656 100644 --- a/crates/ui-egui/tests/it/paint_tool_tabs.rs +++ b/crates/ui-egui/tests/it/paint_tool_tabs.rs @@ -75,3 +75,21 @@ fn the_brush_preview_stays_under_the_tabs_while_the_sections_scroll() { assert_eq!(harness.get_by_label("Brush preview").rect(), preview_before, "the preview stayed where it was"); assert!(preview_before.top() >= harness.get_by_role_and_label(Role::Tab, "Material").rect().bottom(), "under the tabs"); } + +#[test] +fn the_brush_preview_keeps_its_picture_until_the_paint_colour_changes() { + let mut harness = paint_harness("paint"); + let pictures = |harness: &Harness<'_, TextureCraftApp>| -> Vec { + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name == "brush_stroke_preview").map(|(id, _)| *id).collect() + }; + let first = pictures(&harness); + + harness.run_steps(SCROLL_FRAMES); + assert_eq!(pictures(&harness), first, "an unchanged brush reuses its picture"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + harness.run_steps(SCROLL_FRAMES); + let recoloured = pictures(&harness); + assert_eq!(recoloured.len(), 1, "the old picture is released"); + assert_ne!(recoloured, first, "a new colour draws a new picture"); +} From 6f3cd3d661a3681f71738e9276df90834fb0564b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:53:13 +0000 Subject: [PATCH 147/190] Keep only the current stencil's overlay texture when another stencil is picked --- crates/ui-egui/src/thumbs.rs | 9 +++++++-- crates/ui-egui/tests/it/stencil.rs | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 75777c3c..ead88415 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -36,6 +36,8 @@ const GENERATOR_SET_KEY_PREFIX: &str = "generator-set:"; const SAVED_FILE_KEY_PREFIX: &str = "saved-"; /// Largest stencil preview dimension in pixels const STENCIL_MAX_SIZE_PX: f32 = 1024.0; +/// The `images` key prefix of a stencil preview +const STENCIL_KEY_PREFIX: &str = "stencil:"; /// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; @@ -77,13 +79,16 @@ pub struct Thumbs { impl Thumbs { /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px) pub fn stencil(&mut self, ctx: &egui::Context, name: &str, image: &Arc) -> TextureHandle { - let key = format!("stencil:{name}"); + let key = format!("{STENCIL_KEY_PREFIX}{name}"); if let Some((cached_image, texture)) = self.images.get(&key) && cached_image.ptr_eq(&Arc::downgrade(image)) { return texture.clone(); } + // Only the current stencil is drawn this big, so a new one releases the last one's texture + self.images.retain(|cached_key, _| !cached_key.starts_with(STENCIL_KEY_PREFIX)); + let scale = (STENCIL_MAX_SIZE_PX / image.width.max(image.height).max(1) as f32).min(1.0); let (w, h) = (((image.width as f32 * scale) as usize).max(1), ((image.height as f32 * scale) as usize).max(1)); let mut color_image = ColorImage::filled([w, h], Color32::TRANSPARENT); @@ -148,7 +153,7 @@ impl Thumbs { self.images_revision = Some(revision); self.images.retain(|key, (cached_image, _)| { - let name = key.strip_prefix("stencil:").unwrap_or(key); + let name = key.strip_prefix(STENCIL_KEY_PREFIX).unwrap_or(key); images.get(name).is_some_and(|image| cached_image.ptr_eq(&Arc::downgrade(image))) }); } diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index 5691c0ae..3ff73bf2 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -228,3 +228,23 @@ fn the_2d_view_says_projection_paints_in_3d_and_paints_nothing() { drag_holding(&mut harness, &[], Modifiers::NONE, from, vec2(60.0, 0.0)); assert!(history(&harness) > steps, "the paint tool paints there"); } + +#[test] +fn picking_another_stencil_releases_the_last_ones_overlay_texture() { + let (mut harness, _) = tool_app(Tool::Paint); + let stencil_textures = |harness: &Harness<'_, TextureCraftApp>| { + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("stencil:")).count() + }; + + // Three distinct images picked in turn, each drawn over the view + for gray in [64, 128, 192] { + let mut png = Vec::new(); + let image = image::RgbaImage::from_pixel(IMAGE_SIZE, IMAGE_SIZE, image::Rgba([gray, gray, gray, 255])); + image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes(&format!("stencil_{gray}.png"), png).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({ "image": name })).unwrap(); + harness.run_steps(REDRAW_FRAMES); + } + + assert_eq!(stencil_textures(&harness), 1, "only the current stencil keeps its big texture"); +} From fe0208f5d3db30f31a10589a1e7201f43e071bad Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:19:40 +0000 Subject: [PATCH 148/190] Count no high part as unused while a set matching "Always" bakes from it, note the occlusion Rust Runoff reads, and keep the maps still queued when a bake is canceled --- crates/core/src/layer.rs | 8 ++++ crates/engine/src/bake/bake_log.rs | 11 +++-- crates/engine/tests/it/bake_log.rs | 16 +++++++ .../ui-egui/src/generator_panel/bake_note.rs | 2 +- crates/ui-egui/src/lib.rs | 9 +++- crates/ui-egui/tests/it/bake_job_mesh.rs | 45 +++++++++++++++---- crates/ui-egui/tests/it/baking_log.rs | 14 ++++-- .../ui-egui/tests/it/generator_bake_note.rs | 13 +++++- 8 files changed, 99 insertions(+), 19 deletions(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 158a1b6a..56a8ebb0 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1268,6 +1268,14 @@ impl Generator { if reads_geometry { &[] } else { self.kind.inputs() } } + /// The mesh maps the generator reads that a bake makes: its inputs in use, and the occlusion Dripping Rust reads whole, which no input replaces + pub fn baked_maps_read(&self) -> &'static [BakedMap] { + match self.kind { + GeneratorKind::DrippingRust => &[BakedMap::AmbientOcclusion], + _ => self.inputs_in_use(), + } + } + /// The texture the generator blends over its signal: only on the section controls, turned on with some opacity pub fn texture_in_use(&self) -> Option<&TextureLayer> { self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 2f7936c8..c03315e7 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; use texturecraft_bake::NamePair; -use texturecraft_core::{BakedMap, Project}; +use texturecraft_core::{BakedMap, MeshMatchMode, Project}; use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh}; use crate::Session; @@ -149,13 +149,16 @@ impl Session { .collect(); } - /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it and no set matching "Always" bakes from every part fn bake_log_matching(&self, sets: &[usize]) -> Option { let mut matching: Option = None; let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new()); + let mut every_high_used = false; for &set in sets { - let (Ok(Some(pairs)), Ok(texture_set)) = (self.bake_name_pairs(set), self.doc.project.texture_set(set)) else { continue }; + let Ok(texture_set) = self.doc.project.texture_set(set) else { continue }; let settings = &texture_set.bake.high_poly; + every_high_used |= !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always; + let Ok(Some(pairs)) = self.bake_name_pairs(set) else { continue }; let matching = matching.get_or_insert_with(|| BakeLogMatching { low_suffix: settings.low_suffix.clone(), high_suffix: settings.high_suffix.clone(), @@ -173,7 +176,7 @@ impl Session { } } - if let Some(matching) = &mut matching { + if let Some(matching) = matching.as_mut().filter(|_| !every_high_used) { let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high)); matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) })); } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index ee26594a..2fbd461b 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -129,6 +129,22 @@ fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_ assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); } +#[test] +fn a_high_part_counts_as_unused_only_when_no_set_of_the_bake_matches_always() { + let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + session.begin_bake_log(&[0, 1]); + + let matching = session.bake_log.matching.clone().unwrap(); + assert!(matching.pairs.iter().all(|pair| pair.low.is_some()), "the set matching \"Always\" bakes from Extra_high: {:?}", matching.pairs); + assert_eq!(matching.issue_count(), 0); +} + #[test] fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() { let mut session = sample_session(256, 64).unwrap(); diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 44a9b4f7..4d576753 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -23,7 +23,7 @@ const TOOLTIP_TEXT_SIZE: f32 = 12.0; /// The note for each mesh map `generator` reads from the active texture set that is not baked or out of date pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, generator: &Generator) { let texture_set = app.session.ts(); - for map in generator.inputs_in_use() { + for map in generator.baked_maps_read() { if generator.inputs.contains_key(map) { continue; } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4d6ff3eb..5e793a7c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -973,9 +973,16 @@ impl TextureCraftApp { let Some(job) = self.bake.take() else { return }; let mut discarded = None; - if let Some(running) = job.current { + if let Some(mut running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); + // The maps the worker sent that no frame has taken yet are finished too + while let Ok(map) = running.maps.try_recv() { + running.finished.resolution = map.resolution; + running.finished.maps.insert(map.map, map.data); + self.session.bake_log.map_baked(running.set_index, map.map); + } + // Maps baked for a mesh that has since been replaced are never kept let same_mesh = job.mesh_id == self.session.mesh_id; let kept = match same_mesh { diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index c3292beb..8b3971b2 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -1,15 +1,27 @@ -//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps -//! the mesh meanwhile, the job is cancelled and its result is dropped. +//! A bake job belongs to the mesh it started on: when `file.changeMesh` or a reimport swaps the mesh meanwhile, the job is cancelled and its result dropped; a cancel keeps the maps it finished use std::sync::Arc; use std::sync::atomic::Ordering; +use std::sync::mpsc::Sender; use egui_kittest::Harness; +use texturecraft_engine::StreamedMap; use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; -/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. +/// An app with a running bake job (its worker never answers) started on mesh `mesh_id` fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harness<'static, TextureCraftApp>, &Progress)) { + let (mut harness, progress, _senders) = running_job(mesh_id); + harness.step(); + check(&harness, &progress); +} + +/// The ends a test plays the bake worker with: its result (never sent) and its finished maps +type WorkerSenders = (Sender>, Sender); + +/// An app with a running bake job of set 0 started on mesh `mesh_id`, whose worker sends only what the test sends +fn running_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc, WorkerSenders) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder() .with_size(egui::vec2(1600.0, 960.0)) @@ -17,8 +29,8 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); let progress = Arc::new(Progress::new()); - let (_result_sender, receiver) = std::sync::mpsc::channel(); - let (_map_sender, maps) = std::sync::mpsc::channel(); + let (result_sender, receiver) = std::sync::mpsc::channel(); + let (map_sender, maps) = std::sync::mpsc::channel(); let job_mesh_id = mesh_id(harness.state().session.mesh_id); let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let running = RunningBake { @@ -33,9 +45,7 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes painted_stroke: 0, }; harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); - - harness.step(); - check(&harness, &progress); + (harness, progress, (result_sender, map_sender)) } #[test] @@ -59,3 +69,22 @@ fn a_job_on_the_current_mesh_keeps_running() { }, ); } + +#[test] +fn a_cancel_keeps_the_maps_the_worker_sent_before_any_frame_took_them() { + let (mut harness, _progress, (_result_sender, map_sender)) = running_job(|current| current); + let data = Arc::new(vec![0.5; 64 * 64]); + let normal_before = harness.state().session.baked(0).and_then(|baked| baked.maps.get(&BakedMap::Normal).cloned()); + assert!(normal_before.is_some(), "the sample's Normal map is baked before the job"); + for (index, map) in [BakedMap::Curvature, BakedMap::AmbientOcclusion].into_iter().enumerate() { + map_sender.send(StreamedMap { map, index, total: 2, resolution: 64, height: 64, data: data.clone() }).unwrap(); + } + + harness.state_mut().cancel_bake(); + let baked = harness.state().session.baked(0).unwrap(); + for map in [BakedMap::Curvature, BakedMap::AmbientOcclusion] { + assert!(baked.maps.get(&map).is_some_and(|kept| Arc::ptr_eq(kept, &data)), "{map:?} is kept"); + } + let normal = baked.maps.get(&BakedMap::Normal); + assert!(normal.zip(normal_before.as_ref()).is_some_and(|(now, before)| Arc::ptr_eq(now, before)), "a map the worker never sent keeps the one baked before"); +} diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index f52fe624..5e7e9681 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -100,16 +100,22 @@ fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() { let app = harness.state(); assert_eq!(state(app, 0, BakedMap::Id), Some(BakeMapState::Baked), "a ticked map keeps its tick"); - for (set, map) in [(0, BakedMap::Position), (1, BakedMap::Id), (1, BakedMap::Position)] { - assert_eq!(state(app, set, map), Some(BakeMapState::Canceled), "set {set}'s unfinished {map:?} warns"); + for map in [BakedMap::Id, BakedMap::Position] { + assert_eq!(state(app, 1, map), Some(BakeMapState::Canceled), "set 1 was still queued, so its {map:?} warns"); } + + // A map the worker sent before the cancel is kept too, so whether set 0's Position finished depends on timing + let row = state(app, 0, BakedMap::Position); + assert!(matches!(row, Some(BakeMapState::Baked | BakeMapState::Canceled)), "set 0's Position is ticked or, unfinished, warns: {row:?}"); let after = app.session.baked(0).cloned().unwrap_or_default(); let changed = |map: BakedMap| match (before.maps.get(&map), after.maps.get(&map)) { (Some(old), Some(new)) => !std::sync::Arc::ptr_eq(old, new), (old, new) => old.is_some() != new.is_some(), }; - assert!(changed(BakedMap::Id), "the ticked map is in the document"); - assert!(!changed(BakedMap::Position), "the unfinished map stays as it was"); + for map in [BakedMap::Id, BakedMap::Position] { + let ticked = state(app, 0, map) == Some(BakeMapState::Baked); + assert_eq!(changed(map), ticked, "set 0's {map:?} is in the document exactly when its row is ticked"); + } } #[test] diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index 6c879100..b4c2be8a 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -11,12 +11,17 @@ use texturecraft_ui_egui::docking::Panel; /// A plane whose bake makes only the position map, with a curvature generator selected in a fill layer's mask fn harness() -> Harness<'static, TextureCraftApp> { + harness_with("curvature") +} + +/// A plane whose bake makes only the position map, with a `generator` selected in a fill layer's mask +fn harness_with(generator: &str) -> Harness<'static, TextureCraftApp> { let mesh = primitives::builtin("plane").unwrap(); let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); execute(&mut session, "bake.settings", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); let layer = execute(&mut session, "layer.add.fill", &json!({ "color": [0.8, 0.3, 0.1] })).unwrap()["layer"].as_u64().unwrap(); execute(&mut session, "mask.add.black", &json!({})).unwrap(); - execute(&mut session, "effect.add.generator", &json!({ "generator": "curvature" })).unwrap(); + execute(&mut session, "effect.add.generator", &json!({ "generator": generator })).unwrap(); session.view = ViewMode::Mask(LayerId(layer)); session.update(); @@ -67,3 +72,9 @@ fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() { assert!(harness.state().session.baked(0).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Curvature))); assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); } + +#[test] +fn rust_runoff_notes_the_occlusion_it_reads_though_no_input_replaces_it() { + let harness = harness_with("Dripping Rust"); + harness.get_by_label("Ambient Occlusion map not baked"); +} From 57ffd56a039794a4a8bc220f0e47668a0e47a4b6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:42:53 +0000 Subject: [PATCH 149/190] Start an auto-rebake canceled in one project again in the next project opened, and wait while a press is held in a floating panel's window --- crates/ui-egui/src/auto_rebake.rs | 60 +++++++++++++++++++++++++- crates/ui-egui/src/docking.rs | 25 +++++++---- crates/ui-egui/tests/it/auto_rebake.rs | 23 ++++++++++ 3 files changed, 98 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 07bbcaab..473e80ce 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -13,6 +13,8 @@ pub type Due = (usize, BakedMap, BakeSource, Option); /// What the app has seen of the out-of-date auto-rebake maps #[derive(Default)] pub struct AutoRebake { + /// The project these records are of: another project starts with none + project: u64, /// The due maps and the frame time they were first seen as they are pending: Option<(Vec, f64)>, /// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes @@ -21,6 +23,10 @@ pub struct AutoRebake { /// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + if app.auto_rebake.project != app.session.project_id { + app.auto_rebake = AutoRebake { project: app.session.project_id, ..AutoRebake::default() }; + } + if app.ui.mode != state::Mode::Baking { app.auto_rebake.pending = None; return; @@ -48,10 +54,11 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); // A held press (a slider dragged and paused) is still editing: the wait starts once it is let go - if ctx.input(|input| input.pointer.any_down()) { + if pointer_held(ctx, app.docks.floating_windows()) { app.auto_rebake.pending = Some((waiting, now)); return; } + match &app.auto_rebake.pending { Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} Some((seen, _)) if *seen == waiting => return, @@ -68,6 +75,11 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { } } +/// Whether a mouse button is down in the main window or in one of the floating panels' own `windows` +fn pointer_held(ctx: &egui::Context, windows: &[egui::ViewportId]) -> bool { + ctx.input(|input| input.pointer.any_down()) || windows.iter().any(|window| ctx.input_for(*window, |input| input.pointer.any_down())) +} + /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { let (set, map, ..) = rebake; @@ -83,3 +95,49 @@ fn start(app: &mut TextureCraftApp, rebake: Due) { app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: None, rebake: Some(rebake) }); } + +#[cfg(test)] +mod tests { + use super::*; + + /// Whether a press is held, seen from the main window after a button went down in a floating panel's window (`window_listed`) + fn held_after_a_press_in_a_floating_window(window_listed: bool) -> bool { + use std::{cell::RefCell, rc::Rc}; + + let window = egui::ViewportId::from_hash_of("floating panel"); + let context = egui::Context::default(); + context.set_embed_viewports(false); + + // Runs the window's pass inside its parent's, as eframe does + let arriving = Rc::new(RefCell::new(Vec::new())); + let queued = Rc::clone(&arriving); + egui::Context::set_immediate_viewport_renderer(move |context, viewport| { + let mut input = egui::RawInput { viewport_id: viewport.ids.this, events: queued.take(), ..Default::default() }; + input.viewports.insert(viewport.ids.this, egui::ViewportInfo { parent: Some(viewport.ids.parent), ..Default::default() }); + let mut output = context.run_ui(input, viewport.viewport_ui_cb); + output.textures_delta.clear(); + }); + + let at = egui::pos2(20.0, 20.0); + let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + *arriving.borrow_mut() = vec![egui::Event::PointerMoved(at), press]; + let windows: &[egui::ViewportId] = if window_listed { &[window] } else { &[] }; + let mut held = false; + + // The first pass hands the press to the window after the hold was read; the second reads it + for _ in 0..2 { + let mut output = context.run_ui(egui::RawInput::default(), |ui| { + held = pointer_held(ui.ctx(), windows); + ui.ctx().show_viewport_immediate(window, egui::ViewportBuilder::default(), |_, _| {}); + }); + output.textures_delta.clear(); + } + held + } + + #[test] + fn a_press_held_in_a_floating_panels_window_counts_as_held() { + assert!(held_after_a_press_in_a_floating_window(true), "the slider dragged in a floating panel is still editing"); + assert!(!held_after_a_press_in_a_floating_window(false), "the main window's own pointer is up"); + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index f1acd9e7..5f75aaae 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -391,23 +391,29 @@ impl Dock { } } -/// What the dock area keeps between passes: the workspace it shows and the panels' specs. +/// What the dock area keeps between passes: the workspace it shows and the panels' specs #[derive(Default)] pub(crate) struct LiveDock { shown: Option>, specs: Tracked, - /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window. + /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window continue_move: Option<(Panel, egui::Vec2)>, + /// The OS windows of the floating panels, as the last pass's dock drew them + floating_windows: Vec, } impl LiveDock { - /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab`. + /// The OS windows the last pass's dock drew floating panels in + pub(crate) fn floating_windows(&self) -> &[ViewportId] { + &self.floating_windows + } + + /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab` pub(crate) fn hand_over(&mut self, panel: Panel, grab: egui::Vec2) { self.continue_move = Some((panel, grab)); } - /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, - /// so an idle pass keeps the workspace's revision and the dock reads no spec. + /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, so an idle pass reads no spec fn shown(&mut self, workspace: &Workspace) -> Arc { if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) { return Arc::clone(shown); @@ -470,7 +476,7 @@ pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> b modal } -/// Draw the dock (viewport and panels) into `ui`. +/// Draw the dock (viewport and panels) into `ui` pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { // Rendering keeps disabled panels visible because it shares the painting dock let dock_mode = if app.ui.mode == crate::state::Mode::Rendering { crate::state::Mode::Painting } else { app.ui.mode }; @@ -484,12 +490,11 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let context = ui.ctx().clone(); refresh_specs(app); let shown = app.docks.shown(&app.ui.dock.workspace); - // The specs leave the app while its panels borrow it, and come back with their revision. + // The specs leave the app while its panels borrow it, and come back with their revision let specs = std::mem::take(&mut app.docks.specs); let hand_over = app.docks.continue_move.take(); let raise = app.ui.dock.raise.take(); - // Panels arrange in a split tree around the viewport; floating title bars only move windows. - // Each closable tab has its close button, as each group header had one for its shown panel. + // Panels split around the viewport, floating title bars only move windows, and each closable tab has its close button let config = DockConfig::default().new_dock_zones(false).title_bar_docks(false).tab_close_buttons(true); let (output, focused_windows) = { let tokens = Tokens::get(&context); @@ -505,6 +510,8 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { (output, panels.focused_windows) }; app.docks.specs = specs; + app.docks.floating_windows.clear(); + app.docks.floating_windows.extend(output.windows.iter().map(|(_, viewport)| *viewport)); // The popup needs the viewport the dock recorded this frame crate::rail_popup::show(app, &context); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 398e93b8..15534f76 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -9,6 +9,9 @@ use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::Mode; +/// Frames far past the half-second settle wait, at the harness's quarter-second step +const PAST_THE_SETTLE_FRAMES: usize = 60; + /// A plane in Bake mode with its position and ID maps baked and Auto-rebake on for the position map fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { let mesh = primitives::builtin("plane").unwrap(); @@ -174,3 +177,23 @@ fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_st harness.drop_at(corner); super::step_until(&mut harness, "the rebake after the release", |app| app.bake.is_some()); } + +#[test] +fn a_rebake_canceled_in_one_project_still_runs_in_the_next_project_opened() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + harness.state_mut().cancel_bake(); + harness.run_steps(PAST_THE_SETTLE_FRAMES); + assert!(harness.state().bake.is_none(), "a canceled rebake is not tried again in its project"); + + // The same project opened again: its out-of-date map reads what the canceled one read + let mesh = primitives::builtin("plane").unwrap(); + let mut next = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut next, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + execute(&mut next, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut next, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + harness.state_mut().session.switch_to(next); + + super::step_until(&mut harness, "the rebake in the opened project", |app| app.bake.is_some()); +} From ba1d3aebc33c42621d70943f838d68165cc1cae7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:03:15 +0000 Subject: [PATCH 150/190] Keep the Baking Log tabs clear of the issues filter on a narrow dock, scrolling them when they don't fit, and cut Matching by Name's part names short to their column, in full on hover --- crates/ui-egui/src/baking_log.rs | 122 ++++++++++++------ .../ui-egui/src/baking_log/matching_list.rs | 86 ++++++++++-- crates/ui-egui/tests/it/baking_log.rs | 53 ++++++++ 3 files changed, 204 insertions(+), 57 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index db0db2a7..affb1803 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -3,7 +3,7 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeLogMatching, BakeMapState}; use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; @@ -71,15 +71,15 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, &app.session.bake_log) { + + // The tabs keep clear of the issues filter at its widest, so picking a tab never moves the edge they scroll under + let filter_room = BakingLogTab::ALL.into_iter().map(|tab| filter_width(ui, issue_count(&app.session.bake_log, tab))).fold(0.0, f32::max); + let tabs_right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT - filter_room - TAB_GAP; + if let Some(tab) = tabs(ui, strip.with_max_x(tabs_right.max(strip.left())), app.ui.baking_log_tab, &app.session.bake_log) { app.ui.baking_log_tab = tab; } let tab = app.ui.baking_log_tab; - let issue_count = match tab { - BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::MatchingByName => app.session.bake_log.matching.as_ref().map_or(0, |matching| matching.issue_count()), - }; + let issue_count = issue_count(&app.session.bake_log, tab); if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; } @@ -136,55 +136,91 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa app.ui.dock.focus(Panel::MeshMapSettings); } -/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +/// How many rows of `tab` have an issue, for the issues filter's count +fn issue_count(log: &BakeLog, tab: BakingLogTab) -> usize { + match tab { + BakingLogTab::BakingProcess => log.maps.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::HighPolyParameters => log.highs.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::MatchingByName => log.matching.as_ref().map_or(0, BakeLogMatching::issue_count), + } +} + +/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; they scroll sideways when wider than it fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, log: &BakeLog) -> Option { let tokens = Tokens::get(ui.ctx()); - let mut picked = None; - let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; - for tab in BakingLogTab::ALL { - let name = tr(tab.name()); - let on = tab == shown; - let width = ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING; - let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom())); - let response = ui.interact(rect, ui.scope_id().with(("baking_log_tab", tab)), Sense::click()); - response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); - if response.clicked() { - picked = Some(tab); - } + let names = BakingLogTab::ALL.map(|tab| tr(tab.name())); + let widths = names.map(|name| ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING); + let first_left = SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; + let content_width = first_left + widths.iter().sum::() + TAB_GAP * (widths.len() - 1) as f32; - let painter = ui.painter(); - if on { - shown_tab_box(painter, &tokens, rect); - } - let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; - let in_progress = match tab { - BakingLogTab::BakingProcess => log.is_running(), - BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), - BakingLogTab::MatchingByName => false, - }; - let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; - let center_y = strip.center().y + TAB_TOP / 2.0; - painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); - let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; - painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); - if response.has_focus() { - crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); - } + let mut strip_ui = ui.new_child(egui::UiBuilder::new().max_rect(strip).id_salt("baking_log_tabs")); + egui::ScrollArea::horizontal() + .id_salt("baking_log_tabs") + .auto_shrink([false, false]) + .show(&mut strip_ui, |ui| { + let (content, _) = ui.allocate_exact_size(vec2(content_width, strip.height()), Sense::hover()); + let mut picked = None; + let mut left = content.left() + first_left; + for ((tab, name), width) in BakingLogTab::ALL.into_iter().zip(names).zip(widths) { + if tab_button(ui, content, left, width, (tab, name), tab == shown, log) { + picked = Some(tab); + } + left += width + TAB_GAP; + } + picked + }) + .inner +} - left += width + TAB_GAP; +/// One tab `width` wide from `left` on the `strip`, scrolled into view when the focus reaches it; dots for its icon while its work runs +fn tab_button(ui: &mut Ui, strip: Rect, left: f32, width: f32, (tab, name): (BakingLogTab, &str), on: bool, log: &BakeLog) -> bool { + let tokens = Tokens::get(ui.ctx()); + let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom())); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_tab", tab)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); + if response.gained_focus() { + response.scroll_to_me(None); } - picked + + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, rect); + } + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let in_progress = match tab { + BakingLogTab::BakingProcess => log.is_running(), + BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), + BakingLogTab::MatchingByName => false, + }; + let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); + } + response.clicked() +} + +/// The issues filter's width when it counts `issue_count` rows +fn filter_width(ui: &Ui, issue_count: usize) -> f32 { + let count_width = if issue_count == 0 { + 0.0 + } else { + let tokens = Tokens::get(ui.ctx()); + ui.painter().layout_no_wrap(issue_count.to_string(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP + }; + FILTER_BUTTON_WIDTH + count_width } /// The toggle at the `strip`'s right end that keeps only the rows with an issue: a warning glyph and how many there are fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool { let tokens = Tokens::get(ui.ctx()); let count = (issue_count > 0).then(|| issue_count.to_string()); - let count_width = - count.as_ref().map_or(0.0, |count| ui.painter().layout_no_wrap(count.clone(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP); let right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT; let center_y = strip.center().y + FILTER_DROP; - let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); + let rect = Rect::from_min_max(pos2(right - filter_width(ui, issue_count), center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); let name = match &count { Some(count) => trf("{count}, Show only rows with an issue", &[("count", count)]), diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs index b64565cb..8f4e278b 100644 --- a/crates/ui-egui/src/baking_log/matching_list.rs +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -1,6 +1,6 @@ //! The Baking Log's Matching by Name tab: which low poly part the latest bake paired with which high poly part -use egui::{Align2, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use texturecraft_engine::bake::{BakeLogMatching, NamePair}; @@ -8,17 +8,21 @@ use super::{GLYPH_SIZE, HOVER_INSET, NAME_SIZE, ROW_HEIGHT}; use crate::i18n::{tr, trf}; use crate::property_sheet::SIDE_PADDING_POINTS; use crate::theme::{Tokens, semibold}; +use crate::widgets::elided; /// Size of the column captions const CAPTION_SIZE: f32 = 11.0; +/// Air between the end of a low poly name and the high poly column +const COLUMN_GAP: f32 = 8.0; + /// The two columns' captions and a row per pair (only the parts with no partner, if `issues_only`), each ruled off below pub(super) fn matching_list(ui: &mut Ui, matching: &BakeLogMatching, issues_only: bool) { let tokens = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let captions = [caption(tr("Low poly mesh ({suffix})"), &matching.low_suffix), caption(tr("High poly mesh ({suffix})"), &matching.high_suffix)]; - for (left, caption) in columns(rect).into_iter().zip(captions) { - ui.painter().text(pos2(left, rect.center().y), Align2::LEFT_CENTER, caption, FontId::proportional(CAPTION_SIZE), tokens.text_dim); + for (column, caption) in columns(rect).into_iter().zip(captions) { + column_text(ui, column, caption, CAPTION_SIZE, tokens.text_dim); } rule(ui, rect); @@ -32,9 +36,19 @@ fn caption(template: &str, suffix: &str) -> String { template.split("{suffix}").map(str::to_uppercase).collect::>().join(suffix) } -/// The left edges of the low and high poly columns of `row` -fn columns(row: Rect) -> [f32; 2] { - [row.left() + SIDE_PADDING_POINTS, row.center().x] +/// The low and high poly columns of `row`, each ending a gap short of the next column or the side padding +fn columns(row: Rect) -> [Rect; 2] { + let low = row.with_min_x(row.left() + SIDE_PADDING_POINTS).with_max_x(row.center().x - COLUMN_GAP); + let high = row.with_min_x(row.center().x).with_max_x(row.right() - SIDE_PADDING_POINTS); + [low, high] +} + +/// Paint `text` in `color` at the left end of `column`, centred on its height and cut short to its width; whether it was cut +fn column_text(ui: &Ui, column: Rect, text: String, size: f32, color: Color32) -> bool { + let galley = elided(ui.painter(), text, size, color, column.width()); + let cut_short = galley.elided; + ui.painter().galley(pos2(column.left(), column.center().y - galley.size().y / 2.0), galley, color); + cut_short } /// The hairline under `row`, inside the side padding @@ -62,19 +76,63 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { if response.hovered() { painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); } - let center_y = rect.center().y; - for (left, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { + let mut cut_short = false; + for (column, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { match part { - Some(part) => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, part, FontId::proportional(NAME_SIZE), tokens.text), - None => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning), - }; + Some(part) => cut_short |= column_text(ui, column, part.clone(), NAME_SIZE, tokens.text), + None => { + painter.text(pos2(column.left(), column.center().y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning); + } + } } rule(ui, rect); - if let Some(reason) = reason { + // A name cut short shows in full on hover; the row's label carries it in full already + if reason.is_some() || cut_short { response.on_hover_ui(|ui| { - ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); - ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + if cut_short { + ui.label(egui::RichText::new(&name).size(NAME_SIZE).color(tokens.text)); + } + if let Some(reason) = reason { + ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + } }); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Names longer than their column, in a list as narrow as a small docked log + #[test] + fn long_names_stay_in_their_own_column() { + let long = |side: &str| format!("Left_shoulder_strap_buckle_with_its_rivets_and_stitching_{side}"); + let matching = BakeLogMatching { + low_suffix: "_low".into(), + high_suffix: "_high".into(), + pairs: vec![NamePair { low: Some(long("low")), high: Some(long("high")) }], + }; + let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(320.0, 200.0)); + let context = egui::Context::default(); + let mut output = context.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| matching_list(ui, &matching, false)); + output.textures_delta.clear(); + + let texts: Vec = output + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some(text.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert_eq!(texts.len(), 4, "two captions and two names"); + for (index, text) in texts.iter().enumerate() { + assert!(screen.contains_rect(*text), "text {index} {text:?} stays inside the list"); + for other in &texts[index + 1..] { + assert!(!text.intersects(*other), "text {index} {text:?} runs into {other:?}"); + } + } + } +} diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 5e7e9681..5c616fa5 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -1,5 +1,6 @@ //! The Baking Log panel: the latest bake, map by map +use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; @@ -251,3 +252,55 @@ fn the_matching_tab_says_when_no_set_matched_by_name() { harness.get_by_label("Set Match to By Mesh Name to pair parts by name."); } + +#[test] +fn on_a_narrow_dock_the_tabs_scroll_clear_of_the_issues_filter() { + // A window this narrow leaves the docked log less room than its three tabs and the filter take together + const NARROW_WINDOW_WIDTH: f32 = 520.0; + + let mut harness = Harness::builder() + .with_size(egui::vec2(NARROW_WINDOW_WIDTH, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, texturecraft_engine::sample_session(256, 64).unwrap())); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let filter = harness.get_by_label("Show only rows with an issue").rect(); + let strip_start = harness.get_by_role_and_label(Role::Tab, "Baking Process").rect().left(); + let last_tab = harness.get_by_role_and_label(Role::Tab, "Matching by Name").rect(); + assert!(last_tab.right() > filter.left(), "unscrolled, the tabs {last_tab:?} run past the filter {filter:?}, so they must scroll"); + + // Frames for the strip's scroll to the focused tab to finish + const SCROLL_FRAMES: usize = 30; + + for tab in ["Baking Process", "High Poly Parameters", "Matching by Name"] { + harness.get_by_role_and_label(Role::Tab, tab).focus(); + harness.run_steps(SCROLL_FRAMES); + + let rect = harness.get_by_role_and_label(Role::Tab, tab).rect(); + assert!(rect.right() <= filter.left(), "the focused {tab} tab {rect:?} ends left of the filter {filter:?}"); + assert!(rect.left() >= strip_start, "the focused {tab} tab {rect:?} starts inside the log, where the first tab starts unscrolled"); + } +} + +#[test] +fn a_matching_name_cut_short_shows_in_full_on_hover() { + const LONG_NAME: &str = "Left_shoulder_strap_buckle_with_its_rivets_and_its_stitching_low"; + + // Frames past the tooltip delay + const TOOLTIP_FRAMES: usize = 60; + + let mut harness = harness(); + log_a_bake(&mut harness, BakeMapState::Baked); + let pair = NamePair { low: Some(LONG_NAME.into()), high: Some("Strap_high".into()) }; + harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { low_suffix: "_low".into(), high_suffix: "_high".into(), pairs: vec![pair] }); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + let label = format!("{LONG_NAME}, Strap_high"); + let row = harness.get_by_label(&label).rect(); + assert_eq!(harness.query_all_by_label(&label).count(), 1, "no tooltip before hovering"); + + harness.hover_at(row.center()); + harness.run_steps(TOOLTIP_FRAMES); + + assert_eq!(harness.query_all_by_label(&label).count(), 2, "the tooltip carries both names in full"); +} From edb8456d62134be8a16bf50a14cd78c900531166 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:55:20 +0100 Subject: [PATCH 151/190] ci(deps): bump the actions group across 1 directory with 6 updates (#831) * ci(deps): bump the actions group across 1 directory with 6 updates Bumps the actions group with 6 updates in the / directory: | Package | From | To | | --- | --- | --- | | [step-security/harden-runner](https://github.com/step-security/harden-runner) | `2.22.4` | `2.23.0` | | [storytold/craft-common-actions/actions/checkout-craft-fonts](https://github.com/storytold/craft-common-actions) | `605d58766e8f536564da8fc81d3676ac86816dea` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | | [storytold/craft-common-actions/actions/checkout-craft-i18n](https://github.com/storytold/craft-common-actions) | `605d58766e8f536564da8fc81d3676ac86816dea` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | | [storytold/craft-common-actions/actions/rust-channel](https://github.com/storytold/craft-common-actions) | `605d58766e8f536564da8fc81d3676ac86816dea` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | | [storytold/craft-common-actions/.github/workflows/nightly-release.yml](https://github.com/storytold/craft-common-actions) | `be00e5ccd18b68e950c8a08532f2230e7c3d0cba` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | | [storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml](https://github.com/storytold/craft-common-actions) | `be00e5ccd18b68e950c8a08532f2230e7c3d0cba` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | Updates `step-security/harden-runner` from 2.22.4 to 2.23.0 - [Release notes](https://github.com/step-security/harden-runner/releases) - [Commits](https://github.com/step-security/harden-runner/compare/1d88384fd173af6ecb012dfd0264a306b711241a...aebdcf6156ab6691adf63218240e476564a1ed4c) Updates `storytold/craft-common-actions/actions/checkout-craft-fonts` from 605d58766e8f536564da8fc81d3676ac86816dea to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/605d58766e8f536564da8fc81d3676ac86816dea...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) Updates `storytold/craft-common-actions/actions/checkout-craft-i18n` from 605d58766e8f536564da8fc81d3676ac86816dea to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/605d58766e8f536564da8fc81d3676ac86816dea...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) Updates `storytold/craft-common-actions/actions/rust-channel` from 605d58766e8f536564da8fc81d3676ac86816dea to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/605d58766e8f536564da8fc81d3676ac86816dea...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) Updates `storytold/craft-common-actions/.github/workflows/nightly-release.yml` from be00e5ccd18b68e950c8a08532f2230e7c3d0cba to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/be00e5ccd18b68e950c8a08532f2230e7c3d0cba...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) Updates `storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml` from be00e5ccd18b68e950c8a08532f2230e7c3d0cba to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/be00e5ccd18b68e950c8a08532f2230e7c3d0cba...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) --- updated-dependencies: - dependency-name: step-security/harden-runner dependency-version: 2.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: actions - dependency-name: storytold/craft-common-actions/.github/workflows/nightly-release.yml dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions - dependency-name: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions - dependency-name: storytold/craft-common-actions/actions/checkout-craft-fonts dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions - dependency-name: storytold/craft-common-actions/actions/checkout-craft-i18n dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions - dependency-name: storytold/craft-common-actions/actions/rust-channel dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions ... Signed-off-by: dependabot[bot] * ci: keep nightly tooling-revision and signing policy in lockstep Dependabot bumped the nightly-unsigned and nightly-release uses pins to f94a438 but left tooling-revision and the installed signing policy on be00e5c. The packaging checks require those pins to match. --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- .github/nightly-signing-policy.json | 6 +++--- .github/workflows/nightly-macos.yml | 8 ++++---- .github/workflows/nightly-sign.yml | 4 ++-- .github/workflows/nightly.yml | 4 ++-- docs/nightly-release-preparation.md | 6 +++--- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 35cb9eeb..ab63e5a3 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1419654881, "producer_workflow_id": 429738073, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml index 75134544..1c49c360 100644 --- a/.github/workflows/nightly-macos.yml +++ b/.github/workflows/nightly-macos.yml @@ -36,7 +36,7 @@ jobs: RUST_BACKTRACE: 1 steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -44,12 +44,12 @@ jobs: persist-credentials: false # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. - name: Check out craft-fonts - uses: storytold/craft-common-actions/actions/checkout-craft-fonts@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: ref: aced4137c022f1f587624d48e81ec77e1914a9cc - - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/actions/rust-channel@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: targets: aarch64-apple-darwin - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 998acbae..65767940 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,9 +34,9 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a app-name: texturecraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 1600b2e0..a0933e12 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a app-name: texturecraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 6ed80ba0..616c743c 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -15,8 +15,8 @@ gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation permissions are for its isolated attester; its compiler narrows to contents and Actions read only, with no OIDC, attestation write, release environment or platform signing secrets. -Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions -main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the +Shared tooling is pinned to `f94a43818dabb2e85f2f4d5cd768bb8e5662600a`, the craft-common-actions +main commit that merged [#382](https://github.com/storytold/craft-common-actions/pull/382) (first-signer-attempt creation time is reconciled on re-read) after [#371](https://github.com/storytold/craft-common-actions/pull/371) (the candidate is admitted on the built commit's own Sonar analysis, not main's latest) after [#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly registry rows for the 14 apps) and @@ -80,7 +80,7 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` |---|---|---| | `repository_id` | `1419654881` | `gh api repos/storytold/texturecraft --jq .id` | | `producer_workflow_id` | `429738073` | `gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id` | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions #371 after #370, #369 and #364) | The callers' pin | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `f94a4381…` (craft-common-actions #382 after #379, #376, #371, #370, #369 and #364) | The callers' pin | | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | | `platforms` | three rows (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | Stable suite signing identities (`Learning Machines Inc` Authenticode subject, Linux OpenPGP fingerprint `2B76741B414AAD6CD33E631213A005C0B9D7C3ED`, Apple Team ID `DJ6XS33FX8`) | From 41a7d1d8a606aac371e23a8311e5268d60220208 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:04:35 +0000 Subject: [PATCH 152/190] Keep the texture set list's keys and Escape from the app's shortcuts Escape drops a rename or description edit even once the window's cancel has taken it from egui's input. With the pointer over the list, F2 renames the selected set and Shift+F10 or the Menu key opens its menu instead of switching the viewers layout or the mode. Escape is no longer a painting cancel while a dialog is open, so the channels window closes on it. A texture set name over the length limit is refused for its length. --- crates/engine/src/set_cmds.rs | 20 +++-- crates/ui-egui/src/menus.rs | 13 +++- crates/ui-egui/src/texture_set_list.rs | 75 +++++++++++++++++-- .../src/texture_set_list/list_state.rs | 12 ++- crates/ui-egui/src/texture_set_settings.rs | 22 ++++++ 5 files changed, 127 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 788d140b..4d62d6fa 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -380,11 +380,12 @@ fn rename(s: &mut Session, p: &Value) -> Result { let name = if boolp(p, "reset") == Some(true) { s.original_set_name(ts).ok_or_else(|| bad("textureSet.rename", "the mesh has no material name for this set"))?.to_string() } else { - strp(p, "name") - .map(str::trim) - .filter(|name| !name.is_empty() && name.chars().count() <= MAX_NAME_CHARS) - .ok_or_else(|| bad("textureSet.rename", "`name` or `reset: true` is required"))? - .to_string() + let name = strp(p, "name").map(str::trim).filter(|name| !name.is_empty()); + let name = name.ok_or_else(|| bad("textureSet.rename", "`name` or `reset: true` is required"))?; + if name.chars().count() > MAX_NAME_CHARS { + return Err(bad("textureSet.rename", format!("`name` is at most {MAX_NAME_CHARS} characters"))); + } + name.to_string() }; s.edit("Rename texture set", |s| { s.doc.project.texture_set_mut(ts)?.name = name; @@ -543,6 +544,15 @@ mod tests { assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1})).is_err()); } + #[test] + fn a_too_long_name_is_refused_for_its_length_not_as_missing() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let long = "n".repeat(MAX_NAME_CHARS + 1); + let error = crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": long})).unwrap_err().to_string(); + assert!(error.contains("at most") && !error.contains("required"), "{error}"); + assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "n".repeat(MAX_NAME_CHARS)})).is_ok()); + } + #[test] fn visibility_shows_hides_inverts_and_solos() { // The material ball has two texture sets. diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 8f6bc3e0..983ed89f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -503,6 +503,10 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { let picker_open = crate::color_picker::open_window(ctx).is_some(); let nothing_focused = !crate::framework::widget_has_keyboard(ctx); + // A dialog closes on Escape itself + let modal_open = ctx.memory(|memory| memory.top_modal_layer().is_some()); + let over_set_list = crate::texture_set_list::pointer_over(ctx); + let mut set_list_keys = (false, false); let log_copies = crate::log_panel::takes_copy(app, ctx); let commands_to_invoke = ctx.input_mut(|input| { // egui's label selection copies on these events at the end of the frame @@ -521,6 +525,12 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.ui.windows.export && app.ui.export.tab == 1 && app.ui.export.ask.is_none() && input.consume_key(Modifiers::NONE, Key::F2) { app.ui.export.rename_key = true; } + // Over the texture set list, F2 renames the selected set and Shift+F10 or the Menu key opens its menu, before + // the 3D view and Render mode bindings + if over_set_list { + let menu = input.consume_key(Modifiers::SHIFT, Key::F10) || input.consume_key(Modifiers::NONE, Key::Menu); + set_list_keys = (input.consume_key(Modifiers::NONE, Key::F2), menu); + } let commands = app.bindings.dispatch(input); for copy in copies { if !input.events.contains(©) { @@ -538,7 +548,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } // The open list or the picker window closes on this Escape itself - let escape_is_free = !popup_open && !picker_open; + let escape_is_free = !popup_open && !picker_open && !modal_open; if confirming_reset { // Its keys were handled before the shortcuts ran } else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { @@ -573,6 +583,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if cancel_point_pick { crate::generator_point_pick::set(ctx, None); } + crate::texture_set_list::take_keys(ctx, set_list_keys.0, set_list_keys.1); for id in &commands_to_invoke { run_shortcut(app, ctx, id); diff --git a/crates/ui-egui/src/texture_set_list.rs b/crates/ui-egui/src/texture_set_list.rs index cd47c652..440c75cb 100644 --- a/crates/ui-egui/src/texture_set_list.rs +++ b/crates/ui-egui/src/texture_set_list.rs @@ -159,9 +159,25 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { } } }); + state.hovered = ui.ui_contains_pointer().then(|| ui.ctx().cumulative_pass_nr()); state.store(ui.ctx()); } +/// Whether the pointer was over the list in the last pass, so F2 and the menu keys are the list's and not their bindings +pub(crate) fn pointer_over(ctx: &egui::Context) -> bool { + // A list no longer drawn (another tab, no project) has none + ListState::stored(ctx).and_then(|state| state.hovered).is_some_and(|pass| pass + 1 == ctx.cumulative_pass_nr()) +} + +/// Hands the selected row F2 (`rename`) or Shift+F10 or the Menu key (`menu`), read before the shortcuts ran +pub(crate) fn take_keys(ctx: &egui::Context, rename: bool, menu: bool) { + if let Some(mut state) = ListState::stored(ctx).filter(|_| rename || menu) { + state.rename_key |= rename; + state.menu_key |= menu; + state.store(ctx); + } +} + /// Visibility menu and solo at the left, the descriptions menu at the right fn toolbar(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, rows: &[SetRow], active: usize, tokens: &Tokens) { let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), BAR_HEIGHT), Sense::hover()); @@ -327,18 +343,20 @@ fn set_row(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, index: } } - // F2 renames the focused row, as a double click does - let rename_key = response.has_focus() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::F2)); + // F2 renames the focused row, or the selected one with the pointer over the list, as a double click does + let rename_key = (selected && std::mem::take(&mut state.rename_key)) + || (response.has_focus() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::F2))); if response.double_clicked() || rename_key { action = Some(RowAction::Edit(RowEdit::Name)); } else if action.is_none() && (response.clicked() || response.secondary_clicked()) { action = Some(RowAction::Select); } - context_menu(ui, &response, row, tokens).or(action) + let menu_key = selected && std::mem::take(&mut state.menu_key); + context_menu(ui, &response, row, menu_key, tokens).or(action) } -/// The row's right-click menu (Shift+F10 or the Menu key on a focused row), in the toolbar menus' look -fn context_menu(ui: &Ui, response: &Response, row: &SetRow, tokens: &Tokens) -> Option { +/// The row's right-click menu in the toolbar menus' look, also from Shift+F10 or the Menu key (`menu_key` over the list) +fn context_menu(ui: &Ui, response: &Response, row: &SetRow, menu_key: bool, tokens: &Tokens) -> Option { let renamed = row.original_name.as_ref().is_some_and(|original| *original != row.name); let visibility = if row.visible { (ic::EYE_SLASH, "Hide Texture Set") } else { (ic::EYE, "Show Texture Set") }; let entries = [ @@ -361,9 +379,9 @@ fn context_menu(ui: &Ui, response: &Response, row: &SetRow, tokens: &Tokens) -> // A menu opened from the keyboard has no pointer to open at: it hangs under the row while it stays open let from_keyboard = response.id.with("ts_menu_from_keyboard"); - let menu_key = + let pressed = |input: &mut egui::InputState| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu); - if response.has_focus() && ui.input_mut(menu_key) { + if menu_key || (response.has_focus() && ui.input_mut(pressed)) { ui.data_mut(|data| data.insert_temp(from_keyboard, true)); popup = popup.open_memory(Some(egui::SetOpenCommand::Bool(true))); } else if !popup.is_open() { @@ -515,7 +533,9 @@ fn edit_field(ui: &mut Ui, state: &mut ListState, rect: Rect, size: f32) -> Opti } let edit = state.edit.take()?; - (!ui.input(|input| input.key_pressed(egui::Key::Escape))).then_some(edit.2) + // Raw Escape: with the field's focus gone, the window's cancel takes it from egui's input + let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + (!escaped).then_some(edit.2) } /// A glyph button of the list: dim glyph, bright and framed when hovered or lit @@ -632,6 +652,45 @@ mod tests { assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_some(), "Shift+F10 opens the row's menu"); } + #[test] + fn escape_drops_a_rename_under_way() { + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + click(&mut harness, egui::Role::ListItem, &original, egui::PointerButton::Secondary); + click(&mut harness, egui::Role::Button, "Edit Name", egui::PointerButton::Primary); + harness.run_steps(3); + harness.event(egui::Event::Text("q".into())); + harness.run_steps(1); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(harness.state().session.doc.project.texture_sets[1].name, original); + } + + #[test] + fn over_the_list_f2_renames_the_selected_set_and_shift_f10_opens_its_menu() { + // A clicked row has no keyboard focus, so these keys would otherwise reach the 3D view and Render mode + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + let layout = harness.state().ui.layout; + click(&mut harness, egui::Role::ListItem, &original, egui::PointerButton::Primary); + harness.key_press(egui::Key::F2); + harness.run_steps(3); + harness.event(egui::Event::Text("w".into())); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + let renamed = harness.state().session.doc.project.texture_sets[1].name.clone(); + assert!(renamed != original && renamed.contains('w'), "{renamed}"); + assert!(harness.state().ui.layout == layout, "the viewers layout stayed"); + + let mode = harness.state().ui.mode; + harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + harness.run_steps(3); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_some(), "Shift+F10 opens the row's menu"); + assert!(harness.state().ui.mode == mode, "the mode stayed"); + } + #[test] fn a_rename_under_way_is_dropped_when_another_project_replaces_this_one() { let mut harness = harness("material_ball"); diff --git a/crates/ui-egui/src/texture_set_list/list_state.rs b/crates/ui-egui/src/texture_set_list/list_state.rs index 772da31d..8c7a4f83 100644 --- a/crates/ui-egui/src/texture_set_list/list_state.rs +++ b/crates/ui-egui/src/texture_set_list/list_state.rs @@ -14,6 +14,11 @@ pub(crate) struct ListState { pub(crate) folded: BTreeSet, /// Set and UDIM of the selected UV tile row pub(crate) tile: Option<(usize, u32)>, + /// The last pass that drew the list with the pointer over it + pub(crate) hovered: Option, + /// F2 or the menu key came while the pointer was over the list: the selected row takes it in this pass + pub(crate) rename_key: bool, + pub(crate) menu_key: bool, } impl ListState { @@ -28,7 +33,12 @@ impl ListState { return state; } - ListState { owner, descriptions: state.descriptions, ..ListState::default() } + ListState { owner, descriptions: state.descriptions, hovered: state.hovered, ..ListState::default() } + } + + /// The stored state, whatever project it belongs to + pub(crate) fn stored(ctx: &egui::Context) -> Option { + ctx.data(|data| data.get_temp::(Self::id())) } pub(crate) fn store(self, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs index 046bd94c..0e36e4b2 100644 --- a/crates/ui-egui/src/texture_set_settings.rs +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -391,4 +391,26 @@ mod tests { assert!(marked("Base weight"), "a channel the shader ignores is marked"); assert!(!marked("User0"), "a user channel is not"); } + + #[test] + fn escape_closes_the_channel_window_with_nothing_focused_and_drops_its_ticks() { + let mut harness = harness("material_ball"); + let had = harness.state().session.doc.project.texture_sets[0].has_channel(Channel::User0); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.run_steps(4); + click(&mut harness, egui::Role::CheckBox, "User0"); + // As after a click on the dialog's empty space: no control keeps the keyboard + let ctx = harness.ctx.clone(); + ctx.memory_mut(|memory| { + if let Some(focused) = memory.focused() { + memory.surrender_focus(focused); + } + }); + harness.run_steps(2); + + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + assert!(harness.query_by_role_and_label(egui::Role::CheckBox, "User0").is_none(), "the window closed"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].has_channel(Channel::User0), had, "nothing was applied"); + } } From 145a4db4ec070532e65c60deda4bd290733c3150 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:08:28 +0000 Subject: [PATCH 153/190] Assets: renaming an image also moves a generator's texture, grunge, micro details and Grayscale Conversion image --- crates/core/src/layer.rs | 13 ++++++++++++- crates/core/src/layer/micro_details.rs | 5 +++++ crates/engine/src/resource_cmds.rs | 20 ++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 1e10a7c8..96c4ea27 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1294,6 +1294,17 @@ impl Generator { self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } + /// [`Generator::sources`], to rename the images they read + pub fn sources_mut(&mut self) -> impl Iterator { + let grayscale = match self.controls.as_deref_mut() { + Some(KindControls::Grayscale(grayscale)) if self.kind == GeneratorKind::GrayscaleConversion => grayscale.source.as_mut(), + _ => None, + }; + let micro = self.micro.iter_mut().flat_map(|micro| micro.sources_mut()).chain(grayscale); + let texture = self.texture.as_mut().and_then(|texture| texture.source.as_mut()); + self.inputs.values_mut().chain(texture).chain(self.grunge.as_mut()).chain(micro) + } + /// The micro details as saved, when the generator computes with them: with a slot switched on, except a micro detail saved before Micro Details on a generator still on the earlier model, which [`Generator::earlier_micro`] reads (bring them into range before use: saved files are not trusted) pub fn micro_in_use(&self) -> Option<&MicroDetails> { self.micro.as_deref().filter(|micro| micro.in_use(self.kind) && !(micro.earlier && self.on_earlier_model())) @@ -2360,7 +2371,7 @@ impl EffectKind { match self { EffectKind::Fill { source, .. } => source.images_mut(), EffectKind::Material(fill) => fill.images_mut().collect(), - EffectKind::Generator(generator) => generator.inputs.values_mut().flat_map(Source::images_mut).collect(), + EffectKind::Generator(generator) => generator.sources_mut().flat_map(Source::images_mut).collect(), EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(), _ => Vec::new(), } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 36248e27..4ccb0373 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -119,6 +119,11 @@ impl MicroDetails { self.height_source.iter().chain(self.normal_source.as_ref()) } + /// [`MicroDetails::sources`], to rename the images they read + pub fn sources_mut(&mut self) -> impl Iterator { + self.height_source.iter_mut().chain(self.normal_source.as_mut()) + } + /// Every value brought into its range, non-finite ones to the defaults of `kind` pub fn clamped(self, kind: GeneratorKind) -> MicroDetails { let Some(defaults) = MicroDetails::defaults(kind) else { return self }; diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 83f9d180..cca76157 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -654,6 +654,26 @@ mod tests { assert_eq!(link.outputs.values().collect::>(), [&renamed], "the link's cooked outputs follow the rename"); } + #[test] + fn renaming_an_image_a_generator_reads_as_its_grunge_moves_the_grunge_with_it() { + use texturecraft_core::{Effect, EffectKind, Generator, GeneratorKind}; + + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let grunge = session.import_resource_bytes("grunge.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": grunge})).unwrap(); + let layer_id = session.selected_layer().unwrap(); + let generator = Generator { grunge: Some(Source::image(grunge.clone())), ..Generator::new(GeneratorKind::EdgeWear) }; + let effect_id = session.doc.project.alloc_id(); + session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(Effect::new(effect_id, EffectKind::Generator(generator))); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": grunge, "to": "worn"})).unwrap()["name"].as_str().unwrap().to_string(); + + let EffectKind::Generator(generator) = &session.doc.project.layers[&layer_id].content_effects[0].kind else { panic!("the effect stays a generator") }; + assert_ne!(renamed, grunge); + assert_eq!(generator.grunge, Some(Source::image(renamed)), "the generator's grunge follows the rename"); + } + #[test] fn reloading_reads_the_file_again_and_undo_restores_the_pixels() { let mut session = crate::sample_session(128, 32).unwrap(); From bd03a0411f37904b5c93494d23b98c15e7989cd0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:01:49 +0100 Subject: [PATCH 154/190] texturecraft-cli: follow RFC-0018 (clap, thiserror, run(args, out, err), packaged completions and man pages) (#875) * texturecraft-cli: follow RFC-0018 (clap, thiserror, run(args, out, err), packaged completions and man pages) Closes #866. Part of storytold/craft-contrib#95. * fix(cli): enable clap env, and close replacement and token gaps - Enable clap's `env` feature so TEXTURECRAFT_CONTROL_TOKEN compiles in a standalone `-p texturecraft-cli` release build (the FreeBSD package job). - An inherited token no longer implies --bridge; only a command-line --token does. - Compare run/bake/new outputs to the path Headless::save actually writes (it appends .tcraft when the extension is missing). - Apply the same replacement rule to batch (save vs open), with --in-place. - Build man-and-completions for the host when CARGO_BUILD_TARGET is set. - Don't panic in the blank-token test when the environment already has a token. * fix(cli): require both roots for headless mcp AGENTS.md rule 18 says an agent entry point must refuse to start without --automation-read-root and --automation-write-root (the --read-root / --write-root aliases here). Headless mcp now exits 2 unless both are set; --bridge is unchanged. The missing-CLI_DOCS diagnostic also names the host-example env -u CARGO_BUILD_TARGET prefix already used to build it. --- .github/workflows/packaging-lint.yml | 18 + Cargo.lock | 169 ++++++- Cargo.toml | 4 + apps/texturecraft-cli/Cargo.toml | 12 + .../examples/man-and-completions.rs | 42 ++ apps/texturecraft-cli/src/args.rs | 422 ++++++++++++++++ apps/texturecraft-cli/src/error.rs | 36 ++ apps/texturecraft-cli/src/lib.rs | 342 +++++++++++++ apps/texturecraft-cli/src/main.rs | 450 +----------------- apps/texturecraft-cli/tests/cli.rs | 14 +- apps/texturecraft-cli/tests/it/cli.rs | 331 +++++++++++++ apps/texturecraft-cli/tests/it/main.rs | 48 ++ .../tests/it/man_and_completions.rs | 55 +++ apps/texturecraft-cli/tests/it/protocol.rs | 118 +++++ crates/automation/src/security.rs | 30 +- docs/control-protocol.md | 34 +- packaging/freebsd/package.sh | 40 +- packaging/linux/nfpm.yaml | 7 + packaging/linux/package.sh | 25 + 19 files changed, 1717 insertions(+), 480 deletions(-) create mode 100644 apps/texturecraft-cli/examples/man-and-completions.rs create mode 100644 apps/texturecraft-cli/src/args.rs create mode 100644 apps/texturecraft-cli/src/error.rs create mode 100644 apps/texturecraft-cli/src/lib.rs create mode 100644 apps/texturecraft-cli/tests/it/cli.rs create mode 100644 apps/texturecraft-cli/tests/it/main.rs create mode 100644 apps/texturecraft-cli/tests/it/man_and_completions.rs create mode 100644 apps/texturecraft-cli/tests/it/protocol.rs diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index feb8675d..75332dd7 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -25,3 +25,21 @@ jobs: # Runs the Nightly synthetic suites, the launcher tests and `bash -n` here, so the checks # that need no compiler are part of CI rather than a local step. extra-checks-script: packaging/nightly-checks.sh + + freebsd-layout: + # The FreeBSD package layout, with stub binaries standing in for the build: RFC-0018 rule 1.9 + # puts texturecraft-cli's man pages and its bash, zsh and fish completions in it. + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: FreeBSD package layout (dry run) + run: | + CARGO_TARGET_DIR="$RUNNER_TEMP/texturecraft-target" bash packaging/freebsd/package.sh --dry-run + listing="$(tar -tzf "$RUNNER_TEMP"/texturecraft-target/freebsd-package/texturecraft-*-freebsd-x86_64.tar.gz)" + for f in man/man1/texturecraft-cli.1 share/bash-completion/completions/texturecraft-cli \ + share/zsh/site-functions/_texturecraft-cli share/fish/vendor_completions.d/texturecraft-cli.fish; do + grep -q "/$f$" <<<"$listing" || { echo "::error::$f is missing from the FreeBSD package"; exit 1; } + done diff --git a/Cargo.lock b/Cargo.lock index 55ae4efa..90fbf93d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -212,12 +212,56 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "arboard" version = "3.6.1" @@ -672,7 +716,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.6", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -776,6 +820,65 @@ dependencies = [ "libloading", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "clap_mangen" +version = "0.2.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78" +dependencies = [ + "clap", + "roff", +] + [[package]] name = "clipboard-win" version = "5.4.1" @@ -820,6 +923,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.8" @@ -1740,7 +1849,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -2141,7 +2250,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2339,7 +2448,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3237,6 +3346,12 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.13.0" @@ -3674,7 +3789,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png", "thiserror 2.0.21", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4343,6 +4458,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "openssl-probe" version = "0.2.2" @@ -4391,7 +4512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5138,6 +5259,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "roff" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" + [[package]] name = "ron" version = "0.12.2" @@ -5192,7 +5319,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5205,7 +5332,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5272,7 +5399,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5650,7 +5777,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -5800,10 +5927,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5878,10 +6005,14 @@ dependencies = [ name = "texturecraft-cli" version = "0.6.1" dependencies = [ + "clap", + "clap_complete", + "clap_mangen", "image", "serde_json", "texturecraft-automation", "texturecraft-engine", + "thiserror 2.0.21", "tokio", "winresource", ] @@ -6385,7 +6516,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -6520,6 +6651,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" @@ -7075,7 +7212,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -7462,7 +7599,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" dependencies = [ "bitflags 2.13.2", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -7869,7 +8006,7 @@ dependencies = [ "memchr", "nix", "typed-path", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "zeroize", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index 2b52c050..9a0cd63a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,10 @@ texturecraft-ui-egui = { path = "crates/ui-egui" } # external thiserror = "2" +# The command line of texturecraft-cli (RFC-0018); the generators are dev-dependencies, for the man pages and completions. +clap = { version = "4", features = ["derive", "string", "env"] } +clap_complete = "4" +clap_mangen = "0.2" chrono = { version = "0.4", default-features = false, features = ["now", "wasmbind"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/apps/texturecraft-cli/Cargo.toml b/apps/texturecraft-cli/Cargo.toml index d458a8d0..61f4c61a 100644 --- a/apps/texturecraft-cli/Cargo.toml +++ b/apps/texturecraft-cli/Cargo.toml @@ -6,6 +6,14 @@ edition.workspace = true license.workspace = true build = "build.rs" +[lib] +name = "texturecraft_cli" +path = "src/lib.rs" + +[[bin]] +name = "texturecraft-cli" +path = "src/main.rs" + [lints] workspace = true @@ -14,9 +22,13 @@ texturecraft-automation = { workspace = true } texturecraft-engine = { workspace = true } serde_json = { workspace = true } tokio = { workspace = true } +thiserror = { workspace = true } +clap = { workspace = true } [dev-dependencies] image = { workspace = true } +clap_complete = { workspace = true } +clap_mangen = { workspace = true } [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft-cli/examples/man-and-completions.rs b/apps/texturecraft-cli/examples/man-and-completions.rs new file mode 100644 index 00000000..55885101 --- /dev/null +++ b/apps/texturecraft-cli/examples/man-and-completions.rs @@ -0,0 +1,42 @@ +//! Writes texturecraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish, +//! PowerShell) and man pages ([`clap_mangen`]: `texturecraft-cli.1` and one per subcommand, such as +//! `texturecraft-cli-info.1`) into a directory. The Linux and FreeBSD packages ship them +//! (`packaging/linux/package.sh`, `packaging/freebsd/package.sh`): +//! +//! ```sh +//! cargo run -p texturecraft-cli --example man-and-completions -- +//! ``` + +use std::path::Path; +use std::process::ExitCode; + +use clap::ValueEnum; +use clap_complete::Shell; + +fn main() -> ExitCode { + let mut args = std::env::args_os().skip(1); + let (Some(dir), None) = (args.next(), args.next()) else { + eprintln!("usage: man-and-completions "); + return ExitCode::from(2); + }; + let dir = Path::new(&dir); + match generate(dir) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {}: {e}", dir.display()); + ExitCode::FAILURE + } + } +} + +/// Also run by `tests/it/man_and_completions.rs`. +pub(crate) fn generate(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let mut cmd = texturecraft_cli::command(); + for &shell in Shell::value_variants() { + clap_complete::generate_to(shell, &mut cmd, "texturecraft-cli", dir)?; + } + // A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand, + // which `clap_mangen` would otherwise give pages of its own (`texturecraft-cli-help-convert.1`). + clap_mangen::generate_to(texturecraft_cli::command(), dir) +} diff --git a/apps/texturecraft-cli/src/args.rs b/apps/texturecraft-cli/src/args.rs new file mode 100644 index 00000000..64373804 --- /dev/null +++ b/apps/texturecraft-cli/src/args.rs @@ -0,0 +1,422 @@ +//! The command line as clap derive types. Values arrive typed, so the commands never validate a +//! string; what clap can't say alone is a [`UsageError`], printed and exited like clap's own. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use clap::error::ErrorKind; +use clap::{Args, FromArgMatches, Parser, Subcommand}; +use serde_json::Value; + +/// The end of `--help` of every command. +const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 a command failed\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell."; + +const INPUTS: &str = "An is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .usd .usda .usdc .usdz .abc .obj .ply .stl) or builtin: (material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate, udim_plane). See docs/control-protocol.md."; + +/// Headless TextureCraft +#[derive(Parser, Debug)] +#[command(name = "texturecraft-cli", propagate_version = true, arg_required_else_help = true, after_help = EXIT_STATUS)] +pub(crate) struct Cli { + #[command(subcommand)] + pub(crate) command: Command, +} + +#[derive(Subcommand, Debug)] +pub(crate) enum Command { + /// Texture sets, layers, triangles, materials and the UV report, as JSON + #[command(after_help = INPUTS)] + Info(InfoArgs), + /// List the engine commands (id, label, params) + Commands(CommandsArgs), + /// Run one command and print its JSON result; -o saves the project + #[command(after_help = INPUTS)] + Run(RunArgs), + /// Run a script of commands + /// + /// The script is JSON: [{"id", "params"}, ...] or {"open": , "steps": [...], "save": }. + Batch(BatchArgs), + /// Bake mesh maps for every texture set + /// + /// A project is saved in place without -o, which needs --in-place; a mesh needs -o. + #[command(after_help = INPUTS)] + Bake(BakeArgs), + /// Export textures (default preset: Document channels + Normal + AO (No Alpha)) + #[command(after_help = INPUTS)] + Export(ExportArgs), + /// Render the viewport to PNG (needs a GPU or software adapter) + /// + /// --camera looks through a camera saved in the project (camera.add); --samples path traces it + /// instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on + /// the CPU. + #[command(after_help = INPUTS)] + Render(RenderArgs), + /// A new project from a mesh or a built-in mesh + /// + /// --sample bakes and applies a smart material to every texture set. The sample's mesh maps are + /// baked at the resolution up to 1024 px (most of the file's size), so a 2048 sample project is + /// as large as a 1024 one. + #[command(after_help = INPUTS)] + New(NewArgs), + /// MCP server on stdio: headless, or bridged to `texturecraft --control ` + /// + /// Headless, file access is only below the roots. + Mcp(McpArgs), + /// JSON lines ({"id","method","params"}) on stdio, or on 127.0.0.1: with a token + Serve(ServeArgs), +} + +#[derive(Args, Debug)] +pub(crate) struct InfoArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, +} + +#[derive(Args, Debug)] +pub(crate) struct CommandsArgs { + /// Only the commands whose id or label contains this text + #[arg(long, value_name = "TEXT")] + pub(crate) filter: Option, + /// Print the list as JSON instead of a table + #[arg(long)] + pub(crate) json: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct RunArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "COMMAND-ID")] + pub(crate) id: String, + /// The command's parameters, as JSON + #[arg(value_name = "PARAMS-JSON", value_parser = json_value)] + pub(crate) params: Option, + /// Save the project here + #[arg(short = 'o', long = "output", value_name = "OUT.TCRAFT")] + pub(crate) output: Option, + /// Allow -o to replace the project it opened + #[arg(long, requires = "output")] + pub(crate) in_place: bool, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("params are not JSON: {0}")] +pub(crate) struct NotJson(String); + +fn json_value(s: &str) -> Result { + serde_json::from_str(s).map_err(|e| NotJson(e.to_string())) +} + +#[derive(Args, Debug)] +pub(crate) struct BatchArgs { + #[arg(value_name = "SCRIPT.JSON")] + pub(crate) script: PathBuf, + /// Allow `save` to replace the project `open` named + #[arg(long)] + pub(crate) in_place: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct BakeArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + /// Save the baked project here + #[arg(short = 'o', long = "output", value_name = "OUT.TCRAFT")] + pub(crate) output: Option, + /// Bake at this size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) resolution: Option, + /// Only these maps (ids, comma separated) + #[arg(long, value_name = "ID,ID,...", value_delimiter = ',')] + pub(crate) maps: Vec, + /// Save over the project it opened (without -o), or allow -o to replace it + #[arg(long)] + pub(crate) in_place: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct ExportArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "DIR")] + pub(crate) dir: PathBuf, + /// An export preset by name + #[arg(long, value_name = "NAME")] + pub(crate) preset: Option, + /// File format (an extension) + #[arg(long, value_name = "EXT")] + pub(crate) format: Option, + /// Padding mode + #[arg(long, value_name = "MODE")] + pub(crate) padding: Option, + /// Texture size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) size: Option, +} + +#[derive(Args, Debug)] +pub(crate) struct RenderArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "OUT.PNG")] + pub(crate) output: PathBuf, + /// Image size + #[arg(long, value_name = "WxH")] + pub(crate) size: Option, + /// The viewport: 3D, or the UV view of the active texture set + #[arg(long, value_name = "VIEW", value_parser = ["3d", "2d", "uv"])] + pub(crate) view: Option, + /// Look through a camera saved in the project + #[arg(long, value_name = "NAME")] + pub(crate) camera: Option, + /// Camera yaw in degrees + #[arg(long, value_name = "DEG", allow_negative_numbers = true, value_parser = finite)] + pub(crate) yaw: Option, + /// Camera pitch in degrees + #[arg(long, value_name = "DEG", allow_negative_numbers = true, value_parser = finite)] + pub(crate) pitch: Option, + /// Path trace with this many samples per pixel + #[arg(long, value_name = "N", value_parser = positive)] + pub(crate) samples: Option, + /// Light bounces of the path tracer + #[arg(long, value_name = "N", requires = "samples")] + pub(crate) bounces: Option, + /// Path trace on the CPU + #[arg(long, requires = "samples")] + pub(crate) cpu: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct NewArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "OUT.TCRAFT")] + pub(crate) output: PathBuf, + /// Texture size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) resolution: Option, + /// Bake and apply a smart material to every texture set + #[arg(long)] + pub(crate) sample: bool, +} + +/// The folders a server may read from and write to; with neither, it has no file access. +#[derive(Args, Debug, Default)] +pub(crate) struct RootArgs { + /// Serve file access below this folder (alias --automation-read-root) + #[arg(long, alias = "automation-read-root", value_name = "DIR")] + pub(crate) read_root: Option, + /// Allow writes below this folder (alias --automation-write-root) + #[arg(long, alias = "automation-write-root", value_name = "DIR")] + pub(crate) write_root: Option, +} + +#[derive(Args, Debug)] +pub(crate) struct McpArgs { + /// Bridge to a running app's control port instead of a headless session + #[arg(long, value_name = "PORT", value_parser = port)] + pub(crate) bridge: Option, + /// The app's control token (TEXTURECRAFT_CONTROL_TOKEN; else the file the app wrote) + #[arg(long, value_name = "TOKEN", env = "TEXTURECRAFT_CONTROL_TOKEN", hide_env_values = true)] + pub(crate) token: Option, + #[command(flatten)] + pub(crate) roots: RootArgs, +} + +#[derive(Args, Debug)] +pub(crate) struct ServeArgs { + /// Listen on 127.0.0.1: with a token, instead of stdio + #[arg(long, value_name = "PORT", value_parser = port)] + pub(crate) port: Option, + #[command(flatten)] + pub(crate) roots: RootArgs, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a number of pixels above zero")] +pub(crate) struct NotPositive(String); + +fn positive(s: &str) -> Result { + s.parse::().ok().filter(|n| *n > 0).ok_or_else(|| NotPositive(s.to_string())) +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a finite number")] +pub(crate) struct NotFinite(String); + +fn finite(s: &str) -> Result { + s.parse::().ok().filter(|n| n.is_finite()).ok_or_else(|| NotFinite(s.to_string())) +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a loopback port (1-65535)")] +pub(crate) struct BadPort(String); + +/// A port, as `7878`, `127.0.0.1:7878` or `localhost:7878`. +fn port(s: &str) -> Result { + let digits = s.strip_prefix("127.0.0.1:").or_else(|| s.strip_prefix("localhost:")).unwrap_or(s); + digits.parse::().ok().filter(|p| *p != 0).ok_or_else(|| BadPort(s.to_string())) +} + +/// `--size` of `render`: WIDTHxHEIGHT. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Dimensions { + pub(crate) width: u32, + pub(crate) height: u32, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not x, e.g. 1280x800")] +pub(crate) struct BadDimensions(String); + +impl FromStr for Dimensions { + type Err = BadDimensions; + + fn from_str(s: &str) -> Result { + let (width, height) = s.split_once(['x', 'X']).ok_or_else(|| BadDimensions(s.to_string()))?; + match (positive(width), positive(height)) { + (Ok(width), Ok(height)) => Ok(Dimensions { width, height }), + _ => Err(BadDimensions(s.to_string())), + } + } +} + +/// A mistake in the command line that clap can't see by itself. +#[derive(Debug, PartialEq, thiserror::Error)] +pub(crate) enum UsageError { + #[error("{output} {} is the {input}, which it would replace: choose another file{}", path.display(), if *in_place_helps { ", or pass --in-place" } else { "" })] + WouldReplace { output: &'static str, input: &'static str, path: PathBuf, in_place_helps: bool }, + #[error("--in-place is for an output that is the INPUT, and this is another file")] + InPlaceNotUsed, + #[error("a mesh is not saved in place: give -o to save the baked project")] + BakeNeedsOutput, + #[error("saving over {} needs --in-place (or give -o )", path.display())] + BakeInPlace { path: PathBuf }, + #[error("{flag} is for a headless server, and --bridge connects to an app")] + RootsWithBridge { flag: &'static str }, + #[error("--token is for --bridge, and this is a headless server")] + TokenNeedsBridge, + #[error("mcp needs --read-root and --write-root (or their --automation-*-root aliases)")] + McpNeedsRoots, +} + +impl UsageError { + /// The clap error, printed with the usage and exited with 2 like clap's own. + pub(crate) fn into_clap(self, subcommand: &str) -> clap::Error { + let mut command = crate::command(); + // Built, so a subcommand's usage names the program: `texturecraft-cli run`. + command.build(); + let mut command = command.find_subcommand_mut(subcommand).map_or_else(crate::command, std::mem::take); + command.error(ErrorKind::ArgumentConflict, self.to_string()) + } +} + +/// Whether two paths name the same existing file, through links and `.` and `..`. +fn same_file(a: &Path, b: &Path) -> bool { + matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b) +} + +/// Whether `path` is a .tcraft project. +pub(crate) fn is_project(path: &Path) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case(texturecraft_engine::core::PROJECT_EXT)) +} + +/// The path `Headless::save` writes: it appends `.tcraft` when the extension is missing. +fn project_save_path(path: &Path) -> PathBuf { + if is_project(path) { + path.to_owned() + } else { + let mut raw = path.as_os_str().to_os_string(); + raw.push("."); + raw.push(texturecraft_engine::core::PROJECT_EXT); + PathBuf::from(raw) + } +} + +fn would_replace(output: &'static str, input: &'static str, to: &Path, from: &Path, in_place_helps: bool) -> Result<(), UsageError> { + if same_file(to, from) { Err(UsageError::WouldReplace { output, input, path: to.to_owned(), in_place_helps }) } else { Ok(()) } +} + +fn would_replace_project(output: &'static str, input: &'static str, to: &Path, from: &Path, in_place_helps: bool) -> Result<(), UsageError> { + would_replace(output, input, &project_save_path(to), from, in_place_helps) +} + +fn same_project(output: &Path, input: &Path) -> bool { + same_file(&project_save_path(output), input) +} + +/// If a batch script's `save` would replace `open`, it needs `--in-place`. An unreadable or +/// malformed script is left to the command, which reports that as a failure (exit 1). +fn batch_would_replace(a: &BatchArgs) -> Result<(), UsageError> { + let Ok(text) = std::fs::read_to_string(&a.script) else { + return Ok(()); + }; + let Ok(script) = serde_json::from_str::(&text) else { + return Ok(()); + }; + let field = |name: &str| script.get(name).and_then(Value::as_str); + let Some(output) = field("save") else { + return Ok(()); + }; + let input = field("open").unwrap_or("builtin:material_ball"); + if input.starts_with("builtin:") { + return if a.in_place { Err(UsageError::InPlaceNotUsed) } else { Ok(()) }; + } + let input = Path::new(input); + let output = Path::new(output); + match (same_project(output, input), a.in_place) { + (true, false) => Err(UsageError::WouldReplace { output: "save", input: "open", path: project_save_path(output), in_place_helps: true }), + (false, true) => Err(UsageError::InPlaceNotUsed), + _ => Ok(()), + } +} + +impl Command { + /// What clap can't check: the files a command would replace, and flags for another mode. + fn check(&self) -> Result<(), (&'static str, UsageError)> { + match self { + Command::Run(a) => match (&a.output, a.in_place) { + (Some(out), false) => would_replace_project("-o", "INPUT", out, &a.input, true).map_err(|e| ("run", e)), + (Some(out), true) if !same_project(out, &a.input) => Err(("run", UsageError::InPlaceNotUsed)), + _ => Ok(()), + }, + Command::Bake(a) => match (&a.output, a.in_place) { + (None, false) if is_project(&a.input) => Err(("bake", UsageError::BakeInPlace { path: a.input.clone() })), + (None, _) if !is_project(&a.input) => Err(("bake", UsageError::BakeNeedsOutput)), + (Some(out), false) => would_replace_project("-o", "INPUT", out, &a.input, true).map_err(|e| ("bake", e)), + (Some(out), true) if !same_project(out, &a.input) => Err(("bake", UsageError::InPlaceNotUsed)), + _ => Ok(()), + }, + Command::Render(a) => would_replace("OUT.PNG", "INPUT", &a.output, &a.input, false).map_err(|e| ("render", e)), + Command::New(a) => would_replace_project("OUT.TCRAFT", "INPUT", &a.output, &a.input, false).map_err(|e| ("new", e)), + Command::Batch(a) => batch_would_replace(a).map_err(|e| ("batch", e)), + Command::Mcp(a) if a.bridge.is_some() => match (&a.roots.read_root, &a.roots.write_root) { + (Some(_), _) => Err(("mcp", UsageError::RootsWithBridge { flag: "--read-root" })), + (_, Some(_)) => Err(("mcp", UsageError::RootsWithBridge { flag: "--write-root" })), + _ => Ok(()), + }, + Command::Mcp(a) if a.bridge.is_none() => match (&a.roots.read_root, &a.roots.write_root) { + (Some(_), Some(_)) => Ok(()), + _ => Err(("mcp", UsageError::McpNeedsRoots)), + }, + _ => Ok(()), + } + } +} + +/// Parses the arguments (without the program name). Help and the version come back as errors too, +/// which print to stdout and exit 0. +pub(crate) fn parse(args: &[OsString]) -> Result { + let matches = crate::command().try_get_matches_from(std::iter::once(OsString::from("texturecraft-cli")).chain(args.iter().cloned()))?; + let cli = Cli::from_arg_matches(&matches)?; + // An inherited TEXTURECRAFT_CONTROL_TOKEN must not force --bridge: the variable is how a + // client authenticates when --bridge is already set. Only an explicit --token flag requires it. + let token_flag_without_bridge = matches + .subcommand_matches("mcp") + .is_some_and(|mcp| mcp.value_source("token") == Some(clap::parser::ValueSource::CommandLine) && mcp.get_one::("bridge").is_none()); + if token_flag_without_bridge { + return Err(UsageError::TokenNeedsBridge.into_clap("mcp")); + } + cli.command.check().map_err(|(sub, e)| e.into_clap(sub))?; + Ok(cli) +} diff --git a/apps/texturecraft-cli/src/error.rs b/apps/texturecraft-cli/src/error.rs new file mode 100644 index 00000000..30687f1c --- /dev/null +++ b/apps/texturecraft-cli/src/error.rs @@ -0,0 +1,36 @@ +use std::path::{Path, PathBuf}; + +use texturecraft_automation::AutomationError; + +/// Why a subcommand failed: printed as `error: {e}`, exit 1. +#[derive(Debug, thiserror::Error)] +pub(crate) enum CliError { + #[error(transparent)] + Automation(#[from] AutomationError), + /// The engine's commands take paths as JSON text, which holds only Unicode. + #[error("{}: the path is not valid Unicode", .0.display())] + NotUnicode(PathBuf), + #[error("unknown built-in mesh `{0}`")] + UnknownBuiltin(String), + #[error("cannot read {}: {message}", path.display())] + Read { path: PathBuf, message: String }, + #[error("cannot write {}: {source}", path.display())] + Write { path: PathBuf, source: std::io::Error }, + #[error("{} is not JSON: {source}", path.display())] + Script { path: PathBuf, source: serde_json::Error }, + #[error("the script must be a list of steps or {{\"steps\": [...]}}")] + ScriptShape, + #[error("the script's `{0}` field must be a string")] + ScriptField(&'static str), + #[error("step {index} (`{id}`) failed: {message}")] + BatchStopped { index: String, id: String, message: String }, + #[error("{} is already a project", .0.display())] + AlreadyProject(PathBuf), + #[error("{0}")] + Serve(std::io::Error), +} + +/// A path as the text the engine's commands take. +pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> { + path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned())) +} diff --git a/apps/texturecraft-cli/src/lib.rs b/apps/texturecraft-cli/src/lib.rs new file mode 100644 index 00000000..872765af --- /dev/null +++ b/apps/texturecraft-cli/src/lib.rs @@ -0,0 +1,342 @@ +//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and +//! serve agents over MCP or JSON lines. Never opens a window. `run` is the whole program, so it can +//! be tested in-process as well as through the binary; `texturecraft-cli --help` lists the +//! subcommands. The conventions are RFC-0018's: exit 0, 1 (a command failed) or 2 (a usage error), +//! results on stdout, `error: ` on stderr. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod args; +mod error; + +use std::ffi::OsString; +use std::io::Write; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use clap::CommandFactory; +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::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report}; + +use args::{ + BakeArgs, BatchArgs, Cli, Command, CommandsArgs, ExportArgs, InfoArgs, McpArgs, NewArgs, RenderArgs, RootArgs, RunArgs, ServeArgs, is_project, parse, +}; +use error::{CliError, unicode}; + +/// Writes a line. A closed pipe (`texturecraft-cli info x | head`) is not worth an error: the rest +/// of the output is dropped. +macro_rules! outln { + ($to:expr, $($arg:tt)*) => { + drop(writeln!($to, $($arg)*)) + }; +} + +/// The version `--version` prints after the program's name: ` ( )`. +fn version() -> String { + let sha = env!("TEXTURECRAFT_BUILD_SHA"); + let short = sha.get(..7).unwrap_or(sha); + let date = env!("TEXTURECRAFT_BUILD_DATE"); + match (short.is_empty(), date.is_empty()) { + (true, true) => texturecraft_engine::VERSION.to_string(), + (true, false) => format!("{} ({date})", texturecraft_engine::VERSION), + _ => format!("{} ({short} {date})", texturecraft_engine::VERSION), + } +} + +/// The command line's clap definition. +pub fn command() -> clap::Command { + Cli::command().version(version()) +} + +/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the +/// GUI only, and a script that passes them to the CLI has the wrong program. +fn launch_profile_argument(args: &[OsString]) -> Option { + args.iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .find(|arg| ["--launch-profile", "--profile-root"].iter().any(|flag| arg == flag || arg.starts_with(&format!("{flag}=")))) +} + +/// Run the CLI on its arguments (without the program name), writing results to `out` and +/// diagnostics to `err`. Returns the process exit code: 0 on success, 1 on failure, 2 for a usage +/// error. Help and the version go to `out`, exit 0. `mcp` and `serve` speak on the process's own +/// stdin and stdout. +pub fn run(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32 +where + I: IntoIterator, + T: Into, +{ + let args: Vec = args.into_iter().map(Into::into).collect(); + if let Some(flag) = launch_profile_argument(&args) { + outln!(err, "error: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); + return 2; + } + // Help and the version (`help`, `-h`, ` --help`, `-V`) come back as errors too. + let cli = match parse(&args) { + Ok(cli) => cli, + Err(e) => { + let to: &mut dyn Write = if e.use_stderr() { err } else { out }; + let _ = write!(to, "{}", e.render()); + return e.exit_code(); + } + }; + match dispatch(cli.command, out, err) { + Ok(()) => 0, + Err(e) => { + outln!(err, "error: {e}"); + 1 + } + } +} + +fn dispatch(command: Command, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + match command { + Command::Info(a) => info(&a, out), + Command::Commands(a) => commands(&a, out), + Command::Run(a) => run_command(&a, out, err), + Command::Batch(a) => batch(&a, out, err), + Command::Bake(a) => bake(&a, out, err), + Command::Export(a) => export(&a, out, err), + Command::Render(a) => render(&a, err), + Command::New(a) => new(&a, err), + Command::Mcp(a) => mcp(&a), + Command::Serve(a) => serve(&a, err), + } +} + +fn print(out: &mut dyn Write, v: &Value) { + outln!(out, "{}", serde_json::to_string_pretty(v).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}"))); +} + +/// A trusted local session on `input`: a project, a mesh file or `builtin:`. +fn open(input: &Path, resolution: Option) -> Result { + let mut h = Headless::new(Headless::default_session()?, Filesystem::TrustedLocal); + match input.to_str().and_then(|text| text.strip_prefix("builtin:")) { + Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ())?, + None if is_project(input) => h.open(unicode(input)?).map(|_| ())?, + None => h.import_mesh(unicode(input)?, resolution, None).map(|_| ())?, + } + Ok(h) +} + +fn save(h: &mut Headless, out: &Path, err: &mut dyn Write) -> Result<(), CliError> { + let r = h.save(Some(unicode(out)?))?; + outln!(err, "saved {}", r["path"].as_str().unwrap_or_default()); + Ok(()) +} + +fn report_json(r: &MeshReport) -> Value { + json!({ + "triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated, + "uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings, + }) +} + +fn info(a: &InfoArgs, out: &mut dyn Write) -> Result<(), CliError> { + let file = unicode(&a.input)?; + if let Some(id) = file.strip_prefix("builtin:") { + let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| CliError::UnknownBuiltin(id.to_string()))?; + let report = mesh_report(&m); + print( + out, + &json!({ + "file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(), + "materials": m.materials, "textureSets": m.materials, "uv": report_json(&report), + }), + ); + return Ok(()); + } + if !is_project(&a.input) { + let m = import_mesh(&a.input).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?; + print( + out, + &json!({ + "file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(), + "materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report), + }), + ); + return Ok(()); + } + let h = open(&a.input, None)?; + let mut v = h.inspect(); + v["file"] = json!(file); + v["kind"] = json!("project"); + // The embedded mesh is re-imported for its UV report (built-in meshes have none). + v["uv"] = match &h.session.mesh_source { + Some((ext, bytes)) => { + let m = import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?; + report_json(&m.report) + } + None => Value::Null, + }; + print(out, &v); + Ok(()) +} + +fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result<(), CliError> { + let h = open(Path::new("builtin:cube"), Some(128))?; + let list = h.command_list(a.filter.as_deref()); + if a.json { + print(out, &list); + return Ok(()); + } + for c in list.as_array().into_iter().flatten() { + let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + outln!(out, "{:<28} {:<36} {}", f("id"), f("label"), f("params")); + } + Ok(()) +} + +fn run_command(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let mut h = open(&a.input, None)?; + print(out, &h.command_run(&a.id, a.params.clone().unwrap_or_else(|| json!({})))?); + match &a.output { + Some(path) => save(&mut h, path, err), + None => Ok(()), + } +} + +fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let text = std::fs::read_to_string(&a.script).map_err(|e| CliError::Read { path: a.script.clone(), message: e.to_string() })?; + let script: Value = serde_json::from_str(&text).map_err(|source| CliError::Script { path: a.script.clone(), source })?; + let steps = script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or(CliError::ScriptShape)?; + let path_field = |field: &'static str| -> Result, CliError> { + match script.get(field) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(path)) => Ok(Some(path.as_str())), + Some(_) => Err(CliError::ScriptField(field)), + } + }; + let input = path_field("open")?.unwrap_or("builtin:material_ball"); + let output = path_field("save")?; + + let mut h = open(Path::new(input), None)?; + let reply = h.batch(steps); + print(out, &reply); + if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) { + return Err(CliError::BatchStopped { + index: failure["index"].to_string(), + id: failure["id"].as_str().unwrap_or_default().to_string(), + message: failure["error"].as_str().unwrap_or_default().to_string(), + }); + } + match output { + Some(path) => save(&mut h, Path::new(path), err), + None => Ok(()), + } +} + +fn bake(a: &BakeArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + // `check` has seen to it: a project without -o is saved in place (--in-place), a mesh has -o. + let target = a.output.as_deref().unwrap_or(&a.input); + let mut p = json!({"ts": "all"}); + if let Some(r) = a.resolution { + p["resolution"] = json!(r); + } + if !a.maps.is_empty() { + p["maps"] = json!(a.maps.iter().map(|m| m.trim()).filter(|m| !m.is_empty()).collect::>()); + } + let mut h = open(&a.input, None)?; + h.command_run("bake.run", p)?; + save(&mut h, target, err)?; + print(out, &h.inspect()["textureSets"]); + Ok(()) +} + +fn export(a: &ExportArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let mut p = json!({"dir": unicode(&a.dir)?}); + for (key, value) in [("preset", &a.preset), ("format", &a.format), ("padding", &a.padding)] { + if let Some(v) = value { + p[key] = json!(v); + } + } + if let Some(v) = a.size { + p["size"] = json!(v); + } + let mut h = open(&a.input, None)?; + let r = h.export(&p)?; + for w in r["warnings"].as_array().into_iter().flatten() { + outln!(err, "warning: {}", w.as_str().unwrap_or_default()); + } + for f in r["files"].as_array().into_iter().flatten() { + outln!(out, "{}", f.as_str().unwrap_or_default()); + } + Ok(()) +} + +fn render(a: &RenderArgs, err: &mut dyn Write) -> Result<(), CliError> { + let options = RenderOptions { + view: a.view.clone(), + width: a.size.map(|s| s.width), + height: a.size.map(|s| s.height), + yaw: a.yaw, + pitch: a.pitch, + samples: a.samples, + bounces: a.bounces, + cpu: a.cpu, + }; + let mut h = open(&a.input, None)?; + if let Some(name) = &a.camera { + h.command_run("camera.select", json!({ "name": name }))?; + } + let t0 = std::time::Instant::now(); + let r = h.render_png(&options)?; + let secs = t0.elapsed().as_secs_f64(); + std::fs::write(&a.output, &r.png).map_err(|source| CliError::Write { path: a.output.clone(), source })?; + outln!(err, "wrote {} ({}x{}, {}, {secs:.2} s)", a.output.display(), r.width, r.height, r.by); + Ok(()) +} + +fn new(a: &NewArgs, err: &mut dyn Write) -> Result<(), CliError> { + if is_project(&a.input) { + return Err(CliError::AlreadyProject(a.input.clone())); + } + let mut h = open(&a.input, a.resolution)?; + if a.sample { + let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024)); + h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res}))?; + for ts in 0..h.session.set_count() { + h.command_run("textureSet.select", json!({"ts": ts}))?; + h.command_run("material.apply", json!({"material": "steel_painted_worn"}))?; + } + h.command_run("textureSet.select", json!({"ts": 0}))?; + } + save(&mut h, &a.output, err) +} + +/// File access for servers: none without roots, else only below them +fn workspace(roots: &RootArgs) -> Result { + if roots.read_root.is_none() && roots.write_root.is_none() { + return Ok(Filesystem::Denied); + } + Ok(Filesystem::Workspace(AuthorizedWorkspace::new(roots.read_root.as_deref(), roots.write_root.as_deref())?)) +} + +fn mcp(a: &McpArgs) -> Result<(), CliError> { + let server = match a.bridge { + Some(port) => TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.token.clone())?)), + None => TexturecraftMcp::headless(Headless::new(Headless::default_session()?, workspace(&a.roots)?)), + }; + let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(CliError::Serve)?; + rt.block_on(server.serve_stdio()).map_err(|e| CliError::Automation(texturecraft_automation::AutomationError::Other(e.to_string()))) +} + +fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result<(), CliError> { + let h = Arc::new(Mutex::new(Headless::new(Headless::default_session()?, workspace(&a.roots)?))); + match a.port { + None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(CliError::Serve)?, + Some(port) => { + // Bind first: a port in use must not replace its server's token file. + let listener = rpc::bind_tcp(port)?; + let addr = listener.local_addr().map_err(CliError::Serve)?; + let (token, file) = server_token(addr.port())?; + match file { + Some(f) => outln!(err, "texturecraft-cli: serving on {addr}; token in {}", f.display()), + None => outln!(err, "texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"), + } + rpc::serve_listener(listener, h, token)?; + } + } + Ok(()) +} diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index 80069d9d..357cf17e 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -1,452 +1,8 @@ -//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and -//! serve agents over MCP or JSON lines. Never opens a window. +//! Headless TextureCraft command line. Never opens a window. See the library crate for the commands. #![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -use std::path::Path; -use std::sync::{Arc, Mutex}; - -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, mesh_report}; - -const USAGE: &str = "\ -texturecraft-cli: headless TextureCraft - -USAGE: - texturecraft-cli --version - 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). - texturecraft-cli run [params-json] [-o ] - Run one command and print its JSON result; -o saves the project. - texturecraft-cli batch - Run [{\"id\", \"params\"}, ...] or {\"open\": , \"steps\": [...], \"save\": }. - texturecraft-cli bake [-o ] [--resolution ] [--maps ] - Bake mesh maps for every texture set (a project is saved in place without -o). - texturecraft-cli export [--preset ] [--format ] [--padding ] [--size ] - Export textures (default preset: Document channels + Normal + AO (No Alpha)). - texturecraft-cli render [--size x] [--view 3d|2d] [--camera ] [--yaw ] - [--pitch ] [--samples ] [--bounces ] [--cpu] - Render the viewport to PNG (needs a GPU or software adapter); --camera looks through a - camera saved in the project (camera.add); --samples path traces it instead (Rendering - mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU. - texturecraft-cli new > [--resolution ] [--sample] - New project; --sample bakes and applies a smart material to every texture set. The - sample's mesh maps are baked at the resolution up to 1024 px (most of the file's size), - so a 2048 sample project is as large as a 1024 one. - texturecraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] - MCP server on stdio: headless (file access only below the roots), or bridged to - `texturecraft --control `. --automation-read-root / --automation-write-root are - the same as --read-root / --write-root (mcp and serve). - texturecraft-cli serve [--port ] [--read-root ] [--write-root ] - JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token. - - is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .usd .usda .usdc .usdz .abc .obj .ply .stl) -or builtin: (material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate, udim_plane). -See docs/control-protocol.md. -"; - -/// (name, flags taking a value, bare flags) -const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ - ("info", &[], &[]), - ("commands", &["--filter"], &[]), - ("run", &["-o"], &[]), - ("batch", &[], &[]), - ("bake", &["-o", "--resolution", "--maps"], &[]), - ("export", &["--preset", "--format", "--padding", "--size"], &[]), - ("render", &["--size", "--view", "--camera", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]), - ("new", &["--resolution"], &["--sample"]), - ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), - ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), -]; - -struct Args { - pos: Vec, - flags: Vec<(String, Option)>, -} - -impl Args { - fn get(&self, k: &str) -> Option<&str> { - self.flags.iter().rev().find(|(f, _)| f == k).and_then(|(_, v)| v.as_deref()) - } - fn has(&self, k: &str) -> bool { - self.flags.iter().any(|(f, _)| f == k) - } - fn num(&self, k: &str) -> Result, String> { - self.get(k).map(|v| v.parse().map_err(|_| format!("{k}: `{v}` is not a valid number"))).transpose() - } - fn pos(&self, n: usize, what: &str) -> Result<&str, String> { - self.pos.get(n).map(String::as_str).ok_or_else(|| format!("missing {what}")) - } -} - -fn parse(values: &[&str], bare: &[&str], args: &[String]) -> Result { - let mut a = Args { pos: Vec::new(), flags: Vec::new() }; - let mut it = args.iter(); - while let Some(s) = it.next() { - let (k, inline) = match s.split_once('=') { - Some((k, v)) if k.starts_with("--") => (k, Some(v.to_string())), - _ => (s.as_str(), None), - }; - if values.contains(&k) { - let v = match inline { - Some(v) => v, - None => it.next().ok_or_else(|| format!("{k} needs a value"))?.clone(), - }; - a.flags.push((k.to_string(), Some(v))); - } else if bare.contains(&k) && inline.is_none() { - a.flags.push((k.to_string(), None)); - } else if k.starts_with('-') && k.len() > 1 && k.parse::().is_err() { - return Err(format!("unknown option `{s}`")); - } else { - a.pos.push(s.clone()); - } - } - Ok(a) -} - -fn version() -> String { - let sha = env!("TEXTURECRAFT_BUILD_SHA"); - let short = sha.get(..7).unwrap_or(sha); - let date = env!("TEXTURECRAFT_BUILD_DATE"); - match (short.is_empty(), date.is_empty()) { - (true, true) => format!("TextureCraft {}", texturecraft_engine::VERSION), - (true, false) => format!("TextureCraft {} ({date})", texturecraft_engine::VERSION), - _ => format!("TextureCraft {} ({short} {date})", texturecraft_engine::VERSION), - } -} - -/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the -/// GUI only, and a script that passes them to the CLI has the wrong program. -fn is_launch_profile_flag(arg: &str) -> bool { - arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") -} fn main() { - let args: Vec = std::env::args().skip(1).collect(); - if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) { - eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); - std::process::exit(2); - } - let code = match args.first().map(String::as_str) { - None => { - eprint!("{USAGE}"); - 2 - } - Some("--version" | "-V" | "version") => { - println!("{}", version()); - 0 - } - Some("--help" | "-h" | "help") => { - print!("{USAGE}"); - 0 - } - Some(cmd) => match SUBCOMMANDS.iter().find(|(n, _, _)| *n == cmd) { - None => { - eprintln!("texturecraft-cli: unknown command `{cmd}`\n\n{USAGE}"); - 2 - } - Some(_) if args.iter().any(|a| a == "--help" || a == "-h") => { - print!("{USAGE}"); - 0 - } - Some((name, values, bare)) => match parse(values, bare, args.get(1..).unwrap_or_default()) { - Err(e) => { - eprintln!("texturecraft-cli {name}: {e}\n\n{USAGE}"); - 2 - } - Ok(a) => match dispatch(name, &a) { - Ok(()) => 0, - Err(e) => { - eprintln!("texturecraft-cli {name}: error: {e}"); - 1 - } - }, - }, - }, - }; + // `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed. + let code = texturecraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); std::process::exit(code); } - -type R = Result<(), String>; - -fn dispatch(name: &str, a: &Args) -> R { - match name { - "info" => info(a), - "commands" => commands(a), - "run" => run(a), - "batch" => batch(a), - "bake" => bake(a), - "export" => export(a), - "render" => render(a), - "new" => new(a), - "mcp" => mcp(a), - "serve" => serve(a), - other => Err(format!("unknown command `{other}`")), - } -} - -fn s(e: impl std::fmt::Display) -> String { - e.to_string() -} - -fn print_json(v: &Value) -> R { - println!("{}", serde_json::to_string_pretty(v).map_err(s)?); - Ok(()) -} - -fn is_project(path: &str) -> bool { - Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case(PROJECT_EXT)) -} - -/// A trusted local session on `input`: a project, a mesh file or `builtin:`. -fn open(input: &str, resolution: Option) -> Result { - let mut h = Headless::new(Headless::default_session().map_err(s)?, Filesystem::TrustedLocal); - match input.strip_prefix("builtin:") { - Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ()), - None if is_project(input) => h.open(input).map(|_| ()), - None => h.import_mesh(input, resolution, None).map(|_| ()), - } - .map_err(s)?; - Ok(h) -} - -fn save(h: &mut Headless, out: &str) -> R { - let r = h.save(Some(out)).map_err(s)?; - eprintln!("saved {}", r["path"].as_str().unwrap_or_default()); - Ok(()) -} - -fn report_json(r: &MeshReport) -> Value { - json!({ - "triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated, - "uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings, - }) -} - -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!({ - "file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(), - "materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report), - })); - } - let h = open(file, None)?; - let mut v = h.inspect(); - v["file"] = json!(file); - v["kind"] = json!("project"); - // The embedded mesh is re-imported for its UV report (built-in meshes have none). - v["uv"] = match &h.session.mesh_source { - Some((ext, bytes)) => import_mesh_bytes(&format!("mesh.{ext}"), bytes).map(|m| report_json(&m.report)).map_err(s)?, - None => Value::Null, - }; - print_json(&v) -} - -fn commands(a: &Args) -> R { - let h = open("builtin:cube", Some(128))?; - for c in h.command_list(a.get("--filter")).as_array().into_iter().flatten() { - let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); - println!("{:<28} {:<36} {}", f("id"), f("label"), f("params")); - } - Ok(()) -} - -fn run(a: &Args) -> R { - let (input, id) = (a.pos(0, "")?, a.pos(1, "")?); - let params: Value = match a.pos.get(2) { - Some(j) => serde_json::from_str(j).map_err(|e| format!("params are not JSON: {e}"))?, - None => json!({}), - }; - let mut h = open(input, None)?; - print_json(&h.command_run(id, params).map_err(s)?)?; - match a.get("-o") { - Some(out) => save(&mut h, out), - None => Ok(()), - } -} - -fn batch(args: &Args) -> R { - let path = args.pos(0, "")?; - let script: Value = { - let script_text = std::fs::read_to_string(path).map_err(|err| format!("cannot read {path}: {err}"))?; - serde_json::from_str(&script_text).map_err(|err| format!("{path} is not JSON: {err}"))? - }; - - let steps = - script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or("the script must be a list of steps or {\"steps\": [...]}")?; - let path_field = |field: &str| -> Result, String> { - match script.get(field) { - None | Some(Value::Null) => Ok(None), - Some(Value::String(path)) => Ok(Some(path.as_str())), - Some(_) => Err(format!("the script's `{field}` field must be a string")), - } - }; - let input = path_field("open")?.unwrap_or("builtin:material_ball"); - let output = path_field("save")?; - - let mut headless = open(input, None)?; - let reply = headless.batch(steps); - print_json(&reply)?; - if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) { - return Err(format!( - "step {} (`{}`) failed: {}", - failure["index"], - failure["id"].as_str().unwrap_or_default(), - failure["error"].as_str().unwrap_or_default() - )); - } - - match output { - Some(output_path) => save(&mut headless, output_path), - None => Ok(()), - } -} - -fn bake(a: &Args) -> R { - let input = a.pos(0, "")?; - let out = a.get("-o").or(is_project(input).then_some(input)).ok_or("give -o to save the baked project")?; - let mut p = json!({"ts": "all"}); - if let Some(r) = a.num::("--resolution")? { - p["resolution"] = json!(r); - } - if let Some(m) = a.get("--maps") { - p["maps"] = json!(m.split(',').map(str::trim).filter(|m| !m.is_empty()).collect::>()); - } - let mut h = open(input, None)?; - h.command_run("bake.run", p).map_err(s)?; - save(&mut h, out)?; - print_json(&h.inspect()["textureSets"]) -} - -fn export(a: &Args) -> R { - let (input, dir) = (a.pos(0, "")?, a.pos(1, "")?); - let mut p = json!({"dir": dir}); - for k in ["preset", "format", "padding"] { - if let Some(v) = a.get(&format!("--{k}")) { - p[k] = json!(v); - } - } - if let Some(v) = a.num::("--size")? { - p["size"] = json!(v); - } - let mut h = open(input, None)?; - let r = h.export(&p).map_err(s)?; - for w in r["warnings"].as_array().into_iter().flatten() { - eprintln!("warning: {}", w.as_str().unwrap_or_default()); - } - for f in r["files"].as_array().into_iter().flatten() { - println!("{}", f.as_str().unwrap_or_default()); - } - Ok(()) -} - -fn render(a: &Args) -> R { - let (input, out) = (a.pos(0, "")?, a.pos(1, "")?); - let (width, height) = match a.get("--size") { - Some(sz) => { - let (w, h) = sz.split_once(['x', 'X']).ok_or("--size must be x, e.g. 1280x800")?; - (Some(w.parse().map_err(|_| "bad --size width")?), Some(h.parse().map_err(|_| "bad --size height")?)) - } - None => (None, None), - }; - let o = RenderOptions { - view: a.get("--view").map(str::to_string), - width, - height, - yaw: a.num("--yaw")?, - pitch: a.num("--pitch")?, - samples: a.num("--samples")?, - bounces: a.num("--bounces")?, - cpu: a.has("--cpu"), - }; - let mut h = open(input, None)?; - if let Some(name) = a.get("--camera") { - h.command_run("camera.select", json!({ "name": name })).map_err(s)?; - } - let t0 = std::time::Instant::now(); - let r = h.render_png(&o).map_err(s)?; - let secs = t0.elapsed().as_secs_f64(); - std::fs::write(out, &r.png).map_err(|e| format!("cannot write {out}: {e}"))?; - eprintln!("wrote {out} ({}x{}, {}, {secs:.2} s)", r.width, r.height, r.by); - Ok(()) -} - -fn new(a: &Args) -> R { - let (input, out) = (a.pos(0, "")?, a.pos(1, "")?); - if is_project(input) { - return Err(format!("{input} is already a project")); - } - let res = a.num::("--resolution")?; - let mut h = open(input, res)?; - if a.has("--sample") { - let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024)); - h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res})).map_err(s)?; - for ts in 0..h.session.set_count() { - h.command_run("textureSet.select", json!({"ts": ts})).map_err(s)?; - h.command_run("material.apply", json!({"material": "steel_painted_worn"})).map_err(s)?; - } - h.command_run("textureSet.select", json!({"ts": 0})).map_err(s)?; - } - save(&mut h, out) -} - -fn workspace(a: &Args) -> Result { - // `--automation-*-root` is the spelling the other crafting apps use. - let root = |k: &str| a.get(&format!("--automation-{k}")).or_else(|| a.get(&format!("--{k}"))).map(Path::new); - let (r, w) = (root("read-root"), root("write-root")); - if r.is_none() && w.is_none() { - return Ok(Filesystem::Denied); - } - Ok(Filesystem::Workspace(AuthorizedWorkspace::new(r, w).map_err(s)?)) -} - -fn port_of(v: &str) -> Result { - let p = v.strip_prefix("127.0.0.1:").or_else(|| v.strip_prefix("localhost:")).unwrap_or(v); - p.parse::().ok().filter(|p| *p != 0).ok_or_else(|| format!("`{v}` is not a loopback port (1-65535)")) -} - -fn mcp(a: &Args) -> R { - let server = match a.get("--bridge") { - Some(b) => { - let port = port_of(b)?; - TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.get("--token").map(str::to_string)).map_err(s)?)) - } - None => TexturecraftMcp::headless(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?)), - }; - let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(s)?; - rt.block_on(server.serve_stdio()).map_err(s) -} - -fn serve(a: &Args) -> R { - let h = Arc::new(Mutex::new(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?))); - match a.get("--port") { - None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(s), - Some(p) => { - // Bind first: a port in use must not replace its server's token file, and port 0's - // token file is named after the port actually picked. - let listener = rpc::bind_tcp(port_of(p)?).map_err(s)?; - let addr = listener.local_addr().map_err(s)?; - let (token, file) = server_token(addr.port()).map_err(s)?; - match file { - Some(f) => eprintln!("texturecraft-cli: serving on {addr}; token in {}", f.display()), - None => eprintln!("texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"), - } - rpc::serve_listener(listener, h, token).map_err(s) - } - } -} diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 6bef0017..a5089e96 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -44,9 +44,9 @@ fn p(path: &Path) -> &str { #[test] fn version_and_usage_errors() { let v = ok(&["--version"]); - assert!(v.starts_with("TextureCraft "), "{v}"); + assert!(v.starts_with("texturecraft-cli "), "{v}"); assert_eq!(v.lines().count(), 1); - assert!(ok(&["--help"]).contains("texturecraft-cli mcp")); + assert!(ok(&["--help"]).contains("Usage: texturecraft-cli ")); assert_eq!(cli(&[]).status.code(), Some(2)); assert_eq!(cli(&["frobnicate"]).status.code(), Some(2)); assert_eq!(cli(&["info", "--bogus"]).status.code(), Some(2)); @@ -54,8 +54,8 @@ fn version_and_usage_errors() { assert_eq!(o.status.code(), Some(1)); assert!(String::from_utf8_lossy(&o.stderr).contains("error")); assert_eq!(cli(&["run", "builtin:nope", "layer.add.fill"]).status.code(), Some(1)); - assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(1)); - assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(1)); + assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(2)); + assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(2)); } #[test] @@ -73,7 +73,7 @@ fn new_info_run_bake_export_batch() { assert!(r["layer"].is_u64(), "{r}"); assert_eq!(json(&["info", p(&b)])["layers"][0]["kind"], "fill"); - ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature"]); + ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature", "--in-place"]); let maps = json(&["info", p(&b)])["textureSets"][0]["baked"]["maps"].clone(); assert_eq!(maps.as_array().unwrap().len(), 2, "{maps}"); @@ -202,10 +202,10 @@ fn path_traced_render_needs_no_gpu() { // --camera looks through a camera saved in the project; an unknown name is an error. let proj = d.join("cams.tcraft"); ok(&["run", "builtin:cube", "camera.set", r#"{"yaw": 80, "distance": 9}"#, "-o", p(&proj)]); - ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj)]); + ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj), "--in-place"]); ok(&["render", p(&proj), p(&out), "--size", "48x32", "--camera", "Side", "--samples", "2", "--cpu"]); assert_eq!(cli(&["render", p(&proj), p(&out), "--camera", "Nope", "--samples", "2", "--cpu"]).status.code(), Some(1)); - assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(1)); + assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(2)); assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "4", "--view", "2d"]).status.code(), Some(1)); let _ = std::fs::remove_dir_all(&d); } diff --git a/apps/texturecraft-cli/tests/it/cli.rs b/apps/texturecraft-cli/tests/it/cli.rs new file mode 100644 index 00000000..332da939 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/cli.rs @@ -0,0 +1,331 @@ +//! RFC-0018 rule 2.7: help, versions, usage errors with exit 2 on stderr, and nothing written +//! before the arguments are checked. + +use std::ffi::OsString; + +use crate::{argv, invoke, project, workdir}; + +const SUBCOMMANDS: [&str; 10] = ["info", "commands", "run", "batch", "bake", "export", "render", "new", "mcp", "serve"]; + +/// The shortest valid command line of each subcommand. +fn minimal(sub: &str) -> Vec<&str> { + match sub { + "info" => vec!["info", "builtin:cube"], + "run" => vec!["run", "builtin:cube", "layer.add.fill"], + "batch" => vec!["batch", "s.json"], + "bake" => vec!["bake", "builtin:cube", "-o", "o.tcraft"], + "export" => vec!["export", "builtin:cube", "dir"], + "render" => vec!["render", "builtin:cube", "o.png"], + "new" => vec!["new", "builtin:cube", "o.tcraft"], + other => vec![other], + } +} + +fn usage_error(args: &[&str]) -> String { + let got = invoke(args.iter().copied()); + assert_eq!(got.code, 2, "{args:?}: {}", got.err); + assert_eq!(got.out, "", "{args:?} wrote to stdout"); + assert!(got.err.starts_with("error: "), "{args:?}: {}", got.err); + got.err +} + +#[test] +fn help_and_the_version_go_to_stdout_with_exit_0() { + for args in [&["--help"][..], &["-h"], &["help"], &["--version"], &["-V"]] { + let got = invoke(args.iter().copied()); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{args:?}"); + assert!(got.out.contains("texturecraft-cli"), "{args:?}: {}", got.out); + } + let help = invoke(["--help"]).out; + assert!(help.contains("Exit status:") && help.contains("128 + the signal number"), "{help}"); + for sub in SUBCOMMANDS { + for flag in ["--help", "-h"] { + let got = invoke([sub, flag]); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{sub} {flag}"); + assert!(got.out.contains(&format!("Usage: texturecraft-cli {sub}")), "{sub}: {}", got.out); + } + assert_eq!(invoke(["help", sub]).out, invoke([sub, "--help"]).out, "{sub}"); + } +} + +#[test] +fn every_subcommand_takes_the_version_and_there_is_no_version_subcommand() { + let top = invoke(["--version"]).out; + let want = top.strip_prefix("texturecraft-cli ").unwrap().trim_end().to_string(); + assert!(want.starts_with(texturecraft_engine::VERSION), "{want}"); + for sub in SUBCOMMANDS { + for flag in ["--version", "-V"] { + let got = invoke([sub, flag]); + assert_eq!((got.code, got.out.as_str(), got.err.as_str()), (0, format!("texturecraft-cli-{sub} {want}\n").as_str(), ""), "{sub} {flag}"); + } + } + usage_error(&["version"]); +} + +#[test] +fn no_arguments_is_a_usage_error_that_prints_the_help_on_stderr() { + let got = invoke(Vec::::new()); + assert_eq!((got.code, got.out.as_str()), (2, "")); + assert!(got.err.contains("Usage: texturecraft-cli "), "{}", got.err); +} + +#[test] +fn an_unknown_flag_or_subcommand_is_refused_by_every_subcommand() { + for sub in SUBCOMMANDS { + let mut args = minimal(sub); + args.push("--fromat"); + let message = usage_error(&args); + assert!(message.contains("--fromat"), "{sub}: {message}"); + } + usage_error(&["rendre"]); + usage_error(&["--fromat"]); +} + +#[test] +fn a_flag_given_twice_is_refused() { + usage_error(&["new", "builtin:cube", "o.tcraft", "--resolution", "8", "--resolution", "9"]); + usage_error(&["bake", "builtin:cube", "-o", "a.tcraft", "-o", "b.tcraft"]); + usage_error(&["render", "builtin:cube", "o.png", "--samples", "2", "--cpu", "--cpu"]); + usage_error(&["mcp", "--read-root", "a", "--automation-read-root", "b"]); +} + +#[test] +fn bad_values_conflicts_and_missing_arguments_are_refused_before_any_file_is_written() { + let dir = workdir("refused"); + let out = dir.join("never"); + let o = out.to_str().unwrap(); + let project_file = dir.join("p.tcraft"); + let p = project_file.to_str().unwrap(); + for (args, expect) in [ + (vec!["new", "builtin:cube", o, "--resolution", "0"], "--resolution"), + (vec!["new", "builtin:cube", o, "--resolution", "big"], "--resolution"), + (vec!["bake", "builtin:cube", "-o", o, "--resolution", "-1"], "-1"), + (vec!["bake", "builtin:cube"], "give -o"), + (vec!["bake", p], "--in-place"), + (vec!["bake", "builtin:cube", "--in-place"], "-o"), + (vec!["export", "builtin:cube", o, "--size", "0"], "--size"), + (vec!["export", "builtin:cube"], "required"), + (vec!["run", "builtin:cube", "layer.add.fill", "{not json"], "not JSON"), + (vec!["run", "builtin:cube", "layer.add.fill", "{}", "--in-place"], "--output"), + (vec!["render", "builtin:cube", o, "--size", "big"], "x"), + (vec!["render", "builtin:cube", o, "--size", "0x5"], "x"), + (vec!["render", "builtin:cube", o, "--view", "4d"], "--view"), + (vec!["render", "builtin:cube", o, "--yaw", "NaN"], "--yaw"), + (vec!["render", "builtin:cube", o, "--samples", "0"], "--samples"), + (vec!["render", "builtin:cube", o, "--cpu"], "--samples"), + (vec!["render", "builtin:cube", o, "--bounces", "3"], "--samples"), + (vec!["mcp", "--token", "abcdefghijklmnop"], "--bridge"), + (vec!["mcp", "--bridge", "9878", "--read-root", o], "headless server"), + (vec!["mcp", "--bridge", "99999"], "--bridge"), + (vec!["mcp", "--bridge", "0"], "--bridge"), + (vec!["serve", "--port", "http"], "--port"), + ] { + let message = usage_error(&args); + assert!(message.contains(expect), "{args:?}: {message}"); + } + assert!(!out.exists()); + assert!(std::fs::read_dir(&dir).unwrap().next().is_none()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn loopback_ports_take_the_host_prefix_and_a_dashed_name_follows_a_double_dash() { + // `--bridge 127.0.0.1:PORT` and `localhost:PORT` are still ports: the failure is the missing token. + for bridge in ["127.0.0.1:9", "localhost:9"] { + let got = invoke(["mcp", "--bridge", bridge, "--token", "short"]); + assert_eq!(got.code, 1, "{bridge}: {}", got.err); + } + let got = invoke(["info", "--", "-odd.tcraft"]); + assert_eq!(got.code, 1); + assert!(got.err.contains("-odd.tcraft"), "{}", got.err); + usage_error(&["render", "builtin:cube", "o.png", "--camera", "--cpu"]); +} + +#[test] +fn info_and_commands_print_what_a_program_reads() { + let got = invoke(["info", "builtin:cube"]); + assert_eq!((got.code, got.err.as_str()), (0, "")); + assert_eq!(serde_json::from_str::(&got.out).unwrap()["kind"], "mesh"); + let table = invoke(["commands", "--filter", "layer.add"]); + assert_eq!((table.code, table.err.as_str()), (0, "")); + assert!(table.out.lines().all(|l| l.starts_with("layer.add") || l.trim().is_empty()) && !table.out.is_empty(), "{}", table.out); + let json = invoke(["commands", "--filter", "layer.add", "--json"]); + assert_eq!(json.code, 0); + let list: serde_json::Value = serde_json::from_str(&json.out).unwrap(); + assert!(list.as_array().is_some_and(|l| !l.is_empty()), "{}", json.out); + let got = invoke(["info", "builtin:bogus"]); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.starts_with("error: unknown built-in mesh `bogus`"), "{}", got.err); +} + +#[test] +fn new_run_bake_and_export_through_files() { + let dir = workdir("files"); + let a = project(&dir, "a.tcraft"); + let b = dir.join("b.tcraft"); + let got = invoke(argv(&[&"run", &a, &"layer.add.fill", &r#"{"color":[1,0,0]}"#, &"-o", &b])); + assert_eq!(got.code, 0, "{}", got.err); + assert!(got.err.starts_with("saved "), "{}", got.err); + assert!(b.is_file()); + let got = invoke(argv(&[&"bake", &b, &"--resolution", &"128", &"--maps", &"ambientOcclusion", &"--in-place"])); + assert_eq!(got.code, 0, "{}", got.err); + let textures = dir.join("tex"); + let got = invoke(argv(&[&"export", &b, &textures, &"--preset", &"glTF PBR Metal Roughness", &"--size", &"128"])); + assert_eq!(got.code, 0, "{}", got.err); + assert!(got.out.lines().count() >= 3, "{}", got.out); + let got = invoke(argv(&[&"new", &"builtin:cube", &a])); + assert_eq!(got.code, 0, "{}", got.err); + let got = invoke(argv(&[&"new", &a, &dir.join("again.tcraft")])); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.contains("is already a project"), "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn an_output_that_would_replace_an_input_is_refused_without_in_place() { + let dir = workdir("replace"); + let source = project(&dir, "a.tcraft"); + let a = source.to_str().unwrap(); + let before = std::fs::read(&source).unwrap(); + let again = dir.join(".").join("a.tcraft"); + let again = again.to_str().unwrap(); + for args in [ + vec!["run", a, "layer.add.fill", "{}", "-o", a], + vec!["run", a, "layer.add.fill", "{}", "-o", again], + vec!["bake", a, "-o", a], + vec!["bake", a], + vec!["render", a, again], + vec!["new", a, a], + ] { + let message = usage_error(&args); + assert!(message.contains("--in-place") || message.contains("would replace"), "{args:?}: {message}"); + } + assert_eq!(std::fs::read(&source).unwrap(), before, "a refused command changes nothing"); + // `--in-place` lets only a project be replaced, and only by itself. + let got = invoke(["run", a, "layer.add.fill", "{}", "-o", a, "--in-place"]); + assert_eq!(got.code, 0, "{}", got.err); + let got = invoke(["bake", a, "--in-place", "--resolution", "128", "--maps", "ambientOcclusion"]); + assert_eq!(got.code, 0, "{}", got.err); + let elsewhere = dir.join("b.tcraft"); + assert!(usage_error(&["run", a, "layer.add.fill", "{}", "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place")); + assert!(usage_error(&["bake", a, "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place")); + assert!(!elsewhere.exists()); + // Headless::save appends .tcraft, so `-o scene` would replace scene.tcraft. + let unsuffixed = dir.join("a"); + let unsuffixed = unsuffixed.to_str().unwrap(); + let after_in_place = std::fs::read(&source).unwrap(); + let message = usage_error(&["run", a, "layer.add.fill", "{}", "-o", unsuffixed]); + assert!(message.contains("would replace") || message.contains("--in-place"), "{message}"); + assert_eq!(std::fs::read(&source).unwrap(), after_in_place, "an unsuffixed -o changes nothing"); + let got = invoke(["run", a, "layer.add.fill", "{}", "-o", unsuffixed, "--in-place"]); + assert_eq!(got.code, 0, "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn batch_runs_a_script_and_a_failing_step_fails_the_command() { + let dir = workdir("batch"); + let good = dir.join("good.json"); + std::fs::write(&good, r#"[{"id": "layer.add.paint", "params": {"name": "Scripted"}}]"#).unwrap(); + let got = invoke(argv(&[&"batch", &good])); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{}", got.out); + let bad = dir.join("bad.json"); + std::fs::write(&bad, r#"[{"id": "layer.add.paint"}, {"id": "no.such.command"}]"#).unwrap(); + let got = invoke(argv(&[&"batch", &bad])); + assert_eq!(got.code, 1); + assert!(got.err.starts_with("error: step 1 (`no.such.command`) failed: "), "{}", got.err); + for (body, expect) in [("[", "is not JSON"), ("{}", "list of steps"), (r#"{"steps": [], "open": false}"#, "`open` field must be a string")] { + let script = dir.join("odd.json"); + std::fs::write(&script, body).unwrap(); + let got = invoke(argv(&[&"batch", &script])); + assert_eq!(got.code, 1, "{body}"); + assert!(got.err.contains(expect), "{body}: {}", got.err); + } + let got = invoke(argv(&[&"batch", &dir.join("missing.json")])); + assert_eq!(got.code, 1); + assert!(got.err.contains("missing.json"), "{}", got.err); + // A script that saves over the project it opened needs --in-place, and must not have run. + let opened = project(&dir, "opened.tcraft"); + let before = std::fs::read(&opened).unwrap(); + let overwrite = dir.join("overwrite.json"); + std::fs::write( + &overwrite, + serde_json::json!({ + "open": opened, + "save": opened, + "steps": [{"id": "layer.add.paint", "params": {"name": "Batch"}}] + }) + .to_string(), + ) + .unwrap(); + let message = usage_error(&["batch", overwrite.to_str().unwrap()]); + assert!(message.contains("--in-place") || message.contains("would replace"), "{message}"); + assert_eq!(std::fs::read(&opened).unwrap(), before); + let got = invoke(argv(&[&"batch", &overwrite, &"--in-place"])); + assert_eq!(got.code, 0, "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_failed_command_exits_1_with_the_message_on_stderr() { + let got = invoke(["run", "builtin:cube", "no.such.command"]); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.starts_with("error: "), "{}", got.err); + let got = invoke(["info", "missing.tcraft"]); + assert_eq!(got.code, 1); + assert!(got.err.starts_with("error: ") && got.err.contains("missing.tcraft"), "{}", got.err); +} + +#[test] +fn the_desktop_launch_options_are_refused_before_any_subcommand() { + for args in + [vec!["--launch-profile", "nightly-v1", "--version"], vec!["--profile-root=/tmp/p", "--version"], vec!["info", "builtin:cube", "--launch-profile=x"]] + { + let message = usage_error(&args); + assert!(message.contains("desktop launch option"), "{args:?}: {message}"); + } +} + +#[cfg(unix)] +#[test] +fn a_path_that_is_not_valid_unicode_is_named_in_the_error() { + use std::os::unix::ffi::OsStringExt; + let dir = workdir("non-unicode"); + // The engine's commands take their paths as JSON text: the command says so and names the file. + let input = dir.join(OsString::from_vec(b"in-\xff.tcraft".to_vec())); + let got = invoke(argv(&[&"info", &input])); + assert_eq!(got.code, 1); + assert!(got.err.contains("the path is not valid Unicode") && got.err.contains("in-"), "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_closed_stdout_is_not_an_error() { + struct Closed; + impl std::io::Write for Closed { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut err = Vec::new(); + assert_eq!(texturecraft_cli::run(["commands"], &mut Closed, &mut err), 0); + assert_eq!(texturecraft_cli::run(["--help"], &mut Closed, &mut err), 0); + assert!(err.is_empty()); +} + +#[test] +fn headless_mcp_requires_both_roots() { + for args in [ + vec!["mcp"], + vec!["mcp", "--read-root", "."], + vec!["mcp", "--write-root", "."], + vec!["mcp", "--automation-read-root", "."], + vec!["mcp", "--automation-write-root", "."], + ] { + let message = usage_error(&args); + assert!(message.contains("--read-root") && message.contains("--write-root"), "{args:?}: {message}"); + } +} diff --git a/apps/texturecraft-cli/tests/it/main.rs b/apps/texturecraft-cli/tests/it/main.rs new file mode 100644 index 00000000..ea1db565 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/main.rs @@ -0,0 +1,48 @@ +//! Integration tests, built as one test binary: each file is a module. They call `run` in-process, +//! except where a test needs the real binary (a protocol on stdio, the environment). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod cli; +mod man_and_completions; +mod protocol; + +use std::ffi::{OsStr, OsString}; +use std::path::{Path, PathBuf}; + +/// What `run` returned and wrote. +pub struct Outcome { + pub code: i32, + pub out: String, + pub err: String, +} + +pub fn invoke(args: I) -> Outcome +where + I: IntoIterator, + T: Into, +{ + let (mut out, mut err) = (Vec::new(), Vec::new()); + let code = texturecraft_cli::run(args, &mut out, &mut err); + Outcome { code, out: String::from_utf8_lossy(&out).into_owned(), err: String::from_utf8_lossy(&err).into_owned() } +} + +/// A new, empty folder for one test. +pub fn workdir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-cli-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A small project made by `new`. +pub fn project(dir: &Path, name: &str) -> PathBuf { + let path = dir.join(name); + let made = invoke(argv(&[&"new", &"builtin:cube", &path, &"--resolution", &"128"])); + assert_eq!(made.code, 0, "{}", made.err); + path +} + +/// An argument vector from parts of different types (strings, paths). +pub fn argv(parts: &[&dyn AsRef]) -> Vec { + parts.iter().map(|p| p.as_ref().to_os_string()).collect() +} diff --git a/apps/texturecraft-cli/tests/it/man_and_completions.rs b/apps/texturecraft-cli/tests/it/man_and_completions.rs new file mode 100644 index 00000000..47607b5a --- /dev/null +++ b/apps/texturecraft-cli/tests/it/man_and_completions.rs @@ -0,0 +1,55 @@ +//! The clap definition is consistent, and every shell's completions and every man page +//! (`examples/man-and-completions.rs`) can be generated from it. + +use clap::ValueEnum; +use clap_complete::Shell; + +// The example itself, so the test writes the files exactly as the packages get them. +#[allow(dead_code)] +#[path = "../../examples/man-and-completions.rs"] +mod example; + +#[test] +fn command_is_consistent() { + texturecraft_cli::command().debug_assert(); +} + +#[test] +fn completions_generate_for_every_shell() { + for &shell in Shell::value_variants() { + let mut out = Vec::new(); + clap_complete::generate(shell, &mut texturecraft_cli::command(), "texturecraft-cli", &mut out); + assert!(!out.is_empty(), "{shell}"); + } +} + +#[test] +fn man_pages_render_for_the_command_and_every_subcommand() { + let cmd = texturecraft_cli::command(); + for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) { + let mut out = Vec::new(); + clap_mangen::Man::new(page.clone()).render(&mut out).unwrap(); + assert!(!out.is_empty(), "{}", page.get_name()); + } +} + +/// The example writes the five completion files under the names `packaging/linux/package.sh` and +/// `packaging/freebsd/package.sh` install, `texturecraft-cli.1` and a page per subcommand, and no +/// pages for the `help` subcommand. +#[test] +fn the_example_writes_the_files_the_packages_install() { + let dir = std::env::temp_dir().join(format!("mc-cli-{}-man-and-completions", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + example::generate(&dir).unwrap(); + + let mut written: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect(); + written.sort(); + let completions = ["texturecraft-cli.bash", "_texturecraft-cli", "texturecraft-cli.fish", "texturecraft-cli.elv", "_texturecraft-cli.ps1"]; + let subcommands = ["info", "commands", "run", "batch", "bake", "export", "render", "new", "mcp", "serve"]; + let mut expected: Vec = completions.map(String::from).into(); + expected.push("texturecraft-cli.1".into()); + expected.extend(subcommands.iter().map(|s| format!("texturecraft-cli-{s}.1"))); + expected.sort(); + assert_eq!(written, expected); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/apps/texturecraft-cli/tests/it/protocol.rs b/apps/texturecraft-cli/tests/it/protocol.rs new file mode 100644 index 00000000..db504b54 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/protocol.rs @@ -0,0 +1,118 @@ +//! The subcommands that talk over a stream (`mcp` and `serve` on stdio, through the real binary, +//! which owns stdin and stdout) and the environment variable of the control token. + +use std::io::Write; +use std::net::TcpListener; +use std::process::{Command, Output, Stdio}; + +fn binary() -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")); + command.env("TEXTURECRAFT_NO_PREFS", "1").env_remove("TEXTURECRAFT_CONTROL_TOKEN"); + command +} + +/// A port nothing listens on, with no token file. +fn free_port() -> String { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port().to_string() +} + +#[test] +fn serve_writes_nothing_but_json_lines_to_stdout() { + let mut child = binary().arg("serve").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + let mut stdin = child.stdin.take().unwrap(); + writeln!(stdin, r#"{{"id":1,"method":"ping","params":{{}}}}"#).unwrap(); + writeln!(stdin, "not json").unwrap(); + drop(stdin); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr)); + let lines: Vec<_> = String::from_utf8(output.stdout).unwrap().lines().map(str::to_string).collect(); + assert_eq!(lines.len(), 2, "{lines:?}"); + for line in &lines { + assert!(serde_json::from_str::(line).unwrap().get("ok").is_some(), "{line}"); + } +} + +#[test] +fn serve_ends_quietly_and_mcp_reports_it_when_stdin_is_closed() { + let output = binary().arg("serve").stdin(Stdio::null()).output().unwrap(); + assert_eq!((output.status.code(), output.stdout.is_empty(), output.stderr.is_empty()), (Some(0), true, true)); + // An MCP client must open with `initialize`; end of input before it is a failed start. + let dir = std::env::temp_dir().join(format!("tc-mcp-stdio-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let output = binary().args(["mcp", "--read-root", dir.to_str().unwrap(), "--write-root", dir.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!((output.status.code(), output.stdout.is_empty()), (Some(1), true)); + assert!(String::from_utf8_lossy(&output.stderr).starts_with("error: MCP start: "), "{}", String::from_utf8_lossy(&output.stderr)); +} + +fn bridge(token_flag: Option<&str>, env: Option<&str>) -> Output { + let port = free_port(); + let mut command = binary(); + command.args(["mcp", "--bridge", &port]); + if let Some(token) = token_flag { + command.args(["--token", token]); + } + if let Some(token) = env { + command.env("TEXTURECRAFT_CONTROL_TOKEN", token); + } + command.stdin(Stdio::null()).output().unwrap() +} + +#[test] +fn the_control_token_variable_is_a_fallback_the_flag_wins_and_an_empty_one_is_unset() { + let secret = "env-token-0123456789-secret"; + // Empty or blank counts as unset: the error says to set one, as when there is none. + for blank in ["", " "] { + let output = bridge(None, Some(blank)); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{err}"); + assert!(err.contains("no control token: set TEXTURECRAFT_CONTROL_TOKEN"), "{err}"); + } + // The variable is used when there is no flag: a good token gets as far as connecting. + let err = String::from_utf8_lossy(&bridge(None, Some(secret)).stderr).into_owned(); + assert!(!err.contains("16 to 1024") && !err.contains(secret), "{err}"); + // The flag wins over a good variable: its bad value is what is reported, without echoing either. + let err = String::from_utf8_lossy(&bridge(Some("short"), Some(secret)).stderr).into_owned(); + assert!(err.contains("control token must be 16 to 1024"), "{err}"); + assert!(!err.contains(secret) && !err.contains("short\n"), "{err}"); + // A bad value in the variable is refused too, and its value stays out of the message. + let err = String::from_utf8_lossy(&bridge(None, Some("bad token")).stderr).into_owned(); + assert!(err.contains("control token must be 16 to 1024") && !err.contains("bad token"), "{err}"); +} + +#[test] +fn help_lists_the_variable_but_never_its_value() { + let output = binary().args(["mcp", "--help"]).env("TEXTURECRAFT_CONTROL_TOKEN", "do-not-print-this-0123456789").output().unwrap(); + let help = String::from_utf8_lossy(&output.stdout); + assert!(help.contains("TEXTURECRAFT_CONTROL_TOKEN") && !help.contains("do-not-print-this"), "{help}"); +} + +#[test] +fn a_variable_alone_grants_no_file_access() { + // The token variable is for authentication only: a headless server with no roots still refuses files. + let mut child = + binary().arg("serve").env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + let mut stdin = child.stdin.take().unwrap(); + writeln!(stdin, r#"{{"id":1,"method":"project.save","params":{{"path":"never.tcraft"}}}}"#).unwrap(); + drop(stdin); + let output = child.wait_with_output().unwrap(); + let reply: serde_json::Value = serde_json::from_str(String::from_utf8(output.stdout).unwrap().lines().next().unwrap()).unwrap(); + assert_eq!(reply["ok"], false, "{reply}"); +} + +#[test] +fn a_token_in_the_environment_does_not_require_bridge() { + // Headless MCP must parse even when TEXTURECRAFT_CONTROL_TOKEN is set; only --token on the + // command line requires --bridge. + let output = binary().args(["mcp", "--fromat"]).env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").output().unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{err}"); + assert!(err.contains("--fromat"), "{err}"); + assert!(!err.contains("--bridge") && !err.contains("--token is for"), "{err}"); + + let output = binary().args(["mcp", "--token", "flag-token-0123456789"]).output().unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{err}"); + assert!(err.contains("--token") && err.contains("--bridge"), "{err}"); +} diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 63c12b0e..6d4bca71 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -45,9 +45,16 @@ pub fn generate_token() -> Result { Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) } +/// `TEXTURECRAFT_CONTROL_TOKEN`; an empty (or blank) variable counts as unset, as for every other +/// variable of the command line (RFC-0018 rule 1.7). +fn env_token() -> Option { + std::env::var(TOKEN_ENV).ok().filter(|t| !t.trim().is_empty()) +} + /// Token for a client of `port`: explicit, else `TEXTURECRAFT_CONTROL_TOKEN`, else the token file. +/// A blank value counts as not given. pub fn client_token(port: u16, supplied: Option) -> Result { - let token = match supplied.or_else(|| std::env::var(TOKEN_ENV).ok()) { + let token = match supplied.filter(|t| !t.trim().is_empty()).or_else(env_token) { Some(t) => t, None => { let path = token_file(port); @@ -64,7 +71,7 @@ pub fn client_token(port: u16, supplied: Option) -> Result Result<(String, Option), AutomationError> { - if let Ok(t) = std::env::var(TOKEN_ENV) { + if let Some(t) = env_token() { validate_token(t.trim())?; return Ok((t.trim().to_string(), None)); } @@ -228,6 +235,25 @@ mod tests { assert!(client_token(1, Some(format!(" {a}\n"))).is_ok()); } + #[test] + fn a_blank_token_counts_as_not_given() { + // No token anywhere (the port has no token file): the error says what to set, not that a + // blank token is invalid. A non-blank inherited TOKEN_ENV can still satisfy the client + // after a blank supplied value, so do not unwrap_err() first. + match client_token(1, Some(" ".into())) { + Err(error) => { + if std::env::var_os(TOKEN_ENV).is_none() { + let message = error.to_string(); + assert!(message.contains("no control token"), "{message}"); + } + } + Ok(_) => { + let inherited = std::env::var(TOKEN_ENV).unwrap_or_default(); + assert!(!inherited.trim().is_empty(), "a blank token was accepted with no inherited value"); + } + } + } + fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("tc-token-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 51684c27..50799e0d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -396,7 +396,8 @@ A `prefs` object without `language` sets the system language (`""`), the default them: `--read-root ` for `project_open` / `mesh_import` / `mesh_reimport` / `bake_mesh_add`, `--write-root ` for `project_save` / `material_save` / `textures_export` / `mesh_export` (`--automation-read-root` / `--automation-write-root`, as in the other crafting apps, are the - same flags). Without roots there is no file access. `..`, absolute + same flags). Headless mcp refuses to start unless both roots are set; file access is only + below them. `..`, absolute paths, drive letters, device names and symlink or junction escapes are refused. - **Bridge**: `--bridge ` forwards to a running `texturecraft --control ` (token from `--token`, `TEXTURECRAFT_CONTROL_TOKEN` or the app's token file). The app reads and writes its @@ -788,15 +789,15 @@ set. ## CLI ```sh -texturecraft-cli --version # TextureCraft 0.1.0 (abc1234 2026-10-14) +texturecraft-cli --version # texturecraft-cli 0.1.0 (abc1234 2026-10-14) texturecraft-cli info model.glb # triangles, materials, UV report texturecraft-cli info project.tcraft # texture sets, layers, baked maps -texturecraft-cli commands --filter mask +texturecraft-cli commands --filter mask --json texturecraft-cli new builtin:material_ball ball.tcraft --resolution 1024 --sample # mesh maps baked at ≤ 1024 px texturecraft-cli new model.glb model.tcraft --resolution 2048 -texturecraft-cli run ball.tcraft layer.add.fill '{"color":"#c08040","metallic":1}' -o ball.tcraft +texturecraft-cli run ball.tcraft layer.add.fill '{"color":"#c08040","metallic":1}' -o ball.tcraft --in-place texturecraft-cli batch script.json -texturecraft-cli bake model.tcraft --resolution 2048 --maps ambientOcclusion,curvature,thickness +texturecraft-cli bake model.tcraft --resolution 2048 --maps ambientOcclusion,curvature,thickness --in-place texturecraft-cli export model.tcraft out/ --preset "Unreal Engine (Packed)" --format png --size 2048 texturecraft-cli render ball.tcraft ball.png --size 1280x800 --view 3d --yaw 30 --pitch 15 texturecraft-cli render scene.tcraft hero.png --size 1200x900 --camera Hero --samples 2048 # a saved camera (camera.add), path traced @@ -817,5 +818,24 @@ steps or an object with an optional input and output (paths relative to the curr } ``` -Errors print `texturecraft-cli : error: …` and exit 1; usage errors exit 2. The CLI is a -console program and never opens a window; `render` needs a GPU or software adapter. +The CLI is a console program and never opens a window; `render` needs a GPU or software adapter. + +`texturecraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md) +(command-line conventions); `texturecraft-cli --help` and ` --help` are the reference for every flag. +Exit status: 0 success, 1 a command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that +conflict or that the subcommand doesn't use, all checked before any file is touched), and 128 plus the signal number +when a signal ends the process. Errors are `error: ` on stderr. `--version`/`-V` work on every subcommand +(`texturecraft-cli 0.6.1 ( )`, with no `version` subcommand), and no arguments print the help on +stderr and exit 2. `info`, `run`, `batch` and `bake` print JSON because agents read it; `commands --json` prints the +list as JSON where it prints a table without it. + +- **Environment.** `TEXTURECRAFT_CONTROL_TOKEN` is the one variable the CLI reads for a flag (`mcp --bridge`'s + `--token`; `serve --port` reads it for its own token). The flag wins, an empty or blank variable counts as unset, + and `--help` never shows its value. No variable grants file access (roots come from `--read-root`/`--write-root`) + or replaces a file. The app's own `TEXTURECRAFT_NO_PREFS` is a setting of the app, not a flag fallback. +- **Replacing files.** `run -o` and `bake -o` onto the project they opened, and `bake` of a project without `-o`, + need `--in-place`; `render` and `new` never replace their input, and `bake` of a mesh needs `-o`. +- **Packages.** The Linux packages (deb, rpm, tar.gz) and the FreeBSD package install `texturecraft-cli`'s man pages + and its bash, zsh and fish completions. Nightly packages ship no CLI, so none; macOS and Windows are outside + RFC-0018's scope. +- **Not yet.** The ast-grep scan of RFC-0018 section 3 is not switched on. diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index 6927f0a4..39ff32fa 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -54,8 +54,14 @@ echo "==> TextureCraft $VERSION for FreeBSD $ARCH" # The release VM has 12 GB; full parallelism on the biggest crates runs it out of memory. export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" +# The man-and-completions example writes texturecraft-cli's man pages and shell completions below. +# It is built in its own cargo run: built with the binaries, its dev-dependencies' features would +# be unified into them. if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli) + # The example is run on this host to write man pages and completions, so it must be a host + # binary even when CARGO_BUILD_TARGET is set for a cross package. + (cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p texturecraft-cli --example man-and-completions) fi WORK="$CARGO_TARGET_DIR/freebsd-package" STAGE="$WORK/$BASENAME" @@ -73,6 +79,16 @@ if [[ "$DRY_RUN" = 1 ]]; then printf '#!/bin/sh\necho "%s %s (dry-run stub)"\n' "$b" "$VERSION" >"$BIN/$b" chmod 755 "$BIN/$b" done + # A stub of the example: it writes the files the real one does. + mkdir -p "$BIN/examples" + cat >"$BIN/examples/man-and-completions" <<'STUB' +#!/bin/sh +mkdir -p "$1" +for f in texturecraft-cli.bash _texturecraft-cli texturecraft-cli.fish texturecraft-cli.elv _texturecraft-cli.ps1 texturecraft-cli.1 texturecraft-cli-info.1; do + echo "dry-run stub" >"$1/$f" +done +STUB + chmod 755 "$BIN/examples/man-and-completions" fi # ---- stage a /usr/local-style tree -------------------------------------------------------------- @@ -88,10 +104,32 @@ sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$TEXTURECRAFT_BUILD_DATE/g" \ "$LINUX/$APP_ID.metainfo.xml.in" >"$STAGE/share/metainfo/$APP_ID.metainfo.xml" cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" copy_docs "$STAGE/share/doc/texturecraft" +# texturecraft-cli's man pages and shell completions, from its clap definition, written by the +# example built above (a --skip-build run needs it built too). Under /usr/local, man pages go in +# man/ and the completions in the directories bash, zsh and fish read there. +if [[ "$DRY_RUN" = 1 ]]; then + CLI_DOCS="$BIN/examples/man-and-completions" +else + # Host path: the example is built with CARGO_BUILD_TARGET unset, above. + CLI_DOCS="$CARGO_TARGET_DIR/release/examples/man-and-completions" +fi +if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is not built (env -u CARGO_BUILD_TARGET cargo build --release -p texturecraft-cli --example man-and-completions)" >&2 + exit 1 +fi +"$CLI_DOCS" "$WORK/cli-docs" +mkdir -p "$STAGE/man/man1" "$STAGE/share/bash-completion/completions" \ + "$STAGE/share/zsh/site-functions" "$STAGE/share/fish/vendor_completions.d" +install -m 644 "$WORK"/cli-docs/*.1 "$STAGE/man/man1/" +install -m 644 "$WORK/cli-docs/texturecraft-cli.bash" "$STAGE/share/bash-completion/completions/texturecraft-cli" +install -m 644 "$WORK/cli-docs/_texturecraft-cli" "$STAGE/share/zsh/site-functions/_texturecraft-cli" +install -m 644 "$WORK/cli-docs/texturecraft-cli.fish" "$STAGE/share/fish/vendor_completions.d/texturecraft-cli.fish" for f in bin/texturecraft bin/texturecraft-cli "share/applications/$APP_ID.desktop" \ "share/icons/hicolor/256x256/apps/$APP_ID.png" "share/icons/hicolor/scalable/apps/$APP_ID.svg" \ - share/doc/texturecraft/LICENSE-MIT share/doc/texturecraft/LICENSE-APACHE; do + share/doc/texturecraft/LICENSE-MIT share/doc/texturecraft/LICENSE-APACHE \ + man/man1/texturecraft-cli.1 share/bash-completion/completions/texturecraft-cli share/zsh/site-functions/_texturecraft-cli \ + share/fish/vendor_completions.d/texturecraft-cli.fish; do if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi done diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 1cea1c4b..bbabbf7e 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -81,6 +81,13 @@ contents: - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree + # Debian's zsh reads vendor-completions, not /usr/share/zsh/site-functions as Fedora's and + # openSUSE's do (its debian/rules sets --enable-additional-fpath). package.sh drops this entry + # from a Nightly build, which has no CLI. + - src: /usr/share/zsh/site-functions/_texturecraft-cli + dst: /usr/share/zsh/vendor-completions/_texturecraft-cli + type: symlink + packager: deb scripts: postinstall: packaging/linux/postinst.sh diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 8c2ca936..52358cf4 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -65,6 +65,14 @@ echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS, channel=${TEXTURECRAF if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"}) + # The man-and-completions example writes texturecraft-cli's man pages and shell completions + # below (Stable only: a Nightly ships no CLI). It is built in its own cargo run: built with the + # binaries, its dev-dependencies' features would be unified into them. It is run here, so a + # cross build builds it for the host. + if [[ "$IS_NIGHTLY" = 0 ]]; then + # Unset CARGO_BUILD_TARGET so a cross package still builds a host example (run below). + (cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p texturecraft-cli --example man-and-completions) + fi fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" WORK="$CARGO_TARGET_DIR/linux-package" @@ -80,6 +88,20 @@ install -Dm755 "$BIN/texturecraft" "$STAGE/usr/bin/texturecraft" if [[ "$IS_NIGHTLY" = 0 ]]; then install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true + # texturecraft-cli's man pages and shell completions (RFC-0018 rule 1.9), from its clap + # definition, written by the example built above (a --skip-build run needs it built too). zsh + # reads site-functions on Fedora and openSUSE; the deb also links the completion into Debian's + # vendor-completions (nfpm.yaml). + CLI_DOCS="$CARGO_TARGET_DIR/release/examples/man-and-completions" + if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is not built (env -u CARGO_BUILD_TARGET cargo build --release -p texturecraft-cli --example man-and-completions)" >&2 + exit 1 + fi + "$CLI_DOCS" "$WORK/cli-docs" + install -Dm644 -t "$STAGE/usr/share/man/man1" "$WORK"/cli-docs/*.1 + install -Dm644 "$WORK/cli-docs/texturecraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/texturecraft-cli" + install -Dm644 "$WORK/cli-docs/_texturecraft-cli" "$STAGE/usr/share/zsh/site-functions/_texturecraft-cli" + install -Dm644 "$WORK/cli-docs/texturecraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/texturecraft-cli.fish" fi install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" if [[ "$IS_NIGHTLY" = 1 ]]; then @@ -192,6 +214,9 @@ WRAPPER # A Nightly package has no CLI, so its file list must not name one either. # shellcheck disable=SC2016 [[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI='\|^ - src: \${STAGE}/usr/bin/\${NFPM_CLI}|,+2d;/Includes texturecraft-cli/d;' + # ... nor the zsh link into Debian's vendor-completions for the CLI's completion. + # shellcheck disable=SC2016 + [[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI="$DROP_CLI"'\|^ - src: /usr/share/zsh/site-functions/_texturecraft-cli|,+3d;' # shellcheck disable=SC2016 sed "${DROP_LIB_TREE}${DROP_CLI}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" # The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39. From 091869033ab9e12c3c0357ad2d54519df771c3f0 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sat, 28 Nov 2026 00:21:21 +0000 Subject: [PATCH 155/190] Auto: Preflight export paths and label tiled atlas previews Reject selections that use one output path as both a file and a folder before rendering or starting a desktop export. Expose tile metadata in export.plan and use it to label atlas previews, including ambiguous filenames. Write quantized 8-bit PSD rows directly into the merged-image buffer. Cover path conflicts in both orders, partial desktop writes, and visible atlas captions with regression tests. --- crates/engine/src/file_cmds.rs | 11 ++- crates/engine/tests/it/export_file_types.rs | 42 ++++++++- crates/formats/README.md | 3 +- crates/formats/src/export/layered_psd.rs | 6 +- crates/formats/src/export/mod.rs | 23 ++++- crates/ui-egui/src/export_templates.rs | 86 +++++++++++++++---- .../src/export_templates/planned_output.rs | 2 + crates/ui-egui/src/export_window.rs | 9 +- .../ui-egui/tests/it/export_map_overrides.rs | 6 +- crates/ui-egui/tests/it/export_progress.rs | 34 ++++++++ docs/control-protocol.md | 15 ++-- 11 files changed, 199 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index daee5a0e..ac846ba5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name and warns about later duplicates)", + "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with or null, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)", always, plan ), @@ -401,7 +401,12 @@ impl Session { // Keep each winning plan with the options of the job that produced it let plans = pending.iter_mut().enumerate().flat_map(|(job, (_, _, plans))| plans.drain(..).map(move |plan| (job, plan))); - for (job, plan) in texturecraft_formats::export::keep_first_planned_names(plans) { + let plans = texturecraft_formats::export::keep_first_planned_names(plans); + if pending.len() > 1 { + texturecraft_formats::export::validate_export_paths(plans.iter().map(|(_, plan)| plan.name.as_str())).map_err(fe)?; + } + + for (job, plan) in plans { pending[job].2.push(plan); } pending.retain(|(_, _, plans)| !plans.is_empty()); @@ -630,6 +635,8 @@ fn plan(session: &mut Session, params: &Value) -> Result { "ts": set_index, "map": output.map, "file": output.name, + "tile": output.tile, + "udimPattern": output.udim_name, "format": output.format.extension(), "bitDepth": output.bit_depth, "dithering": output.dither, diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index 341e196c..dca3a215 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -50,6 +50,45 @@ fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() { println!("Kept {} PSDs totaling {} encoded bytes", batch.len(), batch.iter().map(|file| file.bytes.len()).sum::()); } +#[test] +fn a_psd_file_and_another_sets_folder_conflict_during_planning() { + use texturecraft_engine::core::Channel; + use texturecraft_engine::file_cmds::export_options; + + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let sets = &mut session.doc.project.texture_sets; + sets[0].name = "Body".into(); + sets[0].channels.retain(|(channel, _)| *channel != Channel::Metallic); + sets[1].name = "Trim".into(); + let preset = json!({"name": "Conflicting outputs", "maps": [ + {"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}, + {"file": "$mesh_Body.psd/detail", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Metallic"}}]]} + ]}); + let dir = tempfile::tempdir().unwrap(); + let mut params = json!({"preset": preset, "padding": "none", "dir": dir.path()}); + + params["ts"] = json!(0); + let body = execute(&mut session, "export.plan", ¶ms).unwrap(); + params["ts"] = json!(1); + let trim = execute(&mut session, "export.plan", ¶ms).unwrap(); + let file = body[0]["file"].as_str().unwrap(); + let nested_file = trim.as_array().unwrap().iter().find_map(|file| file["file"].as_str().filter(|name| name.contains('/'))).unwrap(); + assert_eq!(nested_file.split('/').next(), Some(file), "separate plans collide when combined"); + + for order in [[0, 1], [1, 0]] { + params["ts"] = json!(order); + let plan_error = execute(&mut session, "export.plan", ¶ms).unwrap_err(); + let options = export_options(&session, ¶ms, "export.plan").unwrap(); + let render_error = session.export_files(&order, &options).unwrap_err(); + let write_error = execute(&mut session, "file.exportTextures", ¶ms).unwrap_err(); + + for error in [plan_error, render_error, write_error] { + assert!(error.to_string().contains("folder"), "{error}"); + } + assert!(std::fs::read_dir(dir.path()).unwrap().next().is_none()); + } +} + #[test] fn a_map_size_wins_over_the_export_size_in_the_plan() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -127,7 +166,8 @@ fn a_psd_warning_outlives_a_reserved_file_that_carried_it() { {"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness}, {"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness}, ]}); - // Four 16-bit RGBA layers at 8192 pixels and the merged image pass the 2 GiB PSD limit + + // Four 16-bit RGBA layers at 8192 pixels exceed the 2 GiB PSD limit for layer in 0..4 { preset["maps"].as_array_mut().unwrap().push(json!({"file": format!("layer{layer}"), "format": "Psd", "bit_depth": 16, "channels": colour})); } diff --git a/crates/formats/README.md b/crates/formats/README.md index 5f60e6ef..f32292cb 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -110,7 +110,8 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result; deflate alpha), PGM 8/16 (gray; colour becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, WebP 8 (lossless), PSD 8/16, EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. PSD writes one file per texture set or UV tile, with each output map stored as a layer. - Smaller maps keep their sizes and align to the top left of the canvas. A `/` in a map + For tiled sets, `ExportOptions::atlas` writes one document for the whole set. Smaller maps + keep their sizes and align to the top left of the canvas. A `/` in a map name creates a layer group inside the PSD. 8-bit files can be dithered (`ExportOptions::dither`, an 8×8 ordered pattern). When `ExportOptions::color_space` is unset, color maps default to sRGB in integer files and linear Rec.709 in float files. An explicit diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index af95e664..f7be380c 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -8,7 +8,7 @@ use super::encoding::Encoding; use super::map_renderer::MapRenderer; use super::{ ExportOptions, ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, Padding, PlannedFile, PlannedLayer, check_psd_size, psd_size, - quantize_integer, quantize_u16, + quantize_integer, quantize_u8, quantize_u16, }; use crate::{FormatError, Result}; @@ -125,11 +125,11 @@ fn merged_image((width, height): (u32, u32), depth: u8, layers: &[(&str, (u32, u let mut merged = Vec::new(); merged.try_reserve_exact(sample_count).map_err(reserve_error)?; - let encoding = Encoding { format: FileFormat::Psd, depth, dither: false }; for y in 0..height as usize { merge_row(y, width, layers, &mut merged_row, &mut layer_row); - merged.extend(quantize_integer(encoding, width, PSD_RGBA_PLANES, merged_row.iter().copied())?); + merged.extend(merged_row.iter().copied().map(quantize_u8)); } + Ok(PixelData::Rgba8(merged)) } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 3ded1c05..8ca37c57 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -939,7 +939,7 @@ fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: & let mut prefix = lower.as_str(); while let Some((folder, _)) = prefix.rsplit_once('/') { if files.contains(folder) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); + return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another output exports that file"))); } dirs.insert(folder.to_owned()); @@ -949,6 +949,17 @@ fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: & Ok(()) } +/// Reject file and folder conflicts across a selection's retained output paths, ignoring case. +pub fn validate_export_paths<'a>(names: impl IntoIterator) -> Result<()> { + let mut files = BTreeSet::new(); + let mut folders = BTreeSet::new(); + for name in names { + claim_path(&mut files, &mut folders, name)?; + } + + Ok(()) +} + /// The size of a PSD layer of a texture set at `export_size` for `tile` (None: the whole set, an atlas of a UV-tiled one) fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u32, u32) { let block_resolution = set.block_resolution(); @@ -982,6 +993,10 @@ fn plan_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &E } let files = keep_first_planned_names(files); + if sets.len() > 1 { + validate_export_paths(files.iter().map(|(_, file)| file.name.as_str()))?; + } + let mut psd_bytes = 0; for (index, file) in files.iter().filter(|(_, file)| file.format == FileFormat::Psd) { check_psd_batch_within(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes, budget)?; @@ -1565,6 +1580,10 @@ fn encode( write_raster(&image, codec_format).map_err(|error| encoding_error(&error)) } +fn quantize_u8(value: f32) -> u8 { + (value * f32::from(u8::MAX) + 0.5) as u8 +} + fn quantize_u16(value: f32) -> u16 { (value * f32::from(u16::MAX) + 0.5) as u16 } @@ -1593,7 +1612,7 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp if dither { bytes.extend(samples.enumerate().map(|(index, value)| (value * max_sample + threshold(index)).floor().clamp(0.0, max_sample) as u8)); } else { - bytes.extend(samples.map(|value| (value * max_sample + 0.5) as u8)); + bytes.extend(samples.map(quantize_u8)); } } diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 70f708b4..aa7f223d 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1095,33 +1095,46 @@ fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result> = vec![None; map_count]; + let tile_files = tr("UV tile files"); for file in plan.as_array().into_iter().flatten() { let Some(name) = file.get("file").and_then(Value::as_str) else { continue }; - let output = PlannedOutput { - file: name.to_string(), - size: file.get("size").and_then(Value::as_u64).unwrap_or(0), - format: file.get("format").and_then(Value::as_str).and_then(FileFormat::from_extension), - bit_depth: file.get("bitDepth").and_then(Value::as_u64).and_then(|depth| u8::try_from(depth).ok()).unwrap_or(0), - dithering: file.get("dithering").and_then(Value::as_bool).unwrap_or(false), + let tiled = file["tile"].is_number(); + let display_name = if tiled { file["udimPattern"].as_str().unwrap_or(tile_files) } else { name }; + let mut remember = |entry: &Value, layer_name: Option<&str>| { + let Some(slot) = index(entry).and_then(|index| outputs.get_mut(index)) else { return }; + + if let Some(previous) = slot { + // Some disambiguated or truncated paths have no common tile pattern + if tiled && previous.file != display_name && previous.file != tile_files { + previous.file = tile_files.into(); + } + return; + } + + *slot = Some(PlannedOutput { + file: match layer_name { + Some(layer_name) if !tiled => format!("{name} › {layer_name}"), + _ => display_name.to_owned(), + }, + tiled, + size: file.get("size").and_then(Value::as_u64).unwrap_or(0), + format: file.get("format").and_then(Value::as_str).and_then(FileFormat::from_extension), + bit_depth: file.get("bitDepth").and_then(Value::as_u64).and_then(|depth| u8::try_from(depth).ok()).unwrap_or(0), + dithering: file.get("dithering").and_then(Value::as_bool).unwrap_or(false), + }); }; match file.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty()) { Some(layers) => { for layer in layers { - let layer_name = layer.get("name").and_then(Value::as_str).unwrap_or_default(); - if let Some(slot) = index(layer).and_then(|i| outputs.get_mut(i)) { - *slot = Some(PlannedOutput { file: format!("{name} › {layer_name}"), ..output.clone() }); - } - } - } - None => { - if let Some(slot) = index(file).and_then(|i| outputs.get_mut(i)) { - *slot = Some(output); + remember(layer, layer.get("name").and_then(Value::as_str)); } } + None => remember(file, None), } } + Ok(outputs) } @@ -1487,13 +1500,16 @@ fn output_preview(ui: &mut Ui, index: usize, map: &MapSpec, planned: Option<&Pla return; }; - ui.label(RichText::new(&planned.file).color(tokens.text_strong)); + let title = if planned.tiled { trf("Atlas preview: {file}", &[("file", &planned.file)]) } else { planned.file.clone() }; + ui.label(RichText::new(title).color(tokens.text_strong)); if let Some(Some(pictures)) = MapPreviewCache::get(ui.ctx(), index) { preview_pictures(ui, map, &pictures); } + let file_type = planned.format.map_or("", FileFormat::extension); let depth = crate::export_window::depth_label(planned.format, planned.bit_depth, planned.dithering); - ui.label(RichText::new(format!("{size} x {size} · {file_type} {depth}", size = planned.size)).color(tokens.text_dim)); + let details = if planned.tiled { format!("{file_type} {depth}") } else { format!("{size} x {size} · {file_type} {depth}", size = planned.size) }; + ui.label(RichText::new(details).color(tokens.text_dim)); } /// The file's picture with each channel's grey picture, letter and source beside it @@ -1903,6 +1919,40 @@ mod tests { assert_eq!(params["maps"].as_array().unwrap().len(), 2, "the new map and the removed map get no override"); } + #[test] + fn tiled_raster_and_psd_previews_describe_the_whole_atlas() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable as _; + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives::udim_plane; + + let session = Session::new_project("Tiles", udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let mut preset = app.session.export_preset("Separate maps").unwrap(); + preset.maps.truncate(2); + preset.maps[0].file = "Raster".into(); + preset.maps[0].format = FileFormat::Png; + preset.maps[1].file = "Group/Layer.$udim".into(); + preset.maps[1].format = FileFormat::Psd; + let mut ambiguous = preset.maps[0].clone(); + ambiguous.file = "Literal_UDIMTOKEN.$udim".into(); + preset.maps.push(ambiguous); + let params = json!({"ts": 0, "preset": preset}); + + let outputs = planned_outputs(app, ¶ms).unwrap(); + let preview = Harness::builder().with_context_setup(crate::framework::install_headless).build_ui(|ui| { + for (index, map) in preset.maps.iter().enumerate() { + output_preview(ui, index, map, outputs[index].as_ref()); + } + }); + + assert!(preview.query_by_label("Atlas preview: Raster..png").is_some()); + assert!(preview.query_by_label_contains(".psd").is_some()); + assert!(preview.query_by_label("Atlas preview: UV tile files").is_some()); + assert!(preview.query_by_label_contains("128 x 128").is_none(), "the tile size must not describe the whole atlas"); + } + #[test] fn layouts_keep_sources_and_drops_fill_rgb() { let mut map = new_map(Layout::Rgb, "t"); diff --git a/crates/ui-egui/src/export_templates/planned_output.rs b/crates/ui-egui/src/export_templates/planned_output.rs index e81666d4..6c5bcf37 100644 --- a/crates/ui-egui/src/export_templates/planned_output.rs +++ b/crates/ui-egui/src/export_templates/planned_output.rs @@ -4,6 +4,8 @@ use texturecraft_engine::formats::FileFormat; #[derive(Clone)] pub(super) struct PlannedOutput { pub(super) file: String, + /// The picture shows the full atlas while export writes individual tiles + pub(super) tiled: bool, /// Pixels per side (export.plan never plans an atlas, so every file is square) pub(super) size: u64, pub(super) format: Option, diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index a3f6661b..c346d033 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -443,7 +443,10 @@ fn start_export(app: &mut TextureCraftApp) { .collect(); let preview: Vec<_> = pending.iter().filter_map(|(index, params)| plan_set(app, *index, params)).collect(); - let error = preview.iter().find_map(|plan| plan.files.as_ref().err().cloned()).or_else(|| name_clash(&preview)); + let error = preview.iter().find_map(|plan| plan.files.as_ref().err().cloned()).or_else(|| name_clash(&preview)).or_else(|| { + let paths = preview.iter().filter_map(|plan| plan.files.as_ref().ok()).flat_map(planned_names); + texturecraft_engine::formats::export::validate_export_paths(paths).err().map(|error| trf("Export stopped: {error}", &[("error", &error)])) + }); let e = &mut app.ui.export; e.tab = 2; @@ -1505,8 +1508,10 @@ fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui::Id) -> bool { let look = ExportLook::get(ui.ctx()); let response = ui.interact(rect, id, egui::Sense::click()); - // A folding header, as egui's CollapsingHeader reports one + + // Expose the hand-drawn header as a disclosure control response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, name)); + let y = rect.center().y; let chevron = if open { ic::CARET_DOWN diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 15b326b3..d2edee62 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -163,8 +163,7 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { fn export_writes_a_map_with_its_own_file_type() { let mut h = harness(); let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize; - let dir = std::env::temp_dir().join(format!("tc-export-map-overrides-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = TempDir::new("export-map-overrides"); let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None }); @@ -184,10 +183,9 @@ fn export_writes_a_map_with_its_own_file_type() { h.run_steps(1); } h.run_steps(2); - let names: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + let names: Vec = std::fs::read_dir(&*dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); assert_eq!(names.iter().filter(|n| n.ends_with(".tga")).count(), 1, "{names:?}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 8a756d8a..ec4bf518 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -255,6 +255,40 @@ fn texture_sets_writing_the_same_file_name_do_not_start_an_export() { let _ = std::fs::remove_dir_all(&library); } +#[test] +fn a_texture_set_cannot_export_into_another_sets_psd_file() { + use texturecraft_ui_egui::state::SetExport; + + let (mut h, _) = harness("psd-folder-clash"); + let scratch = tempfile::tempdir().unwrap(); + let dir = scratch.path().join("textures"); + let library = tempfile::tempdir().unwrap(); + let app = h.state_mut(); + app.ui.export.dir = dir.display().to_string(); + app.session.load_export_presets(library.path().to_path_buf()); + let psd = json!({"name": "Layered", "maps": [ + {"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + app.run("export.preset.save", json!({"preset": psd})).unwrap(); + let plan = app.run("export.plan", json!({"preset": "Layered", "ts": 0})).unwrap(); + let file_name = plan[0]["file"].as_str().unwrap(); + let nested = json!({"name": "Nested", "maps": [ + {"file": format!("{file_name}/detail"), "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + app.run("export.preset.save", json!({"preset": nested})).unwrap(); + app.ui.export.preset = "Layered".into(); + app.ui.export.sets.insert(1, SetExport { preset: Some("Nested".into()), ..Default::default() }); + h.run_steps(4); + + click(&mut h, "Export"); + finish(&mut h); + + assert!(h.state().ui.export.job.is_none()); + assert_eq!(exports(&h), 0, "the full selection must be checked before starting"); + assert!(!dir.exists()); + assert!(console(&h).iter().any(|line| line.contains("folder")), "{:?}", console(&h)); +} + #[test] fn opening_another_project_stops_the_export() { let (mut h, dir) = harness("project"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3ae31541..27a60c1d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -44,9 +44,11 @@ grayscale image (the whole tile atlas for a UV-tiled set). `file.exportTextures`, `export.plan`, the automation `textures.export` method and the MCP `textures_export` tool accept `maps: [{map, enabled?, format?, bitDepth?, dithering?, size?}]`. Each entry overrides that map's export settings. The `map` field is its index in the selected -template. A map’s `size` in pixels overrides the export size. `enabled: false` suppresses that file while reserving its name. When several texture -sets produce the same name (ignoring case), programmatic and browser exports keep the first file -and warn about later duplicates. The desktop export window reports the collision before writing. +template. A map's `size` in pixels overrides the export size. `enabled: false` leaves out a PSD layer +or suppresses a raster file while reserving its name. When several texture sets produce the same +name (ignoring case), programmatic and browser exports keep the first file and warn about later +duplicates. The desktop export window reports the collision before writing. Texture planning +rejects a selection that uses the same path as both a file and a folder before rendering. `shaderParameters: true` writes `_shaders.json` beside the textures with the shader model, its settings and the names of the exported texture sets. An array of texture set @@ -84,11 +86,14 @@ shared by different sets. `hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and `export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). +Tiled files include their UV tile number in `tile` and, when available, their filename template +with a `` placeholder in `udimPattern`. These fields are null when they do not apply. `export.preview` takes the same parameters plus `map` (an index into the template's maps) and `side` (the maximum width or height, in pixels, capped at 512). It returns `{width, height, channels, pixels}` for the first texture set named by `ts`, or null when the -set writes no file for that map. HDR previews list RGB without alpha. TIFF previews list RGB -or RGBA when the encoder stores luminance in three channels. The preview uses 8-bit values, +set writes no file for that map. For a UV-tiled set the picture shows the atlas. HDR previews +list RGB without alpha. TIFF and WebP previews list RGB or RGBA when the encoder stores +luminance in three channels. PSD previews show the output layer's RGBA channels. The preview uses 8-bit values, with sRGB colour channels and linear data channels. Texels outside the UV islands use the channel defaults. `padding: "diffusion"` dilates by From 7e0bd1e6a2ba8077091c0b2351304ef276b25be5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:33:49 +0000 Subject: [PATCH 156/190] Assets: the refresh popup's tests move a rewritten file's time on Main's Resources Updater counts an equal-size file whose modification time didn't move as unchanged, so a rewrite in the same millisecond as the import read as up to date and the test failed on the gate. --- crates/engine/src/resource_cmds.rs | 3 +++ crates/ui-egui/tests/it/shelf_updates.rs | 11 +++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 75614716..024243c3 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -538,6 +538,9 @@ mod tests { let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap(); + // An equal-size file counts as changed once its time moved, as a later save's does + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap(); let updated = crate::execute(&mut session, "resource.update", &json!({"names": [renamed]})).unwrap(); std::fs::remove_file(&path).unwrap(); diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs index 01a208a7..717a6d4a 100644 --- a/crates/ui-egui/tests/it/shelf_updates.rs +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -29,6 +29,13 @@ fn pass_a_minute(harness: &mut Harness<'_, TextureCraftApp>) { harness.run_steps(2); } +/// Writes `bytes` over the file at `path` with a later time, as a later save would (an equal-size file keeping its time reads as unchanged) +fn rewrite(path: &std::path::Path, bytes: &[u8]) { + std::fs::write(path, bytes).unwrap(); + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10); + std::fs::File::options().write(true).open(path).unwrap().set_modified(later).unwrap(); +} + /// A grey one-pixel PNG of `value` fn grey_png(value: f32) -> Vec { texturecraft_engine::formats::gray16_png(1, 1, [value].into_iter()).unwrap() @@ -41,7 +48,7 @@ fn turning_on_project_resources_reads_a_changed_image_file_again_every_minute() std::fs::write(&path, grey_png(0.2)).unwrap(); let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); let before = harness.state().session.images[&name].rgba.clone(); - std::fs::write(&path, grey_png(0.8)).unwrap(); + rewrite(&path, &grey_png(0.8)); pass_a_minute(&mut harness); let while_off = harness.state().session.images[&name].rgba.clone(); @@ -78,7 +85,7 @@ fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { let before = harness.state().session.images[&name].rgba.clone(); harness.get_by_label("Resources used in project").click(); harness.run_steps(2); - std::fs::write(&path, grey_png(0.8)).unwrap(); + rewrite(&path, &grey_png(0.8)); let steps_before_stroke = harness.state().session.history_labels().len(); harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); From ff18396f78fe1984a3119c0f0772ed7efd955d13 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Fri, 27 Nov 2026 18:57:32 -0600 Subject: [PATCH 157/190] Keep the web build under its size gate by subsetting CJK fonts (#803) * web: cut the CJK interface face to the catalogs' characters The scheduled Release dry run's Web (wasm) job has failed since 23 Nov 2026: the wasm is 27,128,780 bytes against the 25,165,824-byte gate in packaging/web/package.sh, and against Cloudflare's 25 MiB per-file cap. Parsing the last green artifact puts 7.4 MB of the 24.8 MB module in embedded fonts, of which the whole Japanese face is 4.67 MB. WordCraft already cuts its web interface faces to the embedded catalogs (craft-libs' craft-fonts-build `Embed::subset_to`, with `Embed::for_ui`); this app still embedded the whole face. A web build now subsets every face whose manifest script is Hans/Hant/Jpan/Kore to the characters of the embedded catalogs, plus ASCII, Latin-1 and general punctuation, and keeps the CJK punctuation block (U+3000-303F) and the kana blocks (U+3040-30FF) whatever the catalogs say, so Japanese a user types in a layer or file name still draws. That is craft-libs' precedent minus the katakana phonetic extensions and the full-width forms, which cost a further 5 KB and are not in the cut. The subsetter is the skera/skrifa pair the Inter cut already uses. The cut Japanese face is 650,268 bytes instead of 4,669,688, so the wasm comes back to about 23.1 MB, under the gate with about 2.0 MB to spare. The desktop build is unchanged and keeps its CJK faces whole. Trade-off, as in WordCraft: CJK characters outside the catalogs and those ranges (kanji, full-width forms) fall back to the interface font in the browser build only. * ui: drop the catalog builder's unused source-only entry point cargo xtask ci's clippy leg (--all-targets -- -D warnings) fails the ui-egui build script on `i18n_build::generate`: since the web font cut, the build script only calls `embed`, so the wrapper is dead code in that compilation unit and `-D dead-code` rejects it. The integration test was its only caller, and it drives `collect` directly elsewhere, so the tests keep a local `generate` wrapper over `i18n_build::collect` and the production module stops carrying a function nothing builds. * docs: state the web CJK subset's coverage accurately Han ideographs that are not in the shipped catalogs are omitted from the web face and render as missing glyphs. Desktop still embeds the full faces. * style: let cargo fmt order the skera import The earlier rustfmt pass put the function before the types; cargo fmt (with this repo's rustfmt.toml) wants Plan and SubsetFlags first. --------- Co-authored-by: skylartaylor Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/build.rs | 68 +++++++++++++++++++++++------- crates/ui-egui/i18n_build.rs | 26 ++++++++---- crates/ui-egui/tests/i18n_build.rs | 55 +++++++++++++++++++----- 3 files changed, 114 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 322d3297..79f33f27 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -2,15 +2,22 @@ //! at a checkout: Inter for the interface (from its Latin catalog) and the CJK and Arabic //! faces; without it `CRAFT_FONTS` is empty and the UI uses egui's and the system's fonts. The //! recipe follows craft-fonts' `docs/integration.md`; no font file is committed here. The Latin -//! faces are embedded without their Private Use Area ([`without_private_use`]). +//! faces are embedded without their Private Use Area ([`without_private_use`]), and a web build +//! embeds its CJK faces cut to the characters the shipped catalogs use ([`cut_to_catalogs`]): +//! the whole Japanese face alone is 4.5 MB of the wasm download. mod i18n_build; +use skera::{Plan, SubsetFlags, subset_font}; +use skrifa::raw::collections::IntSet; +use skrifa::raw::types::NameId; +use skrifa::{FontRef, GlyphId, MetadataProvider, Tag}; use std::fmt::Write as _; use std::path::PathBuf; /// The UI faces TextureCraft embeds (family, style) per manifest: desktop, then web (the web build -/// has a download budget: of the CJK faces only the Japanese one, ~4.5 MB). +/// has a download budget: of the CJK faces only the Japanese one, cut to the catalogs' characters +/// by [`cut_to_catalogs`]). const MANIFESTS: &[(&str, Faces, Faces)] = &[ ("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular"), ARABIC], &[("BIZ UDPGothic", "Regular"), ARABIC]), // The interface font has regular and semibold faces @@ -25,12 +32,12 @@ const LATIN: Faces = &[("Inter", "Regular"), ("Inter", "SemiBold")]; type Faces = &'static [(&'static str, &'static str)]; fn main() { - i18n_build::embed(); + let catalogs = i18n_build::embed(); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR"); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n"); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from) { - match MANIFESTS.iter().map(|(rel, desktop, web)| craft_fonts(&dir, rel, desktop, web)).collect::>() { + match MANIFESTS.iter().map(|(rel, desktop, web)| craft_fonts(&dir, rel, desktop, web, &catalogs)).collect::>() { Ok(entries) => src.push_str(&entries), Err(e) if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() => { println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()); @@ -47,7 +54,10 @@ fn main() { } /// One `CraftFont { .. }` initialiser per wanted line of manifest `rel`. -fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: &[(&str, &str)]) -> Result { +/// +/// `catalogs` is the characters the embedded catalogs use ([`i18n_build::embed`]): a web build +/// cuts its CJK faces to them. +fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: &[(&str, &str)], catalogs: &[char]) -> Result { let manifest = dir.join(rel); println!("cargo::rerun-if-changed={}", manifest.display()); if rel == LATIN_MANIFEST && !manifest.exists() { @@ -70,14 +80,21 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; println!("cargo::rerun-if-changed={}", path.display()); - if rel == LATIN_MANIFEST { + let tags: Vec<&str> = scripts.split(',').map(str::trim).filter(|s| !s.is_empty()).collect(); + // The Latin faces lose their Private Use Area everywhere; a web build also cuts its CJK + // faces to the characters the shipped catalogs use. The desktop keeps its CJK faces whole: + // the same face draws text the app never ships, a user's Japanese file name. + let cut = rel == LATIN_MANIFEST || (wasm && !catalogs.is_empty() && tags.iter().any(|tag| CJK_SCRIPTS.contains(tag))); + if cut { let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; + let cut = + if rel == LATIN_MANIFEST { without_private_use(&bytes) } else { cut_to_catalogs(&bytes, catalogs) }.map_err(|e| format!("{file}: {e}"))?; let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(path.file_name().unwrap_or_default()); - std::fs::write(&out, without_private_use(&bytes).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{}: {e}", out.display()))?; + std::fs::write(&out, cut).map_err(|e| format!("{}: {e}", out.display()))?; path = out; } - let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); + let scripts: Vec = tags.iter().map(|s| format!("{s:?}")).collect(); let _ = writeln!( out, " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},", @@ -89,26 +106,47 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: Ok(out) } +/// The scripts whose faces a web build cuts to the catalogs' characters: the CJK faces are most of +/// the web build's font download, and the whole Japanese face alone is 4.5 MB. +const CJK_SCRIPTS: [&str; 4] = ["Hans", "Hant", "Jpan", "Kore"]; + /// `font` without the characters of the Private Use Area (U+E000–U+F8FF): the icon font (Phosphor) /// draws there, and Inter, ahead of it in the fallback list, has alternates of its own there that /// would show instead of the icons. Everything else (layout features, hinting) is kept, as /// craft-libs' `craft-fonts-build` subsets. fn without_private_use(font: &[u8]) -> Result, String> { - use skera::{Plan, SubsetFlags, subset_font}; - use skrifa::raw::collections::IntSet; - use skrifa::raw::types::NameId; - use skrifa::{FontRef, GlyphId, MetadataProvider, Tag}; let font = FontRef::new(font).map_err(|e| e.to_string())?; let mut unicodes = IntSet::::empty(); unicodes.extend(font.charmap().mappings().map(|(c, _)| c).filter(|c| !(0xE000..=0xF8FF).contains(c))); + subset(&font, &unicodes) +} + +/// `font` with only the glyphs for the characters the shipped catalogs use, plus ASCII, Latin-1, +/// general punctuation (numbers, names and punctuation in the shipped strings), CJK punctuation +/// (U+3000–303F) and the kana blocks (U+3040–30FF), as craft-libs' `craft-fonts-build` keeps when +/// WordCraft cuts its interface face. The web build has one face per script. Shipped UI strings +/// and user-typed ASCII, Latin-1, punctuation and kana still draw; Han ideographs that are not in +/// the catalogs show as missing glyphs (the desktop build keeps the CJK faces whole, including a +/// user's Japanese file name). The whole Japanese face would otherwise be 4.5 MB of a download +/// that has to stay under the 24 MiB web size gate. +fn cut_to_catalogs(font: &[u8], catalogs: &[char]) -> Result, String> { + let font = FontRef::new(font).map_err(|e| e.to_string())?; + let mut unicodes = IntSet::::empty(); + unicodes.extend((0x20..=0xFF).chain(0x2000..=0x206F).chain(0x3000..=0x303F).chain(0x3040..=0x30FF).chain(catalogs.iter().map(|c| *c as u32))); + subset(&font, &unicodes) +} + +/// `font` with the glyphs for `unicodes` only; layout features, hinting and the face's names are +/// kept, as craft-libs' `craft-fonts-build` subsets. +fn subset(font: &FontRef, unicodes: &IntSet) -> Result, String> { let mut name_ids = IntSet::::empty(); name_ids.insert_range(NameId::new(0)..=NameId::new(6)); let mut languages = IntSet::::empty(); languages.insert(0x0409); let plan = Plan::new( &IntSet::::empty(), - &unicodes, - &font, + unicodes, + font, SubsetFlags::default(), &IntSet::::empty(), &IntSet::::all(), @@ -116,5 +154,5 @@ fn without_private_use(font: &[u8]) -> Result, String> { &name_ids, &languages, ); - subset_font(&font, &plan).map_err(|e| e.to_string()) + subset_font(font, &plan).map_err(|e| e.to_string()) } diff --git a/crates/ui-egui/i18n_build.rs b/crates/ui-egui/i18n_build.rs index cf6ba7e4..58eaae8b 100644 --- a/crates/ui-egui/i18n_build.rs +++ b/crates/ui-egui/i18n_build.rs @@ -2,16 +2,16 @@ use std::fmt::Write as _; use std::path::Path; -/// Generate Rust includes for the optional catalog checkout; required input must contain app catalogs. -/// Paths are escaped as Rust strings so Windows separators and spaces remain valid. -pub fn generate(dir: Option<&Path>, required: bool) -> Result { +/// The catalogs' Rust includes and the distinct characters they use, sorted: the web build cuts +/// its CJK interface face to those characters. +pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec), String> { let mut source = String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"); let Some(dir) = dir else { if required { return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into()); } source.push_str("];\n"); - return Ok(source); + return Ok((source, Vec::new())); }; if !dir.is_absolute() { @@ -32,6 +32,7 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { paths.sort(); let mut count = 0; let mut catalogs = Vec::new(); + let mut characters = Vec::new(); for path in paths { // Watch directories so adding or removing an app catalog rebuilds the embedding println!("cargo::rerun-if-changed={}", path.display()); @@ -52,6 +53,7 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { }; let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") }; let (app, app_text) = embed(&app)?; + characters.extend(shared_text.chars().chain(app_text.chars())); let code: &'static str = Box::leak(locale.to_owned().into_boxed_str()); catalogs.push((code, shared_text, app_text)); let _ = writeln!(source, " ({locale:?}, {shared}, {app}),"); @@ -69,25 +71,30 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result { } source.push_str("];\n"); - Ok(source) + characters.sort_unstable(); + characters.dedup(); + Ok((source, characters)) } /// Write the embedding for both desktop and wasm, reporting optional failures as warnings. /// Required input errors stop Cargo instead of silently shipping an English-only release. -pub fn embed() { +/// +/// Returns the distinct characters the embedded catalogs use: the web build cuts its CJK interface +/// face to them, since every character kept costs glyph data in the wasm download. +pub fn embed() -> Vec { println!("cargo::rerun-if-env-changed=CRAFT_I18N_DIR"); println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED"); let dir = std::env::var_os("CRAFT_I18N_DIR").map(std::path::PathBuf::from); let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v == "1"); - let source = match generate(dir.as_deref(), required) { - Ok(source) => source, + let (source, characters) = match collect(dir.as_deref(), required) { + Ok(embedded) => embedded, Err(error) => { if required { println!("cargo::error={error}"); } else { println!("cargo::warning=building without craft-i18n: {error}"); } - "pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into() + ("pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into(), Vec::new()) } }; @@ -95,4 +102,5 @@ pub fn embed() { if let Err(error) = std::fs::write(&out, source) { println!("cargo::error=writing {}: {error}", out.display()); } + characters } diff --git a/crates/ui-egui/tests/i18n_build.rs b/crates/ui-egui/tests/i18n_build.rs index c972cfc7..d2d690de 100644 --- a/crates/ui-egui/tests/i18n_build.rs +++ b/crates/ui-egui/tests/i18n_build.rs @@ -3,6 +3,12 @@ #[allow(dead_code)] // The production build entry point is not invoked by these pure-input tests. mod i18n_build; +/// The catalogs' Rust includes alone, which is what these tests assert on; the build itself asks +/// [`i18n_build::collect`] for the characters its web font cut needs as well. +fn generate(dir: Option<&std::path::Path>, required: bool) -> Result { + i18n_build::collect(dir, required).map(|(source, _)| source) +} + use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -23,23 +29,23 @@ impl Drop for Fixture { #[test] fn no_input_is_english_but_required_input_errors() { - assert!(!i18n_build::generate(None, false).unwrap().contains("include_str!")); - assert!(i18n_build::generate(None, true).is_err()); + assert!(!generate(None, false).unwrap().contains("include_str!")); + assert!(generate(None, true).is_err()); } #[test] fn invalid_and_relative_checkouts_are_rejected() { let fixture = Fixture::new(); - assert!(i18n_build::generate(Some(&fixture.0.join("missing")), false).is_err()); - assert!(i18n_build::generate(Some(std::path::Path::new("relative")), false).is_err()); + assert!(generate(Some(&fixture.0.join("missing")), false).is_err()); + assert!(generate(Some(std::path::Path::new("relative")), false).is_err()); } #[test] fn shared_only_locale_is_not_offered_and_required_needs_app_catalog() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/common.tsv"), "\tSave\tGuardar\n").unwrap(); - assert!(!i18n_build::generate(Some(&fixture.0), false).unwrap().contains("include_str!")); - assert!(i18n_build::generate(Some(&fixture.0), true).is_err()); + assert!(!generate(Some(&fixture.0), false).unwrap().contains("include_str!")); + assert!(generate(Some(&fixture.0), true).is_err()); } #[test] @@ -47,26 +53,26 @@ fn app_catalog_is_embedded_with_optional_shared_catalog() { let fixture = Fixture::new(); let app = fixture.0.join("locales/es/texturecraft.tsv"); std::fs::write(&app, "\tLayers\tCapas\n").unwrap(); - let source = i18n_build::generate(Some(&fixture.0), true).unwrap(); + let source = generate(Some(&fixture.0), true).unwrap(); assert!(source.contains("texturecraft.tsv")); assert!(source.contains("(\"es\", \"\",")); let common = fixture.0.join("locales/es/common.tsv"); std::fs::write(&common, "\tSave\tGuardar\n").unwrap(); - assert!(i18n_build::generate(Some(&fixture.0), true).unwrap().contains("common.tsv")); + assert!(generate(Some(&fixture.0), true).unwrap().contains("common.tsv")); } #[test] fn unreadable_catalog_fails_before_generating_rust_source() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), [0xff, 0xfe]).unwrap(); - assert!(i18n_build::generate(Some(&fixture.0), true).is_err()); + assert!(generate(Some(&fixture.0), true).is_err()); } #[test] fn generated_paths_compile_and_embed_the_catalog_contents() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); - let generated = i18n_build::generate(Some(&fixture.0), true).unwrap(); + let generated = generate(Some(&fixture.0), true).unwrap(); let program = format!( "extern crate self as craft_i18n;\npub type Embedded = [(&'static str, &'static str, &'static str)];\n{generated}\nfn main() {{ assert_eq!(CRAFT_I18N[0].2, \"\\tLayers\\tCapas\\n\"); }}" ); @@ -93,8 +99,35 @@ fn malformed_utf8_catalogs_and_invalid_rows_fail_during_generation() { std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); std::fs::write(fixture.0.join("locales/es").join(file), invalid).unwrap(); for required in [false, true] { - assert!(i18n_build::generate(Some(&fixture.0), required).is_err(), "accepted {file}: {invalid:?}"); + assert!(generate(Some(&fixture.0), required).is_err(), "accepted {file}: {invalid:?}"); } } } } + +#[test] +fn the_catalog_characters_are_the_ones_the_web_font_keeps() { + let fixture = Fixture::new(); + std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); + std::fs::write(fixture.0.join("locales/es/common.tsv"), "\tSave\tGuardar\n").unwrap(); + std::fs::create_dir_all(fixture.0.join("locales/ja")).unwrap(); + std::fs::write(fixture.0.join("locales/ja/texturecraft.tsv"), "\tLayers\t\u{30ec}\u{30a4}\u{30e4}\u{30fc}\n").unwrap(); + // A shared-only locale contributes no characters: its catalog is not embedded. + std::fs::create_dir_all(fixture.0.join("locales/de")).unwrap(); + std::fs::write(fixture.0.join("locales/de/common.tsv"), "\tSave\tSpeichern \u{fc}\n").unwrap(); + + let (source, characters) = i18n_build::collect(Some(&fixture.0), true).unwrap(); + assert!(source.contains("texturecraft.tsv")); + for used in ['L', 'a', 'y', 'e', 'r', 's', 'C', 'p', 'G', 'u', 'd', '\u{30ec}', '\u{30a4}', '\u{30e4}', '\u{30fc}'] { + assert!(characters.contains(&used), "missing {used:?}"); + } + assert!(!characters.contains(&'\u{fc}'), "the shared-only de catalog is not embedded"); + let mut sorted = characters.clone(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted, characters, "sorted and distinct"); + + // Nothing to cut with no checkout: the web build then keeps the faces whole. + assert_eq!(i18n_build::collect(None, false).unwrap().1, Vec::::new()); + assert!(i18n_build::collect(None, true).is_err()); +} From 95d90ee4532f6cb19e4cbfccf357e51b74ad6c3a Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:21:37 +0100 Subject: [PATCH 158/190] Parity: RFC-0052 headless column in the parity report (#888) docs/parity.md gets a headless column computed from the engine registry that texturecraft-cli and the MCP server load: 21 yes, 40 no (window 33, os 5, engine-gap 2), 3 partial, 0 unknown of 64 items, per RFC-0052. --- AGENTS.md | 2 +- crates/ui-egui/src/parity.rs | 130 ++++++++++++++++++++++++++++- docs/parity.md | 154 ++++++++++++++++++----------------- 3 files changed, 207 insertions(+), 79 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e42b5d53..63517554 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,7 +63,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119 ## This repository -TextureCraft is an open-source, native 3D texture painter in Rust: a native egui/eframe app on wgpu, a headless CLI and MCP server, and the same app in the browser (trunk, wasm-bindgen). The project extension is `.tcraft`. Crates are `texturecraft-*`; the product name is written TextureCraft. MaterialCraft's `.mcmat` portable materials are read here through the shared `craft-mcmat` format crate (craft-libs), with the app's own checks in `formats::mcmat`; each app keeps its own models and policy. Start with `docs/architecture.md`, `docs/control-protocol.md`, `ROADMAP.md` and `docs/parity.md`. +TextureCraft is an open-source, native 3D texture painter in Rust: a native egui/eframe app on wgpu, a headless CLI and MCP server, and the same app in the browser (trunk, wasm-bindgen). The project extension is `.tcraft`. Crates are `texturecraft-*`; the product name is written TextureCraft. MaterialCraft's `.mcmat` portable materials are read here through the shared `craft-mcmat` format crate (craft-libs), with the app's own checks in `formats::mcmat`; each app keeps its own models and policy. Start with `docs/architecture.md`, `docs/control-protocol.md`, `ROADMAP.md` and `docs/parity.md`. `docs/parity.md` carries the [RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md) Headless column: `yes` only when the id is an engine command (`texturecraft_engine::find`), which `texturecraft-cli` and the MCP server reach. A `ui.*` id is live in the desktop app only and gets a `no`/`partial` mark with a `window`, `os` or `engine-gap` reach in `HEADLESS` (`crates/ui-egui/src/parity.rs`). Never write `yes` there. Regenerate with `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. ### Layout ```text diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs index 50b51a55..23316b2b 100644 --- a/crates/ui-egui/src/parity.rs +++ b/crates/ui-egui/src/parity.rs @@ -6,6 +6,83 @@ use crate::menus::{CATALOG, implemented}; /// Live menu items must never drop below this (raise it when parity rises). pub const FLOOR: usize = 51; +/// RFC-0052 hand marks for catalog ids that aren't engine commands: `(id, headless, reach, why)`. +/// +/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer), +/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine +/// command, isn't one yet). `yes` is never written here: an item is `yes` only when its id is an +/// engine command (`texturecraft_engine::find`), the registry `texturecraft-cli` and the MCP server +/// load. A `ui.*` id is live in the desktop app only. An unmarked id is `unknown`. +pub const HEADLESS: &[(&str, &str, &str, &str)] = &[ + ("ui.newProject", "partial", "window", "the dialog is desktop-only; `project.new` creates the project"), + ("ui.saveAsTemplate", "partial", "window", "the dialog is desktop-only; `project.template.save` saves it"), + ("ui.export", "partial", "window", "the dialog is desktop-only; `file.exportTextures` exports"), + ("ui.saveReduced", "no", "engine-gap", "a smaller save could be a command"), + ("ui.projectConfig", "no", "engine-gap", "project settings could be set by a command"), + ("ui.recent.clear", "no", "window", "the desktop recent-projects list"), + ("ui.quit", "no", "window", "quits the desktop app"), + ("ui.settings", "no", "window", "the desktop settings window"), + ("ui.mode.bake", "no", "window", "switches the desktop workspace; `bake.run` bakes"), + ("ui.mode.paint", "no", "window", "switches the desktop workspace"), + ("ui.mode.render", "no", "window", "switches the desktop workspace"), + ("ui.layout.save.painting", "no", "window", "desktop window layout"), + ("ui.layout.save.rendering", "no", "window", "desktop window layout"), + ("ui.layout.save.baking", "no", "window", "desktop window layout"), + ("ui.layout.load", "no", "window", "desktop window layout"), + ("ui.hideUi", "no", "window", "desktop window layout"), + ("ui.resetUi", "no", "window", "desktop window layout"), + ("ui.help.releaseNotes", "no", "os", "opens a web page in the browser"), + ("ui.help.docs", "no", "os", "opens a web page in the browser"), + ("ui.help.discord", "no", "os", "opens a web page in the browser"), + ("ui.help.bug", "no", "os", "opens a web page in the browser"), + ("ui.help.checkForUpdates", "no", "os", "an online update check"), + ("ui.help.shortcuts", "no", "window", "a desktop window"), + ("ui.help.showLog", "no", "window", "a desktop window"), + ("ui.help.exportLog", "no", "window", "saves the desktop app's log"), + ("ui.about", "no", "window", "a desktop window"), +]; + +/// Prefixes whose every id opens or arranges a desktop panel (`no`, `window`). +const WINDOW_PREFIXES: [&str; 2] = ["ui.view.", "ui.toolbar."]; + +/// An item's RFC-0052 `(headless, reach, why)`: `yes` for an engine command, else its mark, else +/// `unknown`. +pub fn headless_of(id: &str, in_engine: bool) -> (&'static str, Option<&'static str>, &'static str) { + if in_engine { + return ("yes", None, ""); + } + if let Some(m) = HEADLESS.iter().find(|m| m.0 == id) { + return (m.1, Some(m.2), m.3); + } + if WINDOW_PREFIXES.iter().any(|p| id.starts_with(p)) { + return ("no", Some("window"), "a desktop panel or toolbar"); + } + ("unknown", None, "") +} + +/// Problems with `marks` against `ids` (`(id, is an engine command)`): bad values, repeats, ids +/// not in the catalog, and marks on engine commands (they would hide a `yes`). +pub fn headless_errors(marks: &[(&str, &str, &str, &str)], ids: &[(&str, bool)]) -> Vec { + let mut errs = Vec::new(); + for (i, (id, value, reach, _)) in marks.iter().enumerate() { + if !matches!(*value, "no" | "partial") { + errs.push(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)")); + } + if !matches!(*reach, "window" | "os" | "engine-gap") { + errs.push(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap")); + } + if marks[..i].iter().any(|m| m.0 == *id) { + errs.push(format!("headless mark `{id}` is written twice")); + } + match ids.iter().find(|x| x.0 == *id) { + None => errs.push(format!("headless mark `{id}` is not a catalog id")), + Some((_, true)) => errs.push(format!("headless mark `{id}` is stale: it is an engine command, so it is `yes`")), + Some(_) => {} + } + } + errs +} + /// (live, total) over the catalog, separators excluded. pub fn counts() -> (usize, usize) { let items: Vec<_> = CATALOG.iter().filter(|i| i.label != "-").collect(); @@ -20,15 +97,32 @@ pub fn report() -> String { out.push_str("Each row is a menu item of the target menu layout with TextureCraft's command id; "); out.push_str("**live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md).\n\n"); out.push_str(&format!("**{live} of {total} menu items live ({:.0}%).**\n\n", live as f32 * 100.0 / total.max(1) as f32)); + let values: Vec<_> = CATALOG.iter().filter(|i| i.label != "-").map(|i| headless_of(i.id, texturecraft_engine::find(i.id).is_some())).collect(); + let count = |v: &str| values.iter().filter(|h| h.0 == v).count(); + let no = |r: &str| values.iter().filter(|h| h.0 == "no" && h.1 == Some(r)).count(); + out.push_str(&format!( + "**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** ", + count("yes"), + count("no"), + no("window"), + no("os"), + no("engine-gap"), + count("partial"), + count("unknown") + )); + out.push_str("An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. "); + out.push_str("A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`).\n\n"); for top in crate::menus::TOP { - out.push_str(&format!("## {top}\n\n| Item | Id | Shortcut | Status |\n|---|---|---|---|\n")); + out.push_str(&format!("## {top}\n\n| Item | Id | Shortcut | Status | Headless |\n|---|---|---|---|---|\n")); for i in CATALOG.iter().filter(|i| i.menu == top && i.label != "-") { let label = match i.sub { Some(s) => format!("{s} ▸ {}", i.label), None => i.label.to_string(), }; let status = if implemented(i.id) { "live" } else { "missing" }; - out.push_str(&format!("| {label} | `{}` | {} | {status} |\n", i.id, i.shortcut.unwrap_or(""))); + let (value, reach, why) = headless_of(i.id, texturecraft_engine::find(i.id).is_some()); + let headless = reach.map_or_else(|| value.to_string(), |r| format!("{value}, reach: {r} ({why})")); + out.push_str(&format!("| {label} | `{}` | {} | {status} | {headless} |\n", i.id, i.shortcut.unwrap_or(""))); } out.push('\n'); } @@ -39,6 +133,38 @@ pub fn report() -> String { mod tests { use super::*; + #[test] + fn headless_marks_are_current() { + let ids: Vec<(&str, bool)> = CATALOG.iter().filter(|i| i.label != "-").map(|i| (i.id, texturecraft_engine::find(i.id).is_some())).collect(); + let errs = headless_errors(HEADLESS, &ids); + assert!(errs.is_empty(), "{errs:?}"); + } + + #[test] + fn a_desktop_only_id_is_live_but_not_headless() { + assert!(implemented("ui.export"), "live in the desktop app"); + assert_eq!(headless_of("ui.export", false).0, "partial"); + assert_eq!(headless_of("ui.view.layers", false), ("no", Some("window"), "a desktop panel or toolbar")); + assert_eq!(headless_of("file.save", true).0, "yes"); + assert_eq!(headless_of("ui.unheardOf", false).0, "unknown"); + let r = report(); + assert!(r.contains("| `file.save` | Ctrl+S | live | yes |"), "{r}"); + let (live, _) = counts(); + let yes = CATALOG.iter().filter(|i| i.label != "-" && texturecraft_engine::find(i.id).is_some()).count(); + assert!(yes < live, "the ui.* ids are live but not headless"); + assert!(r.contains(&format!("{yes} yes,")), "{r}"); + } + + #[test] + fn bad_headless_marks_are_refused() { + let ids = [("a.b", true), ("c.d", false)]; + let marks = [("c.d", "yes", "os", ""), ("c.d", "no", "desk", ""), ("a.b", "no", "os", ""), ("z.z", "no", "os", "")]; + let errs = headless_errors(&marks, &ids); + for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`a.b` is stale", "`z.z` is not a catalog id"] { + assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}"); + } + } + #[test] fn parity_floor_and_report() { let (live, total) = counts(); diff --git a/docs/parity.md b/docs/parity.md index a8bc242d..46707737 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -4,97 +4,99 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac **63 of 64 menu items live (98%).** +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 21 yes, 40 no (window 33, os 5, engine-gap 2), 3 partial, 0 unknown.** An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`). + ## File -| Item | Id | Shortcut | Status | -|---|---|---|---| -| New Project | `ui.newProject` | Ctrl+N | live | -| Open | `file.open` | Ctrl+O | live | -| Recent Projects ▸ Clear | `ui.recent.clear` | | live | -| Open Sample Project | `project.sample` | | live | -| Close | `file.close` | Ctrl+F4 | live | -| Save | `file.save` | Ctrl+S | live | -| Save As | `file.saveAs` | Ctrl+Shift+S | live | -| More Save Options ▸ Save As Template | `ui.saveAsTemplate` | | live | -| More Save Options ▸ Save and Reduce File Size | `ui.saveReduced` | | missing | -| More Save Options ▸ Save As Copy | `file.saveCopy` | | live | -| Remove Unused Resources | `file.removeUnused` | | live | -| Import Resources | `resource.import` | | live | -| Export Textures | `ui.export` | Ctrl+Shift+E | live | -| Export Mesh | `file.exportMesh` | | live | -| Quit | `ui.quit` | Ctrl+Q | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| New Project | `ui.newProject` | Ctrl+N | live | partial, reach: window (the dialog is desktop-only; `project.new` creates the project) | +| Open | `file.open` | Ctrl+O | live | yes | +| Recent Projects ▸ Clear | `ui.recent.clear` | | live | no, reach: window (the desktop recent-projects list) | +| Open Sample Project | `project.sample` | | live | yes | +| Close | `file.close` | Ctrl+F4 | live | yes | +| Save | `file.save` | Ctrl+S | live | yes | +| Save As | `file.saveAs` | Ctrl+Shift+S | live | yes | +| More Save Options ▸ Save As Template | `ui.saveAsTemplate` | | live | partial, reach: window (the dialog is desktop-only; `project.template.save` saves it) | +| More Save Options ▸ Save and Reduce File Size | `ui.saveReduced` | | missing | no, reach: engine-gap (a smaller save could be a command) | +| More Save Options ▸ Save As Copy | `file.saveCopy` | | live | yes | +| Remove Unused Resources | `file.removeUnused` | | live | yes | +| Import Resources | `resource.import` | | live | yes | +| Export Textures | `ui.export` | Ctrl+Shift+E | live | partial, reach: window (the dialog is desktop-only; `file.exportTextures` exports) | +| Export Mesh | `file.exportMesh` | | live | yes | +| Quit | `ui.quit` | Ctrl+Q | live | no, reach: window (quits the desktop app) | ## Edit -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Undo | `edit.undo` | Ctrl+Z | live | -| Redo | `edit.redo` | Ctrl+Y | live | -| Project Configuration | `ui.projectConfig` | | live | -| Reimport Mesh | `file.reimportMesh` | Ctrl+Shift+R | live | -| Settings | `ui.settings` | | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Undo | `edit.undo` | Ctrl+Z | live | yes | +| Redo | `edit.redo` | Ctrl+Y | live | yes | +| Project Configuration | `ui.projectConfig` | | live | no, reach: engine-gap (project settings could be set by a command) | +| Reimport Mesh | `file.reimportMesh` | Ctrl+Shift+R | live | yes | +| Settings | `ui.settings` | | live | no, reach: window (the desktop settings window) | ## Mode -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Bake Mesh Maps | `ui.mode.bake` | F8 | live | -| Painting | `ui.mode.paint` | F9 | live | -| Rendering | `ui.mode.render` | F10 | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Bake Mesh Maps | `ui.mode.bake` | F8 | live | no, reach: window (switches the desktop workspace; `bake.run` bakes) | +| Painting | `ui.mode.paint` | F9 | live | no, reach: window (switches the desktop workspace) | +| Rendering | `ui.mode.render` | F10 | live | no, reach: window (switches the desktop workspace) | ## Window -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Views ▸ Assets | `ui.view.assets` | | live | -| Views ▸ Baking Log | `ui.view.bakingLog` | | live | -| Views ▸ Common Settings | `ui.view.bakeSettings` | | live | -| Views ▸ Display Settings | `ui.view.display` | | live | -| Views ▸ Export | `ui.view.export` | | live | -| Views ▸ History | `ui.view.history` | | live | -| Views ▸ Layers | `ui.view.layers` | | live | -| Views ▸ Log | `ui.view.log` | | live | -| Views ▸ Mesh Map Bakers | `ui.view.meshMapBakers` | | live | -| Views ▸ Mesh Map Settings | `ui.view.bakeMaps` | | live | -| Views ▸ Properties | `ui.view.properties` | | live | -| Views ▸ Renderer Settings | `ui.view.renderer` | | live | -| Views ▸ Shader Settings | `ui.view.shader` | | live | -| Views ▸ Texture Set List | `ui.view.textureSetList` | | live | -| Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | -| Toolbars ▸ Docks | `ui.toolbar.docks` | | live | -| Toolbars ▸ Tools | `ui.toolbar.tools` | | live | -| Save UI Layout ▸ Painting Mode | `ui.layout.save.painting` | | live | -| Save UI Layout ▸ Rendering Mode | `ui.layout.save.rendering` | | live | -| Save UI Layout ▸ Baking Mode | `ui.layout.save.baking` | | live | -| Load UI Layout | `ui.layout.load` | | live | -| Hide UI | `ui.hideUi` | Tab | live | -| Reset UI | `ui.resetUi` | | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Views ▸ Assets | `ui.view.assets` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Baking Log | `ui.view.bakingLog` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Common Settings | `ui.view.bakeSettings` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Display Settings | `ui.view.display` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Export | `ui.view.export` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ History | `ui.view.history` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Layers | `ui.view.layers` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Log | `ui.view.log` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Mesh Map Bakers | `ui.view.meshMapBakers` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Mesh Map Settings | `ui.view.bakeMaps` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Properties | `ui.view.properties` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Renderer Settings | `ui.view.renderer` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Shader Settings | `ui.view.shader` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Texture Set List | `ui.view.textureSetList` | | live | no, reach: window (a desktop panel or toolbar) | +| Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | no, reach: window (a desktop panel or toolbar) | +| Toolbars ▸ Docks | `ui.toolbar.docks` | | live | no, reach: window (a desktop panel or toolbar) | +| Toolbars ▸ Tools | `ui.toolbar.tools` | | live | no, reach: window (a desktop panel or toolbar) | +| Save UI Layout ▸ Painting Mode | `ui.layout.save.painting` | | live | no, reach: window (desktop window layout) | +| Save UI Layout ▸ Rendering Mode | `ui.layout.save.rendering` | | live | no, reach: window (desktop window layout) | +| Save UI Layout ▸ Baking Mode | `ui.layout.save.baking` | | live | no, reach: window (desktop window layout) | +| Load UI Layout | `ui.layout.load` | | live | no, reach: window (desktop window layout) | +| Hide UI | `ui.hideUi` | Tab | live | no, reach: window (desktop window layout) | +| Reset UI | `ui.resetUi` | | live | no, reach: window (desktop window layout) | ## Viewport -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Display Material | `viewport.displayMaterial` | M | live | -| Display Next Channel | `viewport.nextChannel` | C | live | -| Display Previous Channel | `viewport.previousChannel` | Shift+C | live | -| Display Next Mesh Map | `viewport.nextMeshMap` | B | live | -| Display Previous Mesh Map | `viewport.previousMeshMap` | Shift+B | live | -| Show Entire Mesh/Path | `viewport.frame` | F | live | -| Enable Quick Mask | `viewport.quickMask` | Y | live | -| Edit Quick Mask | `viewport.quickMask.edit` | U | live | -| Invert Quick Mask | `viewport.quickMask.invert` | Ctrl+Shift+I | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Display Material | `viewport.displayMaterial` | M | live | yes | +| Display Next Channel | `viewport.nextChannel` | C | live | yes | +| Display Previous Channel | `viewport.previousChannel` | Shift+C | live | yes | +| Display Next Mesh Map | `viewport.nextMeshMap` | B | live | yes | +| Display Previous Mesh Map | `viewport.previousMeshMap` | Shift+B | live | yes | +| Show Entire Mesh/Path | `viewport.frame` | F | live | yes | +| Enable Quick Mask | `viewport.quickMask` | Y | live | yes | +| Edit Quick Mask | `viewport.quickMask.edit` | U | live | yes | +| Invert Quick Mask | `viewport.quickMask.invert` | Ctrl+Shift+I | live | yes | ## Help -| Item | Id | Shortcut | Status | -|---|---|---|---| -| Release Notes | `ui.help.releaseNotes` | | live | -| Documentation | `ui.help.docs` | | live | -| Shortcuts List | `ui.help.shortcuts` | | live | -| Discord | `ui.help.discord` | | live | -| Report a Bug | `ui.help.bug` | | live | -| Show Log | `ui.help.showLog` | | live | -| Export Log | `ui.help.exportLog` | | live | -| Check for Updates | `ui.help.checkForUpdates` | | live | -| About TextureCraft | `ui.about` | | live | +| Item | Id | Shortcut | Status | Headless | +|---|---|---|---|---| +| Release Notes | `ui.help.releaseNotes` | | live | no, reach: os (opens a web page in the browser) | +| Documentation | `ui.help.docs` | | live | no, reach: os (opens a web page in the browser) | +| Shortcuts List | `ui.help.shortcuts` | | live | no, reach: window (a desktop window) | +| Discord | `ui.help.discord` | | live | no, reach: os (opens a web page in the browser) | +| Report a Bug | `ui.help.bug` | | live | no, reach: os (opens a web page in the browser) | +| Show Log | `ui.help.showLog` | | live | no, reach: window (a desktop window) | +| Export Log | `ui.help.exportLog` | | live | no, reach: window (saves the desktop app's log) | +| Check for Updates | `ui.help.checkForUpdates` | | live | no, reach: os (an online update check) | +| About TextureCraft | `ui.about` | | live | no, reach: window (a desktop window) | From 4c181c99041912c2814eb1ac1e640c14ebc30de8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:30:42 +0000 Subject: [PATCH 159/190] docs: say the stencil is skipped on the quick mask and in the 2D UV view --- docs/features.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/features.md b/docs/features.md index dc27828f..d04b9229 100644 --- a/docs/features.md +++ b/docs/features.md @@ -17,7 +17,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA stroke and keep the size. The Brush section's **Brush presets** popover (and the shelf) also keeps your own: save the current brush, click to use it, rename, replace or delete it. - **Tools:** paint, eraser, **projection** (paints an image's colors), a **stencil** every brush tool - paints through (its gray masks the stroke; hold S to move, turn and scale it), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a + paints through (its gray masks the stroke; hold S to move, turn and scale it; painting the quick mask, + or in the 2D UV view with any tool but projection, ignores the stencil), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a **particle brush**, **smudge**, **clone** (V + click sets the source, marked in the 3D and 2D views; an Aligned option keeps or restarts the offset per stroke), material picker, Shift+click straight lines (Ctrl+Shift+click snaps them to 15 degree steps), and painting directly in the **2D UV view**. From 8c06badf771be52192e49430eaa5bf15e3059dfa Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:16:26 -0500 Subject: [PATCH 160/190] fix(engine): find MaterialCraft in the launcher's sibling folder, tested in a temp dir A pure find_installed_tool(app_dir, exe) is tested in a temp folder (sibling found, beside-the-program wins, missing is None) instead of writing into target/. The 'did not start' hints name the sibling folder; control-protocol.md lists the step. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/link_cmds.rs | 60 ++++++++++++++++++-- crates/engine/src/link_cmds/link_job.rs | 2 +- crates/engine/tests/materialcraft_sibling.rs | 17 ------ docs/control-protocol.md | 2 +- 4 files changed, 56 insertions(+), 25 deletions(-) delete mode 100644 crates/engine/tests/materialcraft_sibling.rs diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index db52a8b6..b5567e31 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -226,10 +226,18 @@ pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf { } let exe = format!("{name}{}", std::env::consts::EXE_SUFFIX); - let dir = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf)); - let beside = dir.as_ref().map(|d| d.join(&exe)); - let sibling = dir.as_ref().and_then(|d| Some(d.parent()?.join("MaterialCraft").join(&exe))); - beside.into_iter().chain(sibling).find(|p| p.is_file()).unwrap_or_else(|| exe.into()) + let app_dir = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf)); + app_dir.and_then(|d| find_installed_tool(&d, &exe)).unwrap_or_else(|| exe.into()) +} + +/// `exe` in `app_dir` (next to this program), else in the sibling `MaterialCraft` folder beside `app_dir` +/// (`/TextureCraft` and `/MaterialCraft`, as the ArtCraft Launcher installs them). `None` if neither has it. +/// Versioned `//` layouts and macOS `.app` bundles are not searched. +#[cfg(not(target_arch = "wasm32"))] +fn find_installed_tool(app_dir: &std::path::Path, exe: &str) -> Option { + let beside = app_dir.join(exe); + let sibling = app_dir.parent().map(|root| root.join("MaterialCraft").join(exe)); + std::iter::once(beside).chain(sibling).find(|p| p.is_file()) } /// A command for a MaterialCraft executable that opens no console window. @@ -243,12 +251,15 @@ fn quiet(program: &std::path::Path) -> std::process::Command { } /// Open `package` (a published material or authoring package) in the MaterialCraft app (`$MATERIALCRAFT`, next to this -/// program, or on `PATH`). +/// program, in the sibling `MaterialCraft` folder, or on `PATH`). #[cfg(not(target_arch = "wasm32"))] pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { let app = materialcraft_tool("materialcraft", "MATERIALCRAFT"); quiet(&app).arg(package).spawn().map(drop).map_err(|e| { - EngineError::Other(format!("MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT", app.display())) + EngineError::Other(format!( + "MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT", + app.display() + )) }) } @@ -582,4 +593,41 @@ mod tests { assert_eq!(typed(&p, &json!("#+f+f+f")), None); assert!(typed(&p, &json!("#ff8000")).is_some()); } + + #[cfg(not(target_arch = "wasm32"))] + fn touch(dir: &std::path::Path, exe: &str) -> std::path::PathBuf { + std::fs::create_dir_all(dir).unwrap(); + let p = dir.join(exe); + std::fs::write(&p, b"").unwrap(); + p + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn launcher_layout_finds_the_sibling_materialcraft_folder() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(&app).unwrap(); + let tool = touch(&root.path().join("MaterialCraft"), "materialcraft-cli"); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(tool)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_tool_beside_the_program_wins_over_the_sibling_folder() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + let beside = touch(&app, "materialcraft-cli"); + touch(&root.path().join("MaterialCraft"), "materialcraft-cli"); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(beside)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_missing_tool_is_none_so_the_caller_falls_back_to_path() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(root.path().join("MaterialCraft")).unwrap(); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None); + } } diff --git a/crates/engine/src/link_cmds/link_job.rs b/crates/engine/src/link_cmds/link_job.rs index 2bfb8595..1c530f07 100644 --- a/crates/engine/src/link_cmds/link_job.rs +++ b/crates/engine/src/link_cmds/link_job.rs @@ -118,7 +118,7 @@ fn run_bounded(command: &std::process::Command, stdout: &Path, stderr: &Path, re .stdout(std::fs::File::create(stdout).map_err(io)?) .stderr(std::fs::File::create(stderr).map_err(io)?) .spawn() - .map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft or set MATERIALCRAFT_CLI")))?; + .map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT_CLI")))?; loop { if canceled.load(Ordering::Relaxed) { diff --git a/crates/engine/tests/materialcraft_sibling.rs b/crates/engine/tests/materialcraft_sibling.rs deleted file mode 100644 index 7a69f713..00000000 --- a/crates/engine/tests/materialcraft_sibling.rs +++ /dev/null @@ -1,17 +0,0 @@ -//! A launcher install puts each app in its own folder: `/TextureCraft` and `/MaterialCraft`. - -#[cfg(not(target_arch = "wasm32"))] -#[test] -fn finds_materialcraft_in_sibling_app_folder() { - let exe = std::env::current_exe().unwrap(); - let root = exe.parent().unwrap().parent().unwrap(); - let dir = root.join("MaterialCraft"); - let name = "mc-sibling-probe"; - let file = format!("{name}{}", std::env::consts::EXE_SUFFIX); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join(&file), b"").unwrap(); - let found = texturecraft_engine::link_cmds::materialcraft_tool(name, "TEXTURECRAFT_TEST_UNSET_ENV"); - std::fs::remove_file(dir.join(&file)).unwrap(); - let _ = std::fs::remove_dir(&dir); - assert_eq!(found, dir.join(&file)); -} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f0e01239..c52aaf08 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -517,7 +517,7 @@ operation returns a busy error and can be retried. | `material.link.saveSource` | `{layer?, path}`: the original linked source with its `.mcmat`, `.mcraft` or `.sbs` extension | For a 1024-pixel texture set, TextureCraft requests `materialcraft-cli export source.mcmat maps --profile maps --size 1024x1024` with repeated `--set` and `--input` arguments. It discovers the published image inputs through `info` when the texture set supplies mesh maps. The desktop worker decodes the returned maps before installing the fill at its original drop target. The executable is resolved from -`$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH` +`$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else in a `MaterialCraft` folder beside TextureCraft's own folder (the launcher's layout), else on `PATH` (the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`, `worldNormal`, `normal`, `height`, `id`, `bentNormal`, `opacity`, `colorMap`, `worldDirection`; From 31bf2a58caf09600f47c23ebea667e08cac2bbdd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:33:59 +0000 Subject: [PATCH 161/190] Assets: Remove unused keeps the package and maps of a material linked in a content effect images_used counted a linked material's package and cooked maps only on a fill layer, so Remove unused dropped them (and a smart material left them out) when the link sat in a content fill effect. --- crates/engine/src/material_lib.rs | 20 ++++++++++++++------ crates/engine/tests/it/materialcraft_link.rs | 2 +- crates/engine/tests/it/resources_used.rs | 20 +++++++++++++++++++- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 9d496630..0277c6fc 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::Value; use texturecraft_compose::PixelStore; -use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{EffectKind, Fill, LayerId, LayerKind, Project, Source, TextureSet}; use crate::commands::{CommandSpec, always, has_layer}; use crate::materials::Place; @@ -36,7 +36,15 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and their patterns, mask or content effects and the images its paths paint with) +/// The package and cooked maps of the MaterialCraft material linked to `fill`, if any +fn link_images(fill: &Fill, out: &mut Vec) { + if let Some(link) = &fill.link { + out.push(link.package.clone()); + out.extend(link.outputs.values().cloned()); + } +} + +/// Image resources a layer subtree uses (fill sources and their patterns, linked materials, mask or content effects and the images its paths paint with) pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; @@ -46,15 +54,15 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, if let LayerKind::Fill(fill) = &layer.kind { out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string)); - if let Some(link) = &fill.link { - out.push(link.package.clone()); - out.extend(link.outputs.values().cloned()); - } + link_images(fill, out); } for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { out.extend(effect.images_read().map(str::to_string)); out.extend(crate::path_tool::path_images(&effect.kind)); + if let EffectKind::Material(fill) = &effect.kind { + link_images(fill, out); + } } for child in layer.children() { diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index 4a4a5d03..1ee696e1 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -47,7 +47,7 @@ fn cooked(roughness: f32, wear: f32) -> CookedMaterial { CookedMaterial::new(serde_json::from_value(interface).unwrap(), maps, 4) } -fn install(session: &mut Session) -> LayerId { +pub(crate) fn install(session: &mut Session) -> LayerId { session.add_cooked_material(&cooked(0.25, 0.5), Arc::new(b"package bytes".to_vec()), "mcmat", Place::Selection).unwrap() } diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index bd89ee77..fbc15d44 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -1,7 +1,7 @@ //! The images a project reads beyond fill sources: a colour selection's ID map, a filter's image input, the mask brush and its paths use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, LayerKind}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; @@ -53,6 +53,24 @@ fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mas assert_eq!(reply["removed"], json!([unused]), "only the image nothing reads goes"); } +#[test] +fn removing_unused_resources_keeps_the_package_and_maps_of_a_material_linked_in_a_content_effect() { + let mut session = session(); + let unused = session.import_resource_bytes("unused.png", white_png()).unwrap(); + let linked = crate::materialcraft_link::install(&mut session); + let LayerKind::Fill(fill) = session.doc.project.layer(linked).unwrap().kind.clone() else { panic!("not a fill") }; + + // The linked material moves into a content effect of another layer, the only place that uses it + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let effect = LayerId(execute(&mut session, "effect.add.fill", &json!({"layer": layer, "target": "content"})).unwrap()["effect"].as_u64().unwrap()); + session.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Material(fill); + execute(&mut session, "layer.remove", &json!({"layer": linked.0})).unwrap(); + + let reply = execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert_eq!(reply["removed"], json!([unused]), "the linked package and its maps stay"); +} + #[test] fn a_smart_material_carries_the_images_its_selection_and_filter_input_read() { let mut session = session(); From 2798746cfc3ea7b9e6a8aad9dbf99262ac0c7600 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:35:26 +0000 Subject: [PATCH 162/190] Reach a mirror or transform across the longer side of a tall set's block, so a tile composited alone near its bottom reads the far end --- crates/compose/src/eval.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 29b7def6..4a138832 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1603,8 +1603,13 @@ fn filter_extent(radius: f32, op: Op, inputs: &Inputs) -> (u32, u32) { // Clamped so a hostile radius can't overflow the region arithmetic let radius_texels = radius.round().clamp(1.0, longest_side as f32) as u32; - // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel - let reach = if is_box_blur(op) { 3 * radius_texels } else { radius_texels + 1 }; + // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel. A + // mirror or transform reads anywhere in its block, so it reaches the block's longer side + let reach = match op { + Op::Mirror { .. } | Op::Transform { .. } => (radius_texels + 1).max(inputs.block_size().into_iter().max().unwrap_or(0)), + _ if is_box_blur(op) => 3 * radius_texels, + _ => radius_texels + 1, + }; // A shadow also reads the shapes it was moved from let moved = match op { @@ -6683,6 +6688,33 @@ soft {soft:?}" } } + /// A set taller than wide: a mirror or transform reads anywhere down its block, so a tile composited alone near the bottom matches the whole set + #[test] + fn a_tile_alone_on_a_tall_set_reads_a_mirror_or_transform_from_the_far_end() { + const WIDTH: u32 = 64; + const HEIGHT: u32 = 256; + let column_of = |out: &Composite| (HEIGHT - TILE..HEIGHT).map(|y| out.value(Channel::Roughness, 20, y)[0]).collect::>(); + let composite = |filter: &Filter, tiles: &[(u32, u32)]| { + let mut f = fixture(); + f.gbuf = UvGBuffer::new(&f.mesh, 0, WIDTH, HEIGHT); + f.project.texture_sets[0].set_size(WIDTH, HEIGHT); + checker_roughness(&mut f, Some(filter.clone())); + let images = ImageStore::default(); + let mut out = Composite::with_size(&f.project.texture_sets[0].channel_list(), WIDTH, HEIGHT); + composite_tiles(&inputs(&f, &images, None), &mut out, tiles); + column_of(&out) + }; + + let mirror = Filter::Mirror(Mirror { mode: texturecraft_core::MirrorMode::AxisY, ..Mirror::LIBRARY }); + let shift = Filter::Transform(TileTransform { offset: [0.0, 0.25], ..TileTransform::LIBRARY }); + for filter in [mirror, shift] { + let whole = composite(&filter, &all_tiles(WIDTH, HEIGHT)); + let bottom_tile = composite(&filter, &[(0, HEIGHT / TILE - 1)]); + let label = filter.label(); + assert!(whole.iter().zip(&bottom_tile).all(|(a, b)| (a - b).abs() < 1e-3), "{label}: the bottom tile alone\n{bottom_tile:?}\nwhole\n{whole:?}"); + } + } + #[test] fn a_gradients_blur_intensity_blurs_what_it_looks_up() { let row = |filter: Option| { From 827af86de3c1447c16a99ceca0474b1d845a3661 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:35:27 +0000 Subject: [PATCH 163/190] Repad the tiles whose padding continues across a seam from a changed tile, however far away they are --- crates/compose/src/eval.rs | 47 ++++++++++++++++++++++++++++-- crates/compose/src/padding_maps.rs | 17 ++++++++++- 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 4a138832..434c3d22 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4887,7 +4887,7 @@ fn store_below(cache: &mut [f32], lanes: &[Lane], stride: usize, o: usize, acc: } } -/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from the covered texel `padding` gives each, returning the tiles written +/// UV padding for display: fill uncovered texels in `tiles`, their neighbours and the tiles padding continues into across a seam from the covered texel `padding` gives each, returning the tiles written pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { let mut written = std::collections::BTreeSet::new(); let (w, h) = (out.resolution, out.height); @@ -4907,6 +4907,9 @@ pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u3 } } } + + // Padding across a seam can continue from this tile into one far away + near_tiles.extend(padding.tiles_crossed_from((tx, ty))); } let near_tiles: Vec<(u32, u32)> = near_tiles.into_iter().collect(); @@ -6443,12 +6446,52 @@ soft {soft:?}" out.channels.get_mut(&Channel::Roughness).unwrap().set(10, 10, &[to_u16(0.9)]); let mut covered = vec![false; 64 * 64]; covered[10 * 64 + 10] = true; - let padding = crate::PaddingMaps { flat: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), crossed: Vec::new(), row_starts: Vec::new() }; + let padding = crate::PaddingMaps { + flat: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), + crossed: Vec::new(), + row_starts: Vec::new(), + crossed_into: Default::default(), + }; pad_tiles(&mut out, &padding, &[(0, 0)]); assert!((out.value(Channel::Roughness, 12, 12)[0] - 0.9).abs() < 1e-3); assert!(out.value(Channel::Roughness, 30, 30)[0] < 0.1 || !out.channels[&Channel::Roughness].is_allocated(0, 0)); } + /// Two islands of one 3D edge, tiles apart: repainting the far island repads the near island's padding past the seam + #[test] + fn padding_past_a_seam_follows_a_change_to_its_other_side_tiles_away() { + use texturecraft_geom::{UvSeam, UvSeamSide}; + let (width, height) = (8 * TILE, TILE); + let (left, right) = (4..=59u32, 404..=460u32); + let covered: Vec = (0..width * height).map(|i| left.contains(&(i % width)) || right.contains(&(i % width))).collect(); + let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); + let seam = UvSeam { + sides: [ + UvSeamSide { start: at(60.0, 0.0), end: at(60.0, height as f32), interior: at(4.0, 0.0) }, + UvSeamSide { start: at(404.0, 0.0), end: at(404.0, height as f32), interior: at(460.0, 0.0) }, + ], + }; + let padding = crate::PaddingMaps::new(texturecraft_core::UvPaddingMode::Space3d, &covered, (width, height), Some(4), (0, 0), &[seam]); + + let mut out = Composite::with_size(&[Channel::Roughness], width, height); + let paint = |out: &mut Composite, xs: std::ops::RangeInclusive, value: f32| { + for y in 0..height { + for x in xs.clone() { + out.channels.get_mut(&Channel::Roughness).unwrap().set(x, y, &[to_u16(value)]); + } + } + }; + paint(&mut out, left.clone(), 0.2); + paint(&mut out, right.clone(), 0.2); + pad_tiles(&mut out, &padding, &all_tiles(width, height)); + + // Past the left island's seam edge, padding continues from the right island six tiles away + paint(&mut out, right, 0.9); + let written = pad_tiles(&mut out, &padding, &[(404 / TILE, 0)]); + assert!((out.value(Channel::Roughness, 61, 3)[0] - 0.9).abs() < 1e-3, "{:?}", out.value(Channel::Roughness, 61, 3)); + assert!(written.contains(&(0, 0)), "the repadded tile is uploaded: {written:?}"); + } + fn content_fx(f: &mut Fixture, id: LayerId, kind: EffectKind) -> LayerId { let eid = f.project.alloc_id(); f.project.layer_mut(id).unwrap().content_effects.push(Effect::new(eid, kind)); diff --git a/crates/compose/src/padding_maps.rs b/crates/compose/src/padding_maps.rs index eb3edd10..26638488 100644 --- a/crates/compose/src/padding_maps.rs +++ b/crates/compose/src/padding_maps.rs @@ -1,7 +1,10 @@ //! A texture set's UV padding: from island edges, and across seams for the texels past one +use std::collections::{BTreeMap, BTreeSet}; + use texturecraft_core::{Channel, ChannelKind, UvPaddingMode}; use texturecraft_geom::UvSeam; +use texturecraft_texel::TILE; use texturecraft_texel::dilate::DilationMap; use crate::seam_padding::{SEAM_REACH, cross_seams}; @@ -15,6 +18,8 @@ pub struct PaddingMaps { pub crossed: Vec<(u32, u32)>, /// Where each row's texels start in `crossed`, one more than the rows (empty without any), so a lookup searches one row pub(crate) row_starts: Vec, + /// For each tile holding a seam's far side, the tiles whose padding continues from it, so a change there repads them however far they are + pub(crate) crossed_into: BTreeMap<(u32, u32), BTreeSet<(u32, u32)>>, } impl PaddingMaps { @@ -27,7 +32,17 @@ impl PaddingMaps { }; let row_starts = if crossed.is_empty() { Vec::new() } else { (0..=height).map(|y| crossed.partition_point(|(texel, _)| *texel < y * width) as u32).collect() }; - PaddingMaps { flat, crossed, row_starts } + let tile_of = |texel: u32| ((texel % width) / TILE, (texel / width) / TILE); + let mut crossed_into: BTreeMap<(u32, u32), BTreeSet<(u32, u32)>> = BTreeMap::new(); + for &(texel, source) in &crossed { + crossed_into.entry(tile_of(source)).or_default().insert(tile_of(texel)); + } + PaddingMaps { flat, crossed, row_starts, crossed_into } + } + + /// The tiles whose padding continues across a seam from texels in `tile` + pub fn tiles_crossed_from(&self, tile: (u32, u32)) -> impl Iterator + '_ { + self.crossed_into.get(&tile).into_iter().flatten().copied() } /// Texels across and down From 1dd4b9758b7d93d1863e1afeac86fdb93a24f8c3 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:35:35 +0000 Subject: [PATCH 164/190] Pad a baked bent normal from its own island like the other tangent-space normals, not across a seam --- crates/formats/src/export/mod.rs | 2 +- crates/formats/src/export/tests.rs | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 786da1a2..b8246fb3 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -295,7 +295,7 @@ impl SourceRef { match self { SourceRef::Channel { channel, .. } => channel.kind() == ChannelKind::NormalMap, SourceRef::Virtual { map, .. } => matches!(map, VirtualMap::NormalOpenGl | VirtualMap::NormalDirectX | VirtualMap::HeightNormal), - SourceRef::Baked { map, .. } => *map == BakedMap::Normal, + SourceRef::Baked { map, .. } => matches!(map, BakedMap::Normal | BakedMap::BentNormal), SourceRef::Constant(_) => false, } } diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 24b24b95..44bd39b7 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1331,15 +1331,19 @@ fn padding_past_a_seam_takes_the_far_island_except_for_normals() { let left = texturecraft_geom::UvSeamSide { start: at(12.0, 0.0), end: at(12.0, 64.0), interior: at(4.0, 0.0) }; let right = texturecraft_geom::UvSeamSide { start: at(20.0, 0.0), end: at(20.0, 64.0), interior: at(28.0, 0.0) }; let seams = [UvSeam { sides: [left, right] }]; + let bent: Vec = (0..RES * RES).flat_map(|i| if i % RES < 16 { [0.3, 0.5, 0.9] } else { [0.7, 0.5, 0.9] }).collect(); + fx.baked = BakedMaps { resolution: RES, maps: [(BakedMap::BentNormal, std::sync::Arc::new(bent))].into() }; + fx.project.texture_sets[0].baked.insert(BakedMap::BentNormal); let normal_x = SourceRef::Channel { channel: Channel::Normal, component: 0 }; - let mut options = one_map(FileFormat::Png, 16, vec![(Dest::R, roughness()[0].1.clone()), (Dest::G, normal_x), (Dest::B, SourceRef::Constant(0.0))]); + let bent_x = SourceRef::Baked { map: BakedMap::BentNormal, component: 0 }; + let mut options = one_map(FileFormat::Png, 16, vec![(Dest::R, roughness()[0].1.clone()), (Dest::G, normal_x), (Dest::B, bent_x)]); options.padding = Padding::Dilation(4); let render = |fx: &Fx| decode(&render_maps(&ExportInput { seams: &seams, ..fx.input() }, &options).unwrap()[0]).to_rgb16(); - // Just right of the left island: roughness continues from the right island, the normal stays the left island's + // Just right of the left island: roughness continues from the right island, the normal and bent normal stay the left island's let space_3d = render(&fx); let (outside, near, far) = (space_3d.get_pixel(13, 30), space_3d.get_pixel(8, 30), space_3d.get_pixel(24, 30)); - assert_eq!((outside[0], outside[1]), (far[0], near[1])); + assert_eq!((outside[0], outside[1], outside[2]), (far[0], near[1], near[2])); fx.project.texture_sets[0].uv_padding = UvPaddingMode::Space2d; let space_2d = render(&fx); From 2ffa8bfa6a83dc75c2ab746dfa6972b49750fdba Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:35:35 +0000 Subject: [PATCH 165/190] Refuse an export size that would scale a tall set's tile past the largest image side, before any buffer is allocated --- crates/formats/src/export/mod.rs | 12 ++++++++++++ crates/formats/src/export/tests.rs | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index b8246fb3..748f3ff0 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -614,6 +614,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let grid = set.tile_grid(); let (block_resolution, block_size) = (set.block_resolution(), set.block_size()); let scale = |side| scale_export_side(side, block_resolution, opts.size); + check_scaled_size(set, (scale(block_size.0), scale(block_size.1)))?; for (i, map) in opts.preset.maps.iter().enumerate() { if !map.channels.iter().any(|(_, s)| source_present(set, s)) { continue; @@ -923,6 +924,9 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned return Ok(Vec::new()); } + // Before any image buffer is allocated + check_scaled_size(set, (scale_export_side(tile_res, tile_res, options.size), scale_export_side(tile_height, tile_res, options.size)))?; + // Padding stays inside each UV tile let padding_maps = |max_dist| PaddingMaps::new(set.uv_padding, input.coverage, (width, height), max_dist, (tile_res, tile_height), input.seams); let padding = match options.padding { @@ -1052,6 +1056,14 @@ fn tile_side(set: &TextureSet, tile: u32, block_resolution: u32) -> u32 { ((block_resolution as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block_resolution.max(1)) } +/// Refuse an export size that scales a non-square set's UV tile past the largest image side +fn check_scaled_size(set: &TextureSet, (width, height): (u32, u32)) -> Result<()> { + if width.max(height) > MAX_IMAGE_SIZE { + return Err(FormatError::Invalid(format!("export size makes texture set \"{}\" {width}×{height}, over {MAX_IMAGE_SIZE} texels a side", set.name))); + } + Ok(()) +} + /// Scale an image side relative to the source block, keeping a pixel for any nonempty source. pub fn scale_export_side(source_side: u32, block_resolution: u32, export_size: Option) -> u32 { let export_size = export_size.unwrap_or(block_resolution); diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 44bd39b7..5747fe97 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1169,6 +1169,18 @@ fn psd_holds_the_merged_image_planar() { assert!(samples[2 * 64 * 64..].as_chunks::<2>().0.iter().all(|sample| *sample == [128, 0])); } +#[test] +fn an_export_size_that_scales_a_tall_set_past_the_largest_side_is_refused() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].set_size(RES, RES * 4); + let mut options = one_map(FileFormat::Png, 8, roughness()); + options.size = Some(MAX_IMAGE_SIZE / 2); + assert!(list_outputs(&fx.project, 0, "sphere", &options).is_err(), "the height would be twice the largest side"); + + options.size = Some(MAX_IMAGE_SIZE / 4); + assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1, "a tall export within the largest side is kept"); +} + #[test] fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { let mut fx = Fx::new(&default_channels()); From 1fbd533358ad3141ed42259d5e7016a53c218b1e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:35:35 +0000 Subject: [PATCH 166/190] Start a new undo step when typing in a texture set's description after the field lost focus --- crates/ui-egui/src/texture_set_settings.rs | 43 +++++++++++++++++++--- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs index 0e36e4b2..920acda9 100644 --- a/crates/ui-egui/src/texture_set_settings.rs +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -62,12 +62,17 @@ fn general(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, sheet.section(tr("General Properties"), false); sheet.attribute(tr("Name"), &set.name); - // Typing merges into one undo step until the field loses focus + // Typing merges into one undo step until the field loses focus; typing after it comes back starts another let mut description = set.description.clone(); - if sheet.text_field_above(tr("Description"), &mut description) { - let typing_id = sheet.ui.scope_id().with(("tss_description_typing", ts)); - let focused = sheet.ui.memory(|memory| memory.focused()); - let merge = sheet.ui.data(|data| data.get_temp::>(typing_id)).flatten().is_some_and(|id| Some(id) == focused); + let changed = sheet.text_field_above(tr("Description"), &mut description); + let typing_id = sheet.ui.scope_id().with(("tss_description_typing", ts)); + let focused = sheet.ui.memory(|memory| memory.focused()); + let typing = sheet.ui.data(|data| data.get_temp::>(typing_id)).flatten(); + if typing.is_some() && typing != focused { + sheet.ui.data_mut(|data| data.remove::>(typing_id)); + } + if changed { + let merge = typing.is_some() && typing == focused; sheet.ui.data_mut(|data| data.insert_temp(typing_id, focused)); app.run("textureSet.settings", json!({"ts": ts, "description": description, "merge": merge})); } @@ -335,6 +340,34 @@ mod tests { harness.run_steps(2); } + #[test] + fn typing_in_the_description_again_after_leaving_it_is_its_own_undo_step() { + let mut harness = harness("material_ball"); + let description = |harness: &Harness<'static, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].description.clone(); + let type_into_description = |harness: &mut Harness<'static, TextureCraftApp>, text: &str| { + click(harness, egui::Role::TextInput, "Description"); + for character in text.chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } + let ctx = harness.ctx.clone(); + ctx.memory_mut(|memory| { + if let Some(focused) = memory.focused() { + memory.surrender_focus(focused); + } + }); + harness.run_steps(2); + }; + + type_into_description(&mut harness, "ab"); + let first = description(&harness); + type_into_description(&mut harness, "c"); + assert!(description(&harness).len() > first.len(), "the second typing landed: {:?}", description(&harness)); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(description(&harness), first, "undo takes back the second typing alone"); + } + #[test] fn a_uv_tile_picked_in_the_list_is_what_size_edits() { let mut harness = harness("udim_plane"); From c1a395f3fa553161414678a3b5b22d4231c657ef Mon Sep 17 00:00:00 2001 From: FredApps Date: Sat, 28 Nov 2026 08:23:58 +0100 Subject: [PATCH 167/190] web: size-optimize the wasm profile and report the biggest contributors The web build's wasm has been over the 24 MiB gate in packaging/web/package.sh since the nightly Release dry run of 23 Nov. This change brings it down by about 4.2 MB; it does not bring it under the gate on its own. - Cargo.toml: the wasm-release profile uses opt-level "z" instead of "s". The crates that rely on inlining (fearless_simd, vello_cpu, vello_common, craft-image-codecs, texturecraft-core) stay at "s", because they come out larger at "z". The per-pixel crates stay at opt-level 3. - packaging/web/wasm_size_report.py: lists the wasm's sections and its largest crates and functions. - packaging/web/package.sh: when the size gate fails, it prints that report. --- Cargo.toml | 16 +++++- packaging/web/package.sh | 12 +++++ packaging/web/wasm_size_report.py | 81 +++++++++++++++++++++++++++++++ 3 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 packaging/web/wasm_size_report.py diff --git a/Cargo.toml b/Cargo.toml index 1f07aa7a..bb398c92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,12 +138,26 @@ codegen-units = 16 [profile.wasm-release] inherits = "release" -opt-level = "s" +# "z" over "s": the browser build must stay under the 24 MiB gate in packaging/web/package.sh. +# Measured on main 7c8dd1ae: 30,812,862 bytes with "s", 26,654,524 bytes with the levels below. +opt-level = "z" lto = "fat" codegen-units = 1 strip = "debuginfo" [profile.wasm-release.package."*"] +opt-level = "z" + +# Kept at "s": these rely on inlining, and at "z" they come out larger, not smaller. +[profile.wasm-release.package.fearless_simd] +opt-level = "s" +[profile.wasm-release.package.vello_cpu] +opt-level = "s" +[profile.wasm-release.package.vello_common] +opt-level = "s" +[profile.wasm-release.package.craft-image-codecs] +opt-level = "s" +[profile.wasm-release.package.texturecraft-core] opt-level = "s" [profile.wasm-release.package.texturecraft-texel] diff --git a/packaging/web/package.sh b/packaging/web/package.sh index 7b5a4915..8e453f49 100755 --- a/packaging/web/package.sh +++ b/packaging/web/package.sh @@ -36,6 +36,18 @@ for wasm in "$SITE"/*.wasm; do echo "$(basename "$wasm"): $size bytes ($((size / 1048576)) MiB; limit $MAX_WASM_BYTES)" if [[ "$size" -gt "$MAX_WASM_BYTES" ]]; then echo "error: $(basename "$wasm") is $size bytes, over the $MAX_WASM_BYTES-byte limit (Cloudflare's per-file cap is 25 MiB)" >&2 + # Where the bytes go: the optimized file has no function names, so the crate breakdown reads + # cargo's own output (before wasm-bindgen and wasm-opt), which keeps them. Best effort only. + report="$HERE/wasm_size_report.py" + if command -v python3 >/dev/null && [[ -f "$report" ]]; then + echo "--- sections of $(basename "$wasm") ---" >&2 + python3 "$report" "$wasm" >&2 || true + raw="$CARGO_TARGET_DIR/wasm32-unknown-unknown/wasm-release/texturecraft-web.wasm" + if [[ -f "$raw" ]]; then + echo "--- largest crates and functions in cargo's output (before wasm-opt) ---" >&2 + python3 "$report" "$raw" >&2 || true + fi + fi exit 1 fi done diff --git a/packaging/web/wasm_size_report.py b/packaging/web/wasm_size_report.py new file mode 100644 index 00000000..b553882e --- /dev/null +++ b/packaging/web/wasm_size_report.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Print where a wasm module's bytes go: sections, data, and code by crate.""" +import re, sys +from collections import defaultdict + +def leb(b, i): + r = s = 0 + while True: + x = b[i]; i += 1 + r |= (x & 0x7f) << s; s += 7 + if x < 0x80: return r, i + +def crate_of(name): + if name.startswith("_ZN"): + m = re.match(r"_ZN(\d+)", name) + if m: + n = int(m.group(1)); s = name[3 + len(m.group(1)):3 + len(m.group(1)) + n] + if s.startswith("_$LT$"): + inner = re.match(r"_\$LT\$(?:\$RF\$|mut\$u20\$)*([A-Za-z_][A-Za-z0-9_]*)", s) + return (inner.group(1) if inner else s) + " (impl)" + return s + if name.startswith("_R"): + m = re.search(r"C(?:s[0-9A-Za-z]*_)?(\d+)_?([A-Za-z_][A-Za-z0-9_]*)", name) + if m: return m.group(2)[:int(m.group(1))] + return "" if "::" in name else "" + +def main(path, top=25): + b = open(path, "rb").read() + assert b[:4] == b"\0asm" + i = 8; secs = []; names = {}; code_sizes = []; nimports = 0; data_total = 0 + while i < len(b): + sid = b[i]; i += 1 + size, i = leb(b, i); body = b[i:i + size] + label = {0:"custom",1:"type",2:"import",3:"function",4:"table",5:"memory",6:"global",7:"export",8:"start",9:"element",10:"code",11:"data",12:"datacount"}.get(sid, str(sid)) + if sid == 0: + nl, j = leb(body, 0); cname = body[j:j+nl].decode(); label = "custom:" + cname + if cname == "name": + j += nl + while j < len(body): + sub = body[j]; j += 1; sl, j = leb(body, j); end = j + sl + if sub == 1: + cnt, k = leb(body, j) + for _ in range(cnt): + idx, k = leb(body, k); ln, k = leb(body, k); names[idx] = body[k:k+ln].decode("utf-8", "replace"); k += ln + j = end + elif sid == 2: + cnt, j = leb(body, 0) + for _ in range(cnt): + l, j = leb(body, j); j += l; l, j = leb(body, j); j += l + kind = body[j]; j += 1 + if kind == 0: nimports += 1; _, j = leb(body, j) + elif kind == 1: j += 1; fl, j = leb(body, j); _, j = leb(body, j); j = leb(body, j)[1] if fl & 1 else j + elif kind == 2: fl, j = leb(body, j); _, j = leb(body, j); j = leb(body, j)[1] if fl & 1 else j + elif kind == 3: j += 2 + elif sid == 10: + cnt, j = leb(body, 0) + for _ in range(cnt): + fs, j2 = leb(body, j); code_sizes.append(fs + (j2 - j)); j = j2 + fs + elif sid == 11: + data_total = size + secs.append((label, size)); i += size + total = len(b) + print(f"{path}: {total} bytes") + for label, size in sorted(secs, key=lambda s: -s[1])[:8]: + print(f" {label:<24}{size:>12} bytes {100*size/total:5.1f}%") + by_crate = defaultdict(int); funcs = [] + for k, sz in enumerate(code_sizes): + n = names.get(nimports + k, f"func[{nimports+k}]") + by_crate[crate_of(n)] += sz; funcs.append((sz, n)) + if not names: + print(" (no name section: pass the wasm cargo wrote, before wasm-opt, to attribute code to crates)") + return + print(f" largest crates by code size (of {sum(code_sizes)} code bytes):") + for c, sz in sorted(by_crate.items(), key=lambda x: -x[1])[:top]: + print(f" {sz:>10} {c}") + print(" largest functions:") + for sz, n in sorted(funcs, reverse=True)[:10]: + print(f" {sz:>10} {n[:140]}") + +if __name__ == "__main__": + main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 25) From bf379a3937ead2e29bee1d9704a4032866934173 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:16:22 +0100 Subject: [PATCH 168/190] web: only read .wasm files under the repo or CARGO_TARGET_DIR in the size report --- packaging/web/wasm_size_report.py | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/packaging/web/wasm_size_report.py b/packaging/web/wasm_size_report.py index b553882e..a1aee6da 100644 --- a/packaging/web/wasm_size_report.py +++ b/packaging/web/wasm_size_report.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Print where a wasm module's bytes go: sections, data, and code by crate.""" -import re, sys +import os, re, sys from collections import defaultdict def leb(b, i): @@ -24,8 +24,28 @@ def crate_of(name): if m: return m.group(2)[:int(m.group(1))] return "" if "::" in name else "" -def main(path, top=25): - b = open(path, "rb").read() +def allowed_wasm(arg): + """Resolve arg and accept it only as a .wasm file under the repo or CARGO_TARGET_DIR.""" + repo = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) + roots = [repo] + target = os.environ.get("CARGO_TARGET_DIR") + if target: + roots.append(os.path.realpath(target)) + path = os.path.realpath(arg) + if not path.endswith(".wasm") or not os.path.isfile(path): + return None + for root in roots: + if os.path.commonpath([root, path]) == root: + return path + return None + +def main(arg, top=25): + path = allowed_wasm(arg) + if path is None: + print(f"wasm_size_report: skipped {arg!r}: not a .wasm file under the repository or CARGO_TARGET_DIR", file=sys.stderr) + return + with open(path, "rb") as f: + b = f.read() assert b[:4] == b"\0asm" i = 8; secs = []; names = {}; code_sizes = []; nimports = 0; data_total = 0 while i < len(b): From 2332602c4e56c5da628cd4ea6d4d450504e28f13 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:37:56 +0700 Subject: [PATCH 169/190] web: embed fonts, catalogs, the icon font and the studio HDR deflated The web build is under a 24 MiB download budget. Its embedded data is now stored deflated and inflated once at startup: the craft-fonts faces, the translation catalogs, the Phosphor icon font and the studio environment HDR. egui's default faces come from craft-ui's deflated copies instead of egui's default_fonts feature, and the engine's built-in text fonts (Ubuntu Light, Hack) come from the same copies through text_cmds::provide_built_in_fonts. Desktop builds are unchanged. --- Cargo.lock | 1 + apps/texturecraft-web/Cargo.toml | 5 +- crates/engine/Cargo.toml | 3 +- crates/engine/src/text_cmds.rs | 38 +++++++++- crates/ui-egui/Cargo.toml | 10 ++- crates/ui-egui/build.rs | 41 +++++++++- crates/ui-egui/i18n_build.rs | 87 ++++++++++++++++++--- crates/ui-egui/src/fonts.rs | 104 +++++++++++++++++++++++++- crates/ui-egui/src/i18n.rs | 4 +- crates/ui-egui/src/orb_environment.rs | 23 +++++- crates/ui-egui/src/theme.rs | 12 +-- 11 files changed, 298 insertions(+), 30 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7882ab8c..b8d1d044 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6172,6 +6172,7 @@ dependencies = [ "egui", "egui-phosphor", "egui_kittest", + "flate2", "image", "js-sys", "log", diff --git a/apps/texturecraft-web/Cargo.toml b/apps/texturecraft-web/Cargo.toml index bb5c79a6..b2e7dbe7 100644 --- a/apps/texturecraft-web/Cargo.toml +++ b/apps/texturecraft-web/Cargo.toml @@ -18,8 +18,9 @@ texturecraft-engine = { workspace = true } texturecraft-ui-egui = { workspace = true } log = { workspace = true } -# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. -eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] } +# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. No `default_fonts`: the UI takes egui's faces +# from craft-ui's deflated copies (the wasm is under a download budget). +eframe = { workspace = true, features = ["wgpu", "accesskit", "persistence"] } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 52b37891..4052d6d8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -18,12 +18,13 @@ texturecraft-paint = { workspace = true } texturecraft-bake = { workspace = true } texturecraft-formats = { workspace = true } rayon = { workspace = true } -epaint_default_fonts = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The built-in text fonts; the web build gets them from the app (`text_cmds::provide_built_in_fonts`). +epaint_default_fonts = { workspace = true } tempfile = "3" [target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies] diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs index e417ce67..c7216b15 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -24,7 +24,38 @@ pub fn specs() -> Vec { } /// Fonts bundled with the app (egui's), used when nothing is installed or in the browser. +#[cfg(not(target_arch = "wasm32"))] const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)]; +/// The built-in fonts' names, in [`provide_built_in_fonts`]'s order. +#[cfg(target_arch = "wasm32")] +const BUILT_IN_NAMES: [&str; 2] = ["Ubuntu Light", "Hack"]; +#[cfg(target_arch = "wasm32")] +static BUILT_IN_SOURCE: std::sync::OnceLock [&'static [u8]; 2]> = std::sync::OnceLock::new(); + +/// The web build's built-in fonts, Ubuntu Light and Hack, from `source`. The browser app already carries egui's faces +/// (deflated, for its download budget), so it says where to get them instead of the engine embedding a second, raw +/// copy. `source` runs once, when text first needs a built-in font. Only the first call counts. +#[cfg(target_arch = "wasm32")] +pub fn provide_built_in_fonts(source: fn() -> [&'static [u8]; 2]) { + let _ = BUILT_IN_SOURCE.set(source); +} + +/// The built-in fonts: names and bytes. On the web the bytes are empty without [`provide_built_in_fonts`]. +#[cfg(target_arch = "wasm32")] +fn built_in() -> [(&'static str, &'static [u8]); 2] { + static BYTES: std::sync::OnceLock<[&'static [u8]; 2]> = std::sync::OnceLock::new(); + let bytes = match BUILT_IN_SOURCE.get() { + Some(source) => *BYTES.get_or_init(*source), + None => [&[] as &[u8], &[]], + }; + [(BUILT_IN_NAMES[0], bytes[0]), (BUILT_IN_NAMES[1], bytes[1])] +} + +#[cfg(not(target_arch = "wasm32"))] +fn built_in() -> [(&'static str, &'static [u8]); 2] { + BUILT_IN +} + /// Families tried, in order, when no font is asked for. #[cfg(not(target_arch = "wasm32"))] const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"]; @@ -54,7 +85,7 @@ fn fonts() -> Value { let families: Vec<(String, Vec)> = Vec::new(); json!({ "installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::>(), - "builtIn": BUILT_IN.map(|(name, _)| name), + "builtIn": built_in().map(|(name, _)| name), }) } @@ -62,7 +93,8 @@ fn fonts() -> Value { /// or the first default family installed, else the built-in font. fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> { let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b); - if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) { + let built_in = built_in(); + if let Some((_, bytes)) = built_in.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) { return Ok((std::borrow::Cow::Borrowed(bytes), 0)); } #[cfg(not(target_arch = "wasm32"))] @@ -91,7 +123,7 @@ fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow: let _ = style; match family { Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))), - None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)), + None => Ok((std::borrow::Cow::Borrowed(built_in[0].1), 0)), } } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 156bb212..972652cb 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -12,7 +12,8 @@ workspace = true chrono = { workspace = true } texturecraft-engine = { workspace = true } texturecraft-render = { workspace = true } -eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] } +# egui's default fonts: on desktop from egui; the web build uses craft-ui's deflated copies (`fonts::egui_default_definitions`). +eframe = { workspace = true, features = ["wgpu", "persistence"] } egui = { workspace = true } craft-ui = { workspace = true } craft-behavior = { workspace = true } @@ -32,6 +33,7 @@ craft-image-codecs = { workspace = true } # The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +eframe = { workspace = true, features = ["default_fonts"] } sys-locale = "0.3" # Help > Check for Updates and the check at start (updates_ui.rs). craft-update = { workspace = true } @@ -61,12 +63,16 @@ zbus = { version = "5.19", default-features = false, features = ["async-io", "bl # versions craft-libs' craft-fonts-build subsets with). [build-dependencies] craft-i18n = { workspace = true } +# The web build embeds its fonts and catalogs deflated (build.rs, `fonts::CraftFont`, `i18n`). +flate2 = { workspace = true } skera = "0.8" skrifa = { version = "0.48", default-features = false, features = ["std"] } # Browser file I/O (web_files.rs): async pickers and Blob downloads. [target.'cfg(target_arch = "wasm32")'.dependencies] craft-zip = { workspace = true } +# Inflates the embedded fonts and catalogs of the web build. +flate2 = { workspace = true } rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" @@ -74,6 +80,8 @@ js-sys = "0.3" web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] } [dev-dependencies] +# build.rs's `i18n_build.rs`, which tests/i18n_build.rs includes. +flate2 = { workspace = true } craft-zip = { workspace = true } zip = { workspace = true } diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 79f33f27..13927978 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -33,6 +33,7 @@ type Faces = &'static [(&'static str, &'static str)]; fn main() { let catalogs = i18n_build::embed(); + deflate_assets(); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR"); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n"); @@ -94,10 +95,20 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: path = out; } + // The web build embeds its faces deflated: the wasm is under a download budget and fonts halve. + if wasm { + let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(".deflate"); + let deflated = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(name); + std::fs::write(&deflated, i18n_build::deflate(&bytes)?).map_err(|e| format!("{}: {e}", deflated.display()))?; + path = deflated; + } + let scripts: Vec = tags.iter().map(|s| format!("{s:?}")).collect(); let _ = writeln!( out, - " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},", + " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], data: include_bytes!({:?}), deflated: {wasm} }},", scripts.join(", "), path.display().to_string(), ); @@ -156,3 +167,31 @@ fn subset(font: &FontRef, unicodes: &IntSet) -> Result, String> { ); subset_font(font, &plan).map_err(|e| e.to_string()) } + +/// The files a web build embeds deflated (the wasm is under a download budget): the icon font and the studio +/// environment, from this crate's directory to the name they have under `OUT_DIR` (`name.deflate`). The other builds +/// include the files themselves. +const DEFLATED_ASSETS: &[(&str, &str)] = + &[("../../vendor/egui-phosphor/res/Phosphor.ttf", "Phosphor.ttf"), ("../../assets/hdr/studio_small_09_512.hdr", "studio_small_09_512.hdr")]; + +/// Writes [`DEFLATED_ASSETS`] under `OUT_DIR` for the web build. +fn deflate_assets() { + if !std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32") { + return; + } + + let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()); + let manifest = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()); + for (source, name) in DEFLATED_ASSETS { + let source = manifest.join(source); + println!("cargo::rerun-if-changed={}", source.display()); + let target = out.join(format!("{name}.deflate")); + let written = std::fs::read(&source) + .map_err(|e| e.to_string()) + .and_then(|bytes| i18n_build::deflate(&bytes)) + .and_then(|d| std::fs::write(&target, d).map_err(|e| e.to_string())); + if let Err(e) = written { + println!("cargo::error={}: {e}", source.display()); + } + } +} diff --git a/crates/ui-egui/i18n_build.rs b/crates/ui-egui/i18n_build.rs index 58eaae8b..1065757c 100644 --- a/crates/ui-egui/i18n_build.rs +++ b/crates/ui-egui/i18n_build.rs @@ -4,14 +4,62 @@ use std::path::Path; /// The catalogs' Rust includes and the distinct characters they use, sorted: the web build cuts /// its CJK interface face to those characters. +#[allow(dead_code)] // used by tests/i18n_build.rs, not by build.rs pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec), String> { - let mut source = String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"); + collect_into(dir, required, None) +} + +/// `bytes` deflated (raw deflate, as `flate2::read::DeflateDecoder` reads it). +pub fn deflate(bytes: &[u8]) -> Result, String> { + use std::io::Write as _; + let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::best()); + encoder.write_all(bytes).map_err(|e| e.to_string())?; + encoder.finish().map_err(|e| e.to_string()) +} + +/// What the generated source does with the catalogs' text. A web build downloads the wasm, so it embeds each catalog +/// deflated (written under `out`) and inflates all of them on first use; other builds embed the text itself. +const INFLATE_FN: &str = r#" +fn inflate_text(deflated: &[u8]) -> &'static str { + use std::io::Read as _; + let mut text = String::new(); + // A catalog that does not inflate leaves its language without translations, never a panic. + if flate2::read::DeflateDecoder::new(deflated).take(64 << 20).read_to_string(&mut text).is_err() { + text.clear(); + } + Box::leak(text.into_boxed_str()) +} + +pub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded { + static CATALOGS: std::sync::OnceLock<&'static craft_i18n::Embedded> = std::sync::OnceLock::new(); + CATALOGS.get_or_init(|| { + let catalogs: Vec<(&'static str, &'static str, &'static str)> = + CRAFT_I18N_DEFLATED.iter().map(|&(locale, common, app)| (locale, inflate_text(common), inflate_text(app))).collect(); + Box::leak(catalogs.into_boxed_slice()) + }) +} +"#; + +/// [`collect`], embedding the catalogs deflated under the directory `deflated_in` when it is given. +pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Path>) -> Result<(String, Vec), String> { + let mut source = match deflated_in { + Some(_) => String::from("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[\n"), + None => String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"), + }; + let close = |mut source: String| { + source.push_str("];\n"); + source.push_str(if deflated_in.is_some() { + INFLATE_FN + } else { + "\npub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {\n CRAFT_I18N\n}\n" + }); + source + }; let Some(dir) = dir else { if required { return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into()); } - source.push_str("];\n"); - return Ok((source, Vec::new())); + return Ok((close(source), Vec::new())); }; if !dir.is_absolute() { @@ -48,10 +96,19 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec) let name = file.to_str().ok_or("non-UTF-8 catalog path")?; println!("cargo::rerun-if-changed={name}"); + let include = match deflated_in { + Some(out) => { + let copy = out.join(format!("{locale}.{}.deflate", file.file_stem().and_then(|n| n.to_str()).unwrap_or("catalog"))); + std::fs::write(©, deflate(text.as_bytes())?).map_err(|e| format!("{}: {e}", copy.display()))?; + format!("include_bytes!({:?})", copy.display().to_string()) + } + None => format!("include_str!({name:?})"), + }; // The shared runtime needs static inputs for this short-lived build process - Ok((format!("include_str!({name:?})"), Box::leak(text.into_boxed_str()))) + Ok((include, Box::leak(text.into_boxed_str()))) }; - let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") }; + let empty = if deflated_in.is_some() { "&[]" } else { "\"\"" }; + let (shared, shared_text) = if common.is_file() { embed(&common)? } else { (empty.into(), "") }; let (app, app_text) = embed(&app)?; characters.extend(shared_text.chars().chain(app_text.chars())); let code: &'static str = Box::leak(locale.to_owned().into_boxed_str()); @@ -70,10 +127,9 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec) return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; "))); } - source.push_str("];\n"); characters.sort_unstable(); characters.dedup(); - Ok((source, characters)) + Ok((close(source), characters)) } /// Write the embedding for both desktop and wasm, reporting optional failures as warnings. @@ -86,7 +142,9 @@ pub fn embed() -> Vec { println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED"); let dir = std::env::var_os("CRAFT_I18N_DIR").map(std::path::PathBuf::from); let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v == "1"); - let (source, characters) = match collect(dir.as_deref(), required) { + let out_dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()); + let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); + let (source, characters) = match collect_into(dir.as_deref(), required, wasm.then_some(out_dir.as_path())) { Ok(embedded) => embedded, Err(error) => { if required { @@ -94,13 +152,22 @@ pub fn embed() -> Vec { } else { println!("cargo::warning=building without craft-i18n: {error}"); } - ("pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into(), Vec::new()) + (empty_embedding(wasm), Vec::new()) } }; - let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs"); + let out = out_dir.join("craft_i18n.rs"); if let Err(error) = std::fs::write(&out, source) { println!("cargo::error=writing {}: {error}", out.display()); } characters } + +/// The embedding of a build without catalogs. +fn empty_embedding(deflated: bool) -> String { + if deflated { + format!("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[];\n{INFLATE_FN}") + } else { + "pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n\npub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {\n CRAFT_I18N\n}\n".into() + } +} diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 2bf2dba0..88909259 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -23,11 +23,109 @@ pub struct CraftFont { pub style: &'static str, /// ISO 15924 scripts the font is for, e.g. `"Jpan"`. pub scripts: &'static [&'static str], - pub bytes: &'static [u8], + /// The font file; deflated in a web build, where the data is part of the download (see `deflated`). + data: &'static [u8], + deflated: bool, +} + +impl CraftFont { + /// Whether this build carries no data for the font. + pub fn is_empty(&self) -> bool { + self.data.is_empty() + } + + /// The font file's bytes: borrowed as embedded, or inflated from the web build's copy. Data that does not inflate + /// gives no bytes (the font is left out), never a panic. + pub fn bytes(&self) -> std::borrow::Cow<'static, [u8]> { + if self.deflated { std::borrow::Cow::Owned(inflate(self.data)) } else { std::borrow::Cow::Borrowed(self.data) } + } + + /// The font as egui takes it, without copying an embedded one. + pub fn font_data(&self) -> FontData { + match self.bytes() { + std::borrow::Cow::Borrowed(bytes) => FontData::from_static(bytes), + std::borrow::Cow::Owned(bytes) => FontData::from_owned(bytes), + } + } } include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs")); +/// Inflates a font the web build embeds deflated. Empty when the data does not inflate. +#[cfg(target_arch = "wasm32")] +fn inflate(deflated: &[u8]) -> Vec { + use std::io::Read as _; + // The largest face is under 1 MB; the bound keeps corrupt data from growing without limit. + const MAX_INFLATED_BYTES: u64 = 64 << 20; + let mut out = Vec::new(); + match flate2::read::DeflateDecoder::new(deflated).take(MAX_INFLATED_BYTES + 1).read_to_end(&mut out) { + Ok(_) if out.len() as u64 <= MAX_INFLATED_BYTES => out, + _ => Vec::new(), + } +} + +/// Adds the Phosphor icon font to `fonts`: the font itself on desktop, the web build's deflated copy there (the icon +/// font is half a megabyte of the download). Icons draw as missing-glyph boxes if the copy does not inflate. +pub(crate) fn add_icon_font(fonts: &mut egui::FontDefinitions) { + #[cfg(not(target_arch = "wasm32"))] + egui_phosphor::add_to_fonts(fonts, egui_phosphor::Variant::Regular); + #[cfg(target_arch = "wasm32")] + { + static PHOSPHOR: std::sync::OnceLock<&'static [u8]> = std::sync::OnceLock::new(); + let bytes = PHOSPHOR.get_or_init(|| Vec::leak(inflate(include_bytes!(concat!(env!("OUT_DIR"), "/Phosphor.ttf.deflate"))))); + if bytes.is_empty() { + log::warn!("the icon font did not inflate; icons show as boxes"); + } else { + egui_phosphor::add_font_bytes_to_fonts(fonts, "phosphor", bytes); + } + } +} + +/// egui's default fonts (Hack, Ubuntu Light and egui's icons, in egui's family order). The web build takes them from +/// craft-ui's deflated copies instead of egui's `default_fonts` feature, which would embed a second, raw copy, and it +/// hands the engine its built-in text fonts from the same copies. +pub(crate) fn egui_default_definitions() -> egui::FontDefinitions { + #[cfg(not(target_arch = "wasm32"))] + { + egui::FontDefinitions::default() + } + #[cfg(target_arch = "wasm32")] + { + texturecraft_engine::text_cmds::provide_built_in_fonts(engine_fonts); + let mut fonts = craft_ui::fonts::deflated_default_definitions(); + // craft-ui's Inter: TextureCraft adds its own (`theme::font_definitions`) and its own semibold family. + for name in ["Inter-Regular", "Inter-SemiBold"] { + fonts.font_data.remove(name); + } + fonts.families.remove(&FontFamily::Name(craft_ui::fonts::SEMIBOLD.into())); + let known: Vec = fonts.font_data.keys().cloned().collect(); + for list in fonts.families.values_mut() { + list.retain(|name| known.contains(name)); + } + fonts + } +} + +/// The engine's built-in text fonts, Ubuntu Light and Hack, copied once from the deflated defaults. Empty when a face +/// is unavailable (the text command then reports the font as unusable). +#[cfg(target_arch = "wasm32")] +fn engine_fonts() -> [&'static [u8]; 2] { + let fonts = craft_ui::fonts::deflated_default_definitions(); + let face = |name: &str| -> &'static [u8] { + match fonts.font_data.get(name) { + Some(data) => Vec::leak((*data.font).as_ref().to_vec()), + None => &[], + } + }; + [face("Ubuntu-Light"), face("Hack")] +} + +/// Only the web build embeds deflated data. +#[cfg(not(target_arch = "wasm32"))] +fn inflate(_deflated: &[u8]) -> Vec { + Vec::new() +} + /// Skip absurdly large files (a corrupt or non-font path must not eat memory). #[cfg(not(target_arch = "wasm32"))] const MAX_FONT_BYTES: u64 = 128 << 20; @@ -186,8 +284,8 @@ impl UiFonts { /// The first available font for `script`: craft-fonts' (embedded), then the system's. fn load(script: Script) -> Option { - if let Some(f) = CRAFT_FONTS.iter().find(|f| f.scripts.contains(&script.iso()) && f.style == "Regular" && !f.bytes.is_empty()) { - return Some(aligned(FontData::from_static(f.bytes))); + if let Some(f) = CRAFT_FONTS.iter().find(|f| f.scripts.contains(&script.iso()) && f.style == "Regular" && !f.is_empty()) { + return Some(aligned(f.font_data())); } #[cfg(not(target_arch = "wasm32"))] for (path, index) in script.system_files() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index e9cc27f4..dc239fe8 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -9,7 +9,7 @@ include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); static I18N: LazyLock = LazyLock::new(|| { let offered: Vec<_> = LANGUAGES.iter().map(|l| l.code).collect(); - let (i18n, problems) = craft_i18n::I18n::new(CRAFT_I18N, &offered); + let (i18n, problems) = craft_i18n::I18n::new(craft_i18n_catalogs(), &offered); for problem in problems { log::warn!("translation catalog: {problem}"); } @@ -377,7 +377,7 @@ mod tests", let keys = keys(); assert!(keys.len() > 300, "found only {} keys", keys.len()); let used: BTreeSet<_> = keys.iter().map(String::as_str).collect(); - for &(locale, common, app) in CRAFT_I18N { + for &(locale, common, app) in craft_i18n_catalogs() { let Some(lang) = I18N.from_code(locale) else { continue }; let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect(); diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs index d74186f0..5a2699b1 100644 --- a/crates/ui-egui/src/orb_environment.rs +++ b/crates/ui-egui/src/orb_environment.rs @@ -7,7 +7,11 @@ use texturecraft_engine::geom::glam::Vec3; use texturecraft_render::ibl::{self, EnvImage}; /// The bundled environment: a small photo studio with soft boxes, 512 x 256 equirect Radiance HDR +#[cfg(not(target_arch = "wasm32"))] const STUDIO_HDR: &[u8] = include_bytes!("../../../assets/hdr/studio_small_09_512.hdr"); +/// The same file deflated by build.rs: the web build's wasm is under a download budget +#[cfg(target_arch = "wasm32")] +const STUDIO_HDR_DEFLATED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/studio_small_09_512.hdr.deflate")); /// Prefiltered levels from mirror (0) to fully rough (last) const LEVELS: u32 = 6; @@ -15,6 +19,23 @@ const LEVELS: u32 = 6; /// How far the studio is turned about the vertical axis (radians) so its key soft box lights the orb from the upper left const TURN: f32 = 4.4; +/// The bundled file's bytes +#[cfg(not(target_arch = "wasm32"))] +fn studio_hdr() -> std::borrow::Cow<'static, [u8]> { + std::borrow::Cow::Borrowed(STUDIO_HDR) +} + +/// The bundled file's bytes, inflated; none if the copy does not inflate (the studio falls back) +#[cfg(target_arch = "wasm32")] +fn studio_hdr() -> std::borrow::Cow<'static, [u8]> { + use std::io::Read as _; + let mut out = Vec::new(); + match flate2::read::DeflateDecoder::new(STUDIO_HDR_DEFLATED).take(64 << 20).read_to_end(&mut out) { + Ok(_) => std::borrow::Cow::Owned(out), + Err(_) => std::borrow::Cow::Owned(Vec::new()), + } +} + /// The prefiltered studio pub(crate) struct OrbEnvironment { /// Level `l` holds reflections for roughness `l / (LEVELS - 1)` @@ -27,7 +48,7 @@ impl OrbEnvironment { /// The studio, decoded and prefiltered by the first caller (about a tenth of a second in release) pub(crate) fn get() -> &'static OrbEnvironment { static STUDIO: OnceLock = OnceLock::new(); - STUDIO.get_or_init(|| OrbEnvironment::from_hdr(STUDIO_HDR).unwrap_or_else(OrbEnvironment::fallback)) + STUDIO.get_or_init(|| OrbEnvironment::from_hdr(&studio_hdr()).unwrap_or_else(OrbEnvironment::fallback)) } fn from_hdr(bytes: &[u8]) -> Option { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 30af4f1e..3ed5451e 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -301,20 +301,20 @@ pub(crate) const HARD_SHADOW: Color32 = Color32::from_rgb(12, 14, 18); /// adds CJK). pub fn font_definitions() -> egui::FontDefinitions { use std::sync::Arc; - let mut fonts = egui::FontDefinitions::default(); - let face = |style: &str| crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style && !f.bytes.is_empty()); + let mut fonts = crate::fonts::egui_default_definitions(); + let face = |style: &str| crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style && !f.is_empty()); // Inter is drawn a little under its size, as in VectorCraft: its letters are wide. - let inter = |bytes: &'static [u8]| Arc::new(egui::FontData::from_static(bytes).tweak(egui::FontTweak { scale: 0.92, ..Default::default() })); + let inter = |face: &crate::fonts::CraftFont| Arc::new(face.font_data().tweak(egui::FontTweak { scale: 0.92, ..Default::default() })); let mut semibold = None; if let (Some(regular), Some(bold)) = (face("Regular"), face("SemiBold")) { - fonts.font_data.insert("inter".into(), inter(regular.bytes)); - fonts.font_data.insert("inter-semibold".into(), inter(bold.bytes)); + fonts.font_data.insert("inter".into(), inter(regular)); + fonts.font_data.insert("inter-semibold".into(), inter(bold)); if let Some(list) = fonts.families.get_mut(&FontFamily::Proportional) { list.insert(0, "inter".into()); } semibold = Some("inter-semibold"); } - egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); + crate::fonts::add_icon_font(&mut fonts); // The semibold family: the regular family with its first face swapped for the weight. let mut list = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); if let (Some(w), Some(first)) = (semibold, list.first_mut()) { From ccf2ad6b52ad466f5bd192c3b61dd0668652d990 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sat, 28 Nov 2026 08:46:07 +0000 Subject: [PATCH 170/190] Auto: Restore neutral quick-mask previews and clarify size jitter Show neutral coverage in the brush preview while editing the quick mask. Add a headless regression for the tint transition and document how pressure and jitter independently affect 3D stamp size. --- crates/ui-egui/src/dock.rs | 27 +++++++++------ crates/ui-egui/tests/it/paint_tool_tabs.rs | 39 ++++++++++++++++++++++ docs/control-protocol.md | 3 +- 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 8c7d32d3..3df1804c 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2087,7 +2087,7 @@ const STROKE_GRAY_SAMPLES: u32 = 64; /// Gap under the brush preview const BRUSH_PREVIEW_GAP: f32 = 4.0; -/// The brush's own stroke in the colour it paints, and a sphere with the tool's material +/// The brush's stroke in its target's tint, with a material sphere for content targets fn brush_preview(app: &TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let content = targets_content(app); @@ -2101,17 +2101,15 @@ fn brush_preview(app: &TextureCraftApp, ui: &mut Ui) { let brush = &tool.brush; let image = brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)); - if content { - let channel_value = |channel| if tool.enabled.contains(&channel) { tool.values.get(&channel).copied() } else { None }; - let base_color = channel_value(Channel::BaseColor).unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); + let channel_value = |channel| if tool.enabled.contains(&channel) { tool.values.get(&channel).copied() } else { None }; + let base_color = content.then(|| channel_value(Channel::BaseColor).unwrap_or(PREVIEW_FALLBACK_BASE_COLOR)); + + if app.session.quick_mask.editing { + // The quick mask stores coverage independently of the tool's material and mask gray + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, |_| [u8::MAX; 3]); + } else if let Some(base_color) = base_color { let srgb = base_color.map(|linear| (linear_to_srgb(linear) * 255.0 + 0.5) as u8); BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, |_| srgb); - - // The sphere sits in the middle of the preview's right half - let metallic = channel_value(Channel::Metallic).map_or(crate::thumbs::SPHERE_DEFAULT_METALLIC, |metallic| metallic[0]); - let roughness = channel_value(Channel::Roughness).map_or(crate::thumbs::SPHERE_DEFAULT_ROUGHNESS, |roughness| roughness[0]); - let center = pos2(rect.left() + half_width * 1.5, rect.center().y); - crate::thumbs::paint_material_sphere(painter, center, PREVIEW_SPHERE_RADIUS, base_color, metallic, roughness); } else { // A mask paints gray: an image-backed one is read across the stroke let gray = app.session.mask_gray(); @@ -2121,6 +2119,15 @@ fn brush_preview(app: &TextureCraftApp, ui: &mut Ui) { }; BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, mask_tint); } + + if let Some(base_color) = base_color { + // The sphere sits in the middle of the preview's right half + let metallic = channel_value(Channel::Metallic).map_or(crate::thumbs::SPHERE_DEFAULT_METALLIC, |metallic| metallic[0]); + let roughness = channel_value(Channel::Roughness).map_or(crate::thumbs::SPHERE_DEFAULT_ROUGHNESS, |roughness| roughness[0]); + let center = pos2(rect.left() + half_width * 1.5, rect.center().y); + crate::thumbs::paint_material_sphere(painter, center, PREVIEW_SPHERE_RADIUS, base_color, metallic, roughness); + } + ui.add_space(BRUSH_PREVIEW_GAP); } diff --git a/crates/ui-egui/tests/it/paint_tool_tabs.rs b/crates/ui-egui/tests/it/paint_tool_tabs.rs index e5424f7f..ca7ee50c 100644 --- a/crates/ui-egui/tests/it/paint_tool_tabs.rs +++ b/crates/ui-egui/tests/it/paint_tool_tabs.rs @@ -133,3 +133,42 @@ fn the_brush_preview_ignores_values_of_disabled_channels() { assert!(preview_meshes(&harness).1 == enabled.1, "re-enabling {channel} restores its stored value in the sphere"); } } + +#[test] +fn the_brush_preview_uses_neutral_coverage_while_editing_the_quick_mask() { + let mut harness = paint_harness("paint"); + let stroke_texture = |harness: &Harness<'_, TextureCraftApp>| { + let preview = harness.get_by_role_and_label(Role::Image, "Brush preview").rect(); + harness + .output() + .shapes + .iter() + .find_map(|clipped| match &clipped.shape { + egui::Shape::Mesh(mesh) if preview.contains_rect(mesh.calc_bounds()) && mesh.calc_bounds().right() <= preview.center().x => { + Some(mesh.texture_id) + } + _ => None, + }) + .unwrap() + }; + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + harness.step(); + let blue = stroke_texture(&harness); + + execute(&mut harness.state_mut().session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + harness.step(); + + let coverage = stroke_texture(&harness); + assert_ne!(coverage, blue, "editing the quick mask redraws the blue stroke as coverage"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 1.0, 1.0]})).unwrap(); + harness.step(); + + assert_eq!(stroke_texture(&harness), coverage, "material changes do not tint the quick mask stroke"); + + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); + harness.step(); + + assert_eq!(stroke_texture(&harness), coverage, "the quick mask preview uses the same neutral stroke as white paint"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d2097607..a227383c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -175,7 +175,8 @@ through `tool.brush` too and come back with it: `angleFade` (`[from, to]` in deg `backfaceCulling` on, faces turned further than `from` from the view fade out until `to`), `screenSpace` (Size Space Viewport: the size follows the view instead of the object) and `stampDepth` (0.05..4). `sizePressure` (default `true`) lets pen pressure shrink the size towards -`minSize`; `false` keeps every stamp at full size. +`minSize`. Setting `sizePressure` to `false` removes pen-pressure scaling. In 3D, `jitterSize` +still varies stamp size independently. Bake mode applies an edit in Common Settings or Mesh Map Settings to the texture sets sharing that group's settings: Common Settings, and each map's settings, are shared by any set of texture sets From 7001cac3eb6ed46e5c09608ef553cf0189e4638d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:53:44 +0700 Subject: [PATCH 171/190] ui-egui: name each generated font file after its full craft-fonts path Faces that share a file name in different folders no longer overwrite each other under OUT_DIR. --- crates/ui-egui/build.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 13927978..269cde1e 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -90,7 +90,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; let cut = if rel == LATIN_MANIFEST { without_private_use(&bytes) } else { cut_to_catalogs(&bytes, catalogs) }.map_err(|e| format!("{file}: {e}"))?; - let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(path.file_name().unwrap_or_default()); + let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(out_name(file, "")); std::fs::write(&out, cut).map_err(|e| format!("{}: {e}", out.display()))?; path = out; } @@ -98,9 +98,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: // The web build embeds its faces deflated: the wasm is under a download budget and fonts halve. if wasm { let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; - let mut name = path.file_name().unwrap_or_default().to_os_string(); - name.push(".deflate"); - let deflated = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(name); + let deflated = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(out_name(file, ".deflate")); std::fs::write(&deflated, i18n_build::deflate(&bytes)?).map_err(|e| format!("{}: {e}", deflated.display()))?; path = deflated; } @@ -168,6 +166,13 @@ fn subset(font: &FontRef, unicodes: &IntSet) -> Result, String> { subset_font(font, &plan).map_err(|e| e.to_string()) } +/// A face's file name under `OUT_DIR`: its path in the craft-fonts checkout with every separator flattened, so faces +/// that share a file name (`jp/Regular.ttf`, `ar/Regular.ttf`) stay apart. +fn out_name(file: &str, suffix: &str) -> String { + let flat: String = file.chars().map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' { c } else { '_' }).collect(); + format!("craft-font-{flat}{suffix}") +} + /// The files a web build embeds deflated (the wasm is under a download budget): the icon font and the studio /// environment, from this crate's directory to the name they have under `OUT_DIR` (`name.deflate`). The other builds /// include the files themselves. From b6809d1d094b922431cbd5f20442e49a7a1a7337 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:23:18 +0000 Subject: [PATCH 172/190] Scan only the band beside a seam for its padding texels, not the seam's whole bounding box --- crates/compose/src/seam_padding.rs | 6 +++- crates/compose/src/texel_edge.rs | 54 ++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/seam_padding.rs b/crates/compose/src/seam_padding.rs index ef28c354..6640b0ab 100644 --- a/crates/compose/src/seam_padding.rs +++ b/crates/compose/src/seam_padding.rs @@ -32,7 +32,11 @@ pub(crate) fn cross_seams(flat: &DilationMap, reach: u32, block: (u32, u32), inp let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32); let mut side_islands = None; for y in y0..y1 { - for x in x0..x1 { + // Only the texel centres in the band beside the seam can be within its reach + let Some((low_x, high_x)) = near_edge.band_span(reach, y as f32 + 0.5) else { continue }; + let row_x0 = ((low_x - 0.5).floor().max(0.0) as u32).max(x0); + let row_x1 = ((high_x + 0.5).ceil().max(0.0) as u32).min(x1); + for x in row_x0..row_x1 { let index = y * width + x; let Some(&flat_source) = flat.src.get(index as usize) else { continue }; diff --git a/crates/compose/src/texel_edge.rs b/crates/compose/src/texel_edge.rs index f6b57d21..25ea3d36 100644 --- a/crates/compose/src/texel_edge.rs +++ b/crates/compose/src/texel_edge.rs @@ -25,4 +25,58 @@ impl TexelEdge { let outside = -(point - self.start).dot(self.inward); ((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside)) } + + /// The x range at height `y` of the band `reach` deep outside the edge: every point there that `outside` takes within `reach` + pub(crate) fn band_span(&self, reach: f32, y: f32) -> Option<(f32, f32)> { + let depth = self.inward * -reach; + let corners = [self.start, self.end, self.end + depth, self.start + depth]; + let mut span: Option<(f32, f32)> = None; + for (index, &from) in corners.iter().enumerate() { + let to = corners[(index + 1) % corners.len()]; + if y < from.y.min(to.y) || y > from.y.max(to.y) { + continue; + } + + // A level side spans its whole length at its height + let xs = if from.y == to.y { [from.x, to.x] } else { [from.x + (to.x - from.x) * (y - from.y) / (to.y - from.y); 2] }; + for x in xs { + span = Some(span.map_or((x, x), |(low, high)| (low.min(x), high.max(x)))); + } + } + span + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::UvSeamSide; + use texturecraft_geom::glam::Vec2; + + use super::TexelEdge; + + #[test] + fn a_diagonal_edges_band_spans_every_point_beside_it_and_little_else() { + let size = Vec2::splat(512.0); + let side = UvSeamSide { triangle: 0, start: Vec2::new(0.05, 0.05), end: Vec2::new(0.95, 0.9), interior: Vec2::new(0.9, 0.1) }; + let edge = TexelEdge::new(side, size).unwrap(); + let reach = 32.0; + + let (mut beside, mut spanned) = (0, 0); + for y in 0..512 { + let centre_y = y as f32 + 0.5; + let span = edge.band_span(reach, centre_y); + spanned += span.map_or(0, |(low, high)| (high - low).ceil() as usize + 1); + for x in 0..512 { + let point = Vec2::new(x as f32 + 0.5, centre_y); + if edge.outside(point).is_some_and(|(_, outside)| outside <= reach) { + beside += 1; + let (low, high) = span.unwrap_or((f32::MAX, f32::MIN)); + assert!((low..=high).contains(&point.x), "{point} is beside the edge but outside its row's span {span:?}"); + } + } + } + + // The diagonal's bounding box holds far more texels than its band + assert!(beside > 0 && spanned < 512 * 512 / 4, "{spanned} texels spanned for {beside} beside the edge"); + } } From ea94342ff0cd6e4a355d208082f15bfbed8ed973 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:23:18 +0000 Subject: [PATCH 173/190] Leave a set's other files to export when its PSD's map size scales the set past the largest image side --- crates/formats/src/export/mod.rs | 20 ++++++++++++++++++-- crates/formats/src/export/tests.rs | 17 +++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 348e3ab8..3294ad29 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -779,6 +779,9 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti // Bucket layers in tile order to move their names into the corresponding PSD let mut psd_layers = Vec::new(); + + // A PSD map scaled past the largest side fails only the set's PSDs, as their other planning failures do + let mut psd_too_large = None; let project_stem = project.name.replace('/', "_"); let mesh_stem = mesh_name.replace('/', "_"); let set_stem = set.name.replace('/', "_"); @@ -792,8 +795,17 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti let own = opts.maps.get(&map_index); let (format, bit_depth, dither) = opts.map_file_type(map_index, map); let enabled = own.is_none_or(|o| o.enabled); - if enabled { - check_scaled_block(set, (block_width, block_height), opts.map_size(map_index))?; + if enabled && let Err(error) = check_scaled_block(set, (block_width, block_height), opts.map_size(map_index)) { + if format != FileFormat::Psd { + return Err(error); + } + + if psd_too_large.is_none() { + psd_too_large = Some(match error { + FormatError::Invalid(reason) => reason, + other => other.to_string(), + }); + } } let space = opts.space_for_map(map, format, bit_depth); @@ -926,6 +938,10 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) }; let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); + if let Some(reason) = &psd_too_large { + psd_failures.push((name, FormatError::Invalid(reason.clone()))); + continue; + } if let Err(error) = layered_psd::preflight(set, opts, tile, bit_depth, layers.iter(), budget.working_bytes) { psd_failures.push((name, error)); continue; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 8b0b1e77..bc57bfaf 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1294,6 +1294,23 @@ fn an_export_size_that_scales_a_tall_set_past_the_largest_side_is_refused() { assert!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().is_empty(), "a disabled map never allocates an image"); } +#[test] +fn a_psd_scaled_past_the_largest_side_leaves_the_sets_other_maps() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].set_size(RES, RES * 4); + let mut options = one_map(FileFormat::Png, 8, roughness()); + let mut psd = options.preset.maps[0].clone(); + (psd.file, psd.format, psd.bit_depth, psd.channels) = ("layered".into(), FileFormat::Psd, 8, rgba_half_alpha()); + options.preset.maps.push(psd); + options.size = Some(MAX_IMAGE_SIZE / 2); + options.maps.insert(0, MapOverride { size: Some(MAX_IMAGE_SIZE / 4), ..MapOverride::default() }); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert!(plan.len() == 1 && plan[0].format == FileFormat::Png, "{plan:?}"); + assert!(plan[0].warnings.iter().any(|warning| is_set_warning(warning)), "{:?}", plan[0].warnings); +} + #[test] fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { let mut fx = Fx::new(&default_channels()); From 9df6e65efa8489138f578980a80146d47482c5ce Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:23:18 +0000 Subject: [PATCH 174/190] Put the channel window's legend on its own row when the footer is too narrow for it beside Apply to all Texture Sets --- crates/ui-egui/src/channel_manager.rs | 14 +++++++++----- crates/ui-egui/src/texture_set_settings.rs | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/channel_manager.rs b/crates/ui-egui/src/channel_manager.rs index 5931c2f6..499af670 100644 --- a/crates/ui-egui/src/channel_manager.rs +++ b/crates/ui-egui/src/channel_manager.rs @@ -210,8 +210,12 @@ impl ChannelManager { let legend_text = ui.painter().layout_no_wrap(tr("Not used by the shader").to_owned(), FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); let left_width = EDGE_AIR + CHECK_SIZE + CHECK_TO_LABEL + text.size().x + LEGEND_GAP + SMALL_TEXT_SIZE + LEGEND_GLYPH_TO_TEXT + legend_text.size().x; - let stacked = width < left_width + BUTTON_GAP + 2.0 * BUTTON_SIZE.x + 2.0 * EDGE_AIR; - let height = if stacked { 2.0 * BUTTON_SIZE.y + BUTTON_GAP } else { BUTTON_SIZE.y }; + + // A narrow footer puts the buttons on a row of their own, and the legend under the check when the two don't fit side by side + let legend_below = width < left_width + EDGE_AIR; + let stacked = legend_below || width < left_width + BUTTON_GAP + 2.0 * BUTTON_SIZE.x + 2.0 * EDGE_AIR; + let rows = 1.0 + f32::from(u8::from(legend_below)) + f32::from(u8::from(stacked)); + let height = rows * BUTTON_SIZE.y + (rows - 1.0) * BUTTON_GAP; let (row, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover()); ui.painter().hline(row.x_range(), row.top() - FOOTER_AIR / 2.0, Stroke::new(1.0, tokens.separator)); let center_y = row.top() + BUTTON_SIZE.y / 2.0; @@ -227,10 +231,10 @@ impl ChannelManager { ui.painter().galley(pos2(check.right() + CHECK_TO_LABEL, center_y - text.size().y / 2.0), text, tokens.text); paint_keyboard_focus(ui, &response, tokens); - let legend = hit.right() + LEGEND_GAP; - let glyph = ui.painter().text(pos2(legend, center_y), Align2::LEFT_CENTER, icon::PROHIBIT, FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); + let legend = if legend_below { pos2(check.left(), center_y + BUTTON_SIZE.y + BUTTON_GAP) } else { pos2(hit.right() + LEGEND_GAP, center_y) }; + let glyph = ui.painter().text(legend, Align2::LEFT_CENTER, icon::PROHIBIT, FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); let text_left = glyph.right() + LEGEND_GLYPH_TO_TEXT; - ui.painter().galley(pos2(text_left, center_y - legend_text.size().y / 2.0), legend_text, tokens.text_dim); + ui.painter().galley(pos2(text_left, legend.y - legend_text.size().y / 2.0), legend_text, tokens.text_dim); let apply = Rect::from_min_size(pos2(row.right() - EDGE_AIR - BUTTON_SIZE.x, row.bottom() - BUTTON_SIZE.y), BUTTON_SIZE); let cancel = apply.translate(vec2(-(BUTTON_SIZE.x + BUTTON_GAP), 0.0)); diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs index aa2a17f6..38b7fd4e 100644 --- a/crates/ui-egui/src/texture_set_settings.rs +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -446,6 +446,28 @@ mod tests { assert!(harness.state().session.doc.project.texture_sets[0].has_channel(Channel::BaseWeight)); } + #[test] + fn a_narrow_channel_window_keeps_its_legend_inside_the_footer() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.set_size(vec2(300.0, 600.0)); + harness.run_steps(5); + + let legend: Vec<_> = harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == "Not used by the shader" => Some((clipped.clip_rect, text.visual_bounding_rect())), + _ => None, + }) + .collect(); + assert!(!legend.is_empty(), "the footer paints its legend"); + for (clip, painted) in legend { + assert!(clip.contains_rect(painted), "the legend at {painted:?} is cut off by {clip:?}"); + } + } + #[test] fn escape_closes_the_channel_window_with_nothing_focused_and_drops_its_ticks() { let mut harness = harness("material_ball"); From 5883353858beee0d8bae4b90e6d8408f398523a1 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:23:18 +0000 Subject: [PATCH 175/190] Keep F2 and the menu keys from the texture set list while a dialog is open --- crates/ui-egui/src/menus.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b80061d7..5e4938aa 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,8 +526,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.export.rename_key = true; } - // Give the hovered texture set list first use of its rename and menu keys - if over_set_list { + // Give the hovered texture set list first use of its rename and menu keys, as Escape, never under a dialog + if over_set_list && !modal_open { let menu = input.consume_key(Modifiers::SHIFT, Key::F10) || input.consume_key(Modifiers::NONE, Key::Menu); set_list_keys = (input.consume_key(Modifiers::NONE, Key::F2), menu); } From 9d6531c43f7e47d949d3ea71a8d1be42df672b71 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:46:59 +0000 Subject: [PATCH 176/190] Name the view camera and view mode pickers for screen readers Both boxes showed only their value, so they had no accessible name. Once the window settles, the accessibility check fails on them in a short window (rail::history_actions_remain_reachable_in_a_short_window). --- crates/ui-egui/src/view_mode_picker.rs | 7 ++++++- crates/ui-egui/src/viewport.rs | 9 ++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/view_mode_picker.rs b/crates/ui-egui/src/view_mode_picker.rs index 332f136b..734a8a8d 100644 --- a/crates/ui-egui/src/view_mode_picker.rs +++ b/crates/ui-egui/src/view_mode_picker.rs @@ -76,7 +76,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, child: &mut Ui, id_salt: &str, wid // The picker stays greyed without project maps let combo = child .add_enabled_ui(project_open, |child| { - egui::ComboBox::from_id_salt(id_salt).width(width).height(LIST_HEIGHT).selected_text(label).show_ui(child, |ui| { + egui::ComboBox::from_id_salt(id_salt).width(width).height(LIST_HEIGHT).selected_text(label.as_str()).show_ui(child, |ui| { // Bake mode keeps its own list: the material, then the mesh maps, without titles if !baking { section(ui, "Lighting"); @@ -135,6 +135,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, child: &mut Ui, id_salt: &str, wid }) .inner; + // The box shows only the mode's name: it is named for what it picks + combo.response.widget_info(|| egui::WidgetInfo { + current_text_value: Some(label.clone()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, project_open, tr("View mode")) + }); image_picker(app, &combo.response, popup_id); } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4198772d..37c61484 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -572,7 +572,7 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { let names: Vec = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect(); let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str); if project_open { - egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { + let picker = egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { app.run("camera.select", json!({})); } @@ -586,6 +586,13 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("camera.add", json!({})); } }); + + // The box shows only the camera's name: it is named for what it picks + let enabled = child.is_enabled(); + picker.response.widget_info(|| egui::WidgetInfo { + current_text_value: Some(shown.to_owned()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, enabled, tr("View camera")) + }); } // The 2D view of a UV tile project: a checkable button left of the view mode, with no tooltip, that shows or hides the tile numbers and the hover label From f44a45478abac149350f1c2a657c388eed4de1f6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:20:54 +0000 Subject: [PATCH 177/190] Size the channel window's list to the room the title bar and footer leave, so Apply stays on screen in a short window --- crates/ui-egui/src/channel_manager.rs | 58 +++++++++++++++------- crates/ui-egui/src/texture_set_settings.rs | 24 +++++++++ 2 files changed, 65 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/channel_manager.rs b/crates/ui-egui/src/channel_manager.rs index 499af670..25ec4fe4 100644 --- a/crates/ui-egui/src/channel_manager.rs +++ b/crates/ui-egui/src/channel_manager.rs @@ -1,6 +1,8 @@ //! The dialog that adds and removes a texture set's channels: every channel by group, ticked when the set has it -use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use std::sync::Arc; + +use egui::{Align2, CornerRadius, FontId, Galley, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::core::{Channel, ChannelGroup, TextureSet}; @@ -101,11 +103,17 @@ impl ChannelManager { let width = (ctx.content_rect().width() - 2.0 * EDGE_AIR).clamp(1.0, DIALOG_WIDTH); ui.set_width(width); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let footer = FooterLayout::new(ui, &tokens); let closed = title_bar(ui, &tokens, opening); ui.add_space(BODY_AIR); - egui::ScrollArea::both().auto_shrink([false, true]).max_height(ctx.content_rect().height() * MAX_HEIGHT_SHARE).show(ui, |ui| manager.columns(ui)); + + // The list gets what the title bar, the footer and the air between them leave, so Apply stays in a short window + let window = ctx.content_rect().height(); + let room = window - TITLE_BAR_HEIGHT - BODY_AIR - FOOTER_AIR - footer.height - EDGE_AIR; + let max_height = (window * MAX_HEIGHT_SHARE).min(room).max(0.0); + egui::ScrollArea::both().auto_shrink([false, true]).max_height(max_height).show(ui, |ui| manager.columns(ui)); ui.add_space(FOOTER_AIR); - let (apply, cancel) = manager.footer(ui, &tokens); + let (apply, cancel) = manager.footer(ui, &tokens, footer); ui.add_space(EDGE_AIR); (apply, cancel || closed) }); @@ -203,20 +211,9 @@ impl ChannelManager { } /// "Apply to all Texture Sets", the ⊘ legend, then Cancel and Apply at the right; returns (Apply, Cancel) clicked - fn footer(&mut self, ui: &mut Ui, tokens: &Tokens) -> (bool, bool) { - let width = ui.available_width(); - let label = tr("Apply to all Texture Sets"); - let text = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text); - let legend_text = ui.painter().layout_no_wrap(tr("Not used by the shader").to_owned(), FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); - - let left_width = EDGE_AIR + CHECK_SIZE + CHECK_TO_LABEL + text.size().x + LEGEND_GAP + SMALL_TEXT_SIZE + LEGEND_GLYPH_TO_TEXT + legend_text.size().x; - - // A narrow footer puts the buttons on a row of their own, and the legend under the check when the two don't fit side by side - let legend_below = width < left_width + EDGE_AIR; - let stacked = legend_below || width < left_width + BUTTON_GAP + 2.0 * BUTTON_SIZE.x + 2.0 * EDGE_AIR; - let rows = 1.0 + f32::from(u8::from(legend_below)) + f32::from(u8::from(stacked)); - let height = rows * BUTTON_SIZE.y + (rows - 1.0) * BUTTON_GAP; - let (row, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover()); + fn footer(&mut self, ui: &mut Ui, tokens: &Tokens, layout: FooterLayout) -> (bool, bool) { + let FooterLayout { label, text, legend_text, legend_below, height } = layout; + let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); ui.painter().hline(row.x_range(), row.top() - FOOTER_AIR / 2.0, Stroke::new(1.0, tokens.separator)); let center_y = row.top() + BUTTON_SIZE.y / 2.0; @@ -242,6 +239,33 @@ impl ChannelManager { } } +/// The footer's texts and rows, worked out before the channel list so the list can leave the footer its height +struct FooterLayout { + label: &'static str, + text: Arc, + legend_text: Arc, + legend_below: bool, + height: f32, +} + +impl FooterLayout { + fn new(ui: &Ui, tokens: &Tokens) -> Self { + let width = ui.available_width(); + let label = tr("Apply to all Texture Sets"); + let text = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text); + let legend_text = ui.painter().layout_no_wrap(tr("Not used by the shader").to_owned(), FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); + + let left_width = EDGE_AIR + CHECK_SIZE + CHECK_TO_LABEL + text.size().x + LEGEND_GAP + SMALL_TEXT_SIZE + LEGEND_GLYPH_TO_TEXT + legend_text.size().x; + + // A narrow footer puts the buttons on a row of their own, and the legend under the check when the two don't fit side by side + let legend_below = width < left_width + EDGE_AIR; + let stacked = legend_below || width < left_width + BUTTON_GAP + 2.0 * BUTTON_SIZE.x + 2.0 * EDGE_AIR; + let rows = 1.0 + f32::from(u8::from(legend_below)) + f32::from(u8::from(stacked)); + let height = rows * BUTTON_SIZE.y + (rows - 1.0) * BUTTON_GAP; + FooterLayout { label, text, legend_text, legend_below, height } + } +} + /// The title and × at the right; returns whether × was clicked fn title_bar(ui: &mut Ui, tokens: &Tokens, opening: bool) -> bool { let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), TITLE_BAR_HEIGHT), Sense::hover()); diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs index 38b7fd4e..224d5ca4 100644 --- a/crates/ui-egui/src/texture_set_settings.rs +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -468,6 +468,30 @@ mod tests { } } + #[test] + fn a_short_channel_window_keeps_apply_on_screen() { + // A narrow window stacks the footer to three rows: the channel list must leave room for all of them + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.set_size(vec2(300.0, 400.0)); + harness.run_steps(5); + + let screen = harness.ctx.content_rect(); + let apply: Vec<_> = harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == "Apply" => Some(text.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert!(!apply.is_empty(), "the footer paints Apply"); + for painted in apply { + assert!(screen.contains_rect(painted), "Apply at {painted:?} falls outside the window {screen:?}"); + } + } + #[test] fn escape_closes_the_channel_window_with_nothing_focused_and_drops_its_ticks() { let mut harness = harness("material_ball"); From 0097f990530cca249ced7c55a5b9fa362517fbb0 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:30:31 -0500 Subject: [PATCH 178/190] test(engine): edge cases for find_installed_tool (folder named like the tool, no parent, missing app folder) Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/link_cmds.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index b5567e31..9d92b569 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -630,4 +630,31 @@ mod tests { std::fs::create_dir_all(root.path().join("MaterialCraft")).unwrap(); assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_named_like_the_tool_is_not_the_tool() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(app.join("materialcraft-cli")).unwrap(); + std::fs::create_dir_all(root.path().join("MaterialCraft").join("materialcraft-cli")).unwrap(); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_app_folder_with_no_parent_does_not_panic() { + // The root (or an empty path) has no parent: only the beside-the-program step can apply. + assert_eq!(super::find_installed_tool(std::path::Path::new(""), "no-such-materialcraft-tool"), None); + let root = std::env::temp_dir().ancestors().last().map(std::path::Path::to_path_buf).unwrap_or_default(); + assert_eq!(super::find_installed_tool(&root, "no-such-materialcraft-tool"), None); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_missing_app_folder_is_none() { + let root = tempfile::tempdir().unwrap(); + let gone = root.path().join("nowhere").join("TextureCraft"); + assert_eq!(super::find_installed_tool(&gone, "materialcraft-cli"), None); + } } From c80f93efd3a38168de5889398892c567aab3deee Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 11:51:05 -0500 Subject: [PATCH 179/190] ci(nightly): pin shared signing workflows, move macOS notices to Resources/docs, and fix profile reopen (#896) * ci(nightly): pin shared signing workflows, move macOS notices to Resources/docs, and fix profile reopen * style(profile_root): format with rustfmt --- .github/nightly-signing-policy.json | 6 +- .github/workflows/nightly-sign.yml | 18 ++- .github/workflows/nightly.yml | 4 +- apps/texturecraft/src/profile_root.rs | 82 ++++++++++- packaging/macos/nightly.sh | 5 +- packaging/macos/nightly_sign_tests.py | 204 ++++++++++++++++++++++++++ packaging/nightly-release-tests.py | 94 +++++++++++- 7 files changed, 400 insertions(+), 13 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index ab63e5a3..2e7debe0 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1419654881, "producer_workflow_id": 429738073, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a", + "producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", + "signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 65767940..a15f26e3 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,12 +34,26 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 with: - tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a + tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 app-name: texturecraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} # No secrets: inherit or raw platform values in this caller. Only the isolated native # callee job may bind the release environment and export its keys; that environment must # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index a0933e12..f201a529 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 with: - tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a + tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 app-name: texturecraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs index 71265909..db10fdae 100644 --- a/apps/texturecraft/src/profile_root.rs +++ b/apps/texturecraft/src/profile_root.rs @@ -178,13 +178,21 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, /// Nightly's writes at another app's files. fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let child = canonical_future(&chosen.join(name))?; + let entry = chosen.join(name); + let metadata = std::fs::symlink_metadata(&entry).map_err(|e| format!("cannot inspect the nightly {label}: {e}"))?; + if !metadata.is_dir() { + return Err(format!("the nightly {label} must be a directory inside its selected profile")); + } + let child = canonical_future(&entry)?; if child == chosen || !child.starts_with(&chosen) { return Err(format!("the nightly {label} must stay inside its selected profile")); } Ok(child) } +/// Known folder-only entries directly inside a Nightly profile. +const PROFILE_FOLDERS: [&str; 10] = ["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"]; + /// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve /// inside it. fn entries_stay_inside(root: &Path) -> Result<(), String> { @@ -195,11 +203,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> { }; for entry in entries { let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - private_subdirectory(root, entry.file_name(), "profile entry")?; + let path = entry.path(); + let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + // Settings and session state are ordinary files, not directories. Keep the existing + // directory-boundary check for folders (including the known folder-only entries). + let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); + if metadata.is_file() && !folder_only { + private_regular_file(&path, &metadata)?; + } else { + private_subdirectory(root, entry.file_name(), "profile entry")?; + } } Ok(()) } +/// Persisted files must have their own ordinary file identity, not an alias to other data. +fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + if metadata.nlink() != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(windows)] + { + use winsafe::{HFILE, co}; + let (file, _) = HFILE::CreateFile( + path.to_str().ok_or("the nightly profile file path is not textual")?, + co::GENERIC::default(), + Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), + None, + co::DISPOSITION::OPEN_EXISTING, + co::FILE_ATTRIBUTE::NORMAL, + Some(co::FILE_FLAG::OPEN_REPARSE_POINT), + None, + None, + ) + .map_err(|e| e.to_string())?; + let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; + if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { + return Err("the nightly profile file must not be an alias or directory".into()); + } + if info.nNumberOfLinks != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + let _ = (path, metadata); + Ok(()) +} + /// The app's writable probe: create a file exclusively in the profile and remove it again. pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { let probe = dir.join("exclusive-write-probe"); @@ -474,6 +527,31 @@ mod tests { assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err()); } + #[test] + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + let fixture = Fixture::new(); + for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { + let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); + assert_eq!(fixture.check(platform, &private).unwrap(), private); + for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(fixture.check(platform, &private).unwrap(), private); + assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + } + } + #[test] #[cfg(unix)] fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() { diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh index 4140e45a..47d03279 100755 --- a/packaging/macos/nightly.sh +++ b/packaging/macos/nightly.sh @@ -35,11 +35,12 @@ OUTPUT="$DIST/texturecraft-$VERSION-macos-aarch64-nightly.zip" nightly_compile_gui APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP" -mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs" cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" chmod 755 "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" cp "$ROOT/assets/app-icon/$MAC_NIGHTLY_ICON.icns" "$APP/Contents/Resources/$MAC_NIGHTLY_ICON.icns" -nightly_copy_notices "$APP/Contents/Resources" +# Launcher admits notices under Resources/docs, not beside the icon. +nightly_copy_notices "$APP/Contents/Resources/docs" # The private mktemp cwd is the helper authority root: stage the template inside it. cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in" (cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \ diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py index f0a2eddc..74f39763 100644 --- a/packaging/macos/nightly_sign_tests.py +++ b/packaging/macos/nightly_sign_tests.py @@ -6,8 +6,10 @@ crafted archive) as an argument, which is why packaging/macos/nightly_sign_tests app's ordinary Linux CI. """ import os +import shutil import stat import subprocess +import sys import tempfile import unittest import zipfile @@ -16,9 +18,18 @@ from pathlib import Path HERE = Path(__file__).resolve().parent LIB = HERE / "nightly-lib.sh" APP = "TextureCraft Nightly.app" +APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md") +OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT") IDENTITY = "A" * 40 TEAM = "DJ6XS33FX8" APP_CONFIG_ID = "ai.storyteller.texturecraft.nightly" +COMMIT = "0123456789abcdef0123456789abcdef01234567" +VERSION = "0.24.0-nightly.20261124.7.2.g" + COMMIT[:12] +ASSET = f"texturecraft-{VERSION}-macos-aarch64-nightly.zip" +SECRETS = ( + "APPLE_CERTIFICATE", "APPLE_CERTIFICATE_PASSWORD", "KEYCHAIN_PASSWORD", + "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "MACOS_SIGN_IDENTITY", "MACOS_KEYCHAIN", +) @@ -178,5 +189,198 @@ class ZipEntries(unittest.TestCase): self.assertFalse(self.checked([*good, entry]), entry[0]) +class PackageFixture: + """Stand-in POSIX harness for driving packaging/macos/nightly.sh and nightly-verify.sh.""" + + def __init__(self, case): + directory = tempfile.TemporaryDirectory() + case.addCleanup(directory.cleanup) + self.root = Path(directory.name).resolve() + self.bin = self.root / "bin" + self.dist = self.root / "dist" + self.temp = self.root / "tmp" + for path in (self.bin, self.dist, self.temp): + path.mkdir() + self._install_shims() + + def _write_shim(self, name, body): + path = self.bin / name + path.write_text(body) + path.chmod(0o755) + + def _install_shims(self): + python = sys.executable + self._write_shim( + "uname", + "#!/bin/sh\n" + "case \"$1\" in\n" + " -s) echo Darwin ;;\n" + " -m) echo arm64 ;;\n" + " *) /usr/bin/uname \"$@\" ;;\n" + "esac\n", + ) + self._write_shim("lipo", "#!/bin/sh\necho arm64\n") + self._write_shim( + "plutil", + f"#!{python}\n" + "import plistlib, sys\n" + "args = sys.argv[1:]\n" + "if args[:1] == ['-lint']:\n" + " with open(args[1], 'rb') as f:\n" + " plistlib.load(f)\n" + " sys.exit(0)\n" + "if args[:1] == ['-extract'] and len(args) == 6 and args[3:5] == ['-o', '-']:\n" + " key, fmt, plist_path = args[1], args[2], args[5]\n" + " with open(plist_path, 'rb') as f:\n" + " data = plistlib.load(f)\n" + " if key not in data:\n" + " sys.exit(1)\n" + " value = data[key]\n" + " if fmt == 'raw':\n" + " print(value)\n" + " else:\n" + " print(plistlib.dumps(value).decode('utf-8'))\n" + " sys.exit(0)\n" + "sys.exit(f'unsupported plutil args: {args}')\n", + ) + self._write_shim( + "ditto", + f"#!{python}\n" + "import os, stat, sys, zipfile\n" + "from pathlib import Path\n" + "args = sys.argv[1:]\n" + "src, dst = Path(args[-2]), Path(args[-1])\n" + "if '-c' in args:\n" + " base = src.parent if '--keepParent' in args else src\n" + " with zipfile.ZipFile(dst, 'w', compression=zipfile.ZIP_DEFLATED) as z:\n" + " items = [src] + sorted(src.rglob('*')) if '--keepParent' in args else sorted(src.rglob('*'))\n" + " for item in items:\n" + " rel = item.relative_to(base).as_posix()\n" + " if item.is_dir():\n" + " info = zipfile.ZipInfo(rel + '/')\n" + " info.external_attr = (stat.S_IFDIR | (item.stat().st_mode & 0o777)) << 16\n" + " z.writestr(info, b'')\n" + " else:\n" + " info = zipfile.ZipInfo(rel)\n" + " info.external_attr = (stat.S_IFREG | (item.stat().st_mode & 0o777)) << 16\n" + " z.writestr(info, item.read_bytes())\n" + "elif '-x' in args:\n" + " dst.mkdir(parents=True, exist_ok=True)\n" + " with zipfile.ZipFile(src) as z:\n" + " for info in z.infolist():\n" + " target = dst / info.filename\n" + " if info.is_dir():\n" + " target.mkdir(parents=True, exist_ok=True)\n" + " else:\n" + " target.parent.mkdir(parents=True, exist_ok=True)\n" + " target.write_bytes(z.read(info.filename))\n" + " mode = (info.external_attr >> 16) & 0o777\n" + " if mode:\n" + " os.chmod(target, mode)\n" + "else:\n" + " sys.exit(f'unsupported ditto args: {args}')\n", + ) + + def env(self, **changes): + env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "RUNNER_TEMP": str(self.temp)} + for key, value in changes.items(): + if value is None: + env.pop(key, None) + else: + env[key] = str(value) + return env + + def run(self, script, *args, **changes): + path = Path(script) if Path(script).is_absolute() else HERE / script + return subprocess.run( + ["bash", str(path), *(str(a) for a in args)], + env=self.env(**changes), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60, + ) + + def package(self, font_licences): + """Drive the real producer from a clean fixture checkout, without Cargo or Apple tools.""" + source = HERE.parents[1] + checkout = self.root / "source" + checkout.mkdir() + notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file()) + for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py", + "packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh", + "packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py", + "assets/app-icon/texturecraft-nightly.icns"): + target = checkout / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source / relative, target) + env = self.env(**dict.fromkeys(SECRETS)) + + def git(*args): + return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args], + cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout + + git("init", "-q") + git("add", "--", ".") + git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture") + commit = git("rev-parse", "HEAD").strip() + version = VERSION[:-12] + commit[:12] + # Generated licence text exercises the copier without depending on a font checkout. + fonts = self.root / "craft-fonts" + for family, data in font_licences.items(): + licence = fonts / "fonts" / family / "OFL.txt" + licence.parent.mkdir(parents=True) + licence.write_bytes(data) + self._write_shim( + "cargo", + '#!/bin/sh\nset -eu\n' + 'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/texturecraft"\n' + 'mkdir -p "$(dirname "$gui")"\n' + "printf \"#!/bin/sh\\necho 'TextureCraft %s (nightly-v1)'\\n\" \"$TEXTURECRAFT_VERSION\" >\"$gui\"\n", + ) + result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS), + DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts), + TEXTURECRAFT_BUILD_CHANNEL="nightly-v1", TEXTURECRAFT_VERSION=version, + TEXTURECRAFT_BUILD_SHA=commit, TEXTURECRAFT_BUILD_DATE="2026-11-24") + assert result.returncode == 0, result.stdout + return self.dist / ASSET.replace(VERSION, version) + + +class Build(unittest.TestCase): + def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self): + f = PackageFixture(self) + fonts = { + "inter": b"generated font notice one", + "biz-ud-pgothic": b"generated font notice two", + "noto-sans-cjk-sc": b"generated font notice three", + } + archive = f.package(fonts) + source = HERE.parents[1] + resources = f"{APP}/Contents/Resources" + icon = "texturecraft-nightly.icns" + notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES} + notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()}) + notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()}) + # Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon. + expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()} + expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes() + contents = f"{APP}/Contents" + gui = f"{contents}/MacOS/TextureCraft" + with zipfile.ZipFile(archive) as zipped: + entries = zipped.infolist() + names = {entry.filename for entry in entries} + self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case") + self.assertEqual({entry.filename for entry in entries if not entry.is_dir()}, + set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"}) + self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= { + f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"}) + for path, data in expected_files.items(): + with self.subTest(path=path): + self.assertEqual(zipped.read(path), data) + mode = zipped.getinfo(path).external_attr >> 16 + self.assertTrue(stat.S_ISREG(mode)) + self.assertFalse(mode & 0o111) + mode = zipped.getinfo(gui).external_attr >> 16 + self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR) + result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS)) + self.assertEqual(result.returncode, 0, result.stdout) + + if __name__ == "__main__": unittest.main() diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index c55e54c1..83495332 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -13,6 +13,12 @@ APP_NAME = "texturecraft" PRODUCER_WORKFLOW_NAME = "TextureCraft unsigned nightly" NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +# The pinned shared registry enables Windows, Linux and macOS for TextureCraft. +SIGNER_SECRETS = { + "AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT", + "AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE", + "APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD", +} NIGHTLY_TRUST = { "windows-x86_64": ("publisher_subject", "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"), @@ -45,6 +51,49 @@ def assert_nightly_serialization(source): raise ValueError("nightly serialization must use its stable group and no cancellation") +def caller_entries(lines, indent): + """Split the callers' plain YAML block entries; refuse other forms at checked levels.""" + entries = {} + children = None + for line in lines: + if children is not None and line.startswith(" " * (indent + 1)): + children.append(line) + continue + row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line) + if row is None or row[1] in entries: + raise ValueError("malformed or duplicate caller mapping entry") + children = [] + entries[row[1]] = row[2], children + return entries + + +def assert_caller_secrets(source, job_name, names): + """Check the actual caller's root, job and secret blocks without a YAML dependency.""" + lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")] + root = caller_entries(lines, 0) + job_marker, job_lines = root.pop("jobs", (None, [])) + jobs = caller_entries(job_lines, 2) + if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None: + raise ValueError("the caller must have one plain job block") + job = caller_entries(jobs[job_name][1], 4) + if "environment" in job or "environment" in root or "secrets" in root: + raise ValueError("only the native callee may bind the environment") + if names: + if "secrets" not in job: + raise ValueError("signer requires an explicit target-specific secret map") + mode, secret_lines = job.pop("secrets") + expected = {name: ("${{ secrets." + name + " }}", []) for name in names} + if mode is not None or caller_entries(secret_lines, 6) != expected: + raise ValueError("signer must forward exactly the reviewed same-name secret references") + elif "secrets" in job: + raise ValueError("unsigned caller must not pass secrets") + for value, children in (*root.values(), *job.values()): + outside_map = "\n".join([value or "", *children]) + # Scan all remaining text: quoted braces can appear before a secret reference. + if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map): + raise ValueError("secret bindings belong only in the signer map") + + def literal_off(condition): """True only for a guard that a reviewed test update can still see is switched off.""" expression = " ".join(condition.split()) @@ -204,8 +253,49 @@ class TrustedSourcePreparation(unittest.TestCase): with self.subTest(workflow=name): self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") - self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") - self.assertNotIn("secrets.", executable) + + def test_signer_forwards_exactly_the_reviewed_secret_names(self): + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + assert_caller_secrets(signer, "release", SIGNER_SECRETS) + + def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self): + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + header = " secrets:\n" + linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n" + self.assertIn(linux, signer) + mutations = { + "missing name": signer.replace(linux, ""), + "extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n", + "renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")), + "duplicate name": signer.replace(linux, linux + linux), + "duplicate map": signer + header + linux, + "quoted duplicate map": signer + ' "secrets": inherit\n', + "inherit": signer.split(header)[0] + " secrets: inherit\n", + "yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"), + "yaml merge": signer + " <<: *other\n", + "environment": signer + " environment: release\n", + "secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"), + } + for change, source in mutations.items(): + with self.subTest(change=change), self.assertRaises(ValueError): + assert_caller_secrets(source, "release", SIGNER_SECRETS) + + def test_unsigned_caller_has_no_secrets(self): + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + assert_caller_secrets(producer, "unsigned", set()) + for suffix in (" secrets: {}\n", " secrets: inherit\n", + " secrets:\n EXTRA: ${{ secrets.EXTRA }}\n", + " extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"): + with self.subTest(suffix=suffix), self.assertRaises(ValueError): + assert_caller_secrets(producer + suffix, "unsigned", set()) + + def test_unsigned_caller_refuses_secret_after_format_brace(self): + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + # This inert fixture is never dispatched; the brace is part of the format string. + env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n" + source = producer.replace("jobs:\n", env + "jobs:\n", 1) + with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"): + assert_caller_secrets(source, "unsigned", set()) class NightlyTrustAnchors(unittest.TestCase): From 5ebe488019aa72d7a5b383565ecfc387ba6a3528 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:51:39 -0500 Subject: [PATCH 180/190] test(render): an adapter without compute shaders gets a tracer error, not a panic Builds a no-op adapter with WebGL2-class limits: the viewport renderer still builds and the GPU path tracer refuses with a message naming compute shaders. Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/headless.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index 5babad0a..e1ac8d06 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -132,4 +132,22 @@ mod tests { let twice = [info("D3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Gl), info("Microsoft Direct3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Vulkan)]; assert_eq!(pick_adapter(&twice, "rtx 4050", P::HighPerformance), Some(1)); } + + /// On an adapter with WebGL2-class limits (no compute shaders) the viewport renderer still builds + /// and the GPU path tracer refuses with a message instead of panicking. + #[test] + fn an_adapter_without_compute_shaders_gets_an_error_not_a_panic() { + let noop = wgpu::NoopBackendOptions { enable: true, limits: Some(wgpu::Limits::downlevel_webgl2_defaults()), ..Default::default() }; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::NOOP, + backend_options: wgpu::BackendOptions { noop, ..Default::default() }, + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + let (device, queue) = device(&adapter).unwrap(); + let _renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); + assert!(!crate::gpu_trace::GpuTracer::supported(&device)); + let err = crate::gpu_trace::GpuTracer::new(&device).err().expect("the tracer needs compute shaders"); + assert!(err.contains("compute shaders"), "{err}"); + } } From 4336c9accd2559fc423668a8e4abb264c25113c6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 13:24:25 -0500 Subject: [PATCH 181/190] fix(web): inline realpath prefix check in wasm_size_report.py for SonarCloud (#899) --- packaging/web/wasm_size_report.py | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/packaging/web/wasm_size_report.py b/packaging/web/wasm_size_report.py index a1aee6da..f26acddc 100644 --- a/packaging/web/wasm_size_report.py +++ b/packaging/web/wasm_size_report.py @@ -24,24 +24,16 @@ def crate_of(name): if m: return m.group(2)[:int(m.group(1))] return "" if "::" in name else "" -def allowed_wasm(arg): - """Resolve arg and accept it only as a .wasm file under the repo or CARGO_TARGET_DIR.""" - repo = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) - roots = [repo] - target = os.environ.get("CARGO_TARGET_DIR") - if target: - roots.append(os.path.realpath(target)) - path = os.path.realpath(arg) - if not path.endswith(".wasm") or not os.path.isfile(path): - return None - for root in roots: - if os.path.commonpath([root, path]) == root: - return path - return None - def main(arg, top=25): - path = allowed_wasm(arg) - if path is None: + repo = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) + target_env = os.environ.get("CARGO_TARGET_DIR") + target = os.path.realpath(target_env) if target_env else None + path = os.path.realpath(arg) + root = target if target and path.startswith(target + os.sep) else repo + if not path.startswith(root + os.sep): + print(f"wasm_size_report: skipped {arg!r}: not a .wasm file under the repository or CARGO_TARGET_DIR", file=sys.stderr) + return + if not path.endswith(".wasm") or not os.path.isfile(path): print(f"wasm_size_report: skipped {arg!r}: not a .wasm file under the repository or CARGO_TARGET_DIR", file=sys.stderr) return with open(path, "rb") as f: From ded20a74bdd9850eca08f459e2bf6020530cec08 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 14:37:04 -0500 Subject: [PATCH 182/190] ci(sonar): exclude diagnostic wasm_size_report.py CLI script from taint analysis (#900) --- sonar-project.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/sonar-project.properties b/sonar-project.properties index 21de440a..5ac46f82 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1 +1,2 @@ sonar.coverage.exclusions=packaging/** +sonar.exclusions=packaging/web/wasm_size_report.py From 846553d13d9059db35096eb43b91e32d9e905cb1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 16:07:28 -0500 Subject: [PATCH 183/190] ci: pin storytold/craft-common-actions to @main universally (#901) --- .github/nightly-signing-policy.json | 6 +++--- .github/workflows/nightly-macos.yml | 6 +++--- .github/workflows/nightly-sign.yml | 4 ++-- .github/workflows/nightly.yml | 5 +++-- packaging/nightly-release-tests.py | 8 ++++---- 5 files changed, 15 insertions(+), 14 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 2e7debe0..51ac774f 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1419654881, "producer_workflow_id": 429738073, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml index 1c49c360..a863bbfa 100644 --- a/.github/workflows/nightly-macos.yml +++ b/.github/workflows/nightly-macos.yml @@ -44,12 +44,12 @@ jobs: persist-credentials: false # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. - name: Check out craft-fonts - uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main with: ref: aced4137c022f1f587624d48e81ec77e1914a9cc - - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + uses: storytold/craft-common-actions/actions/rust-channel@main with: targets: aarch64-apple-darwin - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index a15f26e3..82d408c1 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,9 +34,9 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + tooling-revision: main app-name: texturecraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index f201a529..c05c2e31 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + tooling-revision: main app-name: texturecraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc @@ -32,3 +32,4 @@ jobs: # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 83495332..55c08d86 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -174,7 +174,7 @@ def reviewed_manual_actors(caller_source, policy): def caller_pin(name): - return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0] + return re.findall(r"(?m)^ tooling-revision: (\S+)$", (ROOT / ".github/workflows" / name).read_text())[0] class TrustedSourcePreparation(unittest.TestCase): @@ -332,7 +332,7 @@ class NightlyTrustAnchors(unittest.TestCase): self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") pins.update(uses) self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") - self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main") class NightlyEnabledCallers(unittest.TestCase): @@ -738,7 +738,7 @@ def trust_closure_problems(workflows): if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): if name == "nightly-sign.yml": signer_calls += 1 - if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + if name != "nightly-sign.yml" or ref != "main": problems.append(name + " calls nightly-release.yml@" + ref) if workflow.lower() in ("release.yml", "release.yaml"): stable_callers.add(name) @@ -788,7 +788,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase): "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, - "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")}, "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, } From 45ea33d09dccaea9560fa9a96022a3199c90175b Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:30:04 -0500 Subject: [PATCH 184/190] fix(render): size-limit tests no longer assume wgpu's default 256 MiB buffer limit The headless device now asks for the adapter's own limits, so on a desktop GPU the 8192x8192 reset in failed_reset_retains_the_active_render succeeds and the test failed. The test now uses a device capped at 256 MiB (Headless::with_buffer_cap, test only). Also: ImageRes fields are private on main, so the environment-usage test builds its image with ImageRes::new. Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/gpu_trace.rs | 14 ++++++++++++-- crates/render/src/headless.rs | 19 ++++++++++++++++++- crates/render/src/renderer.rs | 2 +- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 5d092a0f..e79574e8 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -834,7 +834,17 @@ mod tests { } fn gpu() -> Option<(Headless, GpuTracer)> { - let Ok(h) = Headless::new() else { + gpu_on(Headless::new()) + } + + /// A tracer on a device whose buffers hold at most 256 MiB, as wgpu's default limits do: a GPU's + /// own limits (several GiB on a desktop card) would let an 8192² render succeed. + fn small_buffer_gpu() -> Option<(Headless, GpuTracer)> { + gpu_on(Headless::with_buffer_cap(256 << 20)) + } + + fn gpu_on(headless: Result) -> Option<(Headless, GpuTracer)> { + let Ok(h) = headless else { eprintln!("skipping: no GPU adapter"); return None; }; @@ -908,7 +918,7 @@ mod tests { /// Rejecting an oversized render preserves the image and lets tracing continue. #[test] fn failed_reset_retains_the_active_render() { - let Some((mut headless, mut tracer)) = gpu() else { return }; + let Some((mut headless, mut tracer)) = small_buffer_gpu() else { return }; let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); let camera = camera(); let settings = TraceSettings::default(); diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index e1ac8d06..5b38a625 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -64,7 +64,11 @@ fn pick_adapter(infos: &[wgpu::AdapterInfo], name: &str, power: wgpu::PowerPrefe /// adapter without compute shaders (WebGL2-class, or the GL driver WSL2 offers on an integrated GPU) /// still renders it; the GPU path tracer checks the device's limits itself. fn device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue), String> { - let desc = wgpu::DeviceDescriptor { label: Some("tc_headless"), required_limits: adapter.limits(), ..Default::default() }; + device_with_limits(adapter, adapter.limits()) +} + +fn device_with_limits(adapter: &wgpu::Adapter, limits: wgpu::Limits) -> Result<(wgpu::Device, wgpu::Queue), String> { + let desc = wgpu::DeviceDescriptor { label: Some("tc_headless"), required_limits: limits, ..Default::default() }; pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device on {}: {e}", adapter.get_info().name)) } @@ -77,6 +81,19 @@ impl Headless { Ok(Headless { device, queue, renderer, adapter_name: adapter.get_info().name }) } + /// A device whose buffers are capped at `bytes` (or the adapter's own limit when that is lower), + /// so tests of "too big for this GPU" paths do not depend on how large the machine's limits are. + #[cfg(test)] + pub(crate) fn with_buffer_cap(bytes: u64) -> Result { + let adapter = adapter()?; + let mut limits = adapter.limits(); + limits.max_buffer_size = limits.max_buffer_size.min(bytes); + limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(bytes); + let (device, queue) = device_with_limits(&adapter, limits)?; + let renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); + Ok(Headless { device, queue, renderer, adapter_name: adapter.get_info().name }) + } + /// Render a frame and read it back as RGBA8 (sRGB-encoded). pub fn render(&mut self, frame: &crate::Frame) -> Option<(u32, u32, Vec)> { let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_headless") }); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 3495a056..2eadf143 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -2661,7 +2661,7 @@ mod tests { let usage = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST; assert_eq!(h.renderer.env.texture.usage(), usage, "the built-in environment"); // An imported image of another size makes a new texture. - let image = ImageRes { width: 256, height: 128, rgba: vec![[0.5, 0.5, 0.5, 1.0]; 256 * 128], srgb: false }; + let image = ImageRes::new(256, 128, vec![[0.5, 0.5, 0.5, 1.0]; 256 * 128], false); h.renderer.set_environment(&h.device, &h.queue, "resource:grey", Some(&image)); assert_eq!(h.renderer.env.texture.width(), 256); assert_eq!(h.renderer.env.texture.usage(), usage, "an imported environment"); From b6dbef1b34a7b0643cc89a3248e90102655113ed Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:41:25 -0500 Subject: [PATCH 185/190] test(192): the no-compute test also checks the GPU baker refuses with a reason Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/gpu_bake.rs | 2 +- crates/render/src/headless.rs | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index df45c291..dbfe1860 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -132,7 +132,7 @@ fn bake_adapter() -> Result<(wgpu::Adapter, String, wgpu::Limits), String> { Ok((adapter, info.name, limits)) } -fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> { +pub(crate) fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> { if device_type == wgpu::DeviceType::Cpu { return Some("is a software renderer"); } diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index 5b38a625..a5241dd2 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -150,8 +150,8 @@ mod tests { assert_eq!(pick_adapter(&twice, "rtx 4050", P::HighPerformance), Some(1)); } - /// On an adapter with WebGL2-class limits (no compute shaders) the viewport renderer still builds - /// and the GPU path tracer refuses with a message instead of panicking. + /// On an adapter with WebGL2-class limits (no compute shaders) the viewport renderer still builds, + /// the GPU path tracer and the GPU baker each refuse with a message instead of panicking. #[test] fn an_adapter_without_compute_shaders_gets_an_error_not_a_panic() { let noop = wgpu::NoopBackendOptions { enable: true, limits: Some(wgpu::Limits::downlevel_webgl2_defaults()), ..Default::default() }; @@ -166,5 +166,8 @@ mod tests { assert!(!crate::gpu_trace::GpuTracer::supported(&device)); let err = crate::gpu_trace::GpuTracer::new(&device).err().expect("the tracer needs compute shaders"); assert!(err.contains("compute shaders"), "{err}"); + let flags = adapter.get_downlevel_capabilities().flags; + let reason = crate::gpu_bake::unsupported_adapter(wgpu::DeviceType::IntegratedGpu, flags, &adapter.limits()); + assert!(reason.is_some_and(|r| r.contains("compute")), "{reason:?}"); } } From d6f6f3016913d49cc692f0dd275468a79bb53204 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:55:03 -0500 Subject: [PATCH 186/190] test(192): spawn the CLI through cli_binary() so nextest archives on another runner find it Co-Authored-By: Claude Sonnet 5.5 --- apps/texturecraft-cli/tests/cli.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 2c0c9f4f..0d838118 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -193,7 +193,7 @@ fn render_without_a_gpu_points_to_path_tracing() { let out = d.join("cube.png"); let absent = if cfg!(target_os = "macos") { "dx12" } else { "metal" }; let render = |extra: &[&str]| { - Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) + Command::new(cli_binary()) .env("WGPU_BACKEND", absent) .env_remove("WGPU_ADAPTER_NAME") .env_remove("WGPU_POWER_PREF") From aabf1c06dce0e9e55603acd3be2cb4843d16f17f Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:55:04 -0500 Subject: [PATCH 187/190] fix: a failed or panicking edit marks the restored document's tiles dirty again Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/session.rs | 18 ++++++++++------- crates/engine/tests/session.rs | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index d9c7eb82..3c948a70 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -694,9 +694,7 @@ impl Session { let result = match ran { Ok(result) => result, Err(panic) => { - self.doc = before; - // As for an error below: a repaint may have cached tiles from the discarded document - self.path_cache = None; + self.restore_after_failed_edit(before); std::panic::resume_unwind(panic); } }; @@ -716,15 +714,21 @@ impl Session { Ok(value) } Err(error) => { - self.doc = before; - - // A failed repaint may have cached tiles from the discarded document - self.path_cache = None; + self.restore_after_failed_edit(before); Err(error) } } } + /// Put `before` back after an edit failed or panicked. The edit may have recomposited the + /// discarded document (draining the dirty tiles) or cached path tiles from it, so mark what + /// differs between the two dirty again, as undo does. + fn restore_after_failed_edit(&mut self, before: Document) { + let discarded = std::mem::replace(&mut self.doc, before); + self.path_cache = None; + self.invalidate_changed(&discarded); + } + pub(crate) fn push_history(&mut self, label: &str, before: Document) { self.record(label, before, false); } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 28a51a8f..e06b4fbb 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -536,6 +536,43 @@ fn a_panic_inside_an_edit_restores_the_document() { assert_eq!(s.history_labels(), history, "no undo step was recorded"); } +/// An edit that recomposites the discarded document and then fails or panics: the display shows the +/// restored document again after the next `update`, not the discarded one. +#[test] +fn a_failed_or_panicking_edit_recomposites_the_restored_document() { + for panics in [false, true] { + let mut s = session(); + let hit = s.pick(texturecraft_engine::geom::glam::Vec2::new(200.0, 200.0), s.viewport).unwrap(); + let (x, y) = ((hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32); + let red_at = |s: &mut Session| { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, x, y)[0] + }; + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + let painted = red_at(&mut s); + assert!(painted > 0.9, "the stroke painted: {painted}"); + + let edit = |s: &mut Session| { + let _ = s.edit("Hide everything", |s| -> texturecraft_engine::Result<()> { + s.doc.project.texture_sets[0].stack.clear(); + s.touched(); + s.update(); + assert!(s.caches[0].composite.value(Channel::BaseColor, x, y)[0] < 0.9, "the edit shows the empty stack"); + if panics { + panic!("boom"); + } + Err(texturecraft_engine::EngineError::Other("nope".into())) + }); + }; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| edit(&mut s))); + assert_eq!(r.is_err(), panics); + let shown = red_at(&mut s); + assert!(shown > 0.9, "panics={panics}: the restored paint is shown again: {shown}"); + } +} + /// A command that fails leaves the document and history as they were (commands are atomic). #[test] fn failed_commands_leave_the_document_unchanged() { From 14cd65692eae182fccc0cd5b3ae1553807296803 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:11:06 -0500 Subject: [PATCH 188/190] fix: same_document ignores crate-private Document fields (main added painted_regions) Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/tests/session.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index e06b4fbb..de808261 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -19,9 +19,10 @@ fn session_at(texture_size: u32) -> Session { } /// Whether two documents hold the same content (`Document` has no `PartialEq`). Destructured so -/// a new field must be compared here too. +/// a new public field must be compared here too (crate-private fields, such as `painted_regions`, +/// can't be reached from an integration test). fn same_document(a: &Document, b: &Document) -> bool { - let Document { project, pixels: PixelStore { layers, masks }, baked, bake_paint, resources, bake_meshes } = a; + let Document { project, pixels: PixelStore { layers, masks }, baked, bake_paint, resources, bake_meshes, .. } = a; // Bake meshes have no equality (each holds a mesh and its BVH): the same high polys and cage // stand in for them. let same_meshes = bake_meshes.high.len() == b.bake_meshes.high.len() && bake_meshes.cage.is_some() == b.bake_meshes.cage.is_some(); From 886c7d8aa5e9a4a56859a238ba31f05c3f173f1f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 22:41:27 -0500 Subject: [PATCH 189/190] fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#904) --- .github/nightly-signing-policy.json | 10 +++++++++- docs/nightly-signing-policy.example.json | 10 +++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 51ac774f..61714f01 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -100,7 +100,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", diff --git a/docs/nightly-signing-policy.example.json b/docs/nightly-signing-policy.example.json index 99924a91..1e4070e7 100644 --- a/docs/nightly-signing-policy.example.json +++ b/docs/nightly-signing-policy.example.json @@ -42,7 +42,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", From b5d9abbb917647d3167e08d381c019a850b7fbbf Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 29 Nov 2026 08:04:24 +0000 Subject: [PATCH 190/190] Auto: Fix texture set resize ownership and reduce memory peaks Reject resize results from another project. Release stale pixels and caches before retrying a resize within the original project, preserving intervening edits and one-step undo. Fix rectangular height sampling, seam-boundary coverage, malformed set selectors and saved channel ordering. Reduce temporary composite and mesh-partition storage, and pack mixed-aspect trace textures without changing their samples. Keep channel actions reachable in short windows, strengthen export and modal regressions, document the control commands and remove unrelated formatting changes. --- .../examples/man-and-completions.rs | 5 +- apps/texturecraft-cli/src/args.rs | 12 +-- apps/texturecraft-cli/src/lib.rs | 16 +-- apps/texturecraft-cli/src/main.rs | 2 +- apps/texturecraft-cli/tests/cli.rs | 9 +- apps/texturecraft-cli/tests/it/cli.rs | 14 +-- apps/texturecraft-cli/tests/it/protocol.rs | 20 ++-- crates/automation/src/security.rs | 5 +- crates/compose/src/eval.rs | 85 ++++++++++++---- crates/compose/src/padding_maps.rs | 23 +++++ crates/compose/src/seam_padding.rs | 6 +- crates/compose/src/texel_edge.rs | 71 +++++++++----- crates/core/src/channel_group.rs | 1 + crates/core/src/height_to_normal.rs | 11 ++- crates/core/src/project.rs | 8 +- crates/engine/src/bake/mesh_map_command.rs | 1 - crates/engine/src/link_cmds.rs | 14 +-- crates/engine/src/session.rs | 58 +++++++---- crates/engine/src/set_cmds.rs | 78 +++++++++++---- crates/engine/tests/session.rs | 30 ++++++ crates/formats/src/export/mod.rs | 1 + crates/formats/src/export/tests.rs | 17 ++-- crates/geom/src/triangle_partition.rs | 53 ++++++---- crates/render/src/gpu_trace.rs | 72 +++++++++++--- crates/render/src/shaders/mesh.wgsl | 2 +- crates/render/src/shaders/trace.wgsl | 46 +++++---- crates/ui-egui/src/baking_log.rs | 2 - crates/ui-egui/src/channel_manager.rs | 61 +++--------- .../src/channel_manager/footer_layout.rs | 97 +++++++++++++++++++ crates/ui-egui/src/docking.rs | 2 - crates/ui-egui/src/fonts.rs | 3 +- crates/ui-egui/src/menus.rs | 2 +- .../src/property_sheet/material_rows.rs | 2 +- crates/ui-egui/src/texture_set_list.rs | 40 ++++++++ .../src/texture_set_list/list_state.rs | 2 +- crates/ui-egui/src/texture_set_settings.rs | 35 ++++++- crates/ui-egui/src/toast_action.rs | 1 - crates/ui-egui/src/toolbar.rs | 1 - crates/ui-egui/tests/bake_preview.rs | 26 ++++- docs/control-protocol.md | 21 ++++ 40 files changed, 674 insertions(+), 281 deletions(-) create mode 100644 crates/ui-egui/src/channel_manager/footer_layout.rs diff --git a/apps/texturecraft-cli/examples/man-and-completions.rs b/apps/texturecraft-cli/examples/man-and-completions.rs index 250d9ed4..55885101 100644 --- a/apps/texturecraft-cli/examples/man-and-completions.rs +++ b/apps/texturecraft-cli/examples/man-and-completions.rs @@ -19,7 +19,6 @@ fn main() -> ExitCode { eprintln!("usage: man-and-completions "); return ExitCode::from(2); }; - let dir = Path::new(&dir); match generate(dir) { Ok(()) => ExitCode::SUCCESS, @@ -37,7 +36,7 @@ pub(crate) fn generate(dir: &Path) -> std::io::Result<()> { for &shell in Shell::value_variants() { clap_complete::generate_to(shell, &mut cmd, "texturecraft-cli", dir)?; } - - // Build a fresh command to keep generated help subcommands out of the manual + // A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand, + // which `clap_mangen` would otherwise give pages of its own (`texturecraft-cli-help-convert.1`). clap_mangen::generate_to(texturecraft_cli::command(), dir) } diff --git a/apps/texturecraft-cli/src/args.rs b/apps/texturecraft-cli/src/args.rs index d8267fe0..549d8b0c 100644 --- a/apps/texturecraft-cli/src/args.rs +++ b/apps/texturecraft-cli/src/args.rs @@ -304,8 +304,7 @@ impl UsageError { /// The clap error, printed with the usage and exited with 2 like clap's own. pub(crate) fn into_clap(self, subcommand: &str) -> clap::Error { let mut command = crate::command(); - - // Built, so a subcommand's usage names the program: `texturecraft-cli run` + // Built, so a subcommand's usage names the program: `texturecraft-cli run`. command.build(); let mut command = command.find_subcommand_mut(subcommand).map_or_else(crate::command, std::mem::take); command.error(ErrorKind::ArgumentConflict, self.to_string()) @@ -352,21 +351,17 @@ fn batch_would_replace(a: &BatchArgs) -> Result<(), UsageError> { let Ok(text) = std::fs::read_to_string(&a.script) else { return Ok(()); }; - let Ok(script) = serde_json::from_str::(&text) else { return Ok(()); }; - let field = |name: &str| script.get(name).and_then(Value::as_str); let Some(output) = field("save") else { return Ok(()); }; - let input = field("open").unwrap_or("builtin:material_ball"); if input.starts_with("builtin:") { return if a.in_place { Err(UsageError::InPlaceNotUsed) } else { Ok(()) }; } - let input = Path::new(input); let output = Path::new(output); match (same_project(output, input), a.in_place) { @@ -414,15 +409,14 @@ impl Command { pub(crate) fn parse(args: &[OsString]) -> Result { let matches = crate::command().try_get_matches_from(std::iter::once(OsString::from("texturecraft-cli")).chain(args.iter().cloned()))?; let cli = Cli::from_arg_matches(&matches)?; - - // Only an explicit token flag requires bridge mode + // An inherited TEXTURECRAFT_CONTROL_TOKEN must not force --bridge: the variable is how a + // client authenticates when --bridge is already set. Only an explicit --token flag requires it. let token_flag_without_bridge = matches .subcommand_matches("mcp") .is_some_and(|mcp| mcp.value_source("token") == Some(clap::parser::ValueSource::CommandLine) && mcp.get_one::("bridge").is_none()); if token_flag_without_bridge { return Err(UsageError::TokenNeedsBridge.into_clap("mcp")); } - cli.command.check().map_err(|(sub, e)| e.into_clap(sub))?; Ok(cli) } diff --git a/apps/texturecraft-cli/src/lib.rs b/apps/texturecraft-cli/src/lib.rs index 68d01b5e..872765af 100644 --- a/apps/texturecraft-cli/src/lib.rs +++ b/apps/texturecraft-cli/src/lib.rs @@ -72,8 +72,7 @@ where outln!(err, "error: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); return 2; } - - // Help and the version (`help`, `-h`, ` --help`, `-V`) come back as errors too + // Help and the version (`help`, `-h`, ` --help`, `-V`) come back as errors too. let cli = match parse(&args) { Ok(cli) => cli, Err(e) => { @@ -148,7 +147,6 @@ fn info(a: &InfoArgs, out: &mut dyn Write) -> Result<(), CliError> { ); return Ok(()); } - if !is_project(&a.input) { let m = import_mesh(&a.input).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?; print( @@ -160,13 +158,11 @@ fn info(a: &InfoArgs, out: &mut dyn Write) -> Result<(), CliError> { ); return Ok(()); } - let h = open(&a.input, None)?; let mut v = h.inspect(); v["file"] = json!(file); v["kind"] = json!("project"); - - // The embedded mesh is re-imported for its UV report (built-in meshes have none) + // The embedded mesh is re-imported for its UV report (built-in meshes have none). v["uv"] = match &h.session.mesh_source { Some((ext, bytes)) => { let m = import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?; @@ -185,7 +181,6 @@ fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result<(), CliError> { print(out, &list); return Ok(()); } - for c in list.as_array().into_iter().flatten() { let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); outln!(out, "{:<28} {:<36} {}", f("id"), f("label"), f("params")); @@ -226,7 +221,6 @@ fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), message: failure["error"].as_str().unwrap_or_default().to_string(), }); } - match output { Some(path) => save(&mut h, Path::new(path), err), None => Ok(()), @@ -234,7 +228,7 @@ fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), } fn bake(a: &BakeArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { - // `check` has seen to it: a project without -o is saved in place (--in-place), a mesh has -o + // `check` has seen to it: a project without -o is saved in place (--in-place), a mesh has -o. let target = a.output.as_deref().unwrap_or(&a.input); let mut p = json!({"ts": "all"}); if let Some(r) = a.resolution { @@ -298,7 +292,6 @@ fn new(a: &NewArgs, err: &mut dyn Write) -> Result<(), CliError> { if is_project(&a.input) { return Err(CliError::AlreadyProject(a.input.clone())); } - let mut h = open(&a.input, a.resolution)?; if a.sample { let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024)); @@ -317,7 +310,6 @@ fn workspace(roots: &RootArgs) -> Result { if roots.read_root.is_none() && roots.write_root.is_none() { return Ok(Filesystem::Denied); } - Ok(Filesystem::Workspace(AuthorizedWorkspace::new(roots.read_root.as_deref(), roots.write_root.as_deref())?)) } @@ -335,7 +327,7 @@ fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result<(), CliError> { match a.port { None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(CliError::Serve)?, Some(port) => { - // Bind first: a port in use must not replace its server's token file + // Bind first: a port in use must not replace its server's token file. let listener = rpc::bind_tcp(port)?; let addr = listener.local_addr().map_err(CliError::Serve)?; let (token, file) = server_token(addr.port())?; diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index ffb91e39..357cf17e 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -2,7 +2,7 @@ #![forbid(unsafe_code)] fn main() { - // `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed + // `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed. let code = texturecraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); std::process::exit(code); } diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 0dc768b4..0d838118 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -216,21 +216,18 @@ fn render_without_a_gpu_points_to_path_tracing() { fn path_traced_render_needs_no_gpu() { let d = tmp("trace"); let out = d.join("ball.png"); - - // On the GPU where it has compute shaders, then forced onto the CPU + // On the GPU where it has compute shaders, then forced onto the CPU. for extra in [None, Some("--cpu")] { let mut args = vec!["render", "builtin:material_ball", p(&out), "--size", "96x64", "--samples", "4"]; args.extend(extra); ok(&args); let img = image::open(&out).unwrap().to_rgb8(); assert_eq!(img.dimensions(), (96, 64)); - - // The lit ball in the middle is brighter than the dark backdrop corner + // The lit ball in the middle is brighter than the dark backdrop corner. let lum = |x, y| img.get_pixel(x, y).0.iter().map(|v| *v as u32).sum::(); assert!(lum(48, 28) > lum(1, 1) + 60); } - - // --camera looks through a camera saved in the project; an unknown name is an error + // --camera looks through a camera saved in the project; an unknown name is an error. let proj = d.join("cams.tcraft"); ok(&["run", "builtin:cube", "camera.set", r#"{"yaw": 80, "distance": 9}"#, "-o", p(&proj)]); ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj), "--in-place"]); diff --git a/apps/texturecraft-cli/tests/it/cli.rs b/apps/texturecraft-cli/tests/it/cli.rs index f1307e1b..332da939 100644 --- a/apps/texturecraft-cli/tests/it/cli.rs +++ b/apps/texturecraft-cli/tests/it/cli.rs @@ -130,7 +130,7 @@ fn bad_values_conflicts_and_missing_arguments_are_refused_before_any_file_is_wri #[test] fn loopback_ports_take_the_host_prefix_and_a_dashed_name_follows_a_double_dash() { - // `--bridge 127.0.0.1:PORT` and `localhost:PORT` are still ports: the failure is the missing token + // `--bridge 127.0.0.1:PORT` and `localhost:PORT` are still ports: the failure is the missing token. for bridge in ["127.0.0.1:9", "localhost:9"] { let got = invoke(["mcp", "--bridge", bridge, "--token", "short"]); assert_eq!(got.code, 1, "{bridge}: {}", got.err); @@ -201,8 +201,7 @@ fn an_output_that_would_replace_an_input_is_refused_without_in_place() { assert!(message.contains("--in-place") || message.contains("would replace"), "{args:?}: {message}"); } assert_eq!(std::fs::read(&source).unwrap(), before, "a refused command changes nothing"); - - // `--in-place` lets only a project be replaced, and only by itself + // `--in-place` lets only a project be replaced, and only by itself. let got = invoke(["run", a, "layer.add.fill", "{}", "-o", a, "--in-place"]); assert_eq!(got.code, 0, "{}", got.err); let got = invoke(["bake", a, "--in-place", "--resolution", "128", "--maps", "ambientOcclusion"]); @@ -211,8 +210,7 @@ fn an_output_that_would_replace_an_input_is_refused_without_in_place() { assert!(usage_error(&["run", a, "layer.add.fill", "{}", "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place")); assert!(usage_error(&["bake", a, "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place")); assert!(!elsewhere.exists()); - - // Headless::save appends .tcraft, so `-o scene` would replace scene.tcraft + // Headless::save appends .tcraft, so `-o scene` would replace scene.tcraft. let unsuffixed = dir.join("a"); let unsuffixed = unsuffixed.to_str().unwrap(); let after_in_place = std::fs::read(&source).unwrap(); @@ -246,8 +244,7 @@ fn batch_runs_a_script_and_a_failing_step_fails_the_command() { let got = invoke(argv(&[&"batch", &dir.join("missing.json")])); assert_eq!(got.code, 1); assert!(got.err.contains("missing.json"), "{}", got.err); - - // A script that saves over the project it opened needs --in-place, and must not have run + // A script that saves over the project it opened needs --in-place, and must not have run. let opened = project(&dir, "opened.tcraft"); let before = std::fs::read(&opened).unwrap(); let overwrite = dir.join("overwrite.json"); @@ -294,8 +291,7 @@ fn the_desktop_launch_options_are_refused_before_any_subcommand() { fn a_path_that_is_not_valid_unicode_is_named_in_the_error() { use std::os::unix::ffi::OsStringExt; let dir = workdir("non-unicode"); - - // The engine's commands take their paths as JSON text: the command says so and names the file + // The engine's commands take their paths as JSON text: the command says so and names the file. let input = dir.join(OsString::from_vec(b"in-\xff.tcraft".to_vec())); let got = invoke(argv(&[&"info", &input])); assert_eq!(got.code, 1); diff --git a/apps/texturecraft-cli/tests/it/protocol.rs b/apps/texturecraft-cli/tests/it/protocol.rs index 775754af..db504b54 100644 --- a/apps/texturecraft-cli/tests/it/protocol.rs +++ b/apps/texturecraft-cli/tests/it/protocol.rs @@ -37,8 +37,7 @@ fn serve_writes_nothing_but_json_lines_to_stdout() { fn serve_ends_quietly_and_mcp_reports_it_when_stdin_is_closed() { let output = binary().arg("serve").stdin(Stdio::null()).output().unwrap(); assert_eq!((output.status.code(), output.stdout.is_empty(), output.stderr.is_empty()), (Some(0), true, true)); - - // An MCP client must open with `initialize`; end of input before it is a failed start + // An MCP client must open with `initialize`; end of input before it is a failed start. let dir = std::env::temp_dir().join(format!("tc-mcp-stdio-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let output = binary().args(["mcp", "--read-root", dir.to_str().unwrap(), "--write-root", dir.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); @@ -63,25 +62,21 @@ fn bridge(token_flag: Option<&str>, env: Option<&str>) -> Output { #[test] fn the_control_token_variable_is_a_fallback_the_flag_wins_and_an_empty_one_is_unset() { let secret = "env-token-0123456789-secret"; - - // Empty or blank counts as unset: the error says to set one, as when there is none + // Empty or blank counts as unset: the error says to set one, as when there is none. for blank in ["", " "] { let output = bridge(None, Some(blank)); let err = String::from_utf8_lossy(&output.stderr); assert_eq!(output.status.code(), Some(1), "{err}"); assert!(err.contains("no control token: set TEXTURECRAFT_CONTROL_TOKEN"), "{err}"); } - - // The variable is used when there is no flag: a good token gets as far as connecting + // The variable is used when there is no flag: a good token gets as far as connecting. let err = String::from_utf8_lossy(&bridge(None, Some(secret)).stderr).into_owned(); assert!(!err.contains("16 to 1024") && !err.contains(secret), "{err}"); - - // The flag wins over a good variable: its bad value is what is reported, without echoing either + // The flag wins over a good variable: its bad value is what is reported, without echoing either. let err = String::from_utf8_lossy(&bridge(Some("short"), Some(secret)).stderr).into_owned(); assert!(err.contains("control token must be 16 to 1024"), "{err}"); assert!(!err.contains(secret) && !err.contains("short\n"), "{err}"); - - // A bad value in the variable is refused too, and its value stays out of the message + // A bad value in the variable is refused too, and its value stays out of the message. let err = String::from_utf8_lossy(&bridge(None, Some("bad token")).stderr).into_owned(); assert!(err.contains("control token must be 16 to 1024") && !err.contains("bad token"), "{err}"); } @@ -95,7 +90,7 @@ fn help_lists_the_variable_but_never_its_value() { #[test] fn a_variable_alone_grants_no_file_access() { - // The token variable is for authentication only: a headless server with no roots still refuses files + // The token variable is for authentication only: a headless server with no roots still refuses files. let mut child = binary().arg("serve").env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); let mut stdin = child.stdin.take().unwrap(); @@ -108,7 +103,8 @@ fn a_variable_alone_grants_no_file_access() { #[test] fn a_token_in_the_environment_does_not_require_bridge() { - // An inherited control token also permits headless startup + // Headless MCP must parse even when TEXTURECRAFT_CONTROL_TOKEN is set; only --token on the + // command line requires --bridge. let output = binary().args(["mcp", "--fromat"]).env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").output().unwrap(); let err = String::from_utf8_lossy(&output.stderr); assert_eq!(output.status.code(), Some(2), "{err}"); diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 14a75afb..6d4bca71 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -75,7 +75,6 @@ pub fn server_token(port: u16) -> Result<(String, Option), AutomationEr validate_token(t.trim())?; return Ok((t.trim().to_string(), None)); } - let token = generate_token()?; let path = token_file(port); write_token_file(&path, &token).map_err(|e| { @@ -238,7 +237,9 @@ mod tests { #[test] fn a_blank_token_counts_as_not_given() { - // A blank supplied token can fall back to a nonblank inherited token + // No token anywhere (the port has no token file): the error says what to set, not that a + // blank token is invalid. A non-blank inherited TOKEN_ENV can still satisfy the client + // after a blank supplied value, so do not unwrap_err() first. match client_token(1, Some(" ".into())) { Err(error) => { if std::env::var_os(TOKEN_ENV).is_none() { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index c2818bc8..1a9e393b 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -14,10 +14,10 @@ use rayon::prelude::*; use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelFormat, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, - GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, - MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, - SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, - blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + GrayscaleConversionParameters, HeightMask, HeightToNormal, HeightToNormalMethod, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, + MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, + ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, + WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -818,7 +818,7 @@ fn gather( Op::SourceSlopeBlur(slope) => slope_texel(&slope, (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)), Op::HeightToNormal(filter) => { let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); - height_to_normal_texel(&filter, (x, y), (res, center), &mut acc, &input); + height_to_normal_texel(&filter, (x, y), (tile_size, center), &mut acc, &input); } Op::Kuwahara(kuwahara) => { let radius = (kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS) * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); @@ -959,21 +959,18 @@ fn mean_region_color(data: &[f32], fallback: [f32; 3]) -> [f32; 3] { fn height_to_normal_texel( filter: &HeightToNormal, (x, y): (f32, f32), - (res, center): (u32, &[f32]), + (tile_size, center): ([u32; 2], &[f32]), acc: &mut [f32; 5], height: &dyn Fn(f32, f32) -> Option, ) { let (Some(own), [red, green, blue, cov]) = (height(x, y), center) else { return }; + if *cov <= 0.0 { return; } - let at = |dx: f32, dy: f32| height(x + dx, y + dy).unwrap_or(own); - - // Sobel gradients over the kernel's weight sum - let gx = (at(1.0, -1.0) + 2.0 * at(1.0, 0.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(-1.0, 0.0) - at(-1.0, 1.0)) / 8.0; - let gy = (at(-1.0, 1.0) + 2.0 * at(0.0, 1.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(0.0, -1.0) - at(1.0, -1.0)) / 8.0; - let made = filter.normal([gx, gy], res).map(|v| v * 0.5 + 0.5); + let slope = HeightToNormalMethod::Smooth.slope(|dx, dy| height(x + dx as f32, y + dy as f32).unwrap_or(own)); + let made = filter.normal_for_size(slope, tile_size).map(|value| value * 0.5 + 0.5); let packed = if filter.overwrite { made } else { texturecraft_core::blend::rnm([red, green, blue].map(|v| v / cov), made) }; for (slot, value) in acc.iter_mut().zip(packed) { *slot = value * cov; @@ -3364,9 +3361,11 @@ impl<'a, 'b> Texel<'a, 'b> { let (width, height) = (self.res, self.inp.gbuf.height); let at = |x: u32, y: u32| self.inp.baked.sample_working(BakedMap::Height, x, y, (width, height), &self.inp.block_scales).map(|h| h[0]); let (origin_x, origin_y, tile_width, tile_height) = if let Some(grid) = self.inp.tile_grid() { - let block = (width / grid.cols.max(1)).max(1); - let tile = ((block as f32 * self.inp.block_scales.at(self.x, self.y)).round() as u32).max(1); - (self.x / block * block, self.y / block * block, tile, tile) + let block_width = (width / grid.cols.max(1)).max(1); + let block_height = (height / grid.rows.max(1)).max(1); + let scale = self.inp.block_scales.at(self.x, self.y); + let tile_side = |block_side| ((block_side as f32 * scale).round() as u32).max(1); + (self.x / block_width * block_width, self.y / block_height * block_height, tile_side(block_width), tile_side(block_height)) } else { (0, 0, width, height) }; @@ -4878,20 +4877,26 @@ fn composite_block( // Join the bands of each tile (in parallel; uncovered tiles are freed) let joined: Vec = results - .par_chunks(bands as usize) + .par_chunks_mut(bands as usize) .map(|parts| { let any = parts.iter().any(|p| p.2); let data = (0..channels.len()) .map(|k| { any.then(|| { let mut v = Vec::with_capacity(parts.iter().map(|p| p.0.get(k).map_or(0, Vec::len)).sum()); - for p in parts { + for p in parts.iter() { v.extend_from_slice(p.0.get(k).map_or(&[][..], Vec::as_slice)); } std::sync::Arc::new(v) }) }) .collect(); + + // Only replay data is needed after joining the tile + for (channel_buffers, _, _) in parts { + channel_buffers.clear(); + } + (data, any) }) .collect(); @@ -5675,6 +5680,52 @@ mod tests { assert!(close(composite.value(Channel::BaseColor, 48, 32), [1.0, 0.0, 0.0]), "the exposed side takes the fill"); } + #[test] + fn a_rectangular_height_filter_tilts_equally_for_equal_uv_slopes() { + let (width, height) = (16, 32); + let texels = (width * height) as usize; + let normals: Vec = [0.5, 0.5, 1.0, 1.0].into_iter().cycle().take(texels * 4).collect(); + let coverage = vec![1.0; texels]; + let heights: Vec<_> = (0..width * height).map(|index| (index % width) as f32 / width as f32 + (index / width) as f32 / height as f32).collect(); + + let normal = gather( + Op::HeightToNormal(HeightToNormal::LIBRARY), + (&normals, &coverage, &heights), + 4, + (0, 0, width, height), + 1.0, + (width, [width, height], [width, height]), + 1.0, + ); + let center = (height / 2 * width + width / 2) as usize * 4; + let (red, green) = (normal[center], normal[center + 1]); + + assert!(red < 0.5 && green > 0.5); + assert!((1.0 - red - green).abs() < 1e-6, "equal UV slopes produced unequal tilt: {red}, {green}"); + } + + #[test] + fn baked_height_slopes_respect_rectangular_udim_blocks() { + let mut fixture = fixture(); + let (block_width, block_height) = (64, 128); + let set = &mut fixture.project.texture_sets[0]; + set.set_size(block_width, block_height); + set.uv_tiles = vec![1001, 1011]; + let (width, height) = set.size(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, width, height); + fixture.baked.resolution = width; + let heights = (0..width * height).map(|i| (i % width) as f32 / block_width as f32 + (i / width % block_height) as f32 / block_height as f32).collect(); + fixture.baked.maps.insert(BakedMap::Height, Arc::new(heights)); + let images = ImageStore::default(); + let inputs = inputs(&fixture, &images, None); + + for y in [block_height - 1, block_height] { + let slope = Texel::new(&inputs, 10, y, 0, 0.0).height_slope(); + + assert_eq!(slope, Some([1.0; 2]), "slope at row {y} must stay within its rectangular tile"); + } + } + #[test] fn baked_height_slopes_stay_within_each_uv_tile() { let mut fixture = fixture(); diff --git a/crates/compose/src/padding_maps.rs b/crates/compose/src/padding_maps.rs index 7c932479..28c90f27 100644 --- a/crates/compose/src/padding_maps.rs +++ b/crates/compose/src/padding_maps.rs @@ -104,6 +104,29 @@ mod tests { SeamPaddingInput::new(seams, triangles, partition) } + #[test] + fn a_flat_seam_keeps_the_last_row_within_its_reach() { + let (width, height) = (128, 128); + let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); + // The length rounds the normalized edge slightly below one + let near = UvSeamSide { triangle: 0, start: at(1.0, 32.5), end: at(16.25, 32.5), interior: at(1.0, 40.0) }; + let far = UvSeamSide { triangle: 1, start: at(65.0, 32.5), end: at(80.25, 32.5), interior: at(65.0, 100.0) }; + let triangles: Vec<_> = (0..width * height) + .map(|index| match (index % width, index / width) { + (1..=15, 32..=39) => 0, + (65..=79, 32..=99) => 1, + _ => NO_TRI, + }) + .collect(); + let covered: Vec<_> = triangles.iter().map(|&triangle| triangle != NO_TRI).collect(); + let seams = islands(vec![UvSeam { sides: [near, far] }], &triangles); + + let padding = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (width, height), Some(SEAM_REACH), (64, height), Some(&seams)); + + assert!(padding.source(true, 15, 0).is_some_and(|(x, _)| x >= 64), "the boundary row borrows from the far island"); + assert!(padding.source(false, 15, 0).is_some_and(|(x, _)| x < 64), "flat padding still uses the near island"); + } + #[test] fn padding_stops_at_the_far_islands_edge() { let (_, seams) = two_islands(); diff --git a/crates/compose/src/seam_padding.rs b/crates/compose/src/seam_padding.rs index 6640b0ab..6707983f 100644 --- a/crates/compose/src/seam_padding.rs +++ b/crates/compose/src/seam_padding.rs @@ -32,11 +32,7 @@ pub(crate) fn cross_seams(flat: &DilationMap, reach: u32, block: (u32, u32), inp let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32); let mut side_islands = None; for y in y0..y1 { - // Only the texel centres in the band beside the seam can be within its reach - let Some((low_x, high_x)) = near_edge.band_span(reach, y as f32 + 0.5) else { continue }; - let row_x0 = ((low_x - 0.5).floor().max(0.0) as u32).max(x0); - let row_x1 = ((high_x + 0.5).ceil().max(0.0) as u32).min(x1); - for x in row_x0..row_x1 { + for x in near_edge.outside_columns(y, x0..x1, reach) { let index = y * width + x; let Some(&flat_source) = flat.src.get(index as usize) else { continue }; diff --git a/crates/compose/src/texel_edge.rs b/crates/compose/src/texel_edge.rs index 25ea3d36..30a5e687 100644 --- a/crates/compose/src/texel_edge.rs +++ b/crates/compose/src/texel_edge.rs @@ -1,5 +1,7 @@ //! A UV seam side in texel space +use std::ops::Range; + use texturecraft_geom::UvSeamSide; use texturecraft_geom::glam::Vec2; @@ -22,29 +24,49 @@ impl TexelEdge { pub(crate) fn outside(&self, point: Vec2) -> Option<(f32, f32)> { let direction = self.end - self.start; let along = (point - self.start).dot(direction) / direction.length_squared(); - let outside = -(point - self.start).dot(self.inward); + let outside = self.outside_distance(point); ((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside)) } - /// The x range at height `y` of the band `reach` deep outside the edge: every point there that `outside` takes within `reach` - pub(crate) fn band_span(&self, reach: f32, y: f32) -> Option<(f32, f32)> { - let depth = self.inward * -reach; - let corners = [self.start, self.end, self.end + depth, self.start + depth]; - let mut span: Option<(f32, f32)> = None; - for (index, &from) in corners.iter().enumerate() { - let to = corners[(index + 1) % corners.len()]; - if y < from.y.min(to.y) || y > from.y.max(to.y) { - continue; - } - - // A level side spans its whole length at its height - let xs = if from.y == to.y { [from.x, to.x] } else { [from.x + (to.x - from.x) * (y - from.y) / (to.y - from.y); 2] }; - for x in xs { - span = Some(span.map_or((x, x), |(low, high)| (low.min(x), high.max(x)))); - } - } - span + fn outside_distance(&self, point: Vec2) -> f32 { + -(point - self.start).dot(self.inward) } + + /// Clip columns to the exterior distance band using the same rounded distances as `outside` + pub(crate) fn outside_columns(&self, row: u32, columns: Range, reach: f32) -> Range { + if columns.is_empty() { + return columns; + } + + let distance = |column| self.outside_distance(Vec2::new(column as f32 + 0.5, row as f32 + 0.5)); + if self.inward.x == 0.0 { + let outside = distance(columns.start); + return if outside > 0.0 && outside <= reach { columns } else { 0..0 }; + } + + // Signed distance is monotone across a row even when adjacent values round to the same distance + let (start, end) = if self.inward.x < 0.0 { + let start = first_column_after(columns.clone(), |column| distance(column) <= 0.0); + (start, first_column_after(start..columns.end, |column| distance(column) <= reach)) + } else { + let start = first_column_after(columns.clone(), |column| distance(column) > reach); + (start, first_column_after(start..columns.end, |column| distance(column) > 0.0)) + }; + start..end + } +} + +fn first_column_after(mut columns: Range, before: impl Fn(u32) -> bool) -> u32 { + while columns.start < columns.end { + let middle = columns.start.midpoint(columns.end); + if before(middle) { + columns.start = middle + 1; + } else { + columns.end = middle; + } + } + + columns.start } #[cfg(test)] @@ -55,23 +77,22 @@ mod tests { use super::TexelEdge; #[test] - fn a_diagonal_edges_band_spans_every_point_beside_it_and_little_else() { + fn a_diagonal_edges_band_spans_every_texel_beside_it_without_scanning_the_rectangle() { let size = Vec2::splat(512.0); let side = UvSeamSide { triangle: 0, start: Vec2::new(0.05, 0.05), end: Vec2::new(0.95, 0.9), interior: Vec2::new(0.9, 0.1) }; let edge = TexelEdge::new(side, size).unwrap(); let reach = 32.0; let (mut beside, mut spanned) = (0, 0); - for y in 0..512 { + for y in 0..512u32 { let centre_y = y as f32 + 0.5; - let span = edge.band_span(reach, centre_y); - spanned += span.map_or(0, |(low, high)| (high - low).ceil() as usize + 1); + let span = edge.outside_columns(y, 0..512, reach); + spanned += span.len(); for x in 0..512 { let point = Vec2::new(x as f32 + 0.5, centre_y); if edge.outside(point).is_some_and(|(_, outside)| outside <= reach) { beside += 1; - let (low, high) = span.unwrap_or((f32::MAX, f32::MIN)); - assert!((low..=high).contains(&point.x), "{point} is beside the edge but outside its row's span {span:?}"); + assert!(span.contains(&x), "{point} is beside the edge but outside its row's span {span:?}"); } } } diff --git a/crates/core/src/channel_group.rs b/crates/core/src/channel_group.rs index a1deaae0..99a1ec76 100644 --- a/crates/core/src/channel_group.rs +++ b/crates/core/src/channel_group.rs @@ -112,6 +112,7 @@ mod tests { let count = listed.len(); listed.sort(); listed.dedup(); + assert_eq!(listed.len(), count, "a channel is listed twice"); assert_eq!(listed, Channel::ALL.to_vec()); } diff --git a/crates/core/src/height_to_normal.rs b/crates/core/src/height_to_normal.rs index f88caedf..e3ca2f89 100644 --- a/crates/core/src/height_to_normal.rs +++ b/crates/core/src/height_to_normal.rs @@ -53,9 +53,14 @@ impl HeightToNormal { } /// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down - pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] { - let strength = self.strength(res); - let (x, y) = (-gx * strength, gy * strength); + pub fn normal(&self, slope: [f32; 2], res: u32) -> [f32; 3] { + self.normal_for_size(slope, [res; 2]) + } + + /// The same tangent-space normal for a UV tile with independent width and height + pub fn normal_for_size(&self, [gx, gy]: [f32; 2], [width, height]: [u32; 2]) -> [f32; 3] { + let strength_per_uv = self.strength(1); + let (x, y) = (-gx * (strength_per_uv * width as f32), gy * (strength_per_uv * height as f32)); let length = (x * x + y * y + 1.0).sqrt(); if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] } } diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index af2ed5c6..205db3d2 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -385,8 +385,12 @@ impl TextureSet { /// The channels with the formats they are stored in (8-bit ones read as 16-bit without `format_precision`) pub fn formats(&self) -> Vec<(Channel, ChannelFormat)> { - let held = |format: ChannelFormat| if self.format_precision { format } else { format.at_least_16_bit() }; - self.channels.iter().map(|(channel, format)| (*channel, held(*format))).collect() + self.iter_formats().collect() + } + + /// The effective storage formats in texture-set order + pub fn iter_formats(&self) -> impl Iterator + '_ { + self.channels.iter().map(|&(channel, format)| (channel, if self.format_precision { format } else { format.at_least_16_bit() })) } /// Add channel `c` in its default format (16-bit or more until a format is set, see [`TextureSet::formats`]); false when present diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 5c317d11..4a5162e8 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -877,7 +877,6 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { Ok(tracer) => tracers.push(tracer), Err(error) => { session.bake_log.set_failed(index, &error.to_string()); - // The edit rolls back the sets baked before this one too session.bake_log.discard(); return Err(error); diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index f2fac4e4..1e28b781 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -384,14 +384,11 @@ fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[ if file_name.is_empty() || std::path::Path::new(file_name).file_name() != Some(std::ffi::OsStr::new(file_name)) { return Err(EngineError::Other(format!("`{file_name}` is not a plain file name"))); } - sweep_old_handoffs(base, HANDOFF_MAX_AGE); - - // Dropped (and removed) on any early return, so a failed write leaves no empty folder behind + // Dropped (and removed) on any early return, so a failed write leaves no empty folder behind. let mut builder = tempfile::Builder::new(); builder.prefix(HANDOFF_PREFIX); - - // tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly + // tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly. #[cfg(unix)] builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)); let dir = builder.tempdir_in(base).map_err(io)?; @@ -416,7 +413,6 @@ fn sweep_old_handoffs(base: &std::path::Path, max_age: std::time::Duration) { if !entry.file_name().to_string_lossy().starts_with(HANDOFF_PREFIX) { continue; } - let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; let old = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age); if meta.is_dir() && old { @@ -873,8 +869,7 @@ mod tests { let base = scratch("planted"); let victim = base.join("victim.txt"); std::fs::write(&victim, b"precious").unwrap(); - - // The old code wrote `/` with `fs::write`; a hard link there reaches the victim on every platform + // The old code wrote `/` with `fs::write`; a hard link there reaches the victim on every platform. std::fs::hard_link(&victim, base.join("wood.mcraft")).unwrap(); let path = super::stage_handoff_package_in(&base, "wood.mcraft", b"package").unwrap(); @@ -927,8 +922,7 @@ mod tests { std::fs::create_dir(dir).unwrap(); } std::fs::write(&file, b"x").unwrap(); - - // Zero age limit: everything with the prefix that is a folder counts as old + // Zero age limit: everything with the prefix that is a folder counts as old. super::sweep_old_handoffs(&base, std::time::Duration::ZERO); assert!(!old.exists() && other.exists() && file.exists()); let young = base.join("texturecraft-open-young"); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e0ad858b..eba4e19a 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -89,6 +89,24 @@ impl SetCache { } } + fn has_channels(&self, set: &TextureSet) -> bool { + if self.composite.channels.len() != set.channels.len() { + return false; + } + + if self.composite.channels.keys().copied().eq(set.channels.iter().map(|&(channel, _)| channel)) { + return true; + } + + // Saved sets can list their channels in a different order from the composite + let mut present = [false; Channel::ALL.len()]; + for &(channel, _) in &set.channels { + present[channel.index()] = true; + } + + self.composite.channels.keys().all(|channel| present[channel.index()]) + } + pub fn invalidate_all(&mut self) { self.dirty.extend(self.covered_tiles.iter().copied()); } @@ -974,31 +992,31 @@ impl Session { pub fn sync_caches(&mut self) { let sets = &self.doc.project.texture_sets; self.caches.truncate(sets.len()); - for (i, ts) in sets.iter().enumerate() { - match self.caches.get_mut(i) { - Some(c) if c.size == ts.size() => { - if c.uv_padding != ts.uv_padding { - c.uv_padding = ts.uv_padding; - c.padding = Arc::new(display_padding(&self.mesh, ts, &c.gbuf)); - c.invalidate_all(); - } - let formats = ts.formats(); - if c.formats != formats { - c.formats = formats; - c.invalidate_all(); + for (index, set) in sets.iter().enumerate() { + match self.caches.get_mut(index) { + Some(cache) if cache.size == set.size() => { + if cache.uv_padding != set.uv_padding { + cache.uv_padding = set.uv_padding; + cache.padding = Arc::new(display_padding(&self.mesh, set, &cache.gbuf)); + cache.invalidate_all(); } - let (want, scales) = (ts.channel_list(), ts.block_scales()); - if c.composite.channels.keys().copied().collect::>() != want || c.composite.block_scales != scales { - c.composite = Composite { block_scales: scales, ..Composite::with_size(&want, c.size.0, c.size.1) }; - c.upload.extend(texturecraft_compose::all_tiles(c.size.0, c.size.1)); - c.invalidate_all(); + if !cache.formats.iter().copied().eq(set.iter_formats()) { + cache.formats = set.formats(); + cache.invalidate_all(); + } + + let scales = set.block_scales(); + if !cache.has_channels(set) || cache.composite.block_scales != scales { + cache.composite = Composite { block_scales: scales, ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) }; + cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1)); + cache.invalidate_all(); } } _ => { - let cache = SetCache::new(&self.mesh, ts); - if i < self.caches.len() { - self.caches[i] = cache; + let cache = SetCache::new(&self.mesh, set); + if index < self.caches.len() { + self.caches[index] = cache; } else { self.caches.push(cache); } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 64f7cea9..1df867b3 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -93,18 +93,21 @@ pub fn parts(s: &Session, ts: usize) -> Vec { } pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result { - match u64p(p, "ts") { - Some(t) if (t as usize) < s.set_count() => Ok(t as usize), - Some(t) => Err(bad(cmd, format!("no texture set {t}"))), - None => Ok(s.ts()), + if p.get("ts").is_none_or(Value::is_null) { + return Ok(s.ts()); } + + let index = u64p(p, "ts").ok_or_else(|| bad(cmd, "valid `ts` index required"))?; + usize::try_from(index).ok().filter(|&index| index < s.set_count()).ok_or_else(|| bad(cmd, format!("no texture set {index}"))) } fn select(s: &mut Session, p: &Value) -> Result { - let ts = u64p(p, "ts") - .map(|index| index as usize) - .filter(|index| *index < s.set_count()) - .ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + let cmd = "textureSet.select"; + if p.get("ts").is_none_or(Value::is_null) { + return Err(bad(cmd, "valid `ts` index required")); + } + + let ts = ts_param(s, p, cmd)?; select_set(s, ts)?; Ok(json!({ "ts": ts })) } @@ -148,7 +151,8 @@ pub struct ResizeTask { height: u32, doc: Document, mesh: Arc, - /// The session's revision and mesh when the task was made: the result applies only to them. + project_id: u64, + /// The revision and mesh used to calculate this result. from: (u64, u64), } @@ -161,6 +165,7 @@ pub struct ResizeOutput { /// The set's new caches (None when its UV tile layout moved: the session rebuilds them). cache: Option, log: crate::log::SessionLog, + project_id: u64, from: (u64, u64), } @@ -168,7 +173,7 @@ impl ResizeTask { /// Resample the set's painted pixels (bilinear; strokes are not replayed) and build its /// caches. Progress goes from 0 to 1. pub fn run(self, progress: &texturecraft_bake::Progress) -> Result { - let ResizeTask { ts, resolution, height, mut doc, mesh, from } = self; + let ResizeTask { ts, resolution, height, mut doc, mesh, project_id, from } = self; let set = doc.project.texture_set_mut(ts)?; let old = set.clone(); set.set_size(resolution, height); @@ -190,7 +195,7 @@ impl ResizeTask { let set = doc.project.texture_set(ts)?; let cache = (crate::session::uv_layout(&old) == crate::session::uv_layout(set)).then(|| SetCache::new(&mesh, set)); progress.done.store(10_000, std::sync::atomic::Ordering::Relaxed); - Ok(ResizeOutput { ts, resolution, height, doc, cache, log, from }) + Ok(ResizeOutput { ts, resolution, height, doc, cache, log, project_id, from }) } } @@ -212,15 +217,30 @@ impl Session { let (resolution, height) = (check_resolution(width)?, check_resolution(height)?); self.doc.project.texture_set(ts)?; self.cancel_stroke(); - Ok(ResizeTask { ts, resolution, height, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) }) + Ok(ResizeTask { + ts, + resolution, + height, + doc: self.doc.clone(), + mesh: self.mesh.clone(), + project_id: self.project_id, + from: (self.revision, self.mesh_id), + }) } - /// Apply a finished resize as one undo step. When the document changed while it ran, the - /// resize runs again here on the current document. - pub fn apply_resize(&mut self, out: ResizeOutput) -> Result { + /// Apply a finished resize to its original project as one undo step. Edits made while the + /// resize ran are preserved by recomputing from the current document. + pub fn apply_resize(&mut self, mut out: ResizeOutput) -> Result { + if out.project_id != self.project_id { + return Err(bad("textureSet.resolution", "the project changed while the texture set was resizing")); + } + if out.from != (self.revision, self.mesh_id) || self.stroke_active() { - let task = self.resize_task_to(out.ts, out.resolution, out.height)?; - return self.apply_resize(task.run(&texturecraft_bake::Progress::new())?); + let (ts, width, height) = (out.ts, out.resolution, out.height); + + // Release the stale pixels and cache before building their replacement + drop(out); + out = self.resize_task_to(ts, width, height)?.run(&texturecraft_bake::Progress::new())?; } let ResizeOutput { ts, resolution, height, doc, cache, log, .. } = out; @@ -286,7 +306,11 @@ fn channels(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("{} is both added and removed", both.label()))); } - let sets: Vec = if boolp(p, "allSets").unwrap_or(false) { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] }; + let all_sets = match p.get("allSets") { + None | Some(Value::Null) => false, + Some(value) => value.as_bool().ok_or_else(|| bad(cmd, "`allSets` must be a boolean"))?, + }; + let sets: Vec = if all_sets { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] }; s.edit("Add or remove channels", |s| { for &ts in &sets { @@ -494,6 +518,24 @@ mod tests { assert!(!layer_has_roughness(&s), "the layer's roughness stays off"); } + #[test] + fn invalid_set_selectors_cannot_edit_the_active_set() { + let mut session = crate::sample_session(128, 64).unwrap(); + let before = session.doc.project.texture_sets[session.ts()].clone(); + + for ts in [json!("0"), json!(-1), json!(1_u64 << 32)] { + let params = json!({"ts": ts, "description": "wrong set"}); + + assert!(crate::execute(&mut session, "textureSet.settings", ¶ms).is_err(), "{ts}"); + assert_eq!(session.doc.project.texture_sets[session.ts()], before); + assert!(crate::execute(&mut session, "textureSet.select", ¶ms).is_err(), "{ts}"); + } + + let invalid_scope = json!({"add": ["user7"], "allSets": "true"}); + assert!(crate::execute(&mut session, "textureSet.channels", &invalid_scope).is_err()); + assert_eq!(session.doc.project.texture_sets[session.ts()], before); + } + #[test] fn malformed_size_and_setting_values_are_refused_and_change_nothing() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 3387f652..383946f0 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1093,6 +1093,36 @@ fn committed_strokes_settle_to_the_full_composite() { assert_eq!(full(&mut s), original); } +#[test] +fn synchronizing_a_saved_channel_order_preserves_the_composite() { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + session.doc.project.texture_sets[0].channels.reverse(); + let bytes = session.to_project_bytes().unwrap(); + let mut reopened = Session::from_project_bytes(&bytes).unwrap(); + reopened.update(); + reopened.caches[0].upload.clear(); + + reopened.sync_caches(); + + assert!(reopened.caches[0].dirty.is_empty(), "the unchanged set should keep its composited tiles"); + assert!(reopened.caches[0].upload.is_empty(), "the unchanged set should require no uploads"); +} + +#[test] +fn a_pending_resize_cannot_change_a_replacement_project() { + let mut session = session_at(128); + let task = session.resize_task_to(0, 512, 256).unwrap(); + execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); + let before = session.doc.clone(); + + let output = task.run(&texturecraft_engine::bake::Progress::new()).unwrap(); + let result = session.apply_resize(output); + + assert!(result.is_err(), "a resize from the previous project was accepted"); + assert!(same_document(&session.doc, &before)); + assert!(session.undo_label().is_none()); +} + /// A resize prepared from a snapshot and applied later matches the command, keeps edits made /// while it ran, and undoes in one step. #[test] diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 72e564db..ea6a8cda 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -942,6 +942,7 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti psd_failures.push((name, FormatError::Invalid(reason.clone()))); continue; } + if let Err(error) = layered_psd::preflight(set, opts, tile, bit_depth, layers.iter(), budget.working_bytes) { psd_failures.push((name, error)); continue; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index ec37d13a..971c5d03 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1298,18 +1298,23 @@ fn an_export_size_that_scales_a_tall_set_past_the_largest_side_is_refused() { #[test] fn a_psd_scaled_past_the_largest_side_leaves_the_sets_other_maps() { let mut fx = Fx::new(&default_channels()); - fx.project.texture_sets[0].set_size(RES, RES * 4); + let (width, height) = (RES, RES * 4); + fx.project.texture_sets[0].set_size(width, height); + fx.comp = Composite::with_size(&default_channels(), width, height); + fx.coverage.resize((width * height) as usize, true); + let mut options = one_map(FileFormat::Png, 8, roughness()); let mut psd = options.preset.maps[0].clone(); (psd.file, psd.format, psd.bit_depth, psd.channels) = ("layered".into(), FileFormat::Psd, 8, rgba_half_alpha()); options.preset.maps.push(psd); - options.size = Some(MAX_IMAGE_SIZE / 2); - options.maps.insert(0, MapOverride { size: Some(MAX_IMAGE_SIZE / 4), ..MapOverride::default() }); + options.maps.insert(1, MapOverride { size: Some(MAX_IMAGE_SIZE / 2), ..MapOverride::default() }); - let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + let files = render_maps(&fx.input(), &options).unwrap(); - assert!(plan.len() == 1 && plan[0].format == FileFormat::Png, "{plan:?}"); - assert!(plan[0].warnings.iter().any(|warning| is_set_warning(warning)), "{:?}", plan[0].warnings); + assert_eq!(files.len(), 1); + assert!(files[0].name.ends_with(".png")); + assert_eq!(decode(&files[0]).dimensions(), (width, height)); + assert!(files[0].warnings.iter().any(|warning| is_set_warning(warning) && warning.contains(&MAX_IMAGE_SIZE.to_string()))); } #[test] diff --git a/crates/geom/src/triangle_partition.rs b/crates/geom/src/triangle_partition.rs index 2ad6fb5c..d6a2d658 100644 --- a/crates/geom/src/triangle_partition.rs +++ b/crates/geom/src/triangle_partition.rs @@ -20,42 +20,57 @@ pub struct TrianglePartition { impl TrianglePartition { /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both - pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { // Each triangle's edges once, in mesh order so the groups come out the same every time let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); - let position_of: HashMap = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect(); - let mut edge_lists: Vec> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect(); - let mut by_edge: HashMap> = HashMap::new(); - for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) { - for edge in triangle_edges { - by_edge.entry(edge.clone()).or_default().push(*triangle); + let mut neighbours = Vec::>::new(); + let mut edge_ids = Vec::new(); + let mut offsets = Vec::with_capacity(triangles.len() + 1); + offsets.push(0); + + // Keep compact edge indices for traversal and release the welding keys before the search + { + let mut index_by_edge = HashMap::new(); + for (position, &triangle) in triangles.iter().enumerate() { + for edge in edges(mesh, triangle as usize) { + let index = *index_by_edge.entry(edge).or_insert_with(|| { + neighbours.push(Vec::new()); + neighbours.len() - 1 + }); + neighbours[index].push(position); + edge_ids.push(index); + } + offsets.push(edge_ids.len()); } } let mut groups = Vec::new(); let mut group_of = HashMap::with_capacity(triangles.len()); - for &start in &triangles { - if group_of.contains_key(&start) { + let mut stack = Vec::new(); + for (start, &triangle) in triangles.iter().enumerate() { + if group_of.contains_key(&triangle) { continue; } let mut members = Vec::new(); - let mut stack = vec![start]; - group_of.insert(start, groups.len()); - while let Some(triangle) = stack.pop() { - members.push(triangle); - let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default(); + stack.push(start); + group_of.insert(triangle, groups.len()); + while let Some(position) = stack.pop() { + members.push(triangles[position]); - // Visit a shared edge once, including when many collapsed faces share the same key - for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) { - if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) { - entry.insert(groups.len()); - stack.push(neighbour); + // Visit shared edges once even when many collapsed faces share a key + for &edge in &edge_ids[offsets[position]..offsets[position + 1]] { + for neighbour in std::mem::take(&mut neighbours[edge]) { + if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(triangles[neighbour]) { + entry.insert(groups.len()); + stack.push(neighbour); + } } } } groups.push(members); } + TrianglePartition { groups, group_of } } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 63710915..24789a2e 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -453,27 +453,34 @@ impl GpuTracer { if self.materials.as_ref().is_some_and(|m| m.rev == rev) { return Ok(false); } + let sets = renderer.display_textures(); if sets.len() > MAX_SETS || sets.iter().any(|s| s.len() != KINDS) { return Err(format!("GPU path tracing takes at most {MAX_SETS} texture sets")); } + let layers = sets.len() as u32 + 1; let limits = device.limits(); if layers > limits.max_texture_array_layers { return Err(format!("this GPU takes at most {} texture sets", limits.max_texture_array_layers.saturating_sub(1))); } + let old = self.materials.take(); let mut arrays = Vec::with_capacity(KINDS); for (k, kind) in DisplayKind::ALL.into_iter().enumerate() { - let size = sets.iter().filter_map(|s| s.get(k)).fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h))); + // Fold tall textures into adjacent bands within the widest layer + let sources = sets.iter().filter_map(|set| set.get(k).copied()); + let width = sources.clone().map(wgpu::Texture::width).max().unwrap_or(1); + let height = sources.clone().map(|source| source.height().div_ceil(width / source.width())).max().unwrap_or(1); + let reuse = - old.as_ref().and_then(|m| m.arrays.get(k)).filter(|(t, _)| (t.width(), t.height(), t.depth_or_array_layers()) == (size.0, size.1, layers)); + old.as_ref().and_then(|m| m.arrays.get(k)).filter(|(t, _)| (t.width(), t.height(), t.depth_or_array_layers()) == (width, height, layers)); let (tex, view) = match reuse { Some(a) => a.clone(), None => scoped(device, "GPU path tracing: material textures", || { let tex = device.create_texture(&wgpu::TextureDescriptor { label: Some("tc_trace_material"), - size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: layers }, + size: wgpu::Extent3d { width, height, depth_or_array_layers: layers }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, @@ -488,19 +495,24 @@ impl GpuTracer { if reuse.is_none() { self.bind = None; } - for (layer, src) in sets.iter().filter_map(|s| s.get(k)).enumerate() { - encoder.copy_texture_to_texture( - src.as_image_copy(), - wgpu::TexelCopyTextureInfo { - texture: &tex, - mip_level: 0, - origin: wgpu::Origin3d { x: 0, y: 0, z: layer as u32 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::Extent3d { width: src.width(), height: src.height(), depth_or_array_layers: 1 }, - ); + + for (layer, source) in sources.enumerate() { + for band in 0..source.height().div_ceil(height) { + let source_y = band * height; + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: 0, y: source_y, z: 0 }, ..source.as_image_copy() }, + wgpu::TexelCopyTextureInfo { + texture: &tex, + mip_level: 0, + origin: wgpu::Origin3d { x: band * source.width(), y: 0, z: layer as u32 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { width: source.width(), height: height.min(source.height() - source_y), depth_or_array_layers: 1 }, + ); + } } - // The default material: one texel of the kind's neutral value. + + // The default material occupies one neutral texel in the last layer let texel = kind.default_texel(); queue.write_texture( wgpu::TexelCopyTextureInfo { @@ -515,10 +527,11 @@ impl GpuTracer { ); arrays.push((tex, view)); } + let mut info: Vec<[f32; 3]> = sets .iter() .map(|s| { - // The set's size is its largest texture's; any kind may still be a 1×1 placeholder. + // Individual kinds may still be neutral 1×1 placeholders let dims = s.iter().fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h))); let small = s.iter().enumerate().filter(|(_, t)| (t.width(), t.height()) != dims).fold(0u32, |m, (k, _)| m | 1 << k); [dims.0 as f32, dims.1 as f32, small as f32] @@ -1036,6 +1049,33 @@ mod tests { } } + #[test] + fn mixed_aspect_materials_preserve_texels_and_bound_array_storage() { + let Some((mut headless, mut tracer)) = gpu() else { return }; + let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); + let display = TraceDisplay::from_display(&Default::default()); + let settings = TraceSettings { bounces: 2 }; + let tall = ((128, 513), 0); + let wide = ((512, 128), 1); + headless.renderer.set_texture_sets(&headless.device, &headless.queue, &[tall], 1); + for tile_y in 0..9 { + let color = [23 * tile_y as u8, 255 - 23 * tile_y as u8, 0, 255]; + headless.renderer.upload_tile(&headless.device, &headless.queue, 0, DisplayKind::BaseColor, 0, tile_y, &color.repeat(64 * 64)); + } + + let render = |tracer: &mut GpuTracer, headless: &Headless| { + tracer.render(&headless.device, &headless.queue, &headless.renderer, &scene, &camera(), &settings, &display, [48, 36], 8).unwrap().2 + }; + let reference = render(&mut tracer, &headless); + headless.renderer.set_texture_sets(&headless.device, &headless.queue, &[tall, wide], 2); + headless.renderer.upload_tile(&headless.device, &headless.queue, 1, DisplayKind::BaseColor, 0, 0, &[255; 64 * 64 * 4]); + let mixed = render(&mut tracer, &headless); + + assert_eq!(mixed, reference, "adding another material must preserve every sample of the tall set"); + let array = &tracer.materials.as_ref().unwrap().arrays[0].0; + assert!(array.width() * array.height() < 2 * 128 * 513, "a partial last band must still fit in a compact array layer"); + } + #[test] fn gpu_reads_full_size_channels_beside_placeholders() { // A 1×1 base-color placeholder must not limit sampling of the full-size roughness map diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 31b63ce1..74d6a9cf 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -434,7 +434,7 @@ const DITHER_FRAME_STEP: vec2 = vec2(17.0, 59.0); // Lit single-channel views keep the legacy specular level multiplier const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08; -// The change of height per texel (`ts` = one texel in UV) to the right and down: Sobel when g.uv_rotation.w is 1, else the neighbours across (as HeightToNormalMethod::slope) +// Match the axial and Sobel kernels in HeightToNormalMethod::slope fn height_slope(uv: vec2, ts: vec2) -> vec2 { let r = textureSample(t_height, samp, uv + vec2(ts.x, 0.0)).r; let l = textureSample(t_height, samp, uv - vec2(ts.x, 0.0)).r; diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index b9a390f2..0b1ea9c4 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -213,31 +213,37 @@ fn occluded(o: vec3, d: vec3) -> bool { // ---- Materials ---- -// The change of height per texel to the right and down: Sobel when smooth, else the neighbours across (as HeightToNormalMethod::slope) +// Match the axial and Sobel kernels in HeightToNormalMethod::slope fn height_slope(layer: u32, uv: vec2, sobel: bool) -> vec2 { - let r = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r; - let l = textureLoad(t_height, texel(layer, 3u, uv, -1, 0), layer, 0).r; - let d = textureLoad(t_height, texel(layer, 3u, uv, 0, 1), layer, 0).r; - let u = textureLoad(t_height, texel(layer, 3u, uv, 0, -1), layer, 0).r; + let r = textureLoad(t_height, texel(layer, 3u, uv, 1, 0, i32(textureDimensions(t_height).y)), layer, 0).r; + let l = textureLoad(t_height, texel(layer, 3u, uv, -1, 0, i32(textureDimensions(t_height).y)), layer, 0).r; + let d = textureLoad(t_height, texel(layer, 3u, uv, 0, 1, i32(textureDimensions(t_height).y)), layer, 0).r; + let u = textureLoad(t_height, texel(layer, 3u, uv, 0, -1, i32(textureDimensions(t_height).y)), layer, 0).r; if (!sobel) { return vec2(r - l, d - u) * 0.5; } - let ru = textureLoad(t_height, texel(layer, 3u, uv, 1, -1), layer, 0).r; - let rd = textureLoad(t_height, texel(layer, 3u, uv, 1, 1), layer, 0).r; - let lu = textureLoad(t_height, texel(layer, 3u, uv, -1, -1), layer, 0).r; - let ld = textureLoad(t_height, texel(layer, 3u, uv, -1, 1), layer, 0).r; + let ru = textureLoad(t_height, texel(layer, 3u, uv, 1, -1, i32(textureDimensions(t_height).y)), layer, 0).r; + let rd = textureLoad(t_height, texel(layer, 3u, uv, 1, 1, i32(textureDimensions(t_height).y)), layer, 0).r; + let lu = textureLoad(t_height, texel(layer, 3u, uv, -1, -1, i32(textureDimensions(t_height).y)), layer, 0).r; + let ld = textureLoad(t_height, texel(layer, 3u, uv, -1, 1, i32(textureDimensions(t_height).y)), layer, 0).r; return vec2(ru + 2.0 * r + rd - lu - 2.0 * l - ld, ld + 2.0 * d + rd - lu - 2.0 * u - ru) / 8.0; } -// Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy). -fn texel(layer: u32, k: u32, uv: vec2, dx: i32, dy: i32) -> vec2 { +// Wrap in the source texture before mapping the sample into its array layer +fn texel(layer: u32, k: u32, uv: vec2, dx: i32, dy: i32, band_height: i32) -> vec2 { let info = P.sets[layer]; let small = ((u32(info.z) >> k) & 1u) == 1u; let dims = select(max(vec2(info.xy), vec2(1)), vec2(1), small); let x = i32(floor(uv.x * f32(dims.x))) + dx; let y = i32(floor(uv.y * f32(dims.y))) + dy; - return vec2(((x % dims.x) + dims.x) % dims.x, ((y % dims.y) + dims.y) % dims.y); + let wrapped = vec2(((x % dims.x) + dims.x) % dims.x, ((y % dims.y) + dims.y) % dims.y); + if (wrapped.y < band_height) { + return wrapped; + } + + // The upload lays successive vertical bands side by side + return vec2(wrapped.x + (wrapped.y / band_height) * dims.x, wrapped.y % band_height); } struct Surface { @@ -308,14 +314,14 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { let uv = vec2(verts[ix.x * 2u].w, a0.w) * w0 + vec2(verts[ix.y * 2u].w, a1.w) * u + vec2(verts[ix.z * 2u].w, a2.w) * v; let tw = a0.xyz * w0 + a1.xyz * u + a2.xyz * v; - let base_t = textureLoad(t_base, texel(layer, 0u, uv, 0, 0), layer, 0); - let orm = textureLoad(t_orm, texel(layer, 1u, uv, 0, 0), layer, 0); - let nrm_t = textureLoad(t_normal, texel(layer, 2u, uv, 0, 0), layer, 0); - let hgt = textureLoad(t_height, texel(layer, 3u, uv, 0, 0), layer, 0); - let emi = textureLoad(t_emissive, texel(layer, 4u, uv, 0, 0), layer, 0); - let lobes = textureLoad(t_lobes, texel(layer, 5u, uv, 0, 0), layer, 0); - let sheen_t = textureLoad(t_sheen, texel(layer, 6u, uv, 0, 0), layer, 0); - let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0), layer, 0); + let base_t = textureLoad(t_base, texel(layer, 0u, uv, 0, 0, i32(textureDimensions(t_base).y)), layer, 0); + let orm = textureLoad(t_orm, texel(layer, 1u, uv, 0, 0, i32(textureDimensions(t_orm).y)), layer, 0); + let nrm_t = textureLoad(t_normal, texel(layer, 2u, uv, 0, 0, i32(textureDimensions(t_normal).y)), layer, 0); + let hgt = textureLoad(t_height, texel(layer, 3u, uv, 0, 0, i32(textureDimensions(t_height).y)), layer, 0); + let emi = textureLoad(t_emissive, texel(layer, 4u, uv, 0, 0, i32(textureDimensions(t_emissive).y)), layer, 0); + let lobes = textureLoad(t_lobes, texel(layer, 5u, uv, 0, 0, i32(textureDimensions(t_lobes).y)), layer, 0); + let sheen_t = textureLoad(t_sheen, texel(layer, 6u, uv, 0, 0, i32(textureDimensions(t_sheen).y)), layer, 0); + let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0, i32(textureDimensions(t_extra).y)), layer, 0); let info = P.sets[layer]; diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 703176f4..b29488f9 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -268,7 +268,6 @@ fn matching_not_enabled(ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let mut text = egui::text::LayoutJob::default(); let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() }; - // One sentence to translate, its setting and value kept apart to set them in SemiBold let sentence = tr("Set {setting} to {value} to pair parts by name."); let (before, rest) = sentence.split_once("{setting}").unwrap_or(("", sentence)); @@ -296,7 +295,6 @@ fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option let mut opened = None; for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) { let (rect, open_clicked) = map_row(ui, row); - // Bring the next map into view too, so the list shows what comes after the map being baked if newly_followed && followed == Some(index) { ui.scroll_to_rect(rect.with_max_y(rect.bottom() + ROW_HEIGHT), None); diff --git a/crates/ui-egui/src/channel_manager.rs b/crates/ui-egui/src/channel_manager.rs index 25ec4fe4..1e47ca88 100644 --- a/crates/ui-egui/src/channel_manager.rs +++ b/crates/ui-egui/src/channel_manager.rs @@ -1,12 +1,13 @@ //! The dialog that adds and removes a texture set's channels: every channel by group, ticked when the set has it -use std::sync::Arc; +mod footer_layout; -use egui::{Align2, CornerRadius, FontId, Galley, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::core::{Channel, ChannelGroup, TextureSet}; +use self::footer_layout::FooterLayout; use crate::TextureCraftApp; use crate::i18n::tr; use crate::property_sheet::{CHECK_SIZE, PropertySheet, paint_check, paint_keyboard_focus}; @@ -107,11 +108,11 @@ impl ChannelManager { let closed = title_bar(ui, &tokens, opening); ui.add_space(BODY_AIR); - // The list gets what the title bar, the footer and the air between them leave, so Apply stays in a short window - let window = ctx.content_rect().height(); - let room = window - TITLE_BAR_HEIGHT - BODY_AIR - FOOTER_AIR - footer.height - EDGE_AIR; - let max_height = (window * MAX_HEIGHT_SHARE).min(room).max(0.0); - egui::ScrollArea::both().auto_shrink([false, true]).max_height(max_height).show(ui, |ui| manager.columns(ui)); + // Reserve room for the title and footer so Apply stays visible + let window_height = ctx.content_rect().height(); + let room = window_height - TITLE_BAR_HEIGHT - BODY_AIR - FOOTER_AIR - footer.height() - EDGE_AIR; + let max_height = (window_height * MAX_HEIGHT_SHARE).min(room).max(0.0); + egui::ScrollArea::both().auto_shrink([false, true]).min_scrolled_height(0.0).max_height(max_height).show(ui, |ui| manager.columns(ui)); ui.add_space(FOOTER_AIR); let (apply, cancel) = manager.footer(ui, &tokens, footer); ui.add_space(EDGE_AIR); @@ -212,60 +213,22 @@ impl ChannelManager { /// "Apply to all Texture Sets", the ⊘ legend, then Cancel and Apply at the right; returns (Apply, Cancel) clicked fn footer(&mut self, ui: &mut Ui, tokens: &Tokens, layout: FooterLayout) -> (bool, bool) { - let FooterLayout { label, text, legend_text, legend_below, height } = layout; - let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), layout.height()), Sense::hover()); ui.painter().hline(row.x_range(), row.top() - FOOTER_AIR / 2.0, Stroke::new(1.0, tokens.separator)); - let center_y = row.top() + BUTTON_SIZE.y / 2.0; - - let check = Rect::from_min_size(pos2(row.left() + EDGE_AIR, center_y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); - let hit = Rect::from_min_max(pos2(check.left(), row.top()), pos2(check.right() + CHECK_TO_LABEL + text.size().x, row.top() + BUTTON_SIZE.y)); + let (check, hit) = layout.checkbox_rects(row); let response = ui.interact(hit, ui.scope_id().with("all_sets"), Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, self.all_sets, label)); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, self.all_sets, layout.checkbox_label)); if response.clicked() { self.all_sets = !self.all_sets; } paint_check(ui.painter(), tokens, check, Some(self.all_sets), response.hovered()); - ui.painter().galley(pos2(check.right() + CHECK_TO_LABEL, center_y - text.size().y / 2.0), text, tokens.text); paint_keyboard_focus(ui, &response, tokens); - let legend = if legend_below { pos2(check.left(), center_y + BUTTON_SIZE.y + BUTTON_GAP) } else { pos2(hit.right() + LEGEND_GAP, center_y) }; - let glyph = ui.painter().text(legend, Align2::LEFT_CENTER, icon::PROHIBIT, FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); - let text_left = glyph.right() + LEGEND_GLYPH_TO_TEXT; - ui.painter().galley(pos2(text_left, legend.y - legend_text.size().y / 2.0), legend_text, tokens.text_dim); - - let apply = Rect::from_min_size(pos2(row.right() - EDGE_AIR - BUTTON_SIZE.x, row.bottom() - BUTTON_SIZE.y), BUTTON_SIZE); - let cancel = apply.translate(vec2(-(BUTTON_SIZE.x + BUTTON_GAP), 0.0)); + let (apply, cancel) = layout.paint_labels(ui, tokens, row, check, hit); (dialog_button(ui, tokens, apply, tr("Apply")), dialog_button(ui, tokens, cancel, tr("Cancel"))) } } -/// The footer's texts and rows, worked out before the channel list so the list can leave the footer its height -struct FooterLayout { - label: &'static str, - text: Arc, - legend_text: Arc, - legend_below: bool, - height: f32, -} - -impl FooterLayout { - fn new(ui: &Ui, tokens: &Tokens) -> Self { - let width = ui.available_width(); - let label = tr("Apply to all Texture Sets"); - let text = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text); - let legend_text = ui.painter().layout_no_wrap(tr("Not used by the shader").to_owned(), FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); - - let left_width = EDGE_AIR + CHECK_SIZE + CHECK_TO_LABEL + text.size().x + LEGEND_GAP + SMALL_TEXT_SIZE + LEGEND_GLYPH_TO_TEXT + legend_text.size().x; - - // A narrow footer puts the buttons on a row of their own, and the legend under the check when the two don't fit side by side - let legend_below = width < left_width + EDGE_AIR; - let stacked = legend_below || width < left_width + BUTTON_GAP + 2.0 * BUTTON_SIZE.x + 2.0 * EDGE_AIR; - let rows = 1.0 + f32::from(u8::from(legend_below)) + f32::from(u8::from(stacked)); - let height = rows * BUTTON_SIZE.y + (rows - 1.0) * BUTTON_GAP; - FooterLayout { label, text, legend_text, legend_below, height } - } -} - /// The title and × at the right; returns whether × was clicked fn title_bar(ui: &mut Ui, tokens: &Tokens, opening: bool) -> bool { let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), TITLE_BAR_HEIGHT), Sense::hover()); diff --git a/crates/ui-egui/src/channel_manager/footer_layout.rs b/crates/ui-egui/src/channel_manager/footer_layout.rs new file mode 100644 index 00000000..34fa5ba4 --- /dev/null +++ b/crates/ui-egui/src/channel_manager/footer_layout.rs @@ -0,0 +1,97 @@ +use std::sync::Arc; + +use egui::{FontId, Galley, Rect, Sense, Ui, pos2, vec2}; +use egui_phosphor::regular as icon; + +use super::{BUTTON_GAP, BUTTON_SIZE, CHECK_SIZE, CHECK_TO_LABEL, EDGE_AIR, LEGEND_GAP, LEGEND_GLYPH_TO_TEXT, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::i18n::tr; +use crate::theme::Tokens; + +/// The measured footer, used for both painting and reserving space below the channel list +pub(super) struct FooterLayout { + pub(super) checkbox_label: &'static str, + checkbox_text: Arc, + legend_label: &'static str, + legend_glyph: Arc, + legend_text: Arc, + first_row_height: f32, + legend_row_height: f32, + buttons_row_height: f32, + button_gap: f32, + button_width: f32, +} + +impl FooterLayout { + pub(super) fn new(ui: &Ui, tokens: &Tokens) -> Self { + let content_width = (ui.available_width() - 2.0 * EDGE_AIR).max(0.0); + let checkbox_label = tr("Apply to all Texture Sets"); + let checkbox_text = + ui.painter().layout(checkbox_label.into(), FontId::proportional(TEXT_SIZE), tokens.text, (content_width - CHECK_SIZE - CHECK_TO_LABEL).max(0.0)); + let legend_label = tr("Not used by the shader"); + let legend_font = FontId::proportional(SMALL_TEXT_SIZE); + let legend_glyph = ui.painter().layout_no_wrap(icon::PROHIBIT.into(), legend_font.clone(), tokens.text_dim); + let legend_text_offset = legend_glyph.size().x + LEGEND_GLYPH_TO_TEXT; + let legend_text = ui.painter().layout(legend_label.into(), legend_font, tokens.text_dim, (content_width - legend_text_offset).max(0.0)); + + let left_width = CHECK_SIZE + CHECK_TO_LABEL + checkbox_text.size().x + LEGEND_GAP + legend_text_offset + legend_text.size().x; + let checkbox_height = BUTTON_SIZE.y.max(checkbox_text.size().y); + let legend_height = legend_glyph.size().y.max(legend_text.size().y); + let (first_row_height, legend_row_height) = if left_width > content_width { + (checkbox_height, BUTTON_GAP + BUTTON_SIZE.y.max(legend_height)) + } else { + (checkbox_height.max(legend_height), 0.0) + }; + let buttons_row_height = if left_width + 2.0 * (BUTTON_SIZE.x + BUTTON_GAP) > content_width { BUTTON_GAP + BUTTON_SIZE.y } else { 0.0 }; + let button_gap = BUTTON_GAP.min(content_width); + let button_width = BUTTON_SIZE.x.min((content_width - button_gap) / 2.0); + + Self { + checkbox_label, + checkbox_text, + legend_label, + legend_glyph, + legend_text, + first_row_height, + legend_row_height, + buttons_row_height, + button_gap, + button_width, + } + } + + pub(super) fn height(&self) -> f32 { + self.first_row_height + self.legend_row_height + self.buttons_row_height + } + + pub(super) fn checkbox_rects(&self, row: Rect) -> (Rect, Rect) { + let left = row.left() + EDGE_AIR; + let hit = Rect::from_min_size(pos2(left, row.top()), vec2(CHECK_SIZE + CHECK_TO_LABEL + self.checkbox_text.size().x, self.first_row_height)); + let check = Rect::from_center_size(pos2(left + CHECK_SIZE / 2.0, hit.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); + (check, hit) + } + + pub(super) fn paint_labels(self, ui: &Ui, tokens: &Tokens, row: Rect, check: Rect, hit: Rect) -> (Rect, Rect) { + let paint = |left, center, galley: Arc, color| { + ui.painter().galley(pos2(left, center - galley.size().y / 2.0), galley, color); + }; + paint(check.right() + CHECK_TO_LABEL, hit.center().y, self.checkbox_text, tokens.text); + + let (legend_left, legend_center_y) = if self.legend_row_height > 0.0 { + (check.left(), hit.bottom() + (BUTTON_GAP + self.legend_row_height) / 2.0) + } else { + (hit.right() + LEGEND_GAP, hit.center().y) + }; + let legend_offset = self.legend_glyph.size().x + LEGEND_GLYPH_TO_TEXT; + let legend_height = self.legend_glyph.size().y.max(self.legend_text.size().y); + let legend_rect = + Rect::from_min_size(pos2(legend_left, legend_center_y - legend_height / 2.0), vec2(legend_offset + self.legend_text.size().x, legend_height)); + ui.interact(legend_rect, ui.scope_id().with("legend"), Sense::hover()) + .widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, self.legend_label)); + paint(legend_left, legend_center_y, self.legend_glyph, tokens.text_dim); + paint(legend_left + legend_offset, legend_center_y, self.legend_text, tokens.text_dim); + + let apply = Rect::from_min_size(pos2(row.right() - EDGE_AIR - self.button_width, row.bottom() - BUTTON_SIZE.y), vec2(self.button_width, BUTTON_SIZE.y)); + let cancel = apply.translate(vec2(-(self.button_width + self.button_gap), 0.0)); + (apply, cancel) + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 4ae28b06..71fdba2e 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -30,7 +30,6 @@ pub enum Panel { Assets, /// A second Assets panel with its own search, type and folder (the Assets panel's folder button) AssetsSecond, - // Saved layouts name the bake panels by their earlier names #[serde(rename = "BakeMaps")] MeshMapSettings, @@ -116,7 +115,6 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", - // The second panel shows every type at first, so it's named for that, as the reference names it Panel::AssetsSecond => "All", Panel::MeshMapSettings => "Mesh Map Settings", diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index b473763b..88909259 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -378,7 +378,8 @@ mod tests { assert_eq!(Script::of_language("de"), None); assert_eq!(Script::of_language("ru"), None); for l in &crate::i18n::LANGUAGES { - // Both UI fonts already cover Cyrillic + // Past the Latin blocks and their diacritics. Cyrillic needs no fallback: the UI fonts + // themselves carry it (egui's Ubuntu and craft-fonts' Inter). let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c)); assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code); } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index e508fcd3..82025444 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,7 +526,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.export.rename_key = true; } - // Give the hovered texture set list first use of its rename and menu keys, as Escape, never under a dialog + // Keep the texture set list's shortcuts inactive behind a dialog if over_set_list && !modal_open { let menu = input.consume_key(Modifiers::SHIFT, Key::F10) || input.consume_key(Modifiers::NONE, Key::Menu); set_list_keys = (input.consume_key(Modifiers::NONE, Key::F2), menu); diff --git a/crates/ui-egui/src/property_sheet/material_rows.rs b/crates/ui-egui/src/property_sheet/material_rows.rs index 14fc9b40..78d4b10a 100644 --- a/crates/ui-egui/src/property_sheet/material_rows.rs +++ b/crates/ui-egui/src/property_sheet/material_rows.rs @@ -82,7 +82,7 @@ impl PropertySheet<'_> { /// Controls the sheet has no row for yet, laid out by egui between the panel's edges pub(crate) fn embed(&mut self, body: impl FnOnce(&mut egui::Ui) -> R) -> R { - let width = self.right - self.left; + let width = (self.right - self.left).max(0.0); let top = self.cursor_y(); let inner = self.ui.horizontal(|ui| { ui.add_space(self.left - ui.cursor().left()); diff --git a/crates/ui-egui/src/texture_set_list.rs b/crates/ui-egui/src/texture_set_list.rs index 6ddfc4e7..3e394fcd 100644 --- a/crates/ui-egui/src/texture_set_list.rs +++ b/crates/ui-egui/src/texture_set_list.rs @@ -553,6 +553,11 @@ fn glyph_button(ui: &mut Ui, id: impl egui::AsIdSalt, rect: Rect, glyph: &str, l #[cfg(test)] mod tests { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + use egui_kittest::Harness; use egui_kittest::kittest::Queryable as _; @@ -710,6 +715,41 @@ mod tests { assert!(harness.state().ui.mode == mode, "the mode stayed"); } + #[test] + fn a_modal_opening_over_the_hovered_list_blocks_its_row_keys() { + let mut harness = harness("material_ball"); + let name = harness.state().session.doc.project.texture_sets[1].name.clone(); + click(&mut harness, egui::Role::ListItem, &name, egui::PointerButton::Primary); + harness.state_mut().ui.keymap.insert("ui.layout.3d".into(), "F7".into()); + + // Open the modal after the list records its hover for the next pass + let modal = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("test_modal")); + let open = Arc::new(AtomicBool::new(false)); + let open_in_pass = Arc::clone(&open); + harness.ctx.on_end_pass( + "open test modal", + Arc::new(move |ui| { + if open_in_pass.swap(false, Ordering::Relaxed) { + ui.ctx().memory_mut(|memory| memory.set_modal_layer(modal)); + } + }), + ); + + for (key, modifiers) in [(egui::Key::F2, egui::Modifiers::NONE), (egui::Key::F10, egui::Modifiers::SHIFT), (egui::Key::Menu, egui::Modifiers::NONE)] { + harness.run_steps(2); + open.store(true, Ordering::Relaxed); + harness.step(); + assert_eq!(harness.ctx.memory(|memory| memory.top_modal_layer()), Some(modal)); + assert!(pointer_over(&harness.ctx), "the list still reports hover from the opening pass"); + + harness.event(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); + harness.step(); + + assert!(ListState::stored(&harness.ctx).unwrap().edit.is_none(), "{key:?} did not start a rename behind the modal"); + assert!(!Popup::is_any_open(&harness.ctx), "{key:?} did not open the row menu behind the modal"); + } + } + #[test] fn a_rename_under_way_is_dropped_when_another_project_replaces_this_one() { let mut harness = harness("material_ball"); diff --git a/crates/ui-egui/src/texture_set_list/list_state.rs b/crates/ui-egui/src/texture_set_list/list_state.rs index 8c7a4f83..d3776c43 100644 --- a/crates/ui-egui/src/texture_set_list/list_state.rs +++ b/crates/ui-egui/src/texture_set_list/list_state.rs @@ -26,7 +26,7 @@ impl ListState { egui::Id::unique("texture_set_list_state") } - /// The state for the project and mesh `owner`; another project or mesh starts over, keeping only the descriptions choice + /// Restore row state for `owner`. The description preference and last hover pass survive a change of project or mesh. pub(crate) fn load(ctx: &egui::Context, owner: (u64, u64)) -> Self { let state: Self = ctx.data(|data| data.get_temp::(Self::id())).unwrap_or_default(); if state.owner == owner { diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs index 224d5ca4..8abd249a 100644 --- a/crates/ui-egui/src/texture_set_settings.rs +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -171,6 +171,10 @@ fn channels(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, /// A channel: its name, its format with the gear that lists the formats, and × (Base color stays); returns the format picked and whether × was clicked fn channel_row(sheet: &mut PropertySheet<'_>, channel: Channel, format: ChannelFormat) -> (Option, bool) { sheet.embed(|ui| { + if ui.available_width() < 2.0 * GLYPH_BUTTON + GLYPH_GAP { + return (None, false); + } + let tokens = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), CHANNEL_ROW_HEIGHT), Sense::hover()); let name = tr(channel.label()); @@ -469,11 +473,36 @@ mod tests { } #[test] - fn a_short_channel_window_keeps_apply_on_screen() { - // A narrow window stacks the footer to three rows: the channel list must leave room for all of them + fn a_very_narrow_channel_window_wraps_its_checkbox_label() { let mut harness = harness("material_ball"); click(&mut harness, egui::Role::Button, "Add or remove channels"); - harness.set_size(vec2(300.0, 400.0)); + harness.set_size(vec2(165.0, 300.0)); + harness.run_steps(5); + + let label = "Apply to all Texture Sets"; + let (text, clip) = harness + .output() + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == label => Some((text.visual_bounding_rect(), shape.clip_rect)), + _ => None, + }) + .expect("the footer paints its checkbox label"); + + assert!(clip.contains_rect(text), "the checkbox text must fit on screen: {text:?}"); + + let checkbox = harness.get_by_role_and_label(egui::Role::CheckBox, label).rect(); + let legend = harness.get_by_role_and_label(egui::Role::Label, "Not used by the shader").rect(); + let apply = harness.get_by_role_and_label(egui::Role::Button, "Apply").rect(); + assert!(checkbox.bottom() < legend.top() && legend.bottom() < apply.top(), "the three footer rows must stay separate"); + } + + #[test] + fn a_short_channel_window_keeps_apply_on_screen() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.set_size(vec2(300.0, 175.0)); harness.run_steps(5); let screen = harness.ctx.content_rect(); diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs index 78862418..e7d05308 100644 --- a/crates/ui-egui/src/toast_action.rs +++ b/crates/ui-egui/src/toast_action.rs @@ -33,7 +33,6 @@ impl ToastAction { ToastAction::UpdateResources { project } if project != app.session.project_id => {} #[cfg(not(target_arch = "wasm32"))] ToastAction::UpdateResources { .. } => crate::resources_updater::update(app, None), - // The browser has no files to read again #[cfg(target_arch = "wasm32")] ToastAction::UpdateResources { .. } => {} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 583a0060..72cbf52d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -488,7 +488,6 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let bake_brush = tool == Tool::Paint && app.ui.bake_paint_brush.on; (bake_brush, bake_brush) } - // A greyed tool never shows as selected, even while it stays equipped _ => { let usable = crate::menus::enabled(app, &command); diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 9d99354b..14a949c7 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -72,11 +72,32 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { #[test] fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_alone() { + use std::sync::{Arc, atomic::Ordering, mpsc}; + use texturecraft_engine::bake::Progress; + use texturecraft_ui_egui::RunningBake; + let mut harness = harness(); let before = harness.state().session.doc.baked.get(&0).cloned(); + let progress = Arc::new(Progress::new()); - // One frame starts the worker; a finished map shows only from the next one - harness.state_mut().start_bake(vec![0]); + // Keep both worker channels open and empty so cancellation precedes the first map + let (_map_sender, maps) = mpsc::channel(); + let (_result_sender, receiver) = mpsc::channel(); + let app = harness.state_mut(); + app.start_bake(vec![0]); + let job = app.bake.as_mut().unwrap(); + let set_index = job.queue.remove(0); + job.current = Some(RunningBake { + set_index, + progress: Arc::clone(&progress), + receiver, + maps, + maps_done: Default::default(), + maps_total: MAPS.len(), + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, + }); harness.run_steps(1); assert!(harness.state().session.bake_preview_active()); @@ -87,6 +108,7 @@ fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_al harness.state_mut().cancel_bake(); harness.run_steps(2); + assert!(progress.cancel.load(Ordering::Relaxed), "cancellation reaches the running worker"); assert_eq!(harness.state().session.view, ViewMode::UvChecker); assert!(!harness.state().session.bake_preview_active() && harness.state().bake.is_none()); assert_eq!(harness.state().session.doc.baked.get(&0).cloned(), before); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9c65e129..49df652a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -237,6 +237,27 @@ project file or an export (`file.exportTextures` and the CLI export the whole st back), and removing the soloed layer ends it. `session.inspect` reports it as `solo` (`{layer, ignoreMask}` or `null`). +### Texture sets + +`textureSet.resolution {ts: 0, resolution: 512, height: 256}` resizes the working +texture set to 512 texels across and 256 down. Each side must be a power of two +from 128 to 8192. Omitting `height` makes the set square. A set with individual +UV tile resolution overrides must stay square. Export size overrides set the +width and preserve the texture set's aspect ratio. + +`textureSet.settings {ts: 0, normalMixing: "replace", aoMixing: "none", +heightToNormal: "sharp", uvPadding: "3d"}` changes those four settings in one +undo step. `textureSet.inspect {ts: 0}` reports the size, settings and channels. +Across-seam padding is the default for new sets. Older sets without a padding +mode keep island-edge padding. + +`textureSet.channels {ts: 0, add: ["user0"]}` adds a stored, exportable channel. +Use `remove` to remove channels and `allSets: true` to apply the same edits to +every set. Inspect reports `shaded: false` for channels the viewport shader +does not use. `textureSet.channel.format {ts: 0, channel: "user0", format: "L8"}` +sets the composite format without lowering the precision of the painted layer +data. Float format selections currently store 16-bit precision. + ## Control channel (desktop app) ```sh