From 06ac6c8931e9dc07025ebc9952d80d92f9b6f53d Mon Sep 17 00:00:00 2001 From: Justin John Date: Mon, 2 Nov 2026 20:30:57 +0530 Subject: [PATCH 001/128] Path cache: skip untouched paths, cover channels and alpha images, cap memory Follow-up to #133's review notes. - The cache key now covers the owner layer's and texture set's channels, and each path's brush alpha image, so changing them repaints instead of reusing stale pixels. - The cache keeps a snapshot after each path and the tiles each path painted. An unchanged path above an edit reuses its tiles when the edit didn't reach them; removing a path reuses the paths above it. - Snapshots stay within 256 MB, oldest dropped first, keeping the one below the path being edited so live edits start there. - Path repaints ignore the quick mask: a path paints only from what it stores. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/painting.rs | 8 + crates/engine/src/path_tool.rs | 304 ++++++++++++++++++++++++++------ crates/engine/src/quick_mask.rs | 4 +- crates/engine/src/session.rs | 5 +- 4 files changed, 265 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index de132ffd..3c90af84 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -141,6 +141,8 @@ impl Session { let ts = self.ts(); let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; + // PathCache reuses a path's tiles only if painting one tile reads no other. + debug_assert!(!(self.painting_paths && pickup.is_some()), "path repaints never pick up"); if pickup.is_some() { // Clone and smudge read the composite: bring it up to date first. self.update(); @@ -402,6 +404,9 @@ impl Session { self.doc = st.before; return Ok(()); } + if self.painting_paths { + self.path_tiles.extend(st.canvas.dirty.iter().copied()); + } let gbuf = self.caches.get(st.ts).map(|c| c.gbuf.clone()); let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut st.staging); @@ -502,6 +507,9 @@ impl Session { pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> { let size = (canvas.alpha.width(), canvas.alpha.height()); let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; + if self.painting_paths { + self.path_tiles.extend(canvas.dirty.iter().copied()); + } if self.quick_mask.editing { self.commit_quick_mask(ts, size, src(self.tool.brush.opacity)); return Ok(()); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 0b2903e0..6629c944 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -7,13 +7,16 @@ //! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`). use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use texturecraft_compose::ImageRes; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; +use texturecraft_texel::{TILE_AREA, TileImage}; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; use crate::session::{StackTarget, Tool}; @@ -22,6 +25,9 @@ use crate::{EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// Bytes of tiles the path cache's snapshots may hold (plus the edited path's); the oldest go +/// first. +const CACHE_BYTES: usize = 256 << 20; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). const STEP_PX: f32 = 2.0; const STEP_UV: f32 = 0.001; @@ -58,17 +64,74 @@ impl PathState { } } -/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and -/// texture size they were painted for. +/// Mesh id, texture size, owner layer channels, texture set channels. +type CacheKey = (u64, Option<(u32, u32)>, Vec, Vec); +/// A path sublayer's images: its mask (`None`) and each channel. +type Snap = BTreeMap, TileImage>; +/// A stored path and the brush alpha image it was painted with. +type Painted = (PathShape, Option>); + +/// A path sublayer as last painted for `key`: its paths, its images after each path +/// (`snaps[k]` after the first k; tiles are shared, so a snapshot costs only the tiles that +/// path changed; None once [`evict`]ed) and the tiles each path painted. #[derive(Clone)] -// shortcut: the key doesn't cover image resources a path's brush alpha reads; replacing one -// leaves cached paths with the old alpha until a path below the edited one changes. pub(crate) struct PathCache { eid: LayerId, - key: (u64, Option<(u32, u32)>), - below: Vec, - mask: Option, - layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>, + key: CacheKey, + shapes: Vec, + snaps: Vec>, + tiles: Vec>, +} + +/// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent +/// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live +/// repaint starts there). Snapshot k holds at most path k-1's tiles in each image; the first +/// (empty) and the last (the live pixels) cost nothing. +fn evict(snaps: &mut [Option], tiles: &[BTreeSet<(u32, u32)>], budget: usize, edited: usize) { + let mut bytes = 0; + for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { + if let Some(snap) = &snaps[k] { + bytes += tiles[k - 1].len() * snap.values().map(|i| TILE_AREA * i.comps() * 2).sum::(); + if bytes > budget { + snaps[k] = None; + } + } + } +} + +fn same_handle(a: Option<&Arc>, b: Option<&Arc>) -> bool { + match (a, b) { + (Some(x), Some(y)) => Arc::ptr_eq(x, y), + (x, y) => x.is_none() && y.is_none(), + } +} + +fn same_path(a: &Painted, b: &Painted) -> bool { + a.0 == b.0 && same_handle(a.1.as_ref(), b.1.as_ref()) +} + +/// Whether `a` and `b` hold the same tiles at `tiles`, by shared handle (painting a tile always +/// gives it a new one); a missing image reads as empty. +fn same_tiles(a: &Snap, b: &Snap, tiles: &BTreeSet<(u32, u32)>) -> bool { + a.keys().chain(b.keys()).all(|k| { + let (x, y) = (a.get(k), b.get(k)); + let dims = |i: &TileImage| (i.width(), i.height(), i.comps()); + x.zip(y).is_none_or(|(x, y)| dims(x) == dims(y)) + && tiles.iter().all(|&(tx, ty)| same_handle(x.and_then(|i| i.tile_handle(tx, ty)), y.and_then(|i| i.tile_handle(tx, ty)))) + }) +} + +/// Copy `from`'s tiles at `tiles` into `to`. +fn copy_tiles(to: &mut Snap, from: &Snap, tiles: &BTreeSet<(u32, u32)>) { + for (k, src) in from { + to.entry(*k).or_insert_with(|| TileImage::new(src.width(), src.height(), src.comps())); + } + for (k, dst) in to.iter_mut() { + let src = from.get(k); + for &(x, y) in tiles { + dst.set_tile(x, y, src.and_then(|i| i.tile_handle(x, y)).cloned()); + } + } } /// What a stored path is painted with ([`PathShape::paint`]). @@ -197,7 +260,7 @@ fn remove_path(s: &mut Session, p: &Value) -> Result { { shapes.remove(index); } - s.render_paths(eid, index) + s.render_paths(eid) })?; if s.tool.path.editing.is_some_and(|(e, _)| e == eid) { s.stop_path_edit(); @@ -359,32 +422,43 @@ impl Session { }, _ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))), }; - let mut out = self.render_paths(eid, index)?.get(index).cloned().unwrap_or_else(|| json!({})); + let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({})); out["effect"] = json!(eid.0); out["index"] = json!(index); Ok(out) } - /// Repaint path sublayer `eid` from its stored paths, bottom to top, where paths before - /// `from` are unchanged: their pixels come from [`PathCache`] when it holds them, and are - /// cached for the next repaint otherwise, so editing a path repaints it and the paths above - /// only. Runs inside the caller's undo step. Returns each painted path's report (null for - /// the cached ones). - fn render_paths(&mut self, eid: LayerId, from: usize) -> Result> { + /// Repaint path sublayer `eid` from its stored paths, bottom to top. From [`PathCache`]: the + /// paths before the first changed one keep their pixels, and an unchanged path above it + /// whose tiles the change didn't reach keeps its painted tiles; the rest repaint. Runs + /// inside the caller's undo step. Returns each painted path's report (null for the cached + /// ones). + fn render_paths(&mut self, eid: LayerId) -> Result> { let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec(); - let key = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size)); - self.doc.pixels.masks.remove(&eid); - self.doc.pixels.layers.retain(|(id, _), _| *id != eid); - let start = match &self.path_cache { - Some(c) if c.eid == eid && c.key == key && c.below.len() <= from && shapes.get(..c.below.len()) == Some(&c.below[..]) => { - if let Some(m) = &c.mask { - self.doc.pixels.masks.insert(eid, m.clone()); - } - self.doc.pixels.layers.extend(c.layers.iter().cloned()); - c.below.len() - } - _ => 0, - }; + let images = &self.images; + let alpha = |sh: &PathShape| read_paint(sh).ok().and_then(|p| p.brush.alpha_image).and_then(|n| images.get(&n).cloned()); + let new: Vec = shapes + .into_iter() + .map(|sh| { + let a = alpha(&sh); + (sh, a) + }) + .collect(); + let project = &self.doc.project; + let owner = project.effect(eid).and_then(|(o, _)| project.layer(o).ok()).map(|l| l.channels.keys().copied().collect()).unwrap_or_default(); + let set = project.texture_set(self.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let key: CacheKey = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size), owner, set); + let old = self.path_cache.take().filter(|c| c.eid == eid && c.key == key); + let (prefix, suffix) = old.as_ref().map_or((0, 0), |c| { + let p = c.shapes.iter().zip(&new).take_while(|(a, b)| same_path(a, b)).count(); + (p, c.shapes[p..].iter().rev().zip(new[p..].iter().rev()).take_while(|(a, b)| same_path(a, b)).count()) + }); + // Start from the last snapshot kept at or below the first changed path (the first one, + // empty, is always kept). + let start = old.as_ref().map_or(0, |c| (0..=prefix).rev().find(|&k| c.snaps[k].is_some()).unwrap_or(0)); + let mut snaps = old.as_ref().map_or_else(|| vec![Some(Snap::new())], |c| c.snaps[..=start].to_vec()); + let mut tiles = old.as_ref().map_or_else(Vec::new, |c| c.tiles[..start].to_vec()); + let mut state = snaps[start].clone().unwrap_or_default(); // 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 saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); @@ -395,13 +469,22 @@ impl Session { 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 }); + for (j, (sh, _)) in new.iter().enumerate().skip(start) { + // Painting is per tile: over the same tiles, an unchanged path paints the same. + let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) }; + if let (Some(c), Some(o)) = (&old, o) + && let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1]) + && same_tiles(&state, below, &c.tiles[o]) + { + copy_tiles(&mut state, after, &c.tiles[o]); + tiles.push(c.tiles[o].clone()); + snaps.push(Some(state.clone())); + evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + out.push(Value::Null); + continue; } - let Some(sh) = shapes.get(i) else { break }; + self.put_snap(eid, &state); + self.path_tiles.clear(); match self.paint_shape(sh) { Ok(v) => out.push(v), Err(e) => { @@ -409,13 +492,39 @@ impl Session { break; } } + state = self.take_snap(eid); + tiles.push(std::mem::take(&mut self.path_tiles)); + snaps.push(Some(state.clone())); + evict(&mut snaps, &tiles, CACHE_BYTES, prefix); } + self.put_snap(eid, &state); self.painting_paths = false; (self.tool, self.camera, self.target, self.quick_mask.editing) = saved; (self.undo, self.redo) = history; + if result.is_ok() { + self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles }); + } result.map(|_| out) } + fn take_snap(&self, eid: LayerId) -> Snap { + let p = &self.doc.pixels; + let mask = p.masks.get(&eid).map(|m| (None, m.clone())); + mask.into_iter().chain(p.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, c), img)| (Some(*c), img.clone()))).collect() + } + + fn put_snap(&mut self, eid: LayerId, snap: &Snap) { + let p = &mut self.doc.pixels; + p.masks.remove(&eid); + p.layers.retain(|(id, _), _| *id != eid); + for (k, img) in snap { + match k { + None => p.masks.insert(eid, img.clone()), + Some(c) => p.layers.insert((eid, *c), img.clone()), + }; + } + } + fn paint_shape(&mut self, shape: &PathShape) -> Result { let paint = read_paint(shape)?; self.tool.brush = paint.brush; @@ -493,7 +602,7 @@ impl Session { #[cfg(test)] mod tests { - use serde_json::json; + use serde_json::{Value, json}; use crate::{Session, execute}; @@ -504,29 +613,118 @@ mod tests { v } - #[test] - fn cached_repaint_matches_a_full_repaint() { - let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + /// A session with horizontal UV paths at `rows` (one path sublayer) on a 512 texture. + fn with_paths(rows: &[f32]) -> (Session, texturecraft_core::LayerId) { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 512).unwrap(); s.update(); execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); let mut eid = 0; - for v in [0.2, 0.5, 0.8] { - let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap(); + for v in rows { + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v]], "commit": true})).unwrap(); eid = r["committed"]["effect"].as_u64().unwrap(); } - let eid = texturecraft_core::LayerId(eid); - // Live edits of the middle path reuse the bottom path's pixels. - execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); - for v in [0.4, 0.45] { - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); - } - assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1)); - let r = s.render_paths(eid, 1).unwrap(); - assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}"); - let cached = pixels(&s, eid); + (s, texturecraft_core::LayerId(eid)) + } + + /// Move path `index` to row `v` (a live edit) and check the result against painting every + /// path. Returns which paths were repainted. + fn edit_row(s: &mut Session, eid: texturecraft_core::LayerId, index: usize, v: f32) -> Vec { + execute(s, "path.edit", &json!({"effect": eid.0, "index": index})).unwrap(); + let before = s.path_cache.clone(); + execute(s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); + let cached = pixels(s, eid); + s.path_cache = before; + let painted = s.render_paths(eid).unwrap().iter().map(|r| !r.is_null()).collect(); + assert_eq!(cached, pixels(s, eid)); s.path_cache = None; - s.render_paths(eid, 0).unwrap(); - assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); + s.stop_path_edit(); + painted + } + + #[test] + fn cached_repaint_matches_a_full_repaint() { + // Rows 0.2, 0.45 and 0.8 of 512 texels are in different 64-texel tile rows. + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + assert_eq!(edit_row(&mut s, eid, 1, 0.47), [false, true, false], "only the edited path repaints"); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false, false], "paths above keep their tiles"); + assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints"); + } + + #[test] + fn removing_a_path_keeps_the_paths_above() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let before = s.path_cache.clone(); + execute(&mut s, "path.remove", &json!({"effect": eid.0, "index": 0})).unwrap(); + let cached = pixels(&s, eid); + s.path_cache = before; + assert!(s.render_paths(eid).unwrap().iter().all(Value::is_null), "both paths above came from the cache"); + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + } + + #[test] + fn replacing_the_brush_alpha_image_repaints() { + let (mut s, eid) = with_paths(&[0.2]); + let img = |v: f32| std::sync::Arc::new(texturecraft_compose::ImageRes { width: 2, height: 2, rgba: vec![[v; 4]; 4], srgb: false }); + s.images.insert("a".into(), img(1.0)); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "a"}})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.8], [0.9, 0.8]], "commit": true})).unwrap(); + s.render_paths(eid).unwrap(); + s.images.insert("a".into(), img(0.5)); + let r = s.render_paths(eid).unwrap(); + assert!(r[0].is_null() && !r[1].is_null(), "only the path using the image repaints: {r:?}"); + } + + #[test] + fn snapshots_stay_within_the_budget() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, usize::MAX, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4); + super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert!(c.snaps[0].is_some() && c.snaps[3].is_some() && c.snaps[1..3].iter().all(Option::is_none), "only the free ones stay"); + // Appending still paints the new path alone. + let shape = s.paths(eid).unwrap()[0].clone(); + if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { + v.push(shape); + } + let r = s.render_paths(eid).unwrap(); + assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); + // Editing above evicted snapshots repaints from the bottom and matches a full repaint. + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); + // That edit kept the snapshot below path 3 within a zero budget: its next frame starts there. + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, 0, 2); + assert!(c.snaps[2].is_some() && c.snaps[1].is_none()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, true], "path 4 lost its snapshot too"); + } + + #[test] + fn the_quick_mask_does_not_clip_paths() { + let (mut s, eid) = with_paths(&[0.2, 0.8]); + let plain = pixels(&s, eid); + s.quick_mask.enabled = true; + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(plain, pixels(&s, eid)); + } + + #[test] + fn owner_channel_change_skips_the_cache() { + let (mut s, eid) = with_paths(&[0.3, 0.7]); + s.render_paths(eid).unwrap(); + let owner = s.doc.project.effect(eid).unwrap().0; + let layer = s.doc.project.layer_mut(owner).unwrap(); + let ch = *layer.channels.keys().next().unwrap(); + layer.channels.remove(&ch); + let r = s.render_paths(eid).unwrap(); + assert!(!r[0].is_null(), "the bottom path was repainted: {r:?}"); + assert!(!s.doc.pixels.layers.contains_key(&(eid, ch)), "no pixels left in the removed channel"); } } diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 304ab3c9..f407a9ef 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -86,10 +86,10 @@ impl Session { } /// What limits a paint stroke on `ts`: the mask and whether it is inverted (None when the - /// quick mask is off or being edited). + /// quick mask is off or being edited, and for paths, which repaint from what they store). pub(crate) fn stroke_limit(&self, ts: usize, size: (u32, u32)) -> Option<(TileImage, bool)> { let q = &self.quick_mask; - (q.enabled && !q.editing).then(|| (self.quick_mask_image(ts, size), q.inverted)) + (q.enabled && !q.editing && !self.painting_paths).then(|| (self.quick_mask_image(ts, size), q.inverted)) } /// Commit a stroke into the quick mask of `ts`. diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e9909635..7b49d8e2 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -346,8 +346,10 @@ pub struct Session { pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). pub(crate) painting_paths: bool, - /// Pixels of the paths below the one being edited, so live edits skip repainting them. + /// A path sublayer as last painted, so a repaint skips the paths an edit didn't reach. pub(crate) path_cache: Option, + /// Tiles painted since `render_paths` cleared it (the footprint of one path). + pub(crate) path_tiles: std::collections::BTreeSet<(u32, u32)>, pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -402,6 +404,7 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_tiles: Default::default(), path: None, modified: false, revision: 1, From cda95901388f75aac14b1b4c4696be90b604d9b1 Mon Sep 17 00:00:00 2001 From: JonRC Date: Mon, 2 Nov 2026 23:55:08 -0300 Subject: [PATCH 002/128] 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 003/128] 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 004/128] 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 83e13fb6c083d0dc5969869ed508f2789d71c6e6 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:43:30 -0500 Subject: [PATCH 005/128] fix(geom): Mesh::validate refuses non-finite normals and absurd UVs validate checked positions were finite but not normals or UVs. A UV like 1e30 saturates the integer texel maths in ImageRes::sample, the colour bake and the path tracer, and x0 + 1 then overflows (a panic in debug builds, a wrapped lookup in release). UVs must now be finite and within +-1e6 (UDIM layouts stop at 10 columns); normals must be finite. Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/mesh.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..1d92dc8b 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -47,6 +47,9 @@ pub struct Mesh { /// Hard cap on mesh size accepted from files (triangles). pub const MAX_TRIANGLES: usize = 20_000_000; +/// Largest UV coordinate a mesh may carry (UDIM tiles stop at 10 columns; this is far beyond any +/// real layout). Texel lookups turn UVs into integers, which a UV like 1e30 would overflow. +pub const MAX_UV: f32 = 1.0e6; impl Mesh { pub fn triangle_count(&self) -> usize { @@ -145,6 +148,12 @@ impl Mesh { if self.positions.iter().any(|p| !p.is_finite()) { return Err(GeomError::Invalid("mesh has non-finite positions".into())); } + if self.normals.iter().any(|n| !n.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite normals".into())); + } + if self.uvs.iter().any(|uv| !uv.is_finite() || uv.x.abs() > MAX_UV || uv.y.abs() > MAX_UV) { + return Err(GeomError::Invalid(format!("mesh has non-finite UVs or UVs beyond ±{MAX_UV}"))); + } for s in &self.submeshes { if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); @@ -443,6 +452,26 @@ mod tests { assert!(m.validate().is_err()); } + #[test] + fn validate_refuses_non_finite_normals_and_absurd_uvs() { + assert!(quad().validate().is_ok()); + for bad in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1.0e30, -2.0e6] { + let mut m = quad(); + m.uvs[1].x = bad; + assert!(m.validate().is_err(), "uv {bad}"); + let mut m = quad(); + m.uvs[2].y = bad; + assert!(m.validate().is_err(), "uv {bad}"); + } + let mut m = quad(); + m.normals[0].z = f32::NAN; + assert!(m.validate().is_err()); + // Large but real UDIM-style layouts stay valid. + let mut m = quad(); + m.uvs[0] = Vec2::new(1009.5, 0.5); + assert!(m.validate().is_ok()); + } + #[test] fn append_offsets_indices_and_materials() { let mut a = quad(); From da53dc8a8c37ca21d8b3c5fe2c1c4efc8558c37a Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:29:11 -0500 Subject: [PATCH 006/128] fix(#253): texel lookups at huge finite UVs no longer overflow MAX_UV (1e6) does not protect the 32-bit lookup in the path tracer (1e6 * 4096 saturates i32, then +dx overflows), and sample()/base_color() add 1 to a saturated i64. UVs also come from places other than mesh attributes. Lookups now saturate/64-bit and refuse non-finite coordinates after scaling. Co-Authored-By: Claude Sonnet 5.5 --- crates/bake/src/map/source.rs | 27 +++++++++++++++++++++++---- crates/compose/src/store.rs | 28 +++++++++++++++++++++++++++- crates/render/src/trace.rs | 29 +++++++++++++++++++++++++---- 3 files changed, 75 insertions(+), 9 deletions(-) diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 0e1f9164..27b50ffe 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -117,10 +117,15 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3)) }; let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5); - let (x0, y0) = (fx.floor(), fy.floor()); - let (tx, ty) = (fx - x0, fy - y0); - let (x, y) = (x0 as i64, y0 as i64); - texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty) + if fx.is_finite() && fy.is_finite() { + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x, y) = (x0 as i64, y0 as i64); + let (x1, y1) = (x.saturating_add(1), y.saturating_add(1)); + texel(x, y).lerp(texel(x1, y), tx).lerp(texel(x, y1).lerp(texel(x1, y1), tx), ty) + } else { + Vec4::ONE + } }; let color = sampled_color * material.factor; Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w) @@ -133,3 +138,17 @@ fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { let next = keys.len() as u32; *keys.entry(base).or_insert(next) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base_color_sampling_survives_huge_finite_uvs() { + let material = BaseColor { factor: Vec4::ONE, width: 2, height: 2, texels: vec![[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]] }; + for uv in [Vec2::new(1.0e30, 0.5), Vec2::new(0.5, -1.0e30), Vec2::splat(f32::MAX), Vec2::splat(1.0e6)] { + let c = base_color(&material, uv); + assert!(c.is_finite(), "{uv}: {c}"); + } + } +} diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 1370c0c0..1dc801b5 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -85,9 +85,17 @@ impl ImageRes { } let fx = u * self.width as f32 - 0.5; let fy = v * self.height as f32 - 0.5; + if !fx.is_finite() || !fy.is_finite() { + return [0.0; 4]; + } let (x0, y0) = (fx.floor() as i64, fy.floor() as i64); let (tx, ty) = (fx - fx.floor(), fy - fy.floor()); - let (a, b, c, d) = (self.texel(x0, y0), self.texel(x0 + 1, y0), self.texel(x0, y0 + 1), self.texel(x0 + 1, y0 + 1)); + let (a, b, c, d) = ( + self.texel(x0, y0), + self.texel(x0.saturating_add(1), y0), + self.texel(x0, y0.saturating_add(1)), + self.texel(x0.saturating_add(1), y0.saturating_add(1)), + ); let mut out = [0.0; 4]; for k in 0..4 { let top = a[k] + (b[k] - a[k]) * tx; @@ -97,3 +105,21 @@ impl ImageRes { out } } + +#[cfg(test)] +mod tests { + use super::*; + + fn checker() -> ImageRes { + ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [1.0; 4], [1.0; 4], [0.0; 4]], srgb: false } + } + + #[test] + fn sampling_at_huge_finite_coordinates_does_not_overflow() { + let img = checker(); + for (u, v) in [(1.0e30, 0.5), (0.5, -1.0e30), (f32::MAX, f32::MAX), (1.0e6, -1.0e6)] { + let s = img.sample(u, v); + assert!(s.iter().all(|c| c.is_finite() && (0.0..=1.0).contains(c)), "({u}, {v}) -> {s:?}"); + } + } +} diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index a823a031..39b51d1d 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -537,10 +537,7 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 let set = scene.tri_set.get(tri as usize).and_then(|s| scene.sets.get(*s)); // The composite texel at offset (dx, dy) from the hit. - let texel = |s: &TraceSet, dx: i32, dy: i32| { - let (w, h) = (s.composite.resolution.max(1) as i32, s.composite.height.max(1) as i32); - (((uv.x * w as f32).floor() as i32 + dx).rem_euclid(w) as u32, ((uv.y * h as f32).floor() as i32 + dy).rem_euclid(h) as u32) - }; + let texel = |s: &TraceSet, dx: i32, dy: i32| wrapped_texel(uv, (s.composite.resolution, s.composite.height), dx, dy); let ch = |c: Channel, dx: i32, dy: i32| -> [f32; 3] { let Some(s) = set else { return c.default_value() }; let (x, y) = texel(s, dx, dy); @@ -1042,8 +1039,32 @@ fn trace(scene: &TraceScene, mut o: Vec3, mut d: Vec3, settings: &TraceSettings, Some(Sample { radiance: if l.is_finite() { l } else { Vec3::ZERO }, albedo, normal, depth }) } +/// The texel of a `size` image at `uv` (wrapping), offset by `(dx, dy)`. 64-bit so a far-off UV +/// times a wide image can't overflow the offset (in 32 bits a UV of 1e6 on an image 4096 wide saturated, and the offset then overflowed). +fn wrapped_texel(uv: Vec2, size: (u32, u32), dx: i32, dy: i32) -> (u32, u32) { + let (w, h) = (i64::from(size.0.max(1)), i64::from(size.1.max(1))); + let at = |t: f32, n: i64, d: i32| ((t * n as f32).floor() as i64).saturating_add(i64::from(d)).rem_euclid(n) as u32; + (at(uv.x, w, dx), at(uv.y, h, dy)) +} + #[cfg(test)] mod tests { + #[test] + fn texel_lookup_survives_far_off_uvs() { + use super::wrapped_texel; + use texturecraft_geom::glam::Vec2; + // Inside the image, and offsets wrap around the edges. + assert_eq!(wrapped_texel(Vec2::new(0.25, 0.75), (4, 4), 0, 0), (1, 3)); + assert_eq!(wrapped_texel(Vec2::new(0.0, 0.99), (4, 4), -1, 1), (3, 0)); + // 1e6 (the largest UV a mesh may carry) times 8192 texels is past i32::MAX; 1e30 saturates. + for uv in [1.0e6, -1.0e6, 1.0e30, f32::MAX] { + for (dx, dy) in [(1, 1), (-1, -1), (0, 0)] { + let (x, y) = wrapped_texel(Vec2::new(uv, uv), (8192, 8192), dx, dy); + assert!(x < 8192 && y < 8192, "{uv}: ({x}, {y})"); + } + } + } + use super::*; use texturecraft_geom::primitives; From 88e0eb1ba5417f931bcde44efa08978bc9f234ff Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:40:16 -0500 Subject: [PATCH 007/128] fix(#253): clamp the height sample position so x0 + 1 can't overflow A huge finite UV saturates the cast to isize (32-bit on wasm32), and x0 + 1 then overflowed (a panic in debug). Past one texel outside, every lookup clamps to the same edge texel, so clamping the position first changes no result. Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/displace.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index f2e2b19a..d40c9b73 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -117,6 +117,10 @@ impl Heights { if !(fx.is_finite() && fy.is_finite()) { return 0.0; } + // Past one texel outside, every lookup clamps to the same edge texel, so clamping the + // position first changes no result but keeps `x0 + 1` far from overflowing: a huge finite + // UV saturates the `as isize` cast, and isize is 32 bits on wasm32. + let (fx, fy) = (fx.clamp(-1.0, self.w as f32), fy.clamp(-1.0, self.h as f32)); let (x0, y0) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - x0, fy - y0); let (x0, y0) = (x0 as isize, y0 as isize); @@ -144,6 +148,21 @@ mod tests { TraceSet { material: 0, composite, height_strength: strength } } + #[test] + fn sampling_at_huge_or_far_uvs_clamps_to_the_edge_without_overflow() { + let heights = Heights { w: 2, h: 2, data: vec![1.0, 2.0, 3.0, 4.0] }; + // x0 + 1 used to overflow for these (the cast to isize saturates at isize::MAX). + for far in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN, 1.0e10] { + assert!(heights.sample(Vec2::new(far, far)).is_finite()); + } + assert_eq!(heights.sample(Vec2::new(1.0e30, 1.0e30)), 4.0); + assert_eq!(heights.sample(Vec2::new(-1.0e30, -1.0e30)), 1.0); + assert_eq!(heights.sample(Vec2::new(1.0e30, -1.0e30)), 2.0); + assert_eq!(heights.sample(Vec2::new(f32::NAN, 0.5)), 0.0); + // In range, bilinear is unchanged: the centre of the 2 x 2 is the mean. + assert!((heights.sample(Vec2::new(0.5, 0.5)) - 2.5).abs() < 1e-6); + } + #[test] fn uniform_height_lifts_the_dense_plane_along_its_normal() { let plane = primitives::plane(2.0, 1); From a5ba5eb719646208cfc270dc0963076e9e807ed2 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:24:10 -0500 Subject: [PATCH 008/128] docs(#253): doc comments for the touched functions and the new tests Co-Authored-By: Claude Sonnet 5.5 --- crates/bake/src/map/source.rs | 3 +++ crates/compose/src/store.rs | 2 ++ crates/geom/src/mesh.rs | 1 + crates/render/src/displace.rs | 1 + crates/render/src/trace.rs | 3 +++ 5 files changed, 10 insertions(+) diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 27b50ffe..7f2e7e32 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -106,6 +106,8 @@ impl<'a> Source<'a> { } } +/// The material's base colour at `uv` (bilinear, wrapping), sRGB RGBA times its factor; white +/// where there is no texture or the UV is not finite. fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { let sampled_color = if material.texels.is_empty() || !uv.is_finite() { Vec4::ONE @@ -143,6 +145,7 @@ fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { mod tests { use super::*; + /// Sampling at huge but finite UVs returns a finite colour instead of overflowing. #[test] fn base_color_sampling_survives_huge_finite_uvs() { let material = BaseColor { factor: Vec4::ONE, width: 2, height: 2, texels: vec![[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]] }; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 1dc801b5..d8461f50 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -110,10 +110,12 @@ impl ImageRes { mod tests { use super::*; + /// A 2 x 2 black and white checker image for the sampling test. fn checker() -> ImageRes { ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [1.0; 4], [1.0; 4], [0.0; 4]], srgb: false } } + /// Sampling at huge finite coordinates stays finite and within 0..=1 instead of overflowing. #[test] fn sampling_at_huge_finite_coordinates_does_not_overflow() { let img = checker(); diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 1d92dc8b..64c8b1e5 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -452,6 +452,7 @@ mod tests { assert!(m.validate().is_err()); } + /// Validation rejects non-finite normals and non-finite or beyond-limit UVs, but accepts UDIM-style UVs. #[test] fn validate_refuses_non_finite_normals_and_absurd_uvs() { assert!(quad().validate().is_ok()); diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index d40c9b73..abd71692 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -148,6 +148,7 @@ mod tests { TraceSet { material: 0, composite, height_strength: strength } } + /// Far-off UVs clamp to the nearest edge texel without overflow; NaN gives 0 and in-range sampling is unchanged. #[test] fn sampling_at_huge_or_far_uvs_clamps_to_the_edge_without_overflow() { let heights = Heights { w: 2, h: 2, data: vec![1.0, 2.0, 3.0, 4.0] }; diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 39b51d1d..1ea49e22 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -514,6 +514,8 @@ fn rnm(base: Vec3, detail: Vec3) -> Vec3 { (t * t.dot(u) - u * t.z).normalize_or(Vec3::Z) } +/// Builds the shading surface at a ray hit: interpolated geometry, normal and tangent frame, and the +/// set's channel values (base colour, roughness, metallic, coat and so on) at the hit's UV. fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f32) -> Option { let m = &scene.mesh; let i = tri as usize * 3; @@ -1049,6 +1051,7 @@ fn wrapped_texel(uv: Vec2, size: (u32, u32), dx: i32, dy: i32) -> (u32, u32) { #[cfg(test)] mod tests { + /// `wrapped_texel` wraps offsets at the edges and stays inside the image for far-off UVs. #[test] fn texel_lookup_survives_far_off_uvs() { use super::wrapped_texel; 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 009/128] 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 010/128] 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 011/128] 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 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 012/128] 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 57c6179179b46bbbfddd4deb26143042681cbb79 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 01:18:50 -0500 Subject: [PATCH 013/128] Show a notice when an autosave fails The worker reports its result to the app. A failure, including a worker that cannot start, shows one dismissible notice with the path and the reason, recorded in the Log, until a later autosave works. --- crates/ui-egui/src/autosave_notice.rs | 75 +++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 22 +++++--- crates/ui-egui/tests/autosave_notice.rs | 46 +++++++++++++++ 3 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/autosave_notice.rs create mode 100644 crates/ui-egui/tests/autosave_notice.rs diff --git a/crates/ui-egui/src/autosave_notice.rs b/crates/ui-egui/src/autosave_notice.rs new file mode 100644 index 00000000..cc37af56 --- /dev/null +++ b/crates/ui-egui/src/autosave_notice.rs @@ -0,0 +1,75 @@ +//! Tells the user when an autosave fails: the worker reports back, and one notice stays until a later +//! autosave works, so a missing backup is not mistaken for a saved one. + +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use crate::TextureCraftApp; +use crate::i18n::trf; + +/// How one autosave ended. +struct Outcome { + path: PathBuf, + result: Result<(), String>, +} + +pub(crate) struct AutosaveNotice { + sender: Sender, + receiver: Receiver, + /// The failure the user was last told about; cleared by an autosave that works. + shown: Option, +} + +impl Default for AutosaveNotice { + fn default() -> Self { + let (sender, receiver) = channel(); + Self { sender, receiver, shown: None } + } +} + +/// Sends one autosave's result to the app, from any thread. +pub(crate) struct Reporter { + sender: Sender, + context: egui::Context, +} + +impl Reporter { + pub(crate) fn report(self, path: PathBuf, result: Result<(), String>) { + match &result { + Ok(()) => log::info!("autosaved {}", path.display()), + Err(error) => log::warn!("autosave to {} failed: {error}", path.display()), + } + + // A closed channel means the app is gone, so there is nobody left to tell + if self.sender.send(Outcome { path, result }).is_ok() { + self.context.request_repaint(); + } + } +} + +impl AutosaveNotice { + pub(crate) fn reporter(&self, context: &egui::Context) -> Reporter { + Reporter { sender: self.sender.clone(), context: context.clone() } + } +} + +/// Take in finished autosaves. A failure is announced once, however often it repeats. +pub(crate) fn poll(app: &mut TextureCraftApp) { + while let Ok(Outcome { path, result }) = app.autosave_notice.receiver.try_recv() { + let message = result.err().map(|error| trf("Autosave to {path} failed: {error}", &[("path", &path.display()), ("error", &error)])); + if message == app.autosave_notice.shown { + continue; + } + + if let Some(old) = app.autosave_notice.shown.take() { + app.toasts.retain(|toast| toast.text != old); + } + + if let Some(message) = &message { + app.session.log.error("Autosave", message.clone()); + app.toast_sticky(message.clone()); + } + + app.autosave_notice.shown = message; + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 401581e8..313cca82 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,6 +10,8 @@ mod anchor_properties; mod angle_dial; mod ask; +#[cfg(not(target_arch = "wasm32"))] +mod autosave_notice; mod bake_job; pub mod bake_mode; mod bake_preset; @@ -357,6 +359,8 @@ pub struct TextureCraftApp { /// When the next autosave is due (seconds of app time; desktop only). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, + #[cfg(not(target_arch = "wasm32"))] + autosave_notice: autosave_notice::AutosaveNotice, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. @@ -493,6 +497,8 @@ impl TextureCraftApp { fired_clipboard: Vec::new(), last_time: 0.0, next_autosave, + #[cfg(not(target_arch = "wasm32"))] + autosave_notice: Default::default(), styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] @@ -1033,7 +1039,7 @@ impl TextureCraftApp { /// Every `prefs.autosave_minutes`, write a modified project to the autosave folder (encoded /// and written on a worker thread; the project data is shared copy-on-write). #[cfg(not(target_arch = "wasm32"))] - fn autosave(&mut self, now: f64) { + fn autosave(&mut self, ctx: &egui::Context, now: f64) { let period = autosave_period_seconds(self.ui.prefs.autosave_minutes); // The clock starts at the first unsaved change @@ -1058,19 +1064,19 @@ impl TextureCraftApp { texturecraft_engine::core::PROJECT_EXT )); let snapshot = self.session.project_snapshot(); + let reporter = self.autosave_notice.reporter(ctx); + let spawn_reporter = self.autosave_notice.reporter(ctx); + let target = path.clone(); let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || { let result = std::fs::create_dir_all(&dir).map_err(|e| e.to_string()).and_then(|_| reservation.save(&path, &snapshot).map_err(|error| error.to_string())); drop(snapshot); drop(reservation); - match result { - Ok(()) => log::info!("autosaved {}", path.display()), - Err(e) => log::warn!("autosave to {} failed: {e}", path.display()), - } + reporter.report(path, result); }); if let Err(e) = spawned { - log::warn!("could not start autosave: {e}"); + spawn_reporter.report(target, Err(e.to_string())); } } } @@ -1213,7 +1219,9 @@ impl eframe::App for TextureCraftApp { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] - self.autosave(now); + self.autosave(ctx, now); + #[cfg(not(target_arch = "wasm32"))] + autosave_notice::poll(self); i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] { diff --git a/crates/ui-egui/tests/autosave_notice.rs b/crates/ui-egui/tests/autosave_notice.rs new file mode 100644 index 00000000..d5786734 --- /dev/null +++ b/crates/ui-egui/tests/autosave_notice.rs @@ -0,0 +1,46 @@ +//! A failed autosave is announced in the interface. This is its own test binary because the data +//! folder it breaks is fixed once for the whole process. + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; + +fn notices(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().toasts.iter().filter(|toast| toast.text.contains("autosave-notice")).count() +} + +/// Run frames until `done`, giving the autosave worker real time to finish. +fn run_until(harness: &mut Harness<'_, TextureCraftApp>, done: impl Fn(&Harness<'_, TextureCraftApp>) -> bool) { + let started = Instant::now(); + while !done(harness) { + assert!(started.elapsed() < Duration::from_secs(60), "the autosave did not report"); + harness.step(); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn a_failing_autosave_is_announced_once_until_it_works_again() { + let root = std::env::temp_dir().join(format!("tc-autosave-notice-{}", std::process::id())); + // A file where the data folder should be, so the autosave folder cannot be created + std::fs::write(&root, b"not a folder").unwrap(); + texturecraft_ui_egui::set_data_root(root.clone()); + + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + // Each frame is longer than the shortest autosave period, so every frame is due + let mut harness = Harness::builder().with_step_dt(61.0).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.autosave_minutes = 1; + harness.state_mut().session.modified = true; + + run_until(&mut harness, |harness| notices(harness) > 0); + for _ in 0..20 { + harness.step(); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(notices(&harness), 1, "the same failure is not announced again"); + + std::fs::remove_file(&root).unwrap(); + run_until(&mut harness, |harness| notices(harness) == 0); + let _ = std::fs::remove_dir_all(&root); +} From b01dbe34c67c71697bd873d9c3c3b4b5037d1f78 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:59:40 +0000 Subject: [PATCH 014/128] Layers: add the height-combination mask to the layer row menu --- crates/ui-egui/src/dock.rs | 3 ++- crates/ui-egui/tests/it/layers_panel.rs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e7efb8b9..a66dbdec 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1342,7 +1342,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con let layer_id = layer.id.0; let keymap = app.ui.keymap.clone(); - // The row menu can act on several selected layers. A thumbnail identifies one layer. + // The row menu can act on several selected layers; a thumbnail names one let several = if content_thumbnail { None } else { selection_with(app, layer.id) }; let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, params: Value, enabled: bool| { let mut button = egui::Button::new(label); @@ -1365,6 +1365,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": layer_id}), layer.mask.is_none()); run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": layer_id}), layer.mask.is_none()); run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": layer_id}), true); + run(app, ui, tr("Add mask with height combination"), "mask.add.heightCombination", json!({"layer": layer_id}), true); if !content_thumbnail { ui.separator(); mask_management_menu(app, ui, layer, false); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 72b5ad4b..7b70cc7a 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -378,6 +378,19 @@ fn click_eye(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: egui:: h.run_steps(2); } +#[test] +fn the_row_menu_adds_a_height_combination_to_the_clicked_layers_mask() { + let (mut h, layer) = harness(); + let row = h.get_by_label("Masked fill").rect(); + right_click(&mut h, row.center()); + h.get_by_label("Add mask with height combination").click(); + h.run_steps(3); + + let mask = h.state().session.doc.project.layers[&layer].mask.clone().unwrap(); + assert_eq!(mask.effects.len(), 2, "the compare lands in the existing mask"); + assert!(mask.effects.iter().any(|effect| matches!(effect.kind, texturecraft_engine::core::EffectKind::Compare { .. }))); +} + #[test] fn the_context_menu_solos_a_layer_without_touching_the_document() { let (mut h, layer) = harness(); From 8361234c49ea8b73793657ba51a8d83b5c3a9a53 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:00:50 +0000 Subject: [PATCH 015/128] Layers: move an effect up, down, to the top or bottom from its row menu --- crates/ui-egui/src/dock.rs | 17 ++++++++++++ crates/ui-egui/tests/it/effect_rows.rs | 37 +++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index a66dbdec..8c0bdcd4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1135,6 +1135,23 @@ fn effect_row( } } + // Rows list the stack top first and index 0 is its bottom, so up is one index higher + ui.separator(); + if let Some(index) = position(effect_id.0) { + let top = stack.len() - 1; + for (label, to, enabled) in [ + (tr("Move up"), index + 1, index < top), + (tr("Move down"), index.saturating_sub(1), index > 0), + (tr("Move to top"), top, index < top), + (tr("Move to bottom"), 0, index > 0), + ] { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + app.run("effect.move", json!({"effect": effect_id.0, "index": to})); + ui.close(); + } + } + } + // Blending options can apply across channels or effects ui.separator(); let blends = effect.kind.blends(); diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 54157bba..839f252c 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,4 +1,4 @@ -//! Effect rows in the layer stack: dragging one reorders its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options +//! Effect rows in the layer stack: dragging one or its menu's Move items reorder its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -59,6 +59,41 @@ fn dragging_an_effect_row_reorders_its_stack() { assert_eq!(order(&harness), [a, c, b]); } +/// An effect row's menu moves it one step or to an end of its stack; a move past an end is greyed +#[test] +fn an_effect_rows_menu_moves_it_within_its_stack() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + 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)); + 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::>(); + let menu_item = |harness: &mut Harness<'_, TextureCraftApp>, row: &str, item: &str| { + harness.get_by_label(row).click_secondary(); + harness.run_steps(3); + harness.get_by_label(item).click(); + harness.run_steps(3); + }; + + menu_item(&mut harness, "Effect A", "Move up"); + assert_eq!(order(&harness), [b, a, c]); + menu_item(&mut harness, "Effect A", "Move to top"); + assert_eq!(order(&harness), [b, c, a]); + menu_item(&mut harness, "Effect C", "Move down"); + assert_eq!(order(&harness), [c, b, a]); + menu_item(&mut harness, "Effect A", "Move to bottom"); + assert_eq!(order(&harness), [a, c, b]); + + harness.get_by_label("Effect A").click_secondary(); + harness.run_steps(3); + assert!(harness.get_by_label("Move down").accesskit_node().is_disabled(), "the bottom effect can't go lower"); + assert!(!harness.get_by_label("Move up").accesskit_node().is_disabled()); +} + /// An effect row's blend mode menu and opacity field sit at its right and set the displayed channel's blending, as on layer rows #[test] fn an_effect_row_sets_its_blend_mode_and_opacity() { From a3713d4631e0220dfb803d04d0ac745762b145f7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:03:25 +0000 Subject: [PATCH 016/128] Layers: name generator effects after their kind and remove an effect from its row's cross --- crates/core/src/layer.rs | 8 +++- crates/engine/src/mask_cmds.rs | 8 ++++ crates/engine/tests/it/generator_names.rs | 56 +++++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/dock.rs | 22 +++++++-- crates/ui-egui/tests/it/effect_rows.rs | 30 ++++++++++-- 6 files changed, 117 insertions(+), 8 deletions(-) create mode 100644 crates/engine/tests/it/generator_names.rs diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index e352bbc0..8bb4a9dc 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -2096,10 +2096,16 @@ pub struct Effect { impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { + // Generators are named after their kind, as filters are + let name = match &kind { + EffectKind::Generator(generator) => generator.kind.label(), + _ => kind.name(), + }; + // Generators and fills that build a mask usually add on top of the background Effect { id, - name: kind.name().to_string(), + name: name.to_string(), visible: true, kind, blend: BlendMode::Normal, diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 385447a0..e234f654 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -713,6 +713,9 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The name every generator effect got before they were named after their kind +const FORMER_GENERATOR_NAME: &str = "Generator"; + /// Edit visibility, blending, name, effect parameters, or a filter's type fn set(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.set"; @@ -818,6 +821,11 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(kind) = generator_kind && kind != generator.kind { + // A name taken from the kind follows the new kind + let named_by_kind = edited.name == generator.kind.label() || edited.name == FORMER_GENERATOR_NAME; + if named_by_kind && name_param(params).is_none() { + edited.name = kind.label().to_string(); + } generator.kind = kind; generator.detail = Generator::new(kind).detail; generator.inputs.retain(|map, _| kind.inputs().contains(map)); diff --git a/crates/engine/tests/it/generator_names.rs b/crates/engine/tests/it/generator_names.rs new file mode 100644 index 00000000..f499114b --- /dev/null +++ b/crates/engine/tests/it/generator_names.rs @@ -0,0 +1,56 @@ +//! Generator effects are named after their kind, and a name taken from the kind follows a kind change + +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{Session, execute}; + +/// A sample session with a new generator of `kind` on its top layer's mask +fn generator(kind: &str) -> (Session, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let added = execute(&mut session, "effect.add.generator", &json!({"generator": kind})).unwrap(); + + (session, LayerId(added["effect"].as_u64().unwrap())) +} + +fn name(session: &Session, effect: LayerId) -> String { + session.doc.project.effect(effect).unwrap().1.name.clone() +} + +fn set(session: &mut Session, effect: LayerId, params: Value) { + let mut params = params; + params["effect"] = json!(effect.0); + execute(session, "effect.set", ¶ms).unwrap(); +} + +#[test] +fn a_new_generator_takes_its_kinds_name_and_keeps_following_it() { + let (mut session, effect) = generator("dirt"); + assert_eq!(name(&session, effect), "Dirt"); + + set(&mut session, effect, json!({"generator": "curvature"})); + + assert_eq!(name(&session, effect), "Curvature"); +} + +#[test] +fn a_chosen_name_survives_a_kind_change() { + let (mut session, effect) = generator("dirt"); + set(&mut session, effect, json!({"name": "Grime"})); + + set(&mut session, effect, json!({"generator": "curvature"})); + assert_eq!(name(&session, effect), "Grime"); + + set(&mut session, effect, json!({"generator": "dirt", "name": "Dust"})); + assert_eq!(name(&session, effect), "Dust", "a name given with the change wins"); +} + +#[test] +fn an_older_projects_generic_generator_name_follows_its_next_kind_change() { + let (mut session, effect) = generator("dirt"); + set(&mut session, effect, json!({"name": "Generator"})); + + set(&mut session, effect, json!({"generator": "curvature"})); + + assert_eq!(name(&session, effect), "Curvature"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ce9f1614..2047f670 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -36,6 +36,7 @@ mod filters; mod folder_contents; mod frame_selection; mod generator_inputs; +mod generator_names; mod gradient_map; mod high_poly_missed; mod instances; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 8c0bdcd4..0eda8d6b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -333,6 +333,8 @@ const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5]; /// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part. const EFFECT_BLEND_WIDTH: f32 = 82.0; const EFFECT_OPACITY_WIDTH: f32 = 36.0; +/// Width of the column at an effect row's right end holding its remove cross +const EFFECT_REMOVE_WIDTH: f32 = 17.0; /// Height of the "Content effects" / "Mask effects" header rows. const GROUP_HEADER_H: f32 = 20.0; @@ -977,7 +979,7 @@ fn blend_controls( (picked, field.changed().then_some((percent / 100.0, merge))) } -/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level` #[allow(clippy::too_many_arguments)] fn effect_row( app: &mut TextureCraftApp, @@ -1037,11 +1039,20 @@ fn effect_row( painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim)); } - // The name, then the blend mode and opacity side by side at the right when the name keeps room to be read + // The cross at the right end removes the effect: it ends where a layer row's controls end, and takes clicks left of the panel's floating scroll bar + let remove = + Rect::from_min_max(pos2(rect.right() - ROW_CONTROL_GAP - EFFECT_REMOVE_WIDTH, rect.top()), pos2(rect.right() - ROW_CONTROL_GAP, rect.bottom())); + let remove_hit = Rect::from_min_max(remove.min, pos2(remove.right().min(rect.right() - ui.spacing().scroll.bar_width), remove.bottom())); + let remove_response = ui.interact(remove_hit, ui.scope_id().with(("eff_remove", effect_id.0)), Sense::click()).on_hover_text(tr("Remove effect")); + remove_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, trf("Remove effect {name}", &[("name", &effect.name)]))); + let remove_color = if remove_response.hovered() { tokens.text } else { tokens.text_dim }; + painter.text(remove.center(), egui::Align2::CENTER_CENTER, ic::X, egui::FontId::proportional(EYE_FONT_SIZE), remove_color); + + // The name, then the blend mode and opacity side by side left of the cross when the name keeps room to be read let name_left = thumbnail.right() + THUMBNAIL_GAP; - let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; + let controls_left = remove.left() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH; - let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING }; + let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { remove.left() - ROW_RIGHT_PADDING }; let name_color = if visible { tokens.text } else { tokens.text_dim }; let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == effect_id.0); if renaming { @@ -1076,6 +1087,9 @@ fn effect_row( if eye_response.clicked() { app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if remove_response.clicked() { + app.run("effect.remove", json!({"effect": effect_id.0})); + return; } else if row.double_clicked() && !renaming { app.ui.rename = Some((effect_id.0, effect.name.clone())); } else if row.clicked() { diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 839f252c..d17882ba 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,4 +1,4 @@ -//! Effect rows in the layer stack: dragging one or its menu's Move items reorder its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options +//! Effect rows in the layer stack: dragging one or its menu's Move items reorder its stack, its cross removes it, its blend mode and opacity sit at its right, and its menu holds the Blending options use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -94,6 +94,30 @@ fn an_effect_rows_menu_moves_it_within_its_stack() { assert!(!harness.get_by_label("Move up").accesskit_node().is_disabled()); } +/// The cross at an effect row's right end removes that effect alone, in one undo step +#[test] +fn an_effect_rows_cross_removes_it() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let a = add("Effect A"); + add("Effect B"); + 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.run_steps(4); + let undo_steps = harness.state().session.history_labels().len(); + + let at = harness.get_by_label("Remove effect Effect B").rect().center(); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(3); + + let remaining = harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(remaining, [a]); + assert_eq!(harness.state().session.history_labels().len(), undo_steps + 1); +} + /// An effect row's blend mode menu and opacity field sit at its right and set the displayed channel's blending, as on layer rows #[test] fn an_effect_row_sets_its_blend_mode_and_opacity() { @@ -110,9 +134,9 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.state_mut().ui.layer_material_view = false; harness.run_steps(2); - // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field + // Left of the remove cross: a 4-point gap, then the 82-point pair of mode menu and opacity field let row = harness.get_by_label("Effect A").rect(); - let pair_right = row.right() - 4.0; + let pair_right = harness.get_by_label("Remove effect Effect A").rect().left() - 4.0; let pair_left = pair_right - 82.0; let mode_at = egui::pos2(pair_left + 20.0, row.center().y); harness.drag_at(mode_at); From 2f1927397b48cadb62b5abf325633fba9696a5b5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:51:49 +0000 Subject: [PATCH 017/128] Layers: add a smart material from the toolbar's picker The toolbar's smart material button (a caret like Add effect and Add mask) opens the resource picker filtered to smart materials, the user's saved ones after the built-in ones; a pick adds it above the selection. To keep one row in a 1280 pt window the menu buttons narrow to 30 pt, the plain buttons to 23 pt, and the channel list gives up width down to 70 pt ("Material" still whole) before the row wraps. --- crates/ui-egui/src/layer_toolbar.rs | 98 ++++++++++++++++--- .../layer_toolbar/smart_material_choice.rs | 10 ++ crates/ui-egui/src/shelf.rs | 4 +- crates/ui-egui/tests/it/layer_toolbar.rs | 37 ++++++- crates/ui-egui/tests/it/layers_panel.rs | 2 +- 5 files changed, 131 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/src/layer_toolbar/smart_material_choice.rs diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 83e028db..ec6b1eb5 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -1,10 +1,13 @@ -//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons and remove +//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons, the smart material picker and remove + +use std::path::PathBuf; use egui::{Align2, Color32, CornerRadius, FontId, Frame, Id, Painter, Pos2, Rect, Response, Sense, Shadow, Stroke, StrokeKind, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::Session; use texturecraft_engine::core::{Layer, LayerId}; +use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use crate::TextureCraftApp; @@ -21,12 +24,14 @@ mod bitmap_choice; mod item_icon; mod menu_icon; mod pick; +mod smart_material_choice; use add_item::AddItem; use bitmap_choice::BitmapChoice; use item_icon::ItemIcon; use menu_icon::MenuIcon; use pick::Pick; +use smart_material_choice::SmartMaterialChoice; /// The row's height and its controls' height const BAR_HEIGHT: f32 = 40.0; @@ -37,14 +42,16 @@ const CONTROL_ROUNDING: u8 = 5; const SIDE_PADDING: f32 = 8.0; const CHANNEL_WIDTH: f32 = 88.0; +/// The channel list's width when the row gets tight: "Material" and its caret still fit, and the row fits a 1280 pt wide window's Layers panel +const CHANNEL_MIN_WIDTH: f32 = 70.0; /// A menu button: its icon, then its caret -const MENU_BUTTON_WIDTH: f32 = 32.0; +const MENU_BUTTON_WIDTH: f32 = 30.0; const MENU_ICON_X: f32 = 11.0; const MENU_CARET_INSET: f32 = 8.0; const MENU_ICON_SIZE: f32 = 14.0; const MASK_ICON_SIZE: f32 = 12.0; const CARET_SIZE: f32 = 11.0; -const BUTTON_WIDTH: f32 = 24.0; +const BUTTON_WIDTH: f32 = 23.0; const ICON_SIZE: f32 = 14.0; /// Air after the channel list, between the two menu buttons, before the add-layer buttons and between them const CHANNEL_GAP: f32 = 6.0; @@ -52,16 +59,16 @@ const MENU_GAP: f32 = 3.0; const GROUP_GAP: f32 = 8.0; const BUTTON_GAP: f32 = 2.0; const CHANNEL_TEXT_X: f32 = 8.0; -const CHANNEL_CARET_INSET: f32 = 10.0; +const CHANNEL_CARET_INSET: f32 = 9.0; const CHANNEL_CARET_SIZE: f32 = 12.0; const TEXT_SIZE: f32 = 12.0; /// The row's width besides the channel list's: its padding, the two menu buttons and their gaps const MENUS_ROW_WIDTH: f32 = 2.0 * SIDE_PADDING + CHANNEL_GAP + 2.0 * MENU_BUTTON_WIDTH + MENU_GAP; -/// The three add-layer buttons and Remove -const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + 3.0 * BUTTON_GAP; -/// The width every control takes in one row -const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH; +/// The three add-layer buttons, the smart material button and Remove +const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + MENU_BUTTON_WIDTH + 4.0 * BUTTON_GAP; +/// The smallest width that holds every control in one row, the channel list at its narrowest +const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_MIN_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; @@ -105,8 +112,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let mut x = bar.left() + SIDE_PADDING; let control = |x: f32, top: f32, width: f32| Rect::from_min_size(pos2(x, top), vec2(width, CONTROL_HEIGHT)); - // Narrower still, the channel list gives up width before a menu button leaves the panel - let channel_width = CHANNEL_WIDTH.min(width - MENUS_ROW_WIDTH).max(0.0); + // A tight row takes width from the channel list first; narrower still, it gives up width before a menu button leaves the panel + let channel_room = if two_rows { width - MENUS_ROW_WIDTH } else { width - MENUS_ROW_WIDTH - GROUP_GAP - LAYER_BUTTONS_WIDTH }; + let channel_width = CHANNEL_WIDTH.min(channel_room).max(0.0); channel_list(app, ui, control(x, top, channel_width), &tokens); x += channel_width + CHANNEL_GAP; @@ -119,16 +127,19 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { x += MENU_BUTTON_WIDTH + GROUP_GAP; let (top, mut x) = if two_rows { (top + BAR_HEIGHT, bar.left() + SIDE_PADDING) } else { (top, x) }; - for (glyph, label, command) in [ - (ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"), - (ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill"), - (ic::FOLDER_SIMPLE, tr("Add folder"), "layer.add.group"), - ] { + for (glyph, label, command) in [(ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"), (ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill")] { if plain_button(ui, control(x, top, BUTTON_WIDTH), glyph, label, &tokens).clicked() { app.run(command, Value::Null); } x += BUTTON_WIDTH + BUTTON_GAP; } + let smart_materials = ui.scope_id().with("smart_material_picker"); + picker_button(ui, control(x, top, MENU_BUTTON_WIDTH), tr("Add smart material"), MenuIcon::Glyph(ic::STACK), smart_materials, &tokens); + x += MENU_BUTTON_WIDTH + BUTTON_GAP; + if plain_button(ui, control(x, top, BUTTON_WIDTH), ic::FOLDER_SIMPLE, tr("Add folder"), &tokens).clicked() { + app.run("layer.add.group", Value::Null); + } + x += BUTTON_WIDTH + BUTTON_GAP; let remove = control((bar.right() - SIDE_PADDING - BUTTON_WIDTH).max(x), top, BUTTON_WIDTH); if plain_button(ui, remove, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), &tokens).clicked() { app.run("layer.remove", Value::Null); @@ -144,6 +155,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(layer) = selected { bitmap_picker(app, &anchor, popup(layer), layer); } + smart_material_picker(app, &anchor, smart_materials); } /// Layer `id` of the project, when there is one @@ -256,6 +268,19 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s picked } +/// A button drawn like a menu button whose click opens or closes resource picker `popup`; it keeps its button face while the picker is open +fn picker_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, popup: Id, tokens: &Tokens) { + 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)); + if response.clicked() { + resource_picker::toggle(ui.ctx(), popup); + } + if response.hovered() || egui::Popup::is_id_open(ui.ctx(), popup) { + ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_ROUNDING), tokens.button); + } + button_face(ui.painter(), rect, icon, tokens); +} + /// 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); @@ -461,3 +486,46 @@ fn bitmap_tabs(session: &Session) -> Vec> { let groups = vec![PickerGroup { header: Some(tr("Textures")), items: textures }, PickerGroup { header: Some(tr("Alphas")), items: alphas }]; vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups }] } + +/// The smart material picker, hanging under `anchor` at its width while open: a pick adds the material above the selection, as a shelf click on a saved one does +fn smart_material_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id) { + let tabs = || smart_material_tabs(app.library.as_deref().unwrap_or_default()); + match resource_picker::show(anchor, popup, &mut app.thumbs, None, false, tabs) { + Some(SmartMaterialChoice::BuiltIn(id)) => { + app.run("material.apply", json!({"material": id})); + } + Some(SmartMaterialChoice::Saved(path)) => { + app.run("material.load", json!({"path": path.display().to_string()})); + } + None => {} + } +} + +/// The smart material picker's one tab: the built-in smart materials, then the ones the user saved (once the shelf has read them) +fn smart_material_tabs(library: &[PathBuf]) -> Vec> { + let built_in = MATERIALS + .iter() + .filter(|material| material.smart) + .map(|material| ResourcePickerItem { + id: SmartMaterialChoice::BuiltIn(material.id), + label: tr(material.label).to_owned(), + caption: Some(tr(material.category)), + picture: TilePicture::Material(material.id), + }) + .collect(); + let saved: Vec<_> = library + .iter() + .filter(|path| !crate::shelf::is_saved_mask(path)) + .map(|path| ResourcePickerItem { + id: SmartMaterialChoice::Saved(path.clone()), + label: crate::shelf::saved_material_name(path).to_owned(), + caption: None, + picture: TilePicture::Glyph(ic::SPHERE), + }) + .collect(); + let mut groups = vec![PickerGroup { header: Some(tr("Smart materials")), items: built_in }]; + if !saved.is_empty() { + groups.push(PickerGroup { header: Some(tr("Your assets")), items: saved }); + } + vec![PickerTab { icon: ic::STACK, name: tr("Smart materials"), groups }] +} diff --git a/crates/ui-egui/src/layer_toolbar/smart_material_choice.rs b/crates/ui-egui/src/layer_toolbar/smart_material_choice.rs new file mode 100644 index 00000000..39e7bf9c --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar/smart_material_choice.rs @@ -0,0 +1,10 @@ +//! A pick of the Layers toolbar's smart material picker + +use std::path::PathBuf; + +/// A built-in smart material by id, or one the user saved, by file +#[derive(Clone, PartialEq)] +pub(super) enum SmartMaterialChoice { + BuiltIn(&'static str), + Saved(PathBuf), +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 3416a106..e207b063 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -360,7 +360,7 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: } /// Whether a library file is a saved smart mask (not a smart material) -fn is_saved_mask(path: &std::path::Path) -> bool { +pub(crate) fn is_saved_mask(path: &std::path::Path) -> bool { path.extension().is_some_and(|extension| extension == texturecraft_engine::smart_masks::SMART_MASK_EXT) } @@ -444,7 +444,7 @@ fn scan_library(app: &mut TextureCraftApp) { fn scan_library(_: &mut TextureCraftApp) {} /// A saved smart material's name: its file name without the extension -fn saved_material_name(path: &std::path::Path) -> &str { +pub(crate) fn saved_material_name(path: &std::path::Path) -> &str { path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME) } diff --git a/crates/ui-egui/tests/it/layer_toolbar.rs b/crates/ui-egui/tests/it/layer_toolbar.rs index 9466a76f..2e8bbb5a 100644 --- a/crates/ui-egui/tests/it/layer_toolbar.rs +++ b/crates/ui-egui/tests/it/layer_toolbar.rs @@ -1,11 +1,12 @@ //! The Layers panel's top row: Add effect greys what can't go where the selection is, Add mask adds a mask with its effect, and -//! Bitmap adds nothing until a texture is picked +//! Bitmap adds nothing until a texture is picked; Add smart material adds the smart material picked use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, EffectKind, LayerId, Source}; +use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use texturecraft_engine::{StackTarget, execute}; use texturecraft_ui_egui::TextureCraftApp; @@ -127,6 +128,38 @@ fn the_bitmap_picker_closes_when_the_selection_moves_and_masks_no_other_layer() assert!(mask_kinds(&harness, opener).is_empty(), "nor the layer that opened it"); } +/// The selected texture set's top-level layers, bottom to top +fn stack(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let session = &harness.state().session; + session.doc.project.texture_set(session.ts()).unwrap().stack.clone() +} + +/// Add smart material opens a picker of the smart materials only; a pick adds its folder right above the selected layer +#[test] +fn add_smart_material_adds_the_picked_smart_material_above_the_selection() { + let (mut harness, layer) = app(); + let smart = MATERIALS.iter().find(|material| material.smart).unwrap(); + let simple = MATERIALS.iter().find(|material| !material.smart).unwrap(); + let tiles_of = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.query_all_by_label(label).map(|node| node.rect()).collect::>(); + let (smart_before, simple_before) = (tiles_of(&harness, smart.label), tiles_of(&harness, simple.label)); + + click_widget(&mut harness, Role::Button, "Add smart material"); + let new_tile = tiles_of(&harness, smart.label).into_iter().find(|tile| !smart_before.contains(tile)); + + assert!(egui::Popup::is_any_open(&harness.ctx), "the button opens the picker"); + assert_eq!(tiles_of(&harness, simple.label).len(), simple_before.len(), "simple materials stay out of it"); + + let before = stack(&harness); + click_at(&mut harness, new_tile.expect("a tile for the smart material").center()); + let after = stack(&harness); + let added: Vec<_> = after.iter().filter(|id| !before.contains(id)).copied().collect(); + + assert_eq!(added.len(), 1, "one folder added: {added:?}"); + let place = |id: LayerId| after.iter().position(|shown| *shown == id).unwrap(); + assert_eq!(place(added[0]), place(layer) + 1, "right above the selection"); + assert!(!egui::Popup::is_any_open(&harness.ctx), "the pick closes the picker"); +} + /// A floating Layers panel this narrow cannot hold the toolbar on one row const NARROW_LAYERS: [f32; 4] = [600.0, 200.0, 200.0, 400.0]; @@ -143,7 +176,7 @@ fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() { harness.run_steps(SETTLE_FRAMES); let [left, _, width, _] = NARROW_LAYERS; - for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add folder", "Remove layer"] { + for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add smart material", "Add folder", "Remove layer"] { let button = harness.query_all_by_label_contains(label).find(|node| node.accesskit_node().role() == Role::Button).unwrap().rect(); assert!(button.left() >= left && button.right() <= left + width, "{label} at {button:?} stays inside the panel"); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 7b70cc7a..a0255023 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -266,7 +266,7 @@ fn narrow_harness() -> Harness<'static, TextureCraftApp> { #[test] fn layer_toolbar_stays_on_one_row_in_a_1280_by_800_window() { let h = narrow_harness(); - let buttons = ["Add paint layer", "Add fill layer", "Add folder"].map(|label| h.get_by_label(label).rect()); + let buttons = ["Add paint layer", "Add fill layer", "Add smart material", "Add folder"].map(|label| h.get_by_label(label).rect()); let wand = h.get_by_label("Add effect").rect(); let remove = h.query_all_by_label_contains("Remove layer").next().expect("the remove button").rect(); From e3b589b070fadfc308f72ddb440954473e4632a5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:07:34 +0000 Subject: [PATCH 018/128] Layers: flatten a folder into a fill layer above it --- crates/compose/src/eval.rs | 124 +++++++++++++++++++- crates/compose/src/lib.rs | 2 +- crates/core/src/layer/sampling.rs | 5 +- crates/engine/src/fill_reset_cmds.rs | 4 +- crates/engine/src/layer_ops.rs | 138 +++++++++++++++++++---- crates/engine/tests/it/flatten_folder.rs | 99 ++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/formats/src/image_res.rs | 11 ++ crates/formats/src/lib.rs | 2 +- crates/ui-egui/src/dock.rs | 3 +- 10 files changed, 363 insertions(+), 26 deletions(-) create mode 100644 crates/engine/tests/it/flatten_folder.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3097e768..f96dd739 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3116,7 +3116,30 @@ impl<'a, 'b> Texel<'a, 'b> { None => ch.default_value(), }; let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), projection, fill.sampling, depth) }; - (value, cover) + match source { + Some(Source::Image { name, .. }) if fill.sampling.alpha_coverage && cover > 0.0 => { + (value, cover * self.image_alpha(name, projection, fill.sampling)) + } + _ => (value, cover), + } + } + + /// Image resource `name`'s alpha at this texel through `projection` (0 for a missing image) + fn image_alpha(&mut self, name: &str, projection: &Projection, sampling: Sampling) -> f32 { + let Some(image) = self.inp.images.get(name) else { return 0.0 }; + + let (coords, _) = self.projected(projection); + let samples = self.image_uvs(projection, &coords); + let footprints = match sampling.filtering { + Filtering::BilinearHq => self.footprints(projection, &samples, image), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; + samples + .into_iter() + .zip(footprints) + .map(|((uv, weight), footprint)| image.sample_alpha(uv.x, uv.y, sampling, footprint) * weight) + .sum::() + .clamp(0.0, 1.0) } /// How much a fill projected by `proj` covers this texel: [`Texel::shape_cover`], then depth culling through the projector's `depth` map @@ -4961,6 +4984,105 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti Some(out.into_iter().flatten().collect()) } +/// One tile of a flattened folder's mask: (tile, mask value + coverage data) +pub type FlatMaskTile = ((u32, u32), Vec); + +/// Flatten folder `id`: what its visible layers lay down (premultiplied value and coverage tiles per enabled channel, as [`flatten_layer`]) without its mask or opacity, and its mask and submesh limits as mask tiles (none when it has neither); None for a layer that is not a folder +pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<(Vec, Vec)> { + let set = inputs.project.texture_set(inputs.ts).ok()?; + if !inputs.project.content_layer(id)?.is_group() { + return None; + } + + let channels: Vec = set.channel_list(); + + // Plan the folder forced visible so hidden folders flatten too + let mut forced_visible = inputs.project.clone(); + if let Some(layer) = forced_visible.layers.get_mut(&id) { + layer.visible = true; + } + let visible_inputs = Inputs { project: &forced_visible, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let projectors = ProjectorDepthCache::default(); + let visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + let planned_channels = evaluation_channels(&visible_inputs, channels.clone()); + let fields = evaluation_fields(&visible_inputs, &planned_channels, tiles); + + let out: Vec<(Vec, Option)> = tiles + .par_iter() + .map(|&(tx, ty)| { + let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); + let Some(node) = nodes.first() else { return (Vec::new(), None) }; + let Content::Group(children) = &node.content else { return (Vec::new(), None) }; + let below = below_plan(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields), node.lights); + + // One value + coverage buffer per channel the folder plans; signed channels start at their middle + let mut buffers: Vec<(Channel, Vec, bool)> = node + .chans + .iter() + .filter_map(|planned| Channel::ALL.get(planned.ch).map(|channel| (*channel, vec![0u16; TILE_AREA * (planned.comps + 1)], false))) + .collect(); + for (channel, buffer, _) in &mut buffers { + if channel.kind() == ChannelKind::Signed { + for pixel in buffer.as_chunks_mut::<2>().0 { + pixel[0] = to_u16_signed(0.0); + } + } + } + + let masked = node.mask.is_some() || node.parts.is_some(); + let mut mask = masked.then(|| vec![0u16; TILE_AREA * 2]); + + for (x, y, offset) in tile_texels(inputs.gbuf, tx, ty) { + // The texel with the stack below the folder run, so masks and fills that read it or its anchors find them + let texel_over_below = || { + let mut texel = Texel::new(&visible_inputs, x, y, offset, 0.0); + if !below.is_empty() { + texel.anchors_below(&below, (id, 0)); + } + texel + }; + + // Laid over an all-0 and an all-1 stack, the layers show their premultiplied value and how much of the stack they hide + let over = |background: f32| { + let mut texel = texel_over_below(); + let mut stack: Acc = [[background; 3]; NCH]; + texel.eval(children, &mut stack); + stack + }; + let (low, high) = (over(0.0), over(1.0)); + for (planned, (channel, buffer, laid_down)) in node.chans.iter().zip(buffers.iter_mut()) { + let (Some(premultiplied), Some(shown)) = (low.get(planned.ch), high.get(planned.ch)) else { continue }; + let comps = planned.comps.min(3); + let hidden = premultiplied.iter().zip(shown).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; + let coverage = hidden.clamp(0.0, 1.0); + if coverage <= 0.0 { + continue; + } + + *laid_down = true; + let Some(pixel) = buffer.get_mut(offset * (planned.comps + 1)..(offset + 1) * (planned.comps + 1)) else { continue }; + for (slot, value) in pixel.iter_mut().zip(premultiplied.iter().take(planned.comps)) { + *slot = if channel.kind() == ChannelKind::Signed { to_u16_signed(*value) } else { to_u16(*value) }; + } + if let Some(slot) = pixel.get_mut(planned.comps) { + *slot = to_u16(coverage); + } + } + + if let Some(pixel) = mask.as_mut().and_then(|mask| mask.get_mut(offset * 2..offset * 2 + 2)) { + pixel.copy_from_slice(&[to_u16(texel_over_below().node_mask(node)), u16::MAX]); + } + } + + let content = buffers.into_iter().filter(|(_, _, laid_down)| *laid_down).map(|(channel, buffer, _)| (channel, (tx, ty), buffer)).collect(); + (content, mask.map(|mask| ((tx, ty), mask))) + }) + .collect(); + + let (content, masks): (Vec<_>, Vec<_>) = out.into_iter().unzip(); + Some((content.into_iter().flatten().collect(), masks.into_iter().flatten().collect())) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 2f5c0477..f931da06 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -55,7 +55,7 @@ pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use effect_histogram::EffectHistogram; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached, - composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, + composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; pub use mask_gray::MaskGray; diff --git a/crates/core/src/layer/sampling.rs b/crates/core/src/layer/sampling.rs index 9fa568fb..4a1c4b6d 100644 --- a/crates/core/src/layer/sampling.rs +++ b/crates/core/src/layer/sampling.rs @@ -14,12 +14,15 @@ pub struct Sampling { pub scale: ScaleMode, #[serde(default, skip_serializing_if = "FillSymmetry::is_default")] pub symmetry: FillSymmetry, + /// Each channel's image alpha is how much of that channel shows (the images a folder is flattened into) + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub alpha_coverage: bool, } impl Sampling { /// What fills saved before the sampling choices existed did: plain bilinear pub const SAVED_BEFORE: Sampling = - Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF }; + Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF, alpha_coverage: false }; /// Serde default for fills saved before the field existed pub fn saved_before() -> Sampling { diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index b2e10670..0e12f002 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -19,9 +19,9 @@ pub fn specs() -> Vec { )] } -/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) +/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) and its alpha coverage (a flattened folder's shape) pub fn reset_sampling(current: Sampling) -> Sampling { - Sampling { symmetry: current.symmetry, ..Sampling::default() } + Sampling { symmetry: current.symmetry, alpha_coverage: current.alpha_coverage, ..Sampling::default() } } /// The defaults of `current`'s projection kind: a new fill's projection of that kind, with the frame a placed planar or a warp projects from kept diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 95631f70..1c0bc970 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -2,8 +2,9 @@ //! pixels when a texture set changes size. use serde_json::{Value, json}; -use texturecraft_core::{Channel, ChannelKind, LayerId, LayerKind}; -use texturecraft_texel::TileImage; +use texturecraft_compose::eval::FlatTile; +use texturecraft_core::{Channel, ChannelKind, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source}; +use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; use crate::commands::{CommandSpec, boolp, has_layer, layer_param}; use crate::session::{Document, StackTarget}; @@ -19,7 +20,7 @@ pub fn specs() -> Vec { "Flatten layer", ["Layers"], Some("Ctrl+M"), - "{layer?} — a fill or masked paint layer becomes a plain paint layer", + "{layer?} — a fill or masked paint layer becomes a plain paint layer; a folder becomes a new fill layer above it holding one image per channel (its mask baked into a painted mask) and is hidden", has_layer, flatten ), @@ -197,38 +198,137 @@ fn flatten(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, "layer.flatten", p)?; let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; let layer = s.doc.project.layer(id)?.clone(); - // An instance flattens what it draws into a plain layer of its own. + + // An instance flattens what it draws into a plain layer of its own let content = s.doc.project.content_layer(id).cloned().ok_or_else(|| EngineError::Other("the instance's source is missing".into()))?; if content.is_group() { - return Err(EngineError::Other("flattening a folder is not supported yet; flatten its layers".into())); + return flatten_folder(s, ts, &layer); } + s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let flat = s.flatten(ts, id).ok_or_else(|| EngineError::Other("nothing to flatten".into()))?; s.edit("Flatten layer", |s| { - for c in Channel::ALL { - s.doc.pixels.layers.remove(&(id, c)); + for channel in Channel::ALL { + s.doc.pixels.layers.remove(&(id, channel)); } - let effects: Vec = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()).map(|e| e.id).collect(); - s.doc.pixels.masks.retain(|e, _| !effects.contains(e)); - s.doc.pixels.layers.retain(|(e, _), _| !effects.contains(e)); - for (c, (tx, ty), data) in flat { - let img = s.doc.pixels.layer_mut(id, c, size); - img.set_tile(tx, ty, Some(std::sync::Arc::new(data))); + let effects: Vec = + layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter()).map(|effect| effect.id).collect(); + s.doc.pixels.masks.retain(|effect, _| !effects.contains(effect)); + s.doc.pixels.layers.retain(|(effect, _), _| !effects.contains(effect)); + + for (channel, (tx, ty), data) in flat { + let image = s.doc.pixels.layer_mut(id, channel, size); + image.set_tile(tx, ty, Some(std::sync::Arc::new(data))); } + let channels = s.doc.project.texture_set(ts)?.channel_list(); - let l = s.doc.project.layer_mut(id)?; - l.kind = LayerKind::Paint; - l.mask = None; - l.content_effects.clear(); - l.height_mask = Default::default(); - l.channels = content.channels.into_iter().filter(|(c, _)| channels.contains(c)).collect(); + let flattened = s.doc.project.layer_mut(id)?; + flattened.kind = LayerKind::Paint; + flattened.mask = None; + flattened.content_effects.clear(); + flattened.height_mask = Default::default(); + flattened.channels = content.channels.into_iter().filter(|(channel, _)| channels.contains(channel)).collect(); s.target = StackTarget::Content; Ok(()) })?; Ok(json!({ "layer": id.0 })) } +/// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept +fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { + s.update(); + let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; + let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); + let (content, mask) = s + .with_inputs(ts, |inputs| texturecraft_compose::flatten_folder(inputs, folder.id, &tiles)) + .ok_or_else(|| EngineError::Other("nothing to flatten".into()))?; + let images = channel_images(content, size)?; + if images.is_empty() { + return Err(EngineError::Other("the folder shows nothing to flatten".into())); + } + + let flat = s.edit("Flatten folder", |s| { + let mut fill = Fill { sampling: Sampling { filtering: Filtering::Nearest, alpha_coverage: true, ..Sampling::default() }, ..Fill::default() }; + for (channel, png) in images { + let file_name = format!("{} flattened {}.png", folder.name, channel.id()); + let name = s.add_image_resource(&file_name, png, texturecraft_formats::MAX_RESOURCE_TEXELS)?; + fill.sources.insert(channel, Source::image(name)); + } + + // Only the channels the folder lays down, at its opacity (a folder mixes its result in by opacity alone, whatever its blend mode): a channel without an image would cover the stack with its default + let channels: Vec = fill.sources.keys().copied().collect(); + let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); + for (channel, blend) in &mut layer.channels { + blend.opacity = folder.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); + } + if !mask.is_empty() { + let paint = s.doc.project.alloc_id(); + let mut baked = Mask::new(MaskBackground::Black); + baked.effects.push(Effect::new(paint, EffectKind::Paint)); + layer.mask = Some(baked); + let image = s.doc.pixels.mask_mut(paint, size); + for ((tx, ty), data) in mask { + image.set_tile(tx, ty, Some(std::sync::Arc::new(data))); + } + } + + let flat = s.doc.project.insert_layer(ts, layer, Some(folder.id), false)?; + s.doc.project.layer_mut(folder.id)?.visible = false; + s.select_one(ts, flat); + s.target = StackTarget::Content; + Ok(flat) + })?; + Ok(json!({ "layer": flat.0 })) +} + +/// Flattened tiles as one 16-bit RGBA PNG per channel (straight values as a fill reads them, coverage in the alpha), in channel order +fn channel_images(tiles: Vec, size: (u32, u32)) -> Result)>> { + let (width, height) = size; + let mut by_channel: std::collections::BTreeMap)>> = Default::default(); + for (channel, tile, data) in tiles { + by_channel.entry(channel).or_default().push((tile, data)); + } + + by_channel + .into_iter() + .map(|(channel, tiles)| { + let comps = channel.components(); + let mut rgba = vec![0u16; width as usize * height as usize * 4]; + for ((tx, ty), data) in tiles { + for (offset, texel) in data.chunks_exact(comps + 1).enumerate() { + let (x, y) = (tx * TILE + offset as u32 % TILE, ty * TILE + offset as u32 / TILE); + let coverage = texel.get(comps).copied().map_or(0.0, from_u16); + if x >= width || y >= height || coverage <= 0.0 { + continue; + } + + let straight = |i: usize| { + let premultiplied = texel.get(i).copied().unwrap_or(0); + let value = if channel.kind() == ChannelKind::Signed { from_u16_signed(premultiplied) } else { from_u16(premultiplied) }; + value / coverage + }; + let rgb = match channel.kind() { + ChannelKind::Color => [0, 1, 2].map(|i| linear_to_srgb(straight(i))), + ChannelKind::NormalMap => [0, 1, 2].map(straight), + ChannelKind::Scalar => [straight(0); 3], + + // A fill reads a signed channel's image gray as -1..1 + ChannelKind::Signed => [(straight(0) + 1.0) * 0.5; 3], + }; + let start = (y as usize * width as usize + x as usize) * 4; + if let Some(pixel) = rgba.get_mut(start..start + 4) { + pixel.copy_from_slice(&[to_u16(rgb[0]), to_u16(rgb[1]), to_u16(rgb[2]), to_u16(coverage)]); + } + } + } + let png = + texturecraft_formats::rgba16_png(width, height, &rgba).map_err(|error| EngineError::Other(format!("flattened {}: {error}", channel.id())))?; + Ok((channel, png)) + }) + .collect() +} + impl Session { /// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per /// channel over the set's covered tiles. None for folders or a set not ready. diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs new file mode 100644 index 00000000..741f7e80 --- /dev/null +++ b/crates/engine/tests/it/flatten_folder.rs @@ -0,0 +1,99 @@ +//! Flattening a folder: a new fill layer above it reads one image per channel and its mask is baked, so the stack looks the same with the folder hidden + +use serde_json::{Value, json}; +use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +/// The test project's texture size +const RESOLUTION: u32 = 256; + +/// Largest difference a flattened texel may show (16-bit images, straight values recovered from premultiplied ones) +const TOLERANCE: f32 = 4e-3; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +fn id(reply: Value) -> u64 { + reply["layer"].as_u64().unwrap() +} + +fn stroke(s: &mut Session, size: u32, points: [[u32; 2]; 2]) { + execute(s, "tool.brush", &json!({"size": size, "hardness": 40})).unwrap(); + execute(s, "tool.stroke", &json!({ "points": points })).unwrap(); +} + +/// Every channel's composited value at every texel +fn composite(s: &mut Session) -> Vec<[f32; 3]> { + s.update(); + let channels = s.doc.project.texture_set(0).unwrap().channel_list(); + let cache = &s.caches[0]; + channels.iter().flat_map(|c| (0..RESOLUTION).flat_map(move |y| (0..RESOLUTION).map(move |x| cache.composite.value(*c, x, y)))).collect() +} + +fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { + a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max) +} + +#[test] +fn a_flattened_folder_looks_the_same_as_the_folder_and_undoes_in_one_step() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "roughness": 0.2, "height": -0.3})).unwrap()); + let below = composite(&mut s); + + // A folder over it: a masked red fill and a soft roughness stroke, with a stroke in the folder's own mask + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.9, "height": 0.4})).unwrap()); + s.target = StackTarget::Mask; + stroke(&mut s, 30, [[170, 200], [230, 200]]); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.6})).unwrap(); + stroke(&mut s, 20, [[200, 160], [200, 240]]); + execute(&mut s, "layer.select", &json!({"layer": folder})).unwrap(); + s.target = StackTarget::Mask; + stroke(&mut s, 40, [[160, 215], [240, 215]]); + let before = composite(&mut s); + + assert!(largest_difference(&before, &below) > 0.1, "the folder shows over the layer below"); + + let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + let after = composite(&mut s); + + assert!(matches!(s.doc.project.layer(LayerId(flat)).unwrap().kind, LayerKind::Fill(_)), "the folder becomes a fill layer"); + assert!(!s.doc.project.layer(LayerId(folder)).unwrap().visible, "the folder is hidden under it"); + assert!(s.doc.project.layer(LayerId(flat)).unwrap().mask.is_some(), "the folder's mask is baked into the new layer"); + assert!(largest_difference(&after, &before) < TOLERANCE, "{}", largest_difference(&after, &before)); + + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + + assert!(largest_difference(&composite(&mut reopened), &before) < TOLERANCE, "the baked images keep their coverage when reopened"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + + assert!(s.doc.project.layer(LayerId(flat)).is_err(), "one undo step removes the flattened layer"); + assert!(s.doc.project.layer(LayerId(folder)).unwrap().visible, "and shows the folder again"); +} + +#[test] +fn a_flattened_folder_bakes_a_mask_that_reads_the_layers_below() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap(); + stroke(&mut s, 40, [[160, 200], [240, 200]]); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap()); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": folder})).unwrap(); + let before = composite(&mut s); + + id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2047f670..a1cf0a97 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -33,6 +33,7 @@ mod filter_support; mod filter_swap; mod filter_transform; mod filters; +mod flatten_folder; mod folder_contents; mod frame_selection; mod generator_inputs; diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 903b5b53..55754cba 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -173,6 +173,17 @@ pub fn gray16_resource(width: u32, height: u32, values: impl Iterator Result> { + let texels = u64::from(width) * u64::from(height); + if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE || texels > MAX_RESOURCE_TEXELS { + return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_RESOURCE_TEXELS} texels)"))); + } + + let image = Image::from_u16(width, height, ChannelLayout::Rgba, samples).map_err(|error| FormatError::Invalid(error.to_string()))?; + encode_resource_png(&image) +} + fn encode_resource_png(image: &Image) -> Result> { let options = EncodeOptions { png_compression: PngCompression::Fast, ..EncodeOptions::default() }; craft_image_codecs::encode(image, Format::Png, &options).map_err(|error| FormatError::Invalid(error.to_string())) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a46a6f62..2e6fa186 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -45,7 +45,7 @@ pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, 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 image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource, rgba16_png}; pub use mesh_export::{ GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options, usd_layer_with_textures, usd_texture_bindings, diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 0eda8d6b..3204a6e6 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1406,7 +1406,8 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con ui.separator(); solo_menu(app, ui, layer.id); ui.separator(); - run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": layer_id}), !layer.is_group()); + let flatten = if layer.is_group() { tr("Flatten folder") } else { tr("Flatten layer") }; + run(app, ui, flatten, "layer.flatten", json!({"layer": layer_id}), true); #[cfg(not(target_arch = "wasm32"))] if ui.button(tr("Create smart material")).clicked() { let file = crate::library_dir().join(format!("{}.tcmat", texturecraft_engine::formats::sanitize_resource_name(&layer.name))); From 1ce9ff94b27e23aac50f291ef686aec5d8d8f098 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:09:34 +0000 Subject: [PATCH 019/128] Layers: move the selected effect with Alt+Up and Alt+Down --- crates/engine/src/effect_step.rs | 8 +++++ crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 37 +++++++++++++++++++++++ crates/engine/tests/it/content_effects.rs | 19 ++++++++++++ crates/ui-egui/tests/it/effect_rows.rs | 30 ++++++++++++++++++ 5 files changed, 95 insertions(+) create mode 100644 crates/engine/src/effect_step.rs diff --git a/crates/engine/src/effect_step.rs b/crates/engine/src/effect_step.rs new file mode 100644 index 00000000..32aeb4cf --- /dev/null +++ b/crates/engine/src/effect_step.rs @@ -0,0 +1,8 @@ +//! Which way a step of `effect.moveUp` / `effect.moveDown` moves an effect + +/// Which way an effect moves one place: up is later in its stack (rows list the top first) +#[derive(Clone, Copy)] +pub(crate) enum EffectStep { + Up, + Down, +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..7a700ca5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -18,6 +18,7 @@ pub mod commands; pub mod decal_cmds; pub mod effect_blending_cmds; pub mod effect_clipboard; +mod effect_step; pub mod file_cmds; pub mod fill_alpha; pub mod fill_hit_test; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index e234f654..8fe9c9f2 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -7,6 +7,7 @@ use texturecraft_core::{ }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; +use crate::effect_step::EffectStep; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; use crate::session::StackTarget; @@ -113,6 +114,24 @@ pub fn specs() -> Vec { duplicate_effect ), cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect), + cmd!( + "effect.moveUp", + "Move effect up", + ["Layers"], + Some("Alt+Up"), + "{effect?: the selected effect} — one place up its stack (applied later)", + has_layer, + |s, p| step_effect(s, p, EffectStep::Up) + ), + cmd!( + "effect.moveDown", + "Move effect down", + ["Layers"], + Some("Alt+Down"), + "{effect?: the selected effect} — one place down its stack (applied earlier)", + has_layer, + |s, p| step_effect(s, p, EffectStep::Down) + ), cmd!( "effect.histogram", "Effect input histogram", @@ -1022,6 +1041,24 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Move an effect one place in its stack (one undo step; nothing at its end) +fn step_effect(s: &mut Session, p: &Value, step: EffectStep) -> Result { + let cmd = match step { + EffectStep::Up => "effect.moveUp", + EffectStep::Down => "effect.moveDown", + }; + let effect = effect_id(s, p, cmd)?; + let (list, index) = stack_of(&mut s.doc.project, effect).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?; + let to = match step { + EffectStep::Up if index + 1 < list.len() => index + 1, + EffectStep::Down if index > 0 => index - 1, + _ => return Ok(json!({ "moved": false })), + }; + + crate::execute(s, "effect.move", &json!({ "effect": effect.0, "index": to }))?; + Ok(json!({ "moved": true })) +} + fn remove_effect(s: &mut Session, p: &Value) -> Result { let eid = effect_id(s, p, "effect.remove")?; s.edit("Remove effect", |s| { diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index caba4447..29888e0d 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -610,3 +610,22 @@ fn a_color_histogram_has_its_components_and_luminance() { assert_eq!(counts(&histogram["bins"]), vec![2 * texels, 0, 0, texels]); assert!(roughness.get("components").is_none(), "one value has no components"); } + +#[test] +fn a_named_effect_moves_up_and_down_while_its_layer_content_is_selected() { + let mut s = session(); + let layer = LayerId(id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let add = |s: &mut Session| id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let (bottom, top) = (add(&mut s), add(&mut s)); + let order = |s: &Session| s.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap(); + s.target = StackTarget::Content; + + execute(&mut s, "effect.moveUp", &json!({"effect": bottom})).unwrap(); + + assert_eq!(order(&s), [top, bottom]); + + execute(&mut s, "effect.moveDown", &json!({"effect": bottom})).unwrap(); + + assert_eq!(order(&s), [bottom, top]); +} diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index d17882ba..cccda619 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -94,6 +94,36 @@ fn an_effect_rows_menu_moves_it_within_its_stack() { assert!(!harness.get_by_label("Move up").accesskit_node().is_disabled()); } +/// Alt+Up and Alt+Down move the selected effect one place in its stack; at its end it stays +#[test] +fn alt_up_and_down_move_the_selected_effect() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + 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)); + 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::>(); + let press = |harness: &mut Harness<'_, TextureCraftApp>, key: egui::Key| { + harness.key_press_modifiers(egui::Modifiers::ALT, key); + harness.run_steps(3); + }; + harness.get_by_label("Effect A").click(); + harness.run_steps(3); + + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, a, c]); + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, c, a]); + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, c, a], "the top effect stays"); + press(&mut harness, egui::Key::ArrowDown); + assert_eq!(order(&harness), [b, a, c]); +} + /// The cross at an effect row's right end removes that effect alone, in one undo step #[test] fn an_effect_rows_cross_removes_it() { From 53c501e488dd413f65894e6a5d6fcdc7fba788fc Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:28:50 +0000 Subject: [PATCH 020/128] Layers: hold R over the model to see the layers there and pick one Holding R over the 3D view with any tool shows a label at the pointer naming the top layer laying something down there (any channel in the material view, the shown one in a single-channel view) and how many more. A click selects the layer when it is the only one there; with several it opens a list at the pointer, top first, each row with the layer's thumbnail, name and the channels it changes at that spot. A row click (or Up/Down and Enter) selects that layer, Esc or a click elsewhere closes the list. The click never paints. Hidden layers, masked-out layers and channels at zero opacity are left out. Closed folders holding the picked layer open and its row scrolls into view. The shortcut window lists the gesture. Automation lists the layers with layer.layersAt and selects one with layer.pickAt. --- crates/compose/src/eval.rs | 2 + crates/compose/src/eval/layers_at.rs | 84 ++++++++++ crates/compose/src/lib.rs | 4 +- crates/engine/src/layer_cmds.rs | 40 +++++ crates/engine/src/layer_pick.rs | 69 ++++++++ crates/engine/src/lib.rs | 1 + crates/engine/tests/it/layer_pick.rs | 102 ++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/dock.rs | 6 +- crates/ui-egui/src/keymap.rs | 3 + crates/ui-egui/src/layer_panel.rs | 15 +- crates/ui-egui/src/layer_pick_list.rs | 209 ++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/viewport.rs | 75 ++++++++- crates/ui-egui/tests/it/layers_panel.rs | 71 +++++++- docs/features.md | 5 + 16 files changed, 681 insertions(+), 10 deletions(-) create mode 100644 crates/compose/src/eval/layers_at.rs create mode 100644 crates/engine/src/layer_pick.rs create mode 100644 crates/engine/tests/it/layer_pick.rs create mode 100644 crates/ui-egui/src/layer_pick_list.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index f96dd739..09041f47 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4,6 +4,7 @@ mod draw_placement; mod evaluation_inputs; +mod layers_at; pub(crate) mod thumbnail; use std::borrow::Cow; @@ -42,6 +43,7 @@ use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use draw_placement::DrawPlacement; use evaluation_inputs::EvaluationInputs; +pub use layers_at::layers_at; const NCH: usize = Channel::ALL.len(); diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs new file mode 100644 index 00000000..648dcb4c --- /dev/null +++ b/crates/compose/src/eval/layers_at.rs @@ -0,0 +1,84 @@ +//! Which layers lay something down at one texel, for the viewport's Pick layer tool + +use super::{ + BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, + evaluation_fields, plan, +}; + +/// Below this weight a layer leaves the texel unchanged (one 16-bit step) +const SMALLEST_WEIGHT: f32 = 1.0 / 65535.0; + +/// The paint and fill layers (and instances) that lay something down at texel (x, y) of texture set `inputs.ts` in any of `shown` channels, top first, each with the shown channels it changes there. Hidden layers, layers masked out there (by their own mask or a folder's) and channels at zero opacity count as laying nothing down +pub fn layers_at(inputs: &Inputs, (x, y): (u32, u32), shown: &[Channel]) -> Vec<(LayerId, Vec)> { + let Ok(set) = inputs.project.texture_set(inputs.ts) else { return Vec::new() }; + let gbuf = inputs.gbuf; + let covered = x < gbuf.width && y < gbuf.height && gbuf.tri.get((y * gbuf.width + x) as usize).is_some_and(|tri| *tri != NO_TRI); + if !covered { + return Vec::new(); + } + + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); + let channels = evaluation_channels(inputs, set.channel_list()); + + // Filters and anchors can read texels outside this one's tile: the fields cover what it reads + let (tile_x, tile_y) = (x / TILE, y / TILE); + let fields = evaluation_fields(inputs, &channels, &[(tile_x, tile_y)]); + let nodes = plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)); + let offset = ((y % TILE) * TILE + x % TILE) as usize; + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + + // The whole stack runs first, so masks and fills that read anchors find them + let mut values = Channel::ALL.map(Channel::default_value); + texel.eval(&nodes, &mut values); + + let mut found = Vec::new(); + texel.layers_laying_down(&nodes, [1.0; NCH], shown, &mut found); + + // The stack runs bottom first + found.reverse(); + found +} + +impl Texel<'_, '_> { + /// Push the leaf layers among `nodes` (bottom first) that lay something down in a `shown` channel, with those channels, each channel weighted by `weights` (the opacity and mask of the folders holding them) + fn layers_laying_down(&mut self, nodes: &[Node], weights: [f32; NCH], shown: &[Channel], found: &mut Vec<(LayerId, Vec)>) { + for node in nodes { + let mask = self.node_mask(node); + if mask <= 0.0 { + continue; + } + + let mut node_weights = [0.0; NCH]; + for chan in node.chans.iter().filter(|chan| shown.iter().any(|channel| channel.index() == chan.ch)) { + if let (Some(weight), Some(slot)) = (weights.get(chan.ch), node_weights.get_mut(chan.ch)) { + *slot = weight * chan.opacity * mask; + } + } + + match &node.content { + Content::Group(children) => self.layers_laying_down(children, node_weights, shown, found), + content => { + let changed: Vec = shown + .iter() + .copied() + .filter(|channel| { + node.chans.iter().filter(|chan| chan.ch == channel.index()).any(|chan| { + let weight = node_weights.get(chan.ch).copied().unwrap_or(0.0); + + // Replace lays its value down at full weight wherever the layer has content + weight > SMALLEST_WEIGHT + && self + .content(content, chan) + .is_some_and(|(_, coverage)| chan.blend == BlendMode::Replace || weight * coverage > SMALLEST_WEIGHT) + }) + }) + .collect(); + if !changed.is_empty() { + found.push((node.draw.0, changed)); + } + } + } + } + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f931da06..1f4ff850 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -55,8 +55,8 @@ pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use effect_histogram::EffectHistogram; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached, - composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, - stack_reads_neighbours, + composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, layers_at, mask_at, mask_image, mask_texels, mask_values, + pad_tiles, stack_reads_neighbours, }; pub use mask_gray::MaskGray; pub use pattern_context::PatternContext; diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 4a1f6c7b..7b377ba8 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -87,6 +87,24 @@ pub fn specs() -> Vec { always, select ), + cmd!( + "layer.layersAt", + "Layers under the cursor", + [], + None, + "{x, y, viewport?: [w,h]} a point on the mesh — {layers: [{layer, name, channels}]}: the layers laying something down there in the shown channels, top first, each with the channels it changes there (R + click lists them)", + always, + layers_at + ), + cmd!( + "layer.pickAt", + "Pick layer under the cursor", + [], + None, + "{x, y, viewport?: [w,h], layer?} a point on the mesh — selects `layer` if it lays something down there, else the top layer laying something down there in the shown channels (R + click)", + always, + pick_at + ), cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename), cmd!( "layer.visible", @@ -282,6 +300,28 @@ fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer { folder } +fn pick_at(s: &mut Session, p: &Value) -> Result { + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.pickAt", "`x` and `y` are required")) }; + let viewport = crate::tool_cmds::viewport_of(s, p); + let wanted = u64p(p, "layer").map(LayerId); + let id = s.pick_layer(texturecraft_geom::glam::Vec2::new(x, y), viewport, wanted)?; + Ok(json!({ "layer": id.0 })) +} + +fn layers_at(s: &mut Session, p: &Value) -> Result { + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.layersAt", "`x` and `y` are required")) }; + let viewport = crate::tool_cmds::viewport_of(s, p); + let (_, layers) = s.layers_under(texturecraft_geom::glam::Vec2::new(x, y), viewport)?; + let layers: Vec = layers + .iter() + .map(|(id, channels)| { + let name = s.doc.project.layers.get(id).map(|layer| layer.name.as_str()).unwrap_or_default(); + json!({ "layer": id.0, "name": name, "channels": channels.iter().map(|channel| channel.id()).collect::>() }) + }) + .collect(); + Ok(json!({ "layers": layers })) +} + fn select(s: &mut Session, p: &Value) -> Result { if boolp(p, "all") == Some(true) { return crate::layer_selection::select_all(s); diff --git a/crates/engine/src/layer_pick.rs b/crates/engine/src/layer_pick.rs new file mode 100644 index 00000000..9107fb3e --- /dev/null +++ b/crates/engine/src/layer_pick.rs @@ -0,0 +1,69 @@ +//! Picking a layer on the mesh (R + click in the viewport, `layer.layersAt` and `layer.pickAt`): the layers laying something down where the mesh is clicked, and selecting one of them + +use texturecraft_core::{Channel, LayerId, LayerKind}; +use texturecraft_geom::glam::Vec2; + +use crate::session::ViewMode; +use crate::{EngineError, Result, Session, StackTarget}; + +/// A texture set and the layers laying something down at one of its texels, top first, each with the channels it changes there +pub type LayersUnder = (usize, Vec<(LayerId, Vec)>); + +impl Session { + /// The texture set and texel of the mesh under `screen`, None off the mesh + pub fn texel_under(&self, screen: Vec2, viewport: Vec2) -> Option<(usize, (u32, u32))> { + let hit = self.pick(screen, viewport)?; + let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); + let (width, height) = self.caches.get(ts).map(|cache| (cache.size.0 as f32, cache.size.1 as f32))?; + let texel = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32); + Some((ts, texel)) + } + + /// The layers laying something down at `texel` of texture set `ts` in the shown channels (every channel outside a single-channel view), top first, each with the channels it changes there + pub fn layers_at_texel(&self, ts: usize, texel: (u32, u32)) -> Vec<(LayerId, Vec)> { + let shown = match self.view { + ViewMode::Channel(channel) => vec![channel], + _ => self.doc.project.texture_set(ts).map(|set| set.channel_list()).unwrap_or_default(), + }; + self.with_inputs(ts, |inputs| Some(texturecraft_compose::layers_at(inputs, texel, &shown))).unwrap_or_default() + } + + /// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`]) + pub fn layers_under(&self, screen: Vec2, viewport: Vec2) -> Result { + let (ts, texel) = self.texel_under(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + Ok((ts, self.layers_at_texel(ts, texel))) + } + + /// Select `wanted` when it lays something down under `screen`, else the top layer there + pub fn pick_layer(&mut self, screen: Vec2, viewport: Vec2, wanted: Option) -> Result { + let (ts, layers) = self.layers_under(screen, viewport)?; + let picked = match wanted { + Some(wanted) => layers.iter().find(|(id, _)| *id == wanted).ok_or_else(|| EngineError::Other("that layer lays nothing down here".into()))?, + None => layers.first().ok_or_else(|| EngineError::Other("no visible layer lays anything down here".into()))?, + }; + let id = picked.0; + + // Paths paint into the active set, and the clone source is a point of the set it was picked in + if ts != self.ts() { + self.finish_path()?; + self.tool.clone_source = None; + } + self.active_set = ts; + self.select_one(ts, id); + self.open_folders_holding(id); + self.target = StackTarget::Content; + self.revision = self.revision.wrapping_add(1); + Ok(id) + } + + /// Expand every collapsed folder holding `id`, so the Layers panel shows its row + fn open_folders_holding(&mut self, id: LayerId) { + let mut child = id; + while let Some((_, Some(folder), _)) = self.doc.project.locate(child) { + if let Some(LayerKind::Group { collapsed, .. }) = self.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) { + *collapsed = false; + } + child = folder; + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7a700ca5..c6decb59 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -34,6 +34,7 @@ pub mod inspect; pub mod instance_cmds; pub mod layer_cmds; pub mod layer_ops; +mod layer_pick; pub mod layer_selection; pub mod link_cmds; pub mod log; diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs new file mode 100644 index 00000000..dcd8d38d --- /dev/null +++ b/crates/engine/tests/it/layer_pick.rs @@ -0,0 +1,102 @@ +//! Picking a layer on the mesh (R + click): the layers laying something down at a spot, top first, and selecting one of them + +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerKind; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The middle of the sphere in the test viewport, where the lower paint layer is painted +const MIDDLE: [f32; 2] = [200.0, 200.0]; + +/// A spot on the sphere left of the middle, where only the upper paint layer is painted +const LEFT: [f32; 2] = [130.0, 200.0]; + +/// The test stack: (session, the fill at the bottom, a paint layer over the middle, a paint layer over the left spot above it) +fn stack() -> (Session, u64, u64, u64) { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let middle = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 100})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[190, 200], [210, 200]]})).unwrap(); + let left = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.stroke", &json!({"points": [[125, 200], [135, 200]]})).unwrap(); + s.update(); + (s, fill, middle, left) +} + +fn id(reply: Value) -> u64 { + reply["layer"].as_u64().unwrap() +} + +fn click(s: &mut Session, [x, y]: [f32; 2]) -> Option { + execute(s, "layer.pickAt", &json!({"x": x, "y": y})).ok().map(id) +} + +/// The layers `layer.layersAt` lists at a spot, top first, each with the channels it changes there +fn layers_at(s: &mut Session, [x, y]: [f32; 2]) -> Vec<(u64, Vec)> { + let reply = execute(s, "layer.layersAt", &json!({"x": x, "y": y})).unwrap(); + let channels = |row: &Value| row["channels"].as_array().unwrap().iter().map(|channel| channel.as_str().unwrap().to_owned()).collect(); + reply["layers"].as_array().unwrap().iter().map(|row| (id(row.clone()), channels(row))).collect() +} + +#[test] +fn a_spot_lists_the_layers_laying_something_there_top_first_and_a_pick_selects_the_one_asked_for() { + let (mut s, fill, middle, left) = stack(); + execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "roughness", "opacity": 0.0})).unwrap(); + + let listed = layers_at(&mut s, MIDDLE); + let order: Vec = listed.iter().map(|(layer, _)| *layer).collect(); + assert_eq!(order, [middle, fill], "the layer painted elsewhere is left out; the top one comes first"); + assert!( + !listed[0].1.contains(&"roughness".to_owned()) && listed[1].1.contains(&"roughness".to_owned()), + "a channel at zero opacity is not among the ones the layer changes there" + ); + + assert_eq!(click(&mut s, MIDDLE), Some(middle), "a plain pick selects the top layer"); + assert_eq!(click(&mut s, MIDDLE), Some(middle), "the same spot again keeps the top layer"); + let picked = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": fill})).map(id).ok(); + assert_eq!(picked, Some(fill), "a listed layer is selected when asked for"); + assert_eq!(s.selected_layer_id().map(|layer| layer.0), Some(fill)); + assert!( + execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": left})).is_err(), + "a layer not laying anything down there is refused" + ); + assert_eq!(click(&mut s, LEFT), Some(left), "another spot picks its own top layer"); +} + +#[test] +fn hidden_layers_and_channels_out_of_view_lay_nothing_down() { + let (mut s, fill, middle, _) = stack(); + execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "baseColor", "opacity": 0.0})).unwrap(); + execute(&mut s, "viewport.view", &json!({"mode": "baseColor"})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(fill), "in the base colour view the layer at zero base colour opacity shows nothing"); + + execute(&mut s, "viewport.view", &json!({"mode": "material"})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(middle), "the material view counts its other channels"); + + execute(&mut s, "layer.visible", &json!({"layer": middle, "visible": false})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(fill), "a hidden layer is skipped"); +} + +#[test] +fn a_pick_opens_the_collapsed_folders_holding_the_picked_layer() { + let (mut s, _, middle, _) = stack(); + execute(&mut s, "layer.group", &json!({"layer": middle})).unwrap(); + let inner = s.selected_layer_id().unwrap(); + execute(&mut s, "layer.group", &json!({"layer": inner.0})).unwrap(); + let outer = s.selected_layer_id().unwrap(); + for folder in [inner, outer] { + if let Some(LayerKind::Group { collapsed, .. }) = s.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) { + *collapsed = true; + } + } + + assert_eq!(click(&mut s, MIDDLE), Some(middle)); + + let open = |folder| matches!(s.doc.project.layers[&folder].kind, LayerKind::Group { collapsed: false, .. }); + assert!(open(inner) && open(outer), "both folders holding the picked layer are open"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index a1cf0a97..3aaf5cc2 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -42,6 +42,7 @@ mod gradient_map; mod high_poly_missed; mod instances; mod layer_multi_select; +mod layer_pick; mod mask_clone_smudge; mod mask_export; mod mask_fill_source; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3204a6e6..9a503041 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -271,7 +271,7 @@ const SELECTED_LAYER_TINT: f32 = 0.3; const EYE_CHIP_INSET: f32 = 1.0; const EYE_CHIP_ROUNDING: f32 = 4.0; /// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. -const THUMBNAIL_ROUNDING: f32 = 2.0; +pub(crate) const THUMBNAIL_ROUNDING: f32 = 2.0; const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; const HIDDEN_STRIKE_WIDTH: f32 = 1.5; const DROP_LINE_WIDTH: f32 = 2.0; @@ -455,6 +455,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let row_height = layer_row_height(preferred_size); let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name)); + if app.layer_panel.reveal == Some(layer.id) { + app.layer_panel.reveal = None; + row.scroll_to_me(None); + } // Background, folder lines, the selected rows' accent edge and the colour tag let painter = ui.painter().clone(); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index ee29ac48..7b318972 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -642,6 +642,7 @@ pub fn fixed_gestures_grid(ui: &mut egui::Ui) { pub fn fixed_gestures() -> Vec<(String, String)> { let stencil = crate::viewport::STENCIL_KEY.name(); let clone = crate::viewport::CLONE_SOURCE_KEY.name(); + let pick = crate::viewport::PICK_LAYER_KEY.name(); let keyed = |template: &str| trf(template, &[("key", &stencil)]); vec![ (tr("Alt + LMB drag").into(), tr("Orbit").into()), @@ -663,6 +664,7 @@ pub fn fixed_gestures() -> Vec<(String, String)> { (keyed("{key} + RMB drag"), tr("Projection: scale the stencil").into()), (keyed("{key} + MMB drag"), tr("Projection: move the stencil").into()), (trf("{key} + LMB", &[("key", &clone)]), tr("Clone: pick the point to copy from").into()), + (trf("{key} + LMB", &[("key", &pick)]), tr("Select the layer under the cursor; several there: pick one from a list").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()), (tr("Click the first point (Path tool)").into(), tr("Path: close it (needs 3 points)").into()), @@ -696,6 +698,7 @@ mod tests { 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!("{v} + LMB"), "Clone")); + assert!(has(&format!("{} + LMB", crate::viewport::PICK_LAYER_KEY.name()), "Select the layer")); for (gesture, what) in [ ("Shift + LMB", "straight line"), ("Shift + RMB drag", "environment light"), diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index d5390546..b3efe33b 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -7,6 +7,7 @@ use std::time::Duration; use egui::{Context, TextureHandle, TextureId, TextureOptions}; use texturecraft_engine::Session; use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::LayerId; use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; use crate::TextureCraftApp; @@ -44,18 +45,28 @@ pub struct LayerPanel { pictures_begun: bool, /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. pub(crate) folded: HashSet<(u64, bool)>, + /// The selected layer the panel last drew, and the one whose row scrolls into view because the selection moved to it (a pick on the mesh, a command) + shown_selection: Option, + pub(crate) reveal: Option, } /// How soon to look again for pictures still rendering (milliseconds) const POLL_INTERVAL_MS: u64 = 40; impl LayerPanel { - /// Start drawing the panel for this frame. + /// Start drawing the panel for this frame pub(crate) fn begin(&mut self, session: &Session, now: f64) { self.begin_pictures(session, now); + // A newly selected layer scrolls into view once + let selected = session.selected_layer(); + if selected != self.shown_selection { + self.shown_selection = selected; + self.reveal = selected; + } + // Deleted layer IDs must not accumulate in panel state - self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer))); + self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&LayerId(*layer))); } /// Advance the picture frame once, whether the panel or a picture outside it asks first diff --git a/crates/ui-egui/src/layer_pick_list.rs b/crates/ui-egui/src/layer_pick_list.rs new file mode 100644 index 00000000..39558758 --- /dev/null +++ b/crates/ui-egui/src/layer_pick_list.rs @@ -0,0 +1,209 @@ +//! The layers under the pointer while R is held over the 3D view: a label names the top one live, and a click lists every layer there to pick from + +use egui::{Color32, Key, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; +use serde_json::json; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::session::ViewMode; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::Mode; +use crate::theme::Tokens; + +/// The list's row height, thumbnail side and the room around a row's contents (points) +const ROW_HEIGHT: f32 = 36.0; +const THUMBNAIL_SIZE: f32 = 28.0; +const ROW_PADDING: f32 = 6.0; + +/// The narrowest the list gets, so short names still give a comfortable click target (points) +const MIN_LIST_WIDTH: f32 = 160.0; + +/// How far the list sits right of and below the click, clear of the pointer (points) +const LIST_OFFSET: f32 = 8.0; + +/// Gap the list keeps from the view's edges +const VIEW_MARGIN: f32 = 4.0; + +/// Room between the list's frame and its rows (points) +const LIST_MARGIN: i8 = 2; + +/// Text sizes of a row's name and of the channels line under it +const NAME_FONT_SIZE: f32 = 12.0; +const CHANNELS_FONT_SIZE: f32 = 11.0; + +/// Width of the accent edge around the focused row (points) +const FOCUS_EDGE_WIDTH: f32 = 1.0; + +/// The list of layers laying something down where R + click landed +#[derive(Clone, Debug, PartialEq)] +pub struct LayerPickList { + /// Where the click landed on screen, and in viewport pixels for `layer.pickAt` + at: Pos2, + point: Vec2, + /// The view the list stays inside + bounds: Rect, + /// The layers there, top first, each with the channels it changes there + rows: Vec<(LayerId, Vec)>, + /// The list's first frame: its top row takes the keyboard focus + opening: bool, + /// Closed by a press outside it: until every button is up, that press neither paints nor reopens it + closing: bool, +} + +/// The cached label for the texel under the pointer: (texture set, texel, document revision, view) and its text +type HoverLabel = ((usize, (u32, u32), u64, ViewMode), String); + +/// R + click at `at` (`point` in viewport pixels) in the view `bounds`: one layer there is selected straight away, several open the list +pub(crate) fn click(app: &mut TextureCraftApp, at: Pos2, point: Vec2, bounds: Rect) { + let viewport = app.session.viewport; + match app.session.layers_under(point, viewport) { + Ok((_, rows)) if rows.len() > 1 => app.layer_pick_list = Some(LayerPickList { at, point, bounds, rows, opening: true, closing: false }), + _ => { + app.run("layer.pickAt", json!({"x": point.x, "y": point.y, "viewport": [viewport.x, viewport.y]})); + } + } +} + +/// Whether the list takes the views' clicks: open, or closing until the press that closed it ends +pub(crate) fn blocks_view_input(app: &TextureCraftApp) -> bool { + app.layer_pick_list.is_some() +} + +/// What the label at the pointer says over viewport pixel `point`: the top layer there and how many more, None off the mesh; recomputed only when the texel, document or view changes +pub(crate) fn hover_label(app: &TextureCraftApp, ui: &Ui, point: Vec2) -> Option { + let session = &app.session; + let (ts, texel) = session.texel_under(point, session.viewport)?; + let key = (ts, texel, session.revision, session.view); + let id = egui::Id::unique("layer_pick_hover_label"); + if let Some((cached, label)) = ui.data(|data| data.get_temp::(id)) + && cached == key + { + return Some(label); + } + + let layers = session.layers_at_texel(ts, texel); + let name = |id: &LayerId| session.doc.project.layers.get(id).map(|layer| layer.name.clone()).unwrap_or_default(); + let label = match layers.as_slice() { + [] => tr("No layer here").to_owned(), + [(top, _)] => name(top), + [(top, _), more @ ..] => trf("{name} +{n} more", &[("name", &name(top)), ("n", &more.len())]), + }; + ui.data_mut(|data| data.insert_temp::(id, (key, label.clone()))); + Some(label) +} + +/// The list's area, whose rect egui remembers between frames +fn area_id() -> egui::Id { + egui::Id::unique("layer_pick_list") +} + +/// Draws the open list; a row click selects its layer, Esc or a press outside closes it +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let (any_down, pressed_at, escape) = + ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()), input.key_pressed(Key::Escape))); + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + match &mut app.layer_pick_list { + Some(_) if app.ui.mode != Mode::Painting || escape => app.layer_pick_list = None, + Some(list) if list.closing => { + if !any_down { + app.layer_pick_list = None; + } + } + Some(list) if pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))) => list.closing = true, + _ => {} + } + + let Some(list) = app.layer_pick_list.clone().filter(|list| !list.closing) else { return }; + let tokens = Tokens::get(ctx); + let mut picked = None; + let width = list_width(app, ctx, &list.rows); + + // Right of and below the click; past the view's right edge it opens left of the click, so it never covers the spot + let bounds = list.bounds.shrink(VIEW_MARGIN); + let frame_width = width + 2.0 * f32::from(LIST_MARGIN); + let left = if list.at.x + LIST_OFFSET + frame_width > bounds.right() { list.at.x - LIST_OFFSET - frame_width } else { list.at.x + LIST_OFFSET }; + let at = pos2(left, list.at.y + LIST_OFFSET); + egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds).show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::same(LIST_MARGIN)).show(ui, |ui| { + // A deep stack scrolls inside the view + egui::ScrollArea::vertical().max_height(bounds.height() - 2.0 * f32::from(LIST_MARGIN)).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + // Up and Down move the keyboard focus along the rows (egui's arrow navigation), Enter picks the focused one + for (index, (layer, channels)) in list.rows.iter().enumerate() { + let response = row(app, ui, *layer, channels, width); + if list.opening && index == 0 { + response.request_focus(); + } + if response.clicked() { + picked = Some(*layer); + } + } + }); + }); + }); + + if let Some(list) = &mut app.layer_pick_list { + list.opening = false; + } + if let Some(layer) = picked { + let viewport = app.session.viewport; + app.run("layer.pickAt", json!({"x": list.point.x, "y": list.point.y, "viewport": [viewport.x, viewport.y], "layer": layer.0})); + app.layer_pick_list = None; + } +} + +/// The rows' width: the widest name or channels line beside the thumbnail +fn list_width(app: &TextureCraftApp, ctx: &egui::Context, rows: &[(LayerId, Vec)]) -> f32 { + let text_width = |text: String, font: egui::FontId| ctx.fonts_mut(|fonts| fonts.layout_no_wrap(text, font, Color32::WHITE).size().x); + let widest = rows + .iter() + .map(|(layer, channels)| { + let name = text_width(layer_name(app, *layer), crate::theme::semibold(NAME_FONT_SIZE)); + name.max(text_width(channels_line(channels), egui::FontId::proportional(CHANNELS_FONT_SIZE))) + }) + .fold(0.0, f32::max); + (THUMBNAIL_SIZE + widest + ROW_PADDING * 3.0).max(MIN_LIST_WIDTH) +} + +/// One row: the layer's content thumbnail, its name and the channels it changes at the spot +fn row(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, channels: &[Channel], width: f32) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let name = layer_name(app, layer); + let channels = channels_line(channels); + let (rect, _) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); + let response = ui.interact(rect, egui::Id::unique("layer_pick_row").with(layer.0), Sense::click()); + let selected = app.session.selected_layer() == Some(layer); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &name)); + + // The pointed or focused row takes the selected layer's tint; focus adds an accent edge + let painter = ui.painter(); + if response.hovered() || response.has_focus() { + painter.rect_filled(rect, tokens.radius, crate::dock::selected_layer_fill(&tokens)); + } + if response.has_focus() { + painter.rect_stroke(rect, tokens.radius, Stroke::new(FOCUS_EDGE_WIDTH, tokens.accent), egui::StrokeKind::Inside); + } + + let thumbnail = Rect::from_min_size(pos2(rect.left() + ROW_PADDING, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.rect_filled(thumbnail, crate::dock::THUMBNAIL_ROUNDING, tokens.field); + let target = ThumbTarget::Content { layer, channel: app.ui.layer_channel }; + if let Some(texture) = app.layer_panel.texture_outside(ui.ctx(), &app.session, target) { + painter.image(texture, thumbnail, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + + let text_left = thumbnail.right() + ROW_PADDING; + painter.text(pos2(text_left, rect.center().y), egui::Align2::LEFT_BOTTOM, name, crate::theme::semibold(NAME_FONT_SIZE), tokens.text_strong); + painter.text(pos2(text_left, rect.center().y), egui::Align2::LEFT_TOP, channels, egui::FontId::proportional(CHANNELS_FONT_SIZE), tokens.text_dim); + response +} + +fn layer_name(app: &TextureCraftApp, layer: LayerId) -> String { + app.session.doc.project.layers.get(&layer).map(|layer| layer.name.clone()).unwrap_or_default() +} + +/// The channels a layer changes at the spot, by their names +fn channels_line(channels: &[Channel]) -> String { + channels.iter().map(|channel| tr(channel.label())).collect::>().join(", ") +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9bc2866a..a73eb546 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -57,6 +57,7 @@ mod inactive_set_hint; mod instance_properties; pub mod keymap; pub mod layer_panel; +pub mod layer_pick_list; mod layer_toolbar; mod layout_dialog; mod levels_display; @@ -291,6 +292,8 @@ pub struct TextureCraftApp { pub moving_on_model: Option, /// The Properties popup a right click in a view opens. pub properties_popup: Option, + /// The layers under an R + click in the 3D view to pick one from + pub layer_pick_list: Option, properties_scroll: property_sheet::PropertiesScroll, /// The color selection the next click in the 3D or 2D view picks an ID color for pub picking_id_color: Option, @@ -422,6 +425,7 @@ impl TextureCraftApp { last_paint_uv: None, moving_on_model: None, properties_popup: None, + layer_pick_list: None, properties_scroll: property_sheet::PropertiesScroll::default(), picking_id_color: None, picking_symmetry_plane: false, diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3c5a3d7e..3914782c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -27,6 +27,8 @@ use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; 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; +/// Hold this key with any tool and click the mesh to select the layer laying something down there +pub const PICK_LAYER_KEY: egui::Key = egui::Key::R; pub const VIEW_3D: u64 = 1; pub const VIEW_2D: u64 = 2; @@ -146,6 +148,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } crate::properties_popup::show(app, ui.ctx()); + crate::layer_pick_list::show(app, ui.ctx()); if mode == crate::state::Mode::Rendering { crate::render_mode::show(app, ui, full); @@ -864,6 +867,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } + // Layer pick: R + click lists the layers laying something down there (one is selected straight away), whatever the tool + let r_held = layer_pick_key(app, ui); + if r_held + && !alt + && app.layer_pick_list.is_none() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() + { + crate::layer_pick_list::click(app, pointer, local(pointer), rect); + } + // Depth of field focus pick: a click focuses there instead of painting let focus_pick = focus_picking(ui.ctx()); if focus_pick { @@ -881,11 +895,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // A dismissing click cannot paint or place a decal through the rail popup let rail_popup = crate::rail_popup::blocks_paint_input(app, ui.ctx()); - crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held || r_held); // A press that closes an open colour picker only closes it: it neither paints nor moves a projection let picker = crate::color_picker::blocks_view_press(ui.ctx()); - let popup = app.properties_popup.is_some() || rail_popup || picker; + let popup = app.properties_popup.is_some() || crate::layer_pick_list::blocks_view_input(app) || rail_popup || picker; // A pending ID color pick or eyedropper takes the next click instead of the brush let picking = app.picking_id_color.is_some() || app.picking_color.is_some(); @@ -916,8 +930,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Only a press on a projection handle moves the selected fill - let gizmo_free = - !adjusting && !alt && !holding && !s_held && !v_held && !focus_pick && !popup && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()); + let gizmo_free = !adjusting + && !alt + && !holding + && !s_held + && !v_held + && !r_held + && !focus_pick + && !popup + && !picking + && touch.is_none() + && !DecalDrop::blocks_input(ui.ctx()); let gizmo = ShownGizmo::of(app, rect); let began_on_handle = handle_press(ui.ctx(), |at| gizmo.as_ref().is_some_and(|gizmo| gizmo.on_handle(rect, at))); let frame_drag = gizmo_free && began_on_handle && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref()); @@ -934,6 +957,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let plane_pick = !popup && !s_held && !v_held + && !r_held && !focus_pick && !picking && touch.is_none() @@ -945,6 +969,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !adjusting && !s_held && !v_held + && !r_held && !focus_pick && !popup && !picking @@ -965,6 +990,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !adjusting && !s_held && !v_held + && !r_held && !focus_pick && !picking && touch.is_none() @@ -1038,6 +1064,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin add_callback(app, ui, rect, frame, sync); polygon_fill_box_overlay(ui, rect, fill_box); + // Over the 3D image: the layer under the pointer while the layer pick key is held + if r_held + && app.layer_pick_list.is_none() + && let Some(hover) = response.hover_pos() + && let Some(label) = crate::layer_pick_list::hover_label(app, ui, local(hover)) + { + layer_pick_hint(ui, rect, hover, &label); + } + // Route shelf drops by asset type to a layer, decal, or brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); @@ -1045,6 +1080,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let mut symmetry_cursor = None; if tool_acts(app) && !navigating + && !r_held && response.hovered() && brush_tool(app.session.tool.tool) && (app.session.tool.tool != Tool::Path || adjusting) @@ -1689,6 +1725,37 @@ fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(CLONE_SOURCE_KEY)) && !ui.ctx().egui_wants_keyboard_input() } +/// R held over a view in painting mode, outside a text field: clicks select the layer under the cursor +fn layer_pick_key(app: &TextureCraftApp, ui: &Ui) -> bool { + app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(PICK_LAYER_KEY)) && !ui.ctx().egui_wants_keyboard_input() +} + +/// The pointing hand and a label beside it naming the layer under it while the layer pick key is held +fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let font = egui::TextStyle::Small.resolve(ui.style()); + let galley = painter.layout_no_wrap(label.to_owned(), font, tokens.text); + let at = hover + vec2(LAYER_PICK_HINT_OFFSET, LAYER_PICK_HINT_OFFSET); + let frame = Rect::from_min_size(at, galley.size()).expand(LAYER_PICK_HINT_PADDING); + painter.rect_filled(frame, egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), tokens.panel); + painter.rect_stroke( + frame, + egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), + Stroke::new(LAYER_PICK_HINT_BORDER_WIDTH, tokens.separator), + egui::StrokeKind::Inside, + ); + painter.galley(at, galley, tokens.text); +} + +/// How far the layer pick label sits right of and below the pointer, and the room around its text (points) +const LAYER_PICK_HINT_OFFSET: f32 = 16.0; +const LAYER_PICK_HINT_PADDING: f32 = 4.0; + +/// Width of the layer pick label's border (points) +const LAYER_PICK_HINT_BORDER_WIDTH: f32 = 1.0; + /// Crosshair where the Clone tool reads from. fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { if let Some(center) = project(app, rect, pos) { diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index a0255023..a2dc1368 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -2,7 +2,7 @@ //! fold without touching the document, and the thumbnails arrive from the worker. use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::kittest::{NodeT, Queryable, by}; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{Channel, LayerId}; @@ -517,3 +517,72 @@ fn dragging_a_row_opacity_adds_one_undo_step() { assert!(opacity(&h) < before, "the drag lowers the opacity: {}", opacity(&h)); assert_eq!(h.state().session.history_labels().len(), steps + 1, "every frame of the drag merges into one step"); } + +/// When the selection moves to a layer below the panel's visible rows (a pick on the mesh, a command), its row scrolls into view +#[test] +fn a_newly_selected_layer_out_of_view_scrolls_into_view() { + let (mut h, _) = harness(); + for index in 0..20 { + execute(&mut h.state_mut().session, "layer.add.fill", &json!({"name": format!("Filler {index}")})).unwrap(); + } + h.run_steps(SETTLE_FRAMES); + let bottom = h.state().session.doc.project.texture_sets[h.state().session.ts()].stack[0]; + let name = h.state().session.doc.project.layers[&bottom].name.clone(); + + let before = h.get_by_label(&name).rect(); + assert!(before.top() > properties_top(&h), "the bottom layer starts out of view"); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": bottom.0})).unwrap(); + h.run_steps(SETTLE_FRAMES); + + let after = h.get_by_label(&name).rect(); + assert!(after.bottom() <= properties_top(&h), "its row is inside the panel"); +} + +/// The top of the Properties tab, which sits under the Layers panel +fn properties_top(h: &Harness<'_, TextureCraftApp>) -> f32 { + h.query_all(by().role(egui::Role::Tab).label_contains("Properties")).next().map(|tab| tab.rect().top()).unwrap_or(f32::MAX) +} + +/// Holding R and clicking the model lists the layers laying something down there instead of painting with the current tool; a row of the list, clicked or reached with the arrow keys and Enter, selects its layer +#[test] +fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_without_painting() { + let (mut h, _) = harness(); + let session = &mut h.state_mut().session; + let lower = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Lower fill", "color": "#aa3322"})).unwrap(), "layer")); + let upper = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Upper fill", "color": "#2233aa"})).unwrap(), "layer")); + let empty = LayerId(id(execute(session, "layer.add.paint", &json!({"name": "Empty on top"})).unwrap(), "layer")); + h.run_steps(SETTLE_FRAMES); + let steps = h.state().session.history_labels().len(); + let view = h.state().viewport_rect; + let in_list = |h: &Harness<'_, TextureCraftApp>, name: &str| h.get_all_by_label(name).map(|node| node.rect()).find(|rect| view.contains(rect.center())); + let open_list = |h: &mut Harness<'_, TextureCraftApp>| { + let key = |pressed| egui::Event::Key { key: egui::Key::R, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + h.event(key(true)); + h.hover_at(view.center()); + h.run_steps(1); + click(h, view.center()); + h.event(key(false)); + h.run_steps(SETTLE_FRAMES); + }; + + open_list(&mut h); + + assert!(in_list(&h, "Upper fill").is_some() && in_list(&h, "Lower fill").is_some(), "both fills under the click are listed over the view"); + assert!(in_list(&h, "Empty on top").is_none(), "the empty top layer lays nothing down there"); + assert_eq!(h.state().session.selected_layer(), Some(empty), "opening the list selects nothing yet"); + + h.key_press(egui::Key::ArrowDown); + h.key_press(egui::Key::Enter); + h.run_steps(SETTLE_FRAMES); + + assert_eq!(h.state().session.selected_layer(), Some(lower), "Down from the top row and Enter select the second layer"); + assert!(h.state().layer_pick_list.is_none(), "picking closes the list"); + + open_list(&mut h); + let row = in_list(&h, "Upper fill").unwrap().center(); + click(&mut h, row); + h.run_steps(SETTLE_FRAMES); + + assert_eq!(h.state().session.selected_layer(), Some(upper), "the clicked row's layer is selected"); + assert_eq!(h.state().session.history_labels().len(), steps, "no stroke was painted"); +} diff --git a/docs/features.md b/docs/features.md index 42ea07a6..d4ed5f7b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -45,6 +45,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA one layer alone in the 3D and 2D views, optionally without its mask (Alt+Shift+click, or **Solo layer without its mask**), to judge a material hidden behind a mask. It is only a view: the document, the undo history, saving, exporting and baking never see it. +- **Pick a layer on the model:** hold R over the 3D view, with any tool: a label at the pointer + names the top layer laying something down there (the shown channel in a single-channel view) + and how many more. Click: one layer there is selected; several open a list at the pointer with + each one's thumbnail, name and the channels it changes there, to pick from (Up/Down, Enter, Esc + work too). Closed folders holding the picked layer open and its row scrolls into view. - **Several layers at once:** Shift+click a layer to select the rows from the last clicked one, Ctrl+click (Cmd+click on macOS) to add or take out one layer, Ctrl+A (Cmd+A) with the pointer over the Layers panel to select every shown row (folder rows and the layers of open folders). From f7795c349b8a2799443d320d41b2d15c5d519e43 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:00:59 +0000 Subject: [PATCH 021/128] Layers: a height-combination mask makes the layer's height blend Normal Where the mask shows the layer, its height now replaces the height below instead of mixing with it, in the same undo step as the mask. --- crates/engine/src/add_mask_cmds.rs | 18 ++++++++++++++---- crates/engine/tests/it/add_mask_items.rs | 17 ++++++++++++++++- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/add_mask_cmds.rs b/crates/engine/src/add_mask_cmds.rs index be508092..b904f4b7 100644 --- a/crates/engine/src/add_mask_cmds.rs +++ b/crates/engine/src/add_mask_cmds.rs @@ -1,10 +1,10 @@ //! The layer toolbar's Add mask items that add a mask with an effect in it (a bitmap, a height combination) and Add effect's colour selection use serde_json::Value; -use texturecraft_core::{BlendMode, EffectKind, Sampling, Source}; +use texturecraft_core::{BlendMode, Channel, EffectKind, Sampling, Source}; use texturecraft_paint::alphas; -use crate::commands::{CommandSpec, bad, has_layer, strp}; +use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; use crate::mask_cmds::{color_selection, mask_target, new_compare, push_effect_as, push_own_mask_effect}; use crate::{Result, Session, cmd}; @@ -24,9 +24,9 @@ pub fn specs() -> Vec { "Add mask with height combination", ["Layers", "Mask"], None, - "{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected", + "{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected. The layer's height channel, if it has one, blends Normal", has_layer, - |s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |_| Ok(())) + |s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |s| height_blends_normal(s, p)) ), cmd!( "effect.add.colorSelection", @@ -40,6 +40,16 @@ pub fn specs() -> Vec { ] } +/// Where a height-combination mask shows the layer, the layer's height replaces the height below instead of mixing with it +fn height_blends_normal(s: &mut Session, p: &Value) -> Result<()> { + let id = layer_param(s, "mask.add.heightCombination", p)?; + if let Some(blend) = s.doc.project.layers.get_mut(&id).and_then(|layer| layer.channels.get_mut(&Channel::Height)) { + blend.mode = BlendMode::Normal; + } + + Ok(()) +} + /// A mask fill reading an image resource or a library alpha, in one undo step with the alpha's resource fn add_bitmap(s: &mut Session, p: &Value) -> Result { const CMD: &str = "mask.add.bitmap"; diff --git a/crates/engine/tests/it/add_mask_items.rs b/crates/engine/tests/it/add_mask_items.rs index 1b93b325..94f23c86 100644 --- a/crates/engine/tests/it/add_mask_items.rs +++ b/crates/engine/tests/it/add_mask_items.rs @@ -1,7 +1,7 @@ //! The layer toolbar's Add mask items that add a mask with an effect in it, and Add effect's colour selection: one undo step each, the new effect selected use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source}; +use texturecraft_engine::core::{BlendMode, Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source}; use texturecraft_engine::fill_alpha::resource_name; use texturecraft_engine::geom::primitives; use texturecraft_engine::paint::alphas; @@ -75,6 +75,21 @@ fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_b assert_eq!(s.history_labels().last().map(String::as_str), Some("Add mask with height combination")); } +#[test] +fn a_height_combination_makes_the_layers_height_blend_normal_in_the_same_step() { + let (mut s, layer) = fill(); + execute(&mut s, "layer.blend", &json!({"layer": layer.0, "channel": "height", "enabled": true, "mode": "linearDodge"})).unwrap(); + let height_mode = |s: &Session| s.doc.project.layer(layer).unwrap().channels.get(&Channel::Height).map(|blend| blend.mode); + let before = height_mode(&s); + assert!(before.is_some_and(|mode| mode != BlendMode::Normal), "the height starts out blending another way"); + + execute(&mut s, "mask.add.heightCombination", &json!({"layer": layer.0})).unwrap(); + assert_eq!(height_mode(&s), Some(BlendMode::Normal)); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(height_mode(&s), before, "one undo takes the mask and the blend back"); +} + #[test] fn color_selections_go_in_the_mask_and_are_selected() { let (mut s, layer) = fill(); From 2e9c14ecd4296f5fa92e9a9da068774b699b1ae7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:26:27 +0000 Subject: [PATCH 022/128] Layers: the layers under the cursor reuse the session's projection depth maps --- crates/compose/src/eval/layers_at.rs | 10 ++++++---- crates/compose/src/projector_depth_cache.rs | 5 +++++ crates/engine/src/layer_pick.rs | 2 +- crates/engine/src/session.rs | 2 +- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs index 648dcb4c..4c342707 100644 --- a/crates/compose/src/eval/layers_at.rs +++ b/crates/compose/src/eval/layers_at.rs @@ -8,8 +8,8 @@ use super::{ /// Below this weight a layer leaves the texel unchanged (one 16-bit step) const SMALLEST_WEIGHT: f32 = 1.0 / 65535.0; -/// The paint and fill layers (and instances) that lay something down at texel (x, y) of texture set `inputs.ts` in any of `shown` channels, top first, each with the shown channels it changes there. Hidden layers, layers masked out there (by their own mask or a folder's) and channels at zero opacity count as laying nothing down -pub fn layers_at(inputs: &Inputs, (x, y): (u32, u32), shown: &[Channel]) -> Vec<(LayerId, Vec)> { +/// The paint and fill layers (and instances) that lay something down at texel (x, y) of texture set `inputs.ts` in any of `shown` channels, top first, each with the shown channels it changes there. Hidden layers, layers masked out there (by their own mask or a folder's) and channels at zero opacity count as laying nothing down. Projection depth maps come from `projectors` when it serves `inputs.mesh` +pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32, u32), shown: &[Channel]) -> Vec<(LayerId, Vec)> { let Ok(set) = inputs.project.texture_set(inputs.ts) else { return Vec::new() }; let gbuf = inputs.gbuf; let covered = x < gbuf.width && y < gbuf.height && gbuf.tri.get((y * gbuf.width + x) as usize).is_some_and(|tri| *tri != NO_TRI); @@ -17,8 +17,10 @@ pub fn layers_at(inputs: &Inputs, (x, y): (u32, u32), shown: &[Channel]) -> Vec< return Vec::new(); } - let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + // A cache built for another mesh would hand out its depth maps + let unbound = ProjectorDepthCache::default(); + let projectors = if projectors.serves(inputs.mesh) { projectors } else { &unbound }; + let inputs = &EvaluationInputs::new(inputs, projectors); let channels = evaluation_channels(inputs, set.channel_list()); // Filters and anchors can read texels outside this one's tile: the fields cover what it reads diff --git a/crates/compose/src/projector_depth_cache.rs b/crates/compose/src/projector_depth_cache.rs index 47b56a76..ce289922 100644 --- a/crates/compose/src/projector_depth_cache.rs +++ b/crates/compose/src/projector_depth_cache.rs @@ -24,6 +24,11 @@ impl ProjectorDepthCache { } } + /// Whether its depth maps were built for `mesh` + pub(crate) fn serves(&self, mesh: &Mesh) -> bool { + std::ptr::eq(self.mesh.as_ptr(), mesh) + } + pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option> { // Rasterization is serial so tile workers can wait for a single build let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); diff --git a/crates/engine/src/layer_pick.rs b/crates/engine/src/layer_pick.rs index 9107fb3e..80f84c7e 100644 --- a/crates/engine/src/layer_pick.rs +++ b/crates/engine/src/layer_pick.rs @@ -25,7 +25,7 @@ impl Session { ViewMode::Channel(channel) => vec![channel], _ => self.doc.project.texture_set(ts).map(|set| set.channel_list()).unwrap_or_default(), }; - self.with_inputs(ts, |inputs| Some(texturecraft_compose::layers_at(inputs, texel, &shown))).unwrap_or_default() + self.with_inputs(ts, |inputs| Some(texturecraft_compose::layers_at(inputs, &self.projector_depth_cache, texel, &shown))).unwrap_or_default() } /// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`]) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..bbc0caa2 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -488,7 +488,7 @@ pub struct Session { /// are unchanged, so back-to-back dabs start instantly. pub(crate) depth_cache: Option, /// Projection fill depth maps shared by this session's tile batches. - projector_depth_cache: texturecraft_compose::ProjectorDepthCache, + pub(crate) projector_depth_cache: texturecraft_compose::ProjectorDepthCache, /// The polygon fill box being dragged pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). From 5f51194ab8f195b71b688e6c75e47652f8c3cb50 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:26:27 +0000 Subject: [PATCH 023/128] Layers: a flattened folder's images skip decoding the PNGs just written --- crates/engine/src/layer_ops.rs | 20 ++++++++++++-------- crates/engine/src/resource_cmds.rs | 27 ++++++++++++++++++++++----- crates/formats/src/image_res.rs | 27 ++++++++++++++++++++++++--- crates/formats/src/lib.rs | 2 +- 4 files changed, 59 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 1c0bc970..e11121d3 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use texturecraft_compose::eval::FlatTile; use texturecraft_core::{Channel, ChannelKind, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source}; +use texturecraft_formats::DecodedImage; use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; use crate::commands::{CommandSpec, boolp, has_layer, layer_param}; @@ -250,9 +251,9 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { let flat = s.edit("Flatten folder", |s| { let mut fill = Fill { sampling: Sampling { filtering: Filtering::Nearest, alpha_coverage: true, ..Sampling::default() }, ..Fill::default() }; - for (channel, png) in images { + for (channel, png, image) in images { let file_name = format!("{} flattened {}.png", folder.name, channel.id()); - let name = s.add_image_resource(&file_name, png, texturecraft_formats::MAX_RESOURCE_TEXELS)?; + let name = s.add_decoded_image_resource(&file_name, png, image)?; fill.sources.insert(channel, Source::image(name)); } @@ -282,10 +283,13 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { Ok(json!({ "layer": flat.0 })) } -/// Flattened tiles as one 16-bit RGBA PNG per channel (straight values as a fill reads them, coverage in the alpha), in channel order -fn channel_images(tiles: Vec, size: (u32, u32)) -> Result)>> { +/// One flattened tile of a channel: (tile, value + coverage data) +type ChannelTile = ((u32, u32), Vec); + +/// Flattened tiles as one 16-bit RGBA PNG per channel and its decoded pixels (straight values as a fill reads them, coverage in the alpha), in channel order +fn channel_images(tiles: Vec, size: (u32, u32)) -> Result, DecodedImage)>> { let (width, height) = size; - let mut by_channel: std::collections::BTreeMap)>> = Default::default(); + let mut by_channel: std::collections::BTreeMap> = Default::default(); for (channel, tile, data) in tiles { by_channel.entry(channel).or_default().push((tile, data)); } @@ -322,9 +326,9 @@ fn channel_images(tiles: Vec, size: (u32, u32)) -> Result Arc { Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb)) } +/// Refuse resource files over [`MAX_BYTES`] +fn within_byte_limit(file_name: &str, bytes: &[u8]) -> Result<()> { + if bytes.len() > MAX_BYTES { + return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); + } + + Ok(()) +} + impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { @@ -61,12 +70,21 @@ impl Session { self.add_image_resource_prefixed("", file_name, bytes, max_texels) } + /// [`Self::add_image_resource`] for an image whose decoded pixels the caller already has (bit-identical to decoding `bytes`) + pub(crate) fn add_decoded_image_resource(&mut self, file_name: &str, bytes: Vec, image: texturecraft_formats::DecodedImage) -> Result { + within_byte_limit(file_name, &bytes)?; + Ok(self.insert_image_resource("", file_name, bytes, image)) + } + fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec, max_texels: u64) -> Result { - if bytes.len() > MAX_BYTES { - return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); - } + within_byte_limit(file_name, &bytes)?; let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; + Ok(self.insert_image_resource(prefix, file_name, bytes, image)) + } + + /// Store `bytes` and their decoded `image` under a unique, sanitized name from `file_name` and `prefix`; returns the name + fn insert_image_resource(&mut self, prefix: &str, file_name: &str, bytes: Vec, image: texturecraft_formats::DecodedImage) -> String { let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); let mut base = sanitize_resource_name(leaf); @@ -95,8 +113,7 @@ impl Session { self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); - - Ok(name) + name } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 55754cba..8be2475e 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -173,15 +173,19 @@ pub fn gray16_resource(width: u32, height: u32, values: impl Iterator Result> { +/// A 16-bit RGBA PNG of `samples` (red, green, blue and alpha per pixel, `width × height`, top row first) and its decoded pixels, as reloading it gives them: one channel of a flattened folder +pub fn rgba16_resource(width: u32, height: u32, samples: &[u16]) -> Result<(Vec, DecodedImage)> { let texels = u64::from(width) * u64::from(height); if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE || texels > MAX_RESOURCE_TEXELS { return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_RESOURCE_TEXELS} texels)"))); } let image = Image::from_u16(width, height, ChannelLayout::Rgba, samples).map_err(|error| FormatError::Invalid(error.to_string()))?; - encode_resource_png(&image) + let png = encode_resource_png(&image)?; + + // Divide as the PNG decoder does for RGBA, so reload is bit-identical + let rgba = samples.as_chunks::<4>().0.iter().map(|pixel| pixel.map(|sample| f32::from(sample) / f32::from(u16::MAX))).collect(); + Ok((png, DecodedImage { width, height, rgba, srgb: true })) } fn encode_resource_png(image: &Image) -> Result> { @@ -310,6 +314,23 @@ mod tests { assert!(gray16_resource(2, 1, [0.5].into_iter()).is_err()); } + #[test] + fn generated_rgba16_resource_matches_reload_for_every_sample_value() { + // Every value in each of red, green, blue and alpha, with gray pixels as scalar channels write them + let mixed = (0..=u16::MAX).flat_map(|value| [value, value.wrapping_add(1), value.wrapping_add(2), value.wrapping_mul(3)]); + let gray = (0..=u16::MAX).flat_map(|value| [value, value, value, u16::MAX - value]); + let samples: Vec = mixed.chain(gray).collect(); + + let (png, decoded) = rgba16_resource(512, 256, &samples).unwrap(); + + let reloaded = decode_image(&png).unwrap(); + assert_eq!((decoded.width, decoded.height, decoded.srgb), (reloaded.width, reloaded.height, reloaded.srgb)); + for (index, (cached, saved)) in decoded.rgba.iter().zip(&reloaded.rgba).enumerate() { + assert_eq!(cached, saved, "pixel {index}"); + } + assert!(rgba16_resource(2, 1, &[0; 4]).is_err(), "too few samples for the size"); + } + #[test] fn gray16_stops_after_one_excess_pixel() { let mut pixels_read = 0; diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 2e6fa186..5d693a84 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -45,7 +45,7 @@ pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, 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, rgba16_png}; +pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource, rgba16_resource}; pub use mesh_export::{ GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options, usd_layer_with_textures, usd_texture_bindings, From b41497e8762a47564d436e83cf28ec5f83680d27 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:30:43 +0000 Subject: [PATCH 024/128] Layers: flattening a folder runs the stack below it once per texel --- crates/compose/src/eval.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 09041f47..d901bbda 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2754,6 +2754,7 @@ fn takes_symmetry(proj: &Projection, sampling: Sampling) -> bool { } /// Per-texel context. +#[derive(Clone)] struct Texel<'a, 'b> { inp: &'b Inputs<'a>, x: u32, @@ -2779,6 +2780,7 @@ struct Texel<'a, 'b> { /// What a layer contributes (its mask, its content value and coverage per channel): evaluated /// (`Off`), evaluated and recorded, or replayed from a recording. +#[derive(Clone)] enum Tape<'t> { Off, Record(Vec), @@ -5035,18 +5037,15 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt let mut mask = masked.then(|| vec![0u16; TILE_AREA * 2]); for (x, y, offset) in tile_texels(inputs.gbuf, tx, ty) { - // The texel with the stack below the folder run, so masks and fills that read it or its anchors find them - let texel_over_below = || { - let mut texel = Texel::new(&visible_inputs, x, y, offset, 0.0); - if !below.is_empty() { - texel.anchors_below(&below, (id, 0)); - } - texel - }; + // The texel with the stack below the folder run once, so masks and fills that read it or its anchors find them + let mut over_below = Texel::new(&visible_inputs, x, y, offset, 0.0); + if !below.is_empty() { + over_below.anchors_below(&below, (id, 0)); + } // Laid over an all-0 and an all-1 stack, the layers show their premultiplied value and how much of the stack they hide let over = |background: f32| { - let mut texel = texel_over_below(); + let mut texel = over_below.clone(); let mut stack: Acc = [[background; 3]; NCH]; texel.eval(children, &mut stack); stack @@ -5072,7 +5071,7 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt } if let Some(pixel) = mask.as_mut().and_then(|mask| mask.get_mut(offset * 2..offset * 2 + 2)) { - pixel.copy_from_slice(&[to_u16(texel_over_below().node_mask(node)), u16::MAX]); + pixel.copy_from_slice(&[to_u16(over_below.node_mask(node)), u16::MAX]); } } 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 025/128] 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 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 026/128] 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 d9b1d58d6c0040ceb9ac4c5fe344822de7f64104 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 12:16:22 -0500 Subject: [PATCH 027/128] Report an autosave before releasing its reservation, and fix its notice test A later autosave could start once the reservation was dropped and report first, so an earlier success then cleared its failure. The test now installs the headless runtime the framework needs, counts only the autosave's own notice, and reads it in English. --- crates/ui-egui/src/lib.rs | 3 ++- crates/ui-egui/tests/autosave_notice.rs | 12 ++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3ffaaffe..f2cda0c4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1074,9 +1074,10 @@ impl TextureCraftApp { let result = std::fs::create_dir_all(&dir).map_err(|e| e.to_string()).and_then(|_| reservation.save(&path, &snapshot).map_err(|error| error.to_string())); drop(snapshot); - drop(reservation); + // Report while the reservation still holds off the next autosave, so results arrive in the order of the attempts reporter.report(path, result); + drop(reservation); }); if let Err(e) = spawned { spawn_reporter.report(target, Err(e.to_string())); diff --git a/crates/ui-egui/tests/autosave_notice.rs b/crates/ui-egui/tests/autosave_notice.rs index d5786734..703c13e9 100644 --- a/crates/ui-egui/tests/autosave_notice.rs +++ b/crates/ui-egui/tests/autosave_notice.rs @@ -7,7 +7,8 @@ use egui_kittest::Harness; use texturecraft_ui_egui::TextureCraftApp; fn notices(harness: &Harness<'_, TextureCraftApp>) -> usize { - harness.state().toasts.iter().filter(|toast| toast.text.contains("autosave-notice")).count() + // Other loaders name the broken data folder too: only the autosave's own notice counts + harness.state().toasts.iter().filter(|toast| toast.text.starts_with("Autosave to ") && toast.text.contains("autosave-notice")).count() } /// Run frames until `done`, giving the autosave worker real time to finish. @@ -29,7 +30,14 @@ fn a_failing_autosave_is_announced_once_until_it_works_again() { let session = texturecraft_engine::sample_session(128, 32).unwrap(); // Each frame is longer than the shortest autosave period, so every frame is due - let mut harness = Harness::builder().with_step_dt(61.0).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_step_dt(61.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + // The notice is matched by its English text, whatever the system's language + harness.state_mut().ui.prefs.language = "en".into(); + // One frame applies the language before any autosave reports + harness.step(); harness.state_mut().ui.prefs.autosave_minutes = 1; harness.state_mut().session.modified = true; 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 028/128] 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 029/128] 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 030/128] 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 6d72dbbf940f0cb59501ceb826a8252dfc78bca5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:04:00 +0000 Subject: [PATCH 031/128] Layers: Escape closes the layer list, and a flattened folder keeps its look over the layers below and its hidden state From the first test build: Escape only took the focus off the list's top row, a folder whose layers blend with Multiply, Screen or Overlay over the layers below it flattened into a layer that looked different, and a hidden folder flattened into a visible layer. --- crates/compose/src/eval.rs | 60 ++++++++++++++++++------ crates/engine/src/layer_ops.rs | 3 +- crates/engine/tests/it/flatten_folder.rs | 35 ++++++++++++++ crates/ui-egui/src/menus.rs | 2 + crates/ui-egui/tests/it/layers_panel.rs | 10 +++- 5 files changed, 94 insertions(+), 16 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index d901bbda..93c6b0c2 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1369,6 +1369,17 @@ fn below_plan<'a>( return Vec::new(); } + stack_plan_below(inp, draw, channels, (tile_x, tile_y), fields) +} + +/// Plan the whole stack up to a draw, whatever the draw reads +fn stack_plan_below<'a>( + inp: &EvaluationInputs<'a>, + draw: (LayerId, usize), + channels: &[Channel], + (tile_x, tile_y): (u32, u32), + fields: Option<&'a Fields>, +) -> Vec> { let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; let compare_effects = layer_mask(inp.project, draw.0).into_iter().flat_map(|mask| mask.effects.iter()); let planned = compared_channels(compare_effects, channels.to_vec()); @@ -4988,6 +4999,26 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti Some(out.into_iter().flatten().collect()) } +/// The premultiplied value and coverage (last) of a Normal layer that shows `shown` over `under`, covering at least `coverage`, with straight values inside `range` (Multiply or Overlay hide each component by a different amount, so the coverage grows where a straight value would leave it); None where it shows the stack as it is +fn normal_over(under: &[f32; 3], shown: &[f32; 3], coverage: f32, comps: usize, (low, high): (f32, f32)) -> Option<[f32; 4]> { + let needed = under.iter().zip(shown).take(comps).fold(coverage, |needed, (under, shown)| { + let change = shown - under; + let room = if change > 0.0 { high - under } else { under - low }; + if change.abs() <= f32::EPSILON || room <= 0.0 { needed } else { needed.max(change.abs() / room) } + }); + let coverage = needed.min(1.0); + if coverage <= 0.0 { + return None; + } + + // Over `under`, the layer shows its premultiplied value plus what it leaves of the stack + let mut premultiplied = [0.0, 0.0, 0.0, coverage]; + for ((slot, under), shown) in premultiplied.iter_mut().zip(under).zip(shown).take(comps) { + *slot = shown - (1.0 - coverage) * under; + } + Some(premultiplied) +} + /// One tile of a flattened folder's mask: (tile, mask value + coverage data) pub type FlatMaskTile = ((u32, u32), Vec); @@ -5017,7 +5048,7 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); let Some(node) = nodes.first() else { return (Vec::new(), None) }; let Content::Group(children) = &node.content else { return (Vec::new(), None) }; - let below = below_plan(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields), node.lights); + let below = stack_plan_below(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields)); // One value + coverage buffer per channel the folder plans; signed channels start at their middle let mut buffers: Vec<(Channel, Vec, bool)> = node @@ -5039,29 +5070,30 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt for (x, y, offset) in tile_texels(inputs.gbuf, tx, ty) { // The texel with the stack below the folder run once, so masks and fills that read it or its anchors find them let mut over_below = Texel::new(&visible_inputs, x, y, offset, 0.0); - if !below.is_empty() { - over_below.anchors_below(&below, (id, 0)); - } + over_below.anchors_below(&below, (id, 0)); + let stack_below = over_below.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); - // Laid over an all-0 and an all-1 stack, the layers show their premultiplied value and how much of the stack they hide - let over = |background: f32| { + // The layers over an all-0 and an all-1 stack show how much of the stack they hide, and over the real stack what they show there + let over = |mut stack: Acc| { let mut texel = over_below.clone(); - let mut stack: Acc = [[background; 3]; NCH]; texel.eval(children, &mut stack); stack }; - let (low, high) = (over(0.0), over(1.0)); + let (low, high, shown) = (over([[0.0; 3]; NCH]), over([[1.0; 3]; NCH]), over(stack_below)); for (planned, (channel, buffer, laid_down)) in node.chans.iter().zip(buffers.iter_mut()) { - let (Some(premultiplied), Some(shown)) = (low.get(planned.ch), high.get(planned.ch)) else { continue }; - let comps = planned.comps.min(3); - let hidden = premultiplied.iter().zip(shown).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; - let coverage = hidden.clamp(0.0, 1.0); - if coverage <= 0.0 { + let (Some(low), Some(high), Some(shown), Some(under)) = + (low.get(planned.ch), high.get(planned.ch), shown.get(planned.ch), stack_below.get(planned.ch)) + else { continue; - } + }; + let comps = planned.comps.min(3); + let hidden = low.iter().zip(high).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; + let range = if channel.kind() == ChannelKind::Signed { (-1.0, 1.0) } else { (0.0, 1.0) }; + let Some(premultiplied) = normal_over(under, shown, hidden.clamp(0.0, 1.0), comps, range) else { continue }; *laid_down = true; let Some(pixel) = buffer.get_mut(offset * (planned.comps + 1)..(offset + 1) * (planned.comps + 1)) else { continue }; + let coverage = premultiplied[3]; for (slot, value) in pixel.iter_mut().zip(premultiplied.iter().take(planned.comps)) { *slot = if channel.kind() == ChannelKind::Signed { to_u16_signed(*value) } else { to_u16(*value) }; } diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index e11121d3..4f1cf4d1 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -236,7 +236,7 @@ fn flatten(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": id.0 })) } -/// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept +/// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; @@ -260,6 +260,7 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { // Only the channels the folder lays down, at its opacity (a folder mixes its result in by opacity alone, whatever its blend mode): a channel without an image would cover the stack with its default let channels: Vec = fill.sources.keys().copied().collect(); let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); + layer.visible = folder.visible; for (channel, blend) in &mut layer.channels { blend.opacity = folder.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); } diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 741f7e80..77fefc27 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -97,3 +97,38 @@ fn a_flattened_folder_bakes_a_mask_that_reads_the_layers_below() { assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); } + +/// Inside a folder, layers blending with Multiply, Screen or Overlay over the layers below the folder hide each part of the stack by a different amount: the flattened layer still shows what they did +#[test] +fn a_flattened_folder_looks_the_same_when_its_layers_blend_with_the_layers_below_it() { + for mode in ["multiply", "screen", "overlay"] { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.8], "roughness": 0.4})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.9, 0.3, 0.1], "roughness": 0.7})).unwrap()); + for channel in ["baseColor", "roughness"] { + execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": channel, "mode": mode})).unwrap(); + } + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{mode}: {}", largest_difference(&composite(&mut s), &before)); + } +} + +/// A hidden folder shows nothing, so the layer it flattens into is hidden too +#[test] +fn a_hidden_folder_flattens_into_a_hidden_layer() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap(); + let before = composite(&mut s); + + let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + + assert!(!s.doc.project.layer(LayerId(flat)).unwrap().visible, "the new layer is hidden like the folder"); + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "the image does not change"); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..be585658 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -528,6 +528,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } 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.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + app.layer_pick_list = None; } else if escape_is_free && 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) { diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index a2dc1368..38c865c4 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -543,7 +543,7 @@ fn properties_top(h: &Harness<'_, TextureCraftApp>) -> f32 { h.query_all(by().role(egui::Role::Tab).label_contains("Properties")).next().map(|tab| tab.rect().top()).unwrap_or(f32::MAX) } -/// Holding R and clicking the model lists the layers laying something down there instead of painting with the current tool; a row of the list, clicked or reached with the arrow keys and Enter, selects its layer +/// Holding R and clicking the model lists the layers laying something down there instead of painting with the current tool; a row of the list, clicked or reached with the arrow keys and Enter, selects its layer, and Escape closes it #[test] fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_without_painting() { let (mut h, _) = harness(); @@ -585,4 +585,12 @@ fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_withou assert_eq!(h.state().session.selected_layer(), Some(upper), "the clicked row's layer is selected"); assert_eq!(h.state().session.history_labels().len(), steps, "no stroke was painted"); + + // The first Escape moves egui's focus off the top row: the list must close on it all the same + open_list(&mut h); + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list"); + assert_eq!(h.state().session.selected_layer(), Some(upper), "and selects nothing"); } 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 032/128] 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 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 033/128] 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 034/128] 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 035/128] 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 036/128] 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 037/128] 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 038/128] 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 039/128] 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 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 040/128] 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 041/128] 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 042/128] 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 043/128] 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 044/128] 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 045/128] 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 046/128] 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 047/128] 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 048/128] 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 049/128] 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 050/128] 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 051/128] 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 052/128] 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 053/128] 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 054/128] 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 055/128] 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 056/128] 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 057/128] 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 058/128] 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 059/128] 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 060/128] 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 061/128] 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 062/128] 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 063/128] 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 064/128] 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 065/128] 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 066/128] 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 067/128] 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 068/128] 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 069/128] 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 070/128] 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 071/128] 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 f3d14a3ab413629f33c4f1ae428f1ab15814bda4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:01:24 +0000 Subject: [PATCH 072/128] Layers: a row's eye and blend menu act on its layer when no layer is selected --- crates/engine/src/commands.rs | 25 +++++++++++++++++++- crates/engine/tests/it/layer_multi_select.rs | 18 +++++++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index e34e9327..9d32be37 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -188,6 +188,29 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } +/// [`check_enabled`] for a run with `params`: a command that takes `layer` is checked as if the +/// layer it names were the selected one, so a row's own controls work with no layer selected +/// (after an undo, say). +fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { + let refused = match check_enabled(spec, s) { + Ok(()) => return Ok(()), + Err(why) => why, + }; + let named = u64p(params, "layer").map(texturecraft_core::LayerId).filter(|_| spec.params.contains("layer?")); + let Some((id, ts)) = named.and_then(|id| s.doc.project.locate(id).map(|(ts, _, _)| (id, ts))) else { return Err(refused) }; + if ts != s.ts() { + return Err(refused); + } + + let selected = s.selected.insert(ts, id); + let named_refused = check_enabled(spec, s); + match selected { + Some(old) => s.selected.insert(ts, old), + None => s.selected.remove(&ts), + }; + named_refused +} + pub fn find(id: &str) -> Option<&'static CommandSpec> { command_specs().iter().find(|c| c.id == id) } @@ -196,7 +219,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> { /// `merge: true` its edits continue the previous undo step of the same label (drags). pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result { let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; + check_enabled_for(spec, s, params).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false)); let result = (spec.run)(s, params); s.merge_edits = outer; diff --git a/crates/engine/tests/it/layer_multi_select.rs b/crates/engine/tests/it/layer_multi_select.rs index 14c375d8..f6dfe110 100644 --- a/crates/engine/tests/it/layer_multi_select.rs +++ b/crates/engine/tests/it/layer_multi_select.rs @@ -3,7 +3,7 @@ //! act on every selected layer in one undo step. use serde_json::{Value, json}; -use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::core::{BlendMode, Channel, LayerId, LayerKind}; use texturecraft_engine::geom::primitives; use texturecraft_engine::layer_selection::stack_rows; use texturecraft_engine::{Session, execute}; @@ -523,3 +523,19 @@ fn moving_layers_into_a_folder_in_another_set_preserves_the_document() { assert_eq!(s.history_labels(), history); } } + +#[test] +fn a_rows_controls_act_on_its_layer_with_no_layer_selected() { + let mut s = session(); + let [a, ..] = four(&mut s); + // An undo can leave no layer selected; the row's eye and blend menu still name their layer + s.selected.clear(); + + execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap(); + execute(&mut s, "layer.blend", &json!({"layer": a.0, "channel": "baseColor", "mode": "Multiply"})).unwrap(); + let layer = s.doc.project.layer(a).unwrap(); + assert!(!layer.visible, "the eye hid its layer"); + assert_eq!(layer.blend(Channel::BaseColor).map(|b| b.mode), Some(BlendMode::Multiply), "the blend menu changed its layer"); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); + assert!(execute(&mut s, "layer.visible", &Value::Null).is_err(), "with no layer named, nothing is selected to act on"); +} 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 073/128] 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 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 074/128] 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 075/128] 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 0ec4775ef63ad89f6eccfc84947c2391eceefbf1 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:30:56 -0500 Subject: [PATCH 076/128] fix(path-cache): charge each snapshot for the tile buffers it alone keeps alive evict charged snapshot k for path k-1's tiles only, but snapshot k holds every pixel after k paths and shares tile handles with the others. After an older snapshot was evicted, a newer one could retain a whole older generation (full fill, one-tile stroke, full fill, one-tile stroke) and the 256 MiB cap was exceeded. Walk newest to oldest and charge only handles not already held by the live pixels, the edited snapshot or a kept newer snapshot. Also drop the debug_assert from non-test code. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/painting.rs | 2 - crates/engine/src/path_tool.rs | 103 +++++++++++++++++++++++++++------ 2 files changed, 84 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 3c90af84..dd0013b2 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -141,8 +141,6 @@ impl Session { let ts = self.ts(); let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; - // PathCache reuses a path's tiles only if painting one tile reads no other. - debug_assert!(!(self.painting_paths && pickup.is_some()), "path repaints never pick up"); if pickup.is_some() { // Clone and smudge read the composite: bring it up to date first. self.update(); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 6629c944..b73dd661 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -16,7 +16,7 @@ use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackgrou use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; -use texturecraft_texel::{TILE_AREA, TileImage}; +use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; use crate::session::{StackTarget, Tool}; @@ -83,18 +83,48 @@ pub(crate) struct PathCache { tiles: Vec>, } +/// The identities of the tile buffers `snap` holds, added to `seen`; returns the bytes of those +/// not already there. +fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { + let mut bytes = 0; + for img in snap.values() { + for ty in 0..img.tiles_y() { + for tx in 0..img.tiles_x() { + if let Some(t) = img.tile_handle(tx, ty) + && seen.insert(Arc::as_ptr(t) as usize) + { + bytes += t.len() * 2; + } + } + } + } + bytes +} + /// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent /// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live -/// repaint starts there). Snapshot k holds at most path k-1's tiles in each image; the first -/// (empty) and the last (the live pixels) cost nothing. -fn evict(snaps: &mut [Option], tiles: &[BTreeSet<(u32, u32)>], budget: usize, edited: usize) { +/// repaint starts there). Tiles are shared between snapshots and with the live pixels (the last +/// snapshot) and snapshot k holds every tile as it was after k paths, so each snapshot, newest +/// first, is charged for the tile buffers no live pixels, kept newer snapshot or `edited` already +/// hold: what freeing it would release at most. The first (empty) and the last cost nothing. +fn evict(snaps: &mut [Option], budget: usize, edited: usize) { + let mut seen = BTreeSet::new(); + for k in [snaps.len().saturating_sub(1), edited] { + if let Some(Some(snap)) = snaps.get(k) { + charge(snap, &mut seen); + } + } let mut bytes = 0; for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { - if let Some(snap) = &snaps[k] { - bytes += tiles[k - 1].len() * snap.values().map(|i| TILE_AREA * i.comps() * 2).sum::(); - if bytes > budget { - snaps[k] = None; - } + let Some(Some(snap)) = snaps.get(k) else { continue }; + // Count into a copy: an evicted snapshot's tiles are not retained by it any more. + let mut with = seen.clone(); + let cost = charge(snap, &mut with); + if bytes + cost > budget { + snaps[k] = None; + } else { + bytes += cost; + seen = with; } } } @@ -479,7 +509,7 @@ impl Session { copy_tiles(&mut state, after, &c.tiles[o]); tiles.push(c.tiles[o].clone()); snaps.push(Some(state.clone())); - evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + evict(&mut snaps, CACHE_BYTES, prefix); out.push(Value::Null); continue; } @@ -495,7 +525,7 @@ impl Session { state = self.take_snap(eid); tiles.push(std::mem::take(&mut self.path_tiles)); snaps.push(Some(state.clone())); - evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + evict(&mut snaps, CACHE_BYTES, prefix); } self.put_snap(eid, &state); self.painting_paths = false; @@ -683,10 +713,15 @@ mod tests { fn snapshots_stay_within_the_budget() { let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, usize::MAX, 0); + super::evict(&mut c.snaps, usize::MAX, 0); assert_eq!(c.snaps.iter().flatten().count(), 4); - super::evict(&mut c.snaps, &c.tiles, 0, 0); - assert!(c.snaps[0].is_some() && c.snaps[3].is_some() && c.snaps[1..3].iter().all(Option::is_none), "only the free ones stay"); + // The paths are on different tiles, so keeping every snapshot costs nothing beyond the live + // pixels: even a zero budget keeps them. + super::evict(&mut c.snaps, 0, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels are free"); + // Drop them by hand to test the repaint from the bottom. + c.snaps[1] = None; + c.snaps[2] = None; // Appending still paints the new path alone. let shape = s.paths(eid).unwrap()[0].clone(); if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { @@ -696,13 +731,43 @@ mod tests { assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); // Editing above evicted snapshots repaints from the bottom and matches a full repaint. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); - // That edit kept the snapshot below path 3 within a zero budget: its next frame starts there. + // That edit kept the snapshot below path 3 within a zero budget: its next frame starts + // there, and the snapshots above it that cost nothing keep their paths unrepainted. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, 0, 2); - assert!(c.snaps[2].is_some() && c.snaps[1].is_none()); - assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, true], "path 4 lost its snapshot too"); + super::evict(&mut c.snaps, 0, 2); + assert!(c.snaps[2].is_some()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); + } + + /// `prev` with the tiles in `at` replaced by new handles (what painting a path does). + fn painted(prev: &super::Snap, at: &[(u32, u32)]) -> super::Snap { + let mut next = prev.clone(); + for img in next.values_mut() { + for &(x, y) in at { + img.set_tile(x, y, Some(std::sync::Arc::new(vec![1u16; texturecraft_texel::TILE_AREA * 4]))); + } + } + next + } + + #[test] + fn the_budget_counts_the_tiles_an_old_snapshot_keeps_alive() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + // A full-texture fill, a one-tile stroke, another full fill, another one-tile stroke. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &[(0, 0)]); + let s3 = painted(&s2, &all); + let s4 = painted(&s3, &[(0, 0)]); + let mut snaps = vec![Some(empty), Some(s1), Some(s2), Some(s3), Some(s4)]; + // Snapshot 3 is the edited one. Snapshot 2 alone holds 15 tiles of the first fill that + // neither the live image nor snapshot 3 has: that is over a budget of 8 tiles. + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + super::evict(&mut snaps, 8 * tile_bytes, 3); + assert!(snaps[3].is_some(), "the edited snapshot stays"); + assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); } #[test] From 14f02e5fe79d333f9d115ee3dc0c90c0ba633206 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:17:44 -0500 Subject: [PATCH 077/128] test(path-cache): a snapshot is charged only for tiles no kept snapshot shares Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index b73dd661..bd4c9715 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -770,6 +770,33 @@ mod tests { assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); } + #[test] + fn a_snapshot_is_charged_only_for_what_no_kept_snapshot_shares() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + // Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with + // the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &all); + let s3 = painted(&s2, &[(0, 0)]); + let fresh = || vec![Some(empty.clone()), Some(s1.clone()), Some(s2.clone()), Some(s3.clone())]; + let kept = |snaps: &[Option]| snaps.iter().map(Option::is_some).collect::>(); + let mut snaps = fresh(); + super::evict(&mut snaps, usize::MAX, 0); + assert_eq!(kept(&snaps), [true; 4]); + let mut snaps = fresh(); + super::evict(&mut snaps, tile_bytes, 0); + assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile, snapshot 1 sixteen"); + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 0); + assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget"); + // Keeping snapshot 1 (edited) makes snapshot 2 free of the tiles they share, not of its own. + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 1); + assert_eq!(kept(&snaps), [true, true, false, true]); + } + #[test] fn the_quick_mask_does_not_clip_paths() { let (mut s, eid) = with_paths(&[0.2, 0.8]); 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 078/128] 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 079/128] 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 080/128] 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 081/128] 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 082/128] 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 ccf2ad6b52ad466f5bd192c3b61dd0668652d990 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sat, 28 Nov 2026 08:46:07 +0000 Subject: [PATCH 083/128] 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 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 084/128] 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 085/128] 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 086/128] 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 087/128] 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 088/128] 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 089/128] 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 178e2d192834403e674de1455d2189a1b60d87d3 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:27:35 +0000 Subject: [PATCH 090/128] Show History steps as flat rows with the current step outlined The History panel lists every step as a full-width row: the current step is outlined in the accent, the pointer's row gets a soft band, undone steps stay dim and clickable. The Undo and Redo buttons under the list are gone; undo and redo stay in the Edit menu and on Ctrl+Z / Ctrl+Y. Part of #890. --- crates/ui-egui/src/docking.rs | 11 ++- crates/ui-egui/src/windows.rs | 92 ++++++++++++++---------- crates/ui-egui/tests/it/history_panel.rs | 60 +++++++++++++--- crates/ui-egui/tests/it/rail.rs | 18 ++--- 4 files changed, 124 insertions(+), 57 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index f6a7928f..d9e02747 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -583,6 +583,9 @@ struct Panels<'a> { /// Room between a panel's edges and its contents const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); +/// Room around a panel of full-width list rows: none at the sides +const LIST_PANEL_MARGIN: Margin = Margin::symmetric(0, 4); + /// Narrowest Properties panel and so its dock column: the 300 point design width plus the solid scroll bar; narrower, the 3D projection settings' X, Y, Z fields (the widest row) overlap pub const PROPERTIES_MIN_WIDTH: f32 = 310.0; @@ -613,8 +616,12 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { return; } - // Properties draws full-width bands and tabs, so it keeps its own margins - let margin = if panel == Panel::Properties { Margin::ZERO } else { PANEL_BODY_MARGIN }; + // Properties draws full-width bands and tabs and History full-width rows, so they draw their own side margins + let margin = match panel { + Panel::Properties => Margin::ZERO, + Panel::History => LIST_PANEL_MARGIN, + _ => PANEL_BODY_MARGIN, + }; 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), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index b8eff6e8..c19c89c5 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1,9 +1,6 @@ //! Floating windows and the dockable History panel -#[cfg(any(target_arch = "wasm32", test))] -use egui::vec2; -use egui::{RichText, Ui}; -use egui_phosphor::regular as ic; +use egui::{RichText, Ui, vec2}; use serde_json::json; use crate::TextureCraftApp; @@ -249,45 +246,40 @@ pub(crate) fn dialog_scroll_margin(ui: &egui::Ui) -> egui::Margin { margin } -/// The History panel body (a dock tab) +/// The height of one History row +const HISTORY_ROW_HEIGHT: f32 = 21.0; +/// Where a History row's name starts, from the panel's left edge +const HISTORY_NAME_LEFT: f32 = 12.0; +const HISTORY_NAME_SIZE: f32 = 12.0; +/// The current step's outline sits inside the row: a little air at the left, less before the scrollbar +const HISTORY_MARK_INSET_LEFT: f32 = 4.0; +const HISTORY_MARK_INSET_RIGHT: f32 = 3.0; + +/// The History panel body (a dock tab): one row per step, the current one outlined pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); + let done_count = done.len() as i64; + let rows = std::iter::once((tr("Project opened").to_owned(), tokens.text_dim)) + .chain(done.iter().map(|label| (tr_history(label), tokens.text))) + .chain(undone.iter().map(|label| (trf("{action} (undone)", &[("action", &tr_history(label))]), tokens.text_dim))); // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative let mut jump = 0i64; - - // Bottom up: the Undo and Redo row keeps its place under a list that fills the rest of the panel - ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - ui.horizontal(|ui| { - if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { - app.run("edit.undo", json!({})); + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + for (row, (name, color)) in rows.enumerate() { + // Each row is the state after that many steps + let steps = done_count - row as i64; + if history_row(ui, &tokens, &name, color, steps == 0).on_hover_text(tr("Return to this step")).clicked() { + // Point history is consumed before the document rows shown here + jump = if steps >= 0 { + app.session.history_undo_steps(steps as usize) as i64 + } else { + -(app.session.history_redo_steps((-steps) as usize) as i64) + }; } - if ui.add_enabled(app.session.can_redo(), egui::Button::new(format!("{} {}", ic::ARROW_CLOCKWISE, tr("Redo")))).clicked() { - app.run("edit.redo", json!({})); - } - }); - - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - let done_count = done.len() as i64; - let rows = std::iter::once(RichText::new(tr("Project opened")).color(tokens.text_dim)) - .chain(done.iter().map(|label| RichText::new(tr_history(label)))) - .chain(undone.iter().map(|label| RichText::new(trf("{action} (undone)", &[("action", &tr_history(label))])).color(tokens.text_dim))); - for (row, text) in rows.enumerate() { - // Each row is the state after that many steps - let steps = done_count - row as i64; - if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - // Point history is consumed before the document rows shown here - jump = if steps >= 0 { - app.session.history_undo_steps(steps as usize) as i64 - } else { - -(app.session.history_redo_steps((-steps) as usize) as i64) - }; - } - } - }); - }); + } }); if jump > 0 { @@ -297,6 +289,34 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// One History row across the panel: a band under the pointer, the current step outlined +fn history_row(ui: &mut Ui, tokens: &Tokens, name: &str, color: egui::Color32, current: bool) -> egui::Response { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), HISTORY_ROW_HEIGHT), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, current, name)); + if !ui.is_rect_visible(rect) { + return response; + } + + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + if current { + let mark = egui::Rect::from_min_max(rect.min + vec2(HISTORY_MARK_INSET_LEFT, 0.0), rect.max - vec2(HISTORY_MARK_INSET_RIGHT, 0.0)); + painter.rect(mark, 0.0, tokens.field, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, tokens.row); + } + + // A name too long for the row ends in an ellipsis, as far from the outline's right side as it starts from its left + let room = rect.width() - HISTORY_NAME_LEFT - HISTORY_MARK_INSET_RIGHT - (HISTORY_NAME_LEFT - HISTORY_MARK_INSET_LEFT); + let mut job = egui::text::LayoutJob::simple_singleline(name.to_owned(), egui::FontId::proportional(HISTORY_NAME_SIZE), color); + job.wrap = egui::text::TextWrapping::truncate_at_width(room.max(0.0)); + let shown = painter.layout_job(job); + painter.galley(egui::pos2(rect.left() + HISTORY_NAME_LEFT, rect.center().y - shown.size().y / 2.0), shown, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(&painter, rect, tokens.text_strong); + } + response +} + /// Browser File › Export Mesh: pick the download format #[cfg(target_arch = "wasm32")] fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index 889b3df7..3c138c28 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -1,7 +1,9 @@ //! A click on a step of the History panel goes back or forward to it. +use egui::accesskit::Toggled; +use egui::{Key, Modifiers}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::{Session, execute}; @@ -19,6 +21,22 @@ fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { harness } +/// Undo or redo one step from the keyboard, as the Edit menu's shortcuts do +fn press(harness: &mut Harness<'_, TextureCraftApp>, key: Key) { + harness.key_press_modifiers(Modifiers::COMMAND, key); + harness.run_steps(3); +} + +/// The rows the panel shows as the current step: name and top edge +fn current_rows(harness: &Harness<'_, TextureCraftApp>) -> Vec<(String, f32)> { + harness + .get_all_by_role(egui::accesskit::Role::Button) + .filter(|node| node.accesskit_node().toggled() == Some(Toggled::True)) + .filter_map(|node| Some((node.accesskit_node().label()?, node.rect().top()))) + .filter(|(name, _)| name.contains("Rename layer") || name == "Project opened") + .collect() +} + /// Three document rows provide an intermediate target that detects both short and excessive jumps fn renamed_session() -> Session { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -49,6 +67,7 @@ fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() { session.path_checkpoint(); let mut harness = history_harness(session); + // The list runs oldest first, so the first "Rename layer" row is the oldest step harness.get_all_by_label("Rename layer").next().unwrap().click(); harness.run_steps(3); @@ -60,7 +79,7 @@ fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() { } } -/// A row jump traverses point history, while the Undo and Redo buttons still take one point step +/// A row jump traverses point history, while Ctrl+Z and Ctrl+Y still take one point step #[test] fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() { let mut session = renamed_session(); @@ -77,12 +96,10 @@ fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() let done = session.history_labels().len(); let mut harness = history_harness(session); - harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); - harness.run_steps(3); + press(&mut harness, Key::Z); assert_eq!(harness.state().session.tool.path.points, moved); assert_eq!(harness.state().session.history_labels().len(), done); - harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); - harness.run_steps(3); + press(&mut harness, Key::Y); assert_eq!(harness.state().session.tool.path.points, original); assert_eq!(harness.state().session.history_labels().len(), done); @@ -91,6 +108,7 @@ fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() assert_eq!(harness.state().session.tool.path.points, original); assert_eq!(harness.state().session.history_labels().len(), done); + // The list runs oldest first, so the first "Rename layer" row is the oldest step harness.get_all_by_label("Rename layer").next().unwrap().click(); harness.run_steps(3); @@ -126,15 +144,14 @@ fn history_redo_jump_accounts_for_point_steps_without_changing_single_steps() { assert_eq!(session.redo_labels().len(), 3); let mut harness = history_harness(session); - harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); - harness.run_steps(3); + press(&mut harness, Key::Y); assert_eq!(harness.state().session.tool.path.points.len(), 2); assert_eq!(harness.state().session.history_labels().len(), done - 3); - harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); - harness.run_steps(3); + press(&mut harness, Key::Z); assert_eq!(harness.state().session.tool.path.points, original); assert_eq!(harness.state().session.history_labels().len(), done - 3); + // The last undone row is the newest step, so clicking it redoes up to the end harness.get_all_by_label("Rename layer (undone)").last().unwrap().click(); harness.run_steps(3); @@ -193,3 +210,26 @@ fn clicking_a_history_step_returns_to_it() { assert_eq!(name(&h), "Step C"); assert!(!h.state().session.can_redo()); } + +/// The panel has no Undo and Redo buttons; exactly one row reads as the current step, it moves with Ctrl+Z, and undone rows stay clickable +#[test] +fn only_the_current_step_is_marked_selected() { + let mut harness = history_harness(renamed_session()); + + // Undo and redo live in the Edit menu and on their shortcuts, not in a button row under the list + assert!(harness.query_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).is_none()); + assert!(harness.query_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).is_none()); + + let before = current_rows(&harness); + assert_eq!(before.len(), 1); + assert_eq!(before[0].0, "Rename layer"); + + press(&mut harness, Key::Z); + let after = current_rows(&harness); + assert_eq!(after.len(), 1); + assert!(after[0].1 < before[0].1, "the outline moves up a row"); + + harness.get_by_label("Rename layer (undone)").click(); + harness.run_steps(3); + assert!(harness.state().session.redo_labels().is_empty()); +} diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index 7dbd97f2..260b1c93 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -256,19 +256,19 @@ fn display_settings_remain_reachable_in_a_short_window() { assert!(harness.ctx.content_rect().contains_rect(setting), "the last setting must be reachable: {setting:?}"); } +/// The History panel has no Undo/Redo buttons (the Edit menu and Ctrl+Z/Ctrl+Y undo); its current step stays reachable #[test] -fn history_actions_remain_reachable_in_a_short_window() { +fn the_current_history_step_remains_reachable_in_a_short_window() { let mut harness = app_of_size(egui::vec2(1600.0, 400.0)); click_rail(&mut harness, "History"); - for label in ["Undo", "Redo"] { - let button = harness - .get_all_by_role(Role::Button) - .find(|button| button.accesskit_node().label().is_some_and(|text| text.ends_with(label))) - .expect("the History action") - .rect(); - assert!(harness.ctx.content_rect().contains_rect(button), "{label} must be reachable: {button:?}"); - } + let name = harness.state().session.history_labels().last().cloned().unwrap_or_else(|| "Project opened".to_owned()); + let current = harness + .get_all_by_role_and_label(Role::Button, &name) + .find(|row| row.accesskit_node().toggled() == Some(egui::accesskit::Toggled::True)) + .expect("the current History step") + .rect(); + assert!(harness.ctx.content_rect().contains_rect(current), "the current step must be reachable: {current:?}"); } #[test] 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 091/128] 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 589eb4c76432db8b350ec4c8e8c56f0f956833e8 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:29:26 -0500 Subject: [PATCH 092/128] test(path-cache): a filled path above an edit keeps its tiles from the cache Covers the footprint recorded by commit_fill; emptying it left every other test green. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index bd4c9715..785c779d 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -683,6 +683,15 @@ mod tests { assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints"); } + #[test] + fn a_filled_path_above_an_edit_keeps_its_tiles() { + // The stroke at row 0.2 is edited; the closed, filled path above it lies in other tiles. + let (mut s, eid) = with_paths(&[0.2]); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.7], [0.5, 0.7], [0.5, 0.9], [0.1, 0.9]], "closed": true, "fill": true, "commit": true})) + .unwrap(); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false], "the fill above comes from the cache, with its pixels"); + } + #[test] fn removing_a_path_keeps_the_paths_above() { let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); 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 093/128] 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 7f9ee780a22502ebf7851d04cc69834091a84f76 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:31:38 +0000 Subject: [PATCH 094/128] Keep the current History step in view, with the scrollbar always shown The History list opens at the newest step and scrolls the current step into view when the history changes (a new step, undo, redo or a jump); a tool, camera or selection change leaves a list the user scrolled where it is. Rows are laid out only while visible. The list's scrollbar is a solid 8 px bar in the theme's colours, shown even when the list fits. Part of #890. --- crates/ui-egui/src/log_panel.rs | 53 +++++++++ crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/windows.rs | 37 +++++-- crates/ui-egui/tests/it/history_panel.rs | 132 ++++++++++++++++++++++- 4 files changed, 216 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/log_panel.rs b/crates/ui-egui/src/log_panel.rs index b6df68af..d9376397 100644 --- a/crates/ui-egui/src/log_panel.rs +++ b/crates/ui-egui/src/log_panel.rs @@ -11,6 +11,59 @@ mod log_channel; pub use log_channel::LogChannel; +/// The width of the History and Log lists' scrollbars +const LIST_SCROLLBAR_WIDTH: f32 = 8.0; +const LIST_SCROLLBAR_RADIUS: u8 = 3; +/// The air between a list's scrollbar and the list's edge, and between the rows and the scrollbar +const LIST_SCROLLBAR_OUTER_MARGIN: f32 = 2.0; +const LIST_SCROLLBAR_INNER_MARGIN: f32 = 1.0; + +/// A newly focused row of a list scrolls in with a neighbour on each side: only shown rows are laid out, so Tab needs the next one there +pub(crate) fn reveal_focused_row(ui: &Ui, response: &egui::Response, row: egui::Rect) { + if response.gained_focus() { + // The shown width, so the list never moves sideways + let around = egui::Rect::from_x_y_ranges(ui.clip_rect().x_range(), row.y_range()).expand2(egui::vec2(0.0, row.height())); + ui.scroll_to_rect_animation(around, None, egui::style::ScrollAnimation::none()); + } +} + +/// Show `total_rows` rows of `row_height` in `area` under a solid, always shown, themed scrollbar +pub(crate) fn panel_rows( + ui: &mut Ui, + area: egui::ScrollArea, + row_height: f32, + total_rows: usize, + add_rows: impl FnOnce(&mut Ui, std::ops::Range) -> R, +) -> egui::scroll_area::ScrollAreaOutput { + let tokens = Tokens::get(ui.ctx()); + let row_visuals = ui.visuals().clone(); + ui.scope(|ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.spacing_mut().scroll = egui::style::ScrollStyle { + bar_width: LIST_SCROLLBAR_WIDTH, + bar_outer_margin: LIST_SCROLLBAR_OUTER_MARGIN, + bar_inner_margin: LIST_SCROLLBAR_INNER_MARGIN, + ..egui::style::ScrollStyle::solid() + }; + + let visuals = ui.visuals_mut(); + visuals.extreme_bg_color = tokens.field; + // The thumb stands 3:1 or more off its track in every theme, brighter under the pointer + visuals.widgets.inactive.bg_fill = tokens.text_dim; + visuals.widgets.hovered.bg_fill = tokens.text; + visuals.widgets.active.bg_fill = tokens.text; + for widget in [&mut visuals.widgets.inactive, &mut visuals.widgets.hovered, &mut visuals.widgets.active] { + widget.corner_radius = egui::CornerRadius::same(LIST_SCROLLBAR_RADIUS); + } + + area.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show_rows(ui, row_height, total_rows, |ui, rows| { + *ui.visuals_mut() = row_visuals; + add_rows(ui, rows) + }) + }) + .inner +} + /// The entries a tab lists, as indices into the session log fn listed(app: &TextureCraftApp, channel: LogChannel) -> Vec { app.session.log.iter().enumerate().filter(|(_, entry)| channel_of(entry) == channel).map(|(index, _)| index).collect() diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 1ea83ab4..b40bf69c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -744,6 +744,9 @@ pub struct UiState { /// Identity of the log that owns the selected rows. #[serde(skip)] pub log_id: u64, + /// The History panel's last shown container and steps (done, undone, newest name): a change scrolls to the current step + #[serde(skip)] + pub history_shown: Option<(egui::Id, usize, usize, Option)>, } pub(crate) const MAX_RECENT_PROJECTS: u16 = 100; @@ -912,6 +915,7 @@ impl Default for UiState { log_selection: Default::default(), log_anchor: None, log_id: 0, + history_shown: None, } } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index c19c89c5..dbf29eeb 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -260,15 +260,28 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); let done_count = done.len() as i64; - let rows = std::iter::once((tr("Project opened").to_owned(), tokens.text_dim)) - .chain(done.iter().map(|label| (tr_history(label), tokens.text))) - .chain(undone.iter().map(|label| (trf("{action} (undone)", &[("action", &tr_history(label))]), tokens.text_dim))); + let total_rows = 1 + done.len() + undone.len(); + + // Only new steps or a new container (with its own scroll) bring the current one into view; a tool change keeps the user's scroll + let shown = Some((ui.make_persistent_id("history"), done.len(), undone.len(), done.last().cloned())); + let follow = app.ui.history_shown != shown; + app.ui.history_shown = shown; // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative let mut jump = 0i64; - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 0.0; - for (row, (name, color)) in rows.enumerate() { + + let area = egui::ScrollArea::vertical().id_salt("history").auto_shrink([false, false]); + crate::log_panel::panel_rows(ui, area, HISTORY_ROW_HEIGHT, total_rows, |ui, range| { + if follow { + let top = ui.max_rect().top() + (done.len() as f32 - range.start as f32) * HISTORY_ROW_HEIGHT; + let current = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=top + HISTORY_ROW_HEIGHT); + ui.scroll_to_rect_animation(current, None, egui::style::ScrollAnimation::none()); + } + + // Only the shown rows are translated + for row in range { + let Some((name, color)) = history_row_name(&done, &undone, row, &tokens) else { continue }; + // Each row is the state after that many steps let steps = done_count - row as i64; if history_row(ui, &tokens, &name, color, steps == 0).on_hover_text(tr("Return to this step")).clicked() { @@ -289,10 +302,22 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// The name and colour of History row `row`: the opened project, then the done steps, then the undone ones +fn history_row_name(done: &[String], undone: &[String], row: usize, tokens: &Tokens) -> Option<(String, egui::Color32)> { + let Some(step) = row.checked_sub(1) else { return Some((tr("Project opened").to_owned(), tokens.text_dim)) }; + if let Some(label) = done.get(step) { + return Some((tr_history(label), tokens.text)); + } + + let label = undone.get(step - done.len())?; + Some((trf("{action} (undone)", &[("action", &tr_history(label))]), tokens.text_dim)) +} + /// One History row across the panel: a band under the pointer, the current step outlined fn history_row(ui: &mut Ui, tokens: &Tokens, name: &str, color: egui::Color32, current: bool) -> egui::Response { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), HISTORY_ROW_HEIGHT), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, current, name)); + crate::log_panel::reveal_focused_row(ui, &response, rect); if !ui.is_rect_visible(rect) { return response; } diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index 3c138c28..f9a82b9a 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -1,7 +1,7 @@ -//! A click on a step of the History panel goes back or forward to it. +//! The History panel: a click on a step goes back or forward to it, the current step is marked and kept in view use egui::accesskit::Toggled; -use egui::{Key, Modifiers}; +use egui::{Event, Key, Modifiers, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; @@ -27,13 +27,16 @@ fn press(harness: &mut Harness<'_, TextureCraftApp>, key: Key) { harness.run_steps(3); } -/// The rows the panel shows as the current step: name and top edge +/// The History rows shown as the current step: name and top edge fn current_rows(harness: &Harness<'_, TextureCraftApp>) -> Vec<(String, f32)> { + let session = &harness.state().session; + let undone = session.redo_labels().into_iter().map(|label| format!("{label} (undone)")); + let names: Vec = session.history_labels().into_iter().chain(undone).chain(["Project opened".to_owned()]).collect(); harness .get_all_by_role(egui::accesskit::Role::Button) .filter(|node| node.accesskit_node().toggled() == Some(Toggled::True)) .filter_map(|node| Some((node.accesskit_node().label()?, node.rect().top()))) - .filter(|(name, _)| name.contains("Rename layer") || name == "Project opened") + .filter(|(name, _)| names.contains(name)) .collect() } @@ -233,3 +236,124 @@ fn only_the_current_step_is_marked_selected() { harness.run_steps(3); assert!(harness.state().session.redo_labels().is_empty()); } + +/// Enough steps that the History cannot show them all at once +const STEPS_PAST_THE_PANEL: usize = 100; + +/// A session `steps` renames long, so its History list is taller than the panel +fn long_session(steps: usize) -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for step in 0..steps { + execute(&mut session, "layer.rename", &json!({"name": format!("Step {step}")})).unwrap(); + } + session +} + +/// Whether the current step's row named `name` is on screen +fn current_shown(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool { + let screen = harness.ctx.content_rect(); + current_rows(harness).iter().any(|(row, top)| row == name && screen.y_range().contains(*top)) +} + +/// Scroll the History list back to its first rows with the mouse wheel +fn scroll_to_top(harness: &mut Harness<'_, TextureCraftApp>) { + // Exactly one row is the current step; its top finds the row under the wheel + let (_, top) = current_rows(harness)[0]; + let over = harness.get_all_by_label("Rename layer").find(|node| node.rect().top() == top).unwrap().rect().center(); + harness.hover_at(over); + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 100_000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + harness.run_steps(12); +} + +/// A History list longer than the panel opens at its newest step, not at "Project opened" +#[test] +fn a_long_history_shows_the_newest_step() { + let harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + + assert!(current_shown(&harness, "Rename layer")); + assert!(harness.query_by_label("Project opened").is_none_or(|row| !harness.ctx.content_rect().y_range().contains(row.rect().top()))); +} + +/// A list the user scrolled up stays there when a tool changes but the history doesn't +#[test] +fn scrolling_up_is_not_pulled_back() { + let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + scroll_to_top(&mut harness); + assert!(!current_shown(&harness, "Rename layer")); + + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "path"})).unwrap(); + harness.run_steps(4); + + assert!(!current_shown(&harness, "Rename layer")); +} + +/// Once the history is full, a new step keeps the step count; its new name still brings it into view +#[test] +fn the_newest_step_shows_past_the_history_cap() { + let steps = texturecraft_engine::session::MAX_HISTORY + 60; + let mut harness = history_harness(long_session(steps)); + let capped = harness.state().session.history_labels().len(); + assert!(capped < steps, "the history is full"); + scroll_to_top(&mut harness); + assert!(!current_shown(&harness, "Rename layer")); + + execute(&mut harness.state_mut().session, "layer.add.paint", &json!({})).unwrap(); + harness.run_steps(4); + + let newest = harness.state().session.history_labels().last().cloned().unwrap(); + assert_eq!(harness.state().session.history_labels().len(), capped); + assert!(current_shown(&harness, &newest)); +} + +/// A History list that moves to another container (rail popup to floating window) still shows the current step +#[test] +fn an_undocked_history_shows_the_newest_step() { + let session = long_session(STEPS_PAST_THE_PANEL); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + let icon = harness.get_all_by_role(egui::accesskit::Role::Button).find(|button| { + let label = button.accesskit_node().label().unwrap_or_default(); + label == "History" || label.starts_with("History (") + }); + icon.expect("the History icon on the rail").click(); + harness.run_steps(4); + assert!(current_shown(&harness, "Rename layer")); + + harness.get_by_label("Undock").click(); + harness.run_steps(4); + + assert!(current_shown(&harness, "Rename layer")); +} + +/// Shift+Tab walks from the current step up to the first row, past the rows on screen when the panel opened +#[test] +fn the_keyboard_reaches_rows_scrolled_out_of_view() { + let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + let (_, top) = current_rows(&harness)[0]; + harness.get_all_by_label("Rename layer").find(|node| node.rect().top() == top).unwrap().focus(); + harness.run_steps(2); + + let first_row_focused = |harness: &Harness<'_, TextureCraftApp>| { + let screen = harness.ctx.content_rect(); + harness.query_by_label("Project opened").is_some_and(|row| row.accesskit_node().is_focused() && screen.y_range().contains(row.rect().top())) + }; + // One press per step is enough to reach the first row + for _ in 0..harness.state().session.history_labels().len() + 1 { + if first_row_focused(&harness) { + break; + } + harness.key_press_modifiers(Modifiers::SHIFT, Key::Tab); + harness.run_steps(2); + } + + assert!(first_row_focused(&harness)); +} From 6754228e64c21d38bb0796ced21d1e9a624bc2e9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:33:39 +0000 Subject: [PATCH 095/128] Split the Log panel's width between its General and Assets tabs The two channel tabs fill the panel's width in equal halves, in small bold capitals: the open tab on the list's field colour with no line under it, the other on the row band with dim text. Each tab is a focusable control with the tab role and its selected state. The Log's lines keep a small inset from the panel's edges. Part of #890. --- crates/ui-egui/src/docking.rs | 6 +-- crates/ui-egui/src/log_panel.rs | 63 +++++++++++++++++++----- crates/ui-egui/tests/it/log_panel_680.rs | 10 ++++ 3 files changed, 63 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index d9e02747..66bab1aa 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -584,7 +584,7 @@ struct Panels<'a> { const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); /// Room around a panel of full-width list rows: none at the sides -const LIST_PANEL_MARGIN: Margin = Margin::symmetric(0, 4); +pub(crate) const LIST_PANEL_MARGIN: Margin = Margin::symmetric(0, 4); /// Narrowest Properties panel and so its dock column: the 300 point design width plus the solid scroll bar; narrower, the 3D projection settings' X, Y, Z fields (the widest row) overlap pub const PROPERTIES_MIN_WIDTH: f32 = 310.0; @@ -616,10 +616,10 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { return; } - // Properties draws full-width bands and tabs and History full-width rows, so they draw their own side margins + // Properties draws full-width bands and tabs and History and Log full-width rows, so they draw their own side margins let margin = match panel { Panel::Properties => Margin::ZERO, - Panel::History => LIST_PANEL_MARGIN, + Panel::History | Panel::Log => LIST_PANEL_MARGIN, _ => PANEL_BODY_MARGIN, }; egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel { diff --git a/crates/ui-egui/src/log_panel.rs b/crates/ui-egui/src/log_panel.rs index d9376397..86e8d489 100644 --- a/crates/ui-egui/src/log_panel.rs +++ b/crates/ui-egui/src/log_panel.rs @@ -1,6 +1,6 @@ //! The Log panel: the session's messages under a General and an Assets tab, one per channel -use egui::{Color32, RichText, Ui}; +use egui::{Align2, Color32, Rect, RichText, Sense, Stroke, StrokeKind, Ui, vec2}; use texturecraft_engine::log::{LogEntry, LogLevel}; use crate::TextureCraftApp; @@ -64,6 +64,46 @@ pub(crate) fn panel_rows( .inner } +/// The tab strip's and the list's inset from the panel's edges +const PANEL_INSET: f32 = 6.0; +const TAB_HEIGHT: f32 = 24.0; +const TAB_NAME_SIZE: f32 = 11.0; + +/// The General and Assets tabs, splitting the panel's width; the open one joins the list under it +fn channel_tabs(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) { + // The panel's own margin is above the tabs; the strip adds the rest of the inset + ui.add_space(PANEL_INSET - f32::from(crate::docking::LIST_PANEL_MARGIN.top)); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), TAB_HEIGHT), Sense::hover()); + let strip = strip.shrink2(vec2(PANEL_INSET, 0.0)); + let tab_width = strip.width() / LogChannel::ALL.len() as f32; + let outline = Stroke::new(1.0, tokens.field_border); + for (slot, channel) in LogChannel::ALL.into_iter().enumerate() { + let rect = Rect::from_min_size(strip.min + vec2(slot as f32 * tab_width, 0.0), vec2(tab_width, TAB_HEIGHT)); + let response = ui.interact(rect, ui.make_persistent_id(("log-tab", channel.name())), Sense::click()); + let open = app.ui.log_channel == channel; + let name = tr(channel.name()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, open, name)); + + let painter = ui.painter(); + painter.rect(rect, 0.0, if open { tokens.field } else { tokens.row }, outline, StrokeKind::Inside); + if open { + let joint = Rect::from_min_max(rect.left_bottom() + vec2(1.0, -1.0), rect.right_bottom() + vec2(-1.0, 0.0)); + painter.rect_filled(joint, 0.0, tokens.field); + } + let color = if open || response.hovered() { tokens.text } else { tokens.text_dim }; + painter.text(rect.center(), Align2::CENTER_CENTER, name, crate::theme::semibold(TAB_NAME_SIZE), color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + + if response.clicked() { + app.ui.log_channel = channel; + app.ui.log_selection.clear(); + app.ui.log_anchor = None; + } + } +} + /// The entries a tab lists, as indices into the session log fn listed(app: &TextureCraftApp, channel: LogChannel) -> Vec { app.session.log.iter().enumerate().filter(|(_, entry)| channel_of(entry) == channel).map(|(index, _)| index).collect() @@ -183,16 +223,8 @@ pub(crate) fn takes_copy(app: &TextureCraftApp, ctx: &egui::Context) -> bool { /// The Log panel body (a dock tab or rail popup) pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - for channel in LogChannel::ALL { - if ui.selectable_label(app.ui.log_channel == channel, tr(channel.name())).clicked() { - app.ui.log_channel = channel; - app.ui.log_selection.clear(); - app.ui.log_anchor = None; - } - } - }); - ui.separator(); + let tk = Tokens::get(ui.ctx()); + channel_tabs(app, ui, &tk); // A new session has a new log: indices chosen in the old one point at other lines if app.ui.log_id != app.session.log_id { @@ -201,11 +233,16 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { app.ui.log_anchor = None; } + let inset = PANEL_INSET as i8; + egui::Frame::new().inner_margin(egui::Margin::symmetric(inset, 0)).show(ui, |ui| entries(app, ui, &tk)); +} + +/// The shown tab's lines, under the Assets tab's filter button +fn entries(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { if shown_assets_filter(app) { crate::unavailable::greyed(ui, |ui| ui.add(egui::Button::new(egui_phosphor::regular::WARNING).selected(false))); } - let tk = Tokens::get(ui.ctx()); let shown = app.ui.log_channel; let rows = listed(app, shown); @@ -225,7 +262,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt(("log", shown.name())).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { for index in rows.iter().copied() { let Some(entry) = app.session.log.get(index) else { continue }; - let text = RichText::new(entry.line()).color(level_color(&tk, entry.level)); + let text = RichText::new(entry.line()).color(level_color(tk, entry.level)); let band = ui.painter().add(egui::Shape::Noop); let response = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); if app.ui.log_selection.contains(&index) { diff --git a/crates/ui-egui/tests/it/log_panel_680.rs b/crates/ui-egui/tests/it/log_panel_680.rs index eba3e084..62fbe967 100644 --- a/crates/ui-egui/tests/it/log_panel_680.rs +++ b/crates/ui-egui/tests/it/log_panel_680.rs @@ -145,6 +145,16 @@ fn assets_has_a_greyed_filter_button_with_the_hint() { assert!(h.query_by_label(texturecraft_ui_egui::unavailable::NOT_AVAILABLE).is_some()); } +/// The two tabs share the panel's width equally, side by side +#[test] +fn the_log_tabs_split_the_panel_width() { + let h = app(); + let (general, assets) = (h.get_by_label("GENERAL").rect(), h.get_by_label("ASSETS").rect()); + + assert!((general.width() - assets.width()).abs() < 1.0, "{general:?} {assets:?}"); + assert!((general.right() - assets.left()).abs() < 1.0, "{general:?} {assets:?}"); +} + #[test] fn renderer_settings_stays_open_when_opened_in_rendering_mode() { let mut h = app(); From 5e132ba903c9db99957a6ee5b294d5fc6c39f718 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:35:46 +0000 Subject: [PATCH 096/128] Show the Log as a framed list of one-line entries The Log's lines sit in a sunken box joined to the open tab: one row per line, never wrapped, with vertical and horizontal scrollbars and the whole row banded while selected. The widest line of each tab is measured once per new line, so a long log doesn't lay out every line each frame; rows are laid out only while visible. The Assets tab's greyed warnings filter sits in a strip above the list and has the accessible name "Warnings". Part of #890. --- crates/ui-egui/src/log_panel.rs | 107 +++++++++++++---- .../ui-egui/src/log_panel/log_width_cache.rs | 88 ++++++++++++++ crates/ui-egui/src/state.rs | 4 + crates/ui-egui/tests/it/log_panel_680.rs | 109 ++++++++++++++++-- crates/ui-egui/tests/list_panels.rs | 5 +- 5 files changed, 276 insertions(+), 37 deletions(-) create mode 100644 crates/ui-egui/src/log_panel/log_width_cache.rs diff --git a/crates/ui-egui/src/log_panel.rs b/crates/ui-egui/src/log_panel.rs index 86e8d489..06134c0e 100644 --- a/crates/ui-egui/src/log_panel.rs +++ b/crates/ui-egui/src/log_panel.rs @@ -1,6 +1,8 @@ //! The Log panel: the session's messages under a General and an Assets tab, one per channel -use egui::{Align2, Color32, Rect, RichText, Sense, Stroke, StrokeKind, Ui, vec2}; +use std::hash::{Hash, Hasher}; + +use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, Ui, vec2}; use texturecraft_engine::log::{LogEntry, LogLevel}; use crate::TextureCraftApp; @@ -8,8 +10,10 @@ use crate::i18n::tr; use crate::theme::Tokens; mod log_channel; +mod log_width_cache; pub use log_channel::LogChannel; +pub use log_width_cache::LogWidthCache; /// The width of the History and Log lists' scrollbars const LIST_SCROLLBAR_WIDTH: f32 = 8.0; @@ -68,15 +72,22 @@ pub(crate) fn panel_rows( const PANEL_INSET: f32 = 6.0; const TAB_HEIGHT: f32 = 24.0; const TAB_NAME_SIZE: f32 = 11.0; +/// The Assets tab's strip with its filter button, above the list +const FILTER_STRIP_HEIGHT: f32 = 30.0; +const LINE_HEIGHT: f32 = 19.0; +const LINE_TEXT_SIZE: f32 = 12.0; +/// Where a line's text starts in the list, and the air after the widest line +const LINE_TEXT_LEFT: f32 = 6.0; -/// The General and Assets tabs, splitting the panel's width; the open one joins the list under it -fn channel_tabs(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) { +/// The General and Assets tabs, splitting the panel's width; returns the open tab's rectangle +fn channel_tabs(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) -> Rect { // The panel's own margin is above the tabs; the strip adds the rest of the inset ui.add_space(PANEL_INSET - f32::from(crate::docking::LIST_PANEL_MARGIN.top)); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), TAB_HEIGHT), Sense::hover()); let strip = strip.shrink2(vec2(PANEL_INSET, 0.0)); let tab_width = strip.width() / LogChannel::ALL.len() as f32; let outline = Stroke::new(1.0, tokens.field_border); + let mut open_tab = strip; for (slot, channel) in LogChannel::ALL.into_iter().enumerate() { let rect = Rect::from_min_size(strip.min + vec2(slot as f32 * tab_width, 0.0), vec2(tab_width, TAB_HEIGHT)); let response = ui.interact(rect, ui.make_persistent_id(("log-tab", channel.name())), Sense::click()); @@ -87,8 +98,7 @@ fn channel_tabs(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) { let painter = ui.painter(); painter.rect(rect, 0.0, if open { tokens.field } else { tokens.row }, outline, StrokeKind::Inside); if open { - let joint = Rect::from_min_max(rect.left_bottom() + vec2(1.0, -1.0), rect.right_bottom() + vec2(-1.0, 0.0)); - painter.rect_filled(joint, 0.0, tokens.field); + open_tab = rect; } let color = if open || response.hovered() { tokens.text } else { tokens.text_dim }; painter.text(rect.center(), Align2::CENTER_CENTER, name, crate::theme::semibold(TAB_NAME_SIZE), color); @@ -102,6 +112,46 @@ fn channel_tabs(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) { app.ui.log_anchor = None; } } + open_tab +} + +/// A line as its row shows it: a message's line breaks become spaces, so it stays on its one row +fn row_text(entry: &LogEntry) -> String { + entry.line().replace(['\r', '\n'], " ") +} + +/// One Log line across the list: one row, never wrapped, banded while selected +fn log_line(ui: &mut Ui, tokens: &Tokens, index: usize, entry: &LogEntry, selected: bool) -> egui::Response { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), LINE_HEIGHT), Sense::hover()); + + // A row is as wide as the widest line: only its shown part takes clicks, so its middle is on screen + let response = ui.interact(rect.intersect(ui.clip_rect()), ui.make_persistent_id(("log-line", index)), Sense::click()); + let line = entry.line(); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &line)); + reveal_focused_row(ui, &response, rect); + if !ui.is_rect_visible(rect) { + return response; + } + + let painter = ui.painter(); + if selected { + painter.rect_filled(rect, 0.0, tokens.accent_dim); + } + let text_at = egui::pos2(rect.left() + LINE_TEXT_LEFT, rect.center().y); + painter.text(text_at, Align2::LEFT_CENTER, row_text(entry), egui::FontId::proportional(LINE_TEXT_SIZE), level_color(tokens, entry.level)); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + response +} + +/// Changes when the installed fonts do: fallback fonts arrive while the app runs, and widths change with them +fn font_key(ui: &Ui) -> u64 { + ui.fonts(|fonts| { + let mut hasher = std::hash::DefaultHasher::new(); + fonts.definitions().families.get(&egui::FontFamily::Proportional).hash(&mut hasher); + hasher.finish() + }) } /// The entries a tab lists, as indices into the session log @@ -115,11 +165,11 @@ pub fn channel_of(entry: &LogEntry) -> LogChannel { } /// The line colour of a level: light grey for info, yellow-orange for warnings, red for errors -fn level_color(tk: &Tokens, level: LogLevel) -> Color32 { +fn level_color(tokens: &Tokens, level: LogLevel) -> Color32 { match level { - LogLevel::Info => tk.text, - LogLevel::Warning => tk.warning, - LogLevel::Error => tk.danger, + LogLevel::Info => tokens.text, + LogLevel::Warning => tokens.warning, + LogLevel::Error => tokens.danger, } } @@ -223,8 +273,8 @@ pub(crate) fn takes_copy(app: &TextureCraftApp, ctx: &egui::Context) -> bool { /// The Log panel body (a dock tab or rail popup) pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - channel_tabs(app, ui, &tk); + let tokens = Tokens::get(ui.ctx()); + let open_tab = channel_tabs(app, ui, &tokens); // A new session has a new log: indices chosen in the old one point at other lines if app.ui.log_id != app.session.log_id { @@ -233,14 +283,25 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { app.ui.log_anchor = None; } + // The list's box overlaps the tabs' bottom line, which is then cleared under the open tab; the panel's own margin is below it let inset = PANEL_INSET as i8; - egui::Frame::new().inner_margin(egui::Margin::symmetric(inset, 0)).show(ui, |ui| entries(app, ui, &tk)); + let outer = egui::Margin { left: inset, right: inset, top: -1, bottom: inset - crate::docking::LIST_PANEL_MARGIN.bottom }; + // The 1 px inner margin keeps the rows and scrollbars off the frame's line + let frame = egui::Frame::new().fill(tokens.field).stroke(Stroke::new(1.0, tokens.field_border)).inner_margin(1).outer_margin(outer); + frame.show(ui, |ui| entries(app, ui, &tokens)); + let joint = Rect::from_min_max(open_tab.left_bottom() + vec2(1.0, -1.0), open_tab.right_bottom() + vec2(-1.0, 0.0)); + ui.painter().rect_filled(joint, 0.0, tokens.field); } /// The shown tab's lines, under the Assets tab's filter button -fn entries(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { +fn entries(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) { if shown_assets_filter(app) { - crate::unavailable::greyed(ui, |ui| ui.add(egui::Button::new(egui_phosphor::regular::WARNING).selected(false))); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), FILTER_STRIP_HEIGHT), Sense::hover()); + let layout = egui::Layout::left_to_right(egui::Align::Center); + let mut strip_ui = ui.new_child(egui::UiBuilder::new().max_rect(strip.shrink2(vec2(PANEL_INSET, 0.0))).layout(layout)); + let filter = crate::unavailable::greyed(&mut strip_ui, |ui| ui.add(egui::Button::new(egui_phosphor::regular::WARNING).selected(false))); + filter.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, false, tr("Warnings"))); + ui.painter().hline(strip.x_range(), strip.bottom(), Stroke::new(1.0, tokens.field_border)); } let shown = app.ui.log_channel; @@ -259,16 +320,16 @@ fn entries(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { } } - egui::ScrollArea::vertical().id_salt(("log", shown.name())).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { - for index in rows.iter().copied() { + // Lines never wrap: the list is as wide as its widest line and scrolls sideways + let font = egui::FontId::proportional(LINE_TEXT_SIZE); + let measure = |entry: &LogEntry| ui.painter().layout_no_wrap(row_text(entry), font.clone(), tokens.text).size().x; + let widest = app.ui.log_widths.widest(&app.session.log, app.session.log_id, ui.ctx().pixels_per_point(), font_key(ui), shown, measure); + let scroll_area = egui::ScrollArea::both().id_salt(("log", shown.name())).auto_shrink([false, false]).stick_to_bottom(true); + panel_rows(ui, scroll_area, LINE_HEIGHT, rows.len(), |ui, range| { + ui.set_min_width(widest + 2.0 * LINE_TEXT_LEFT); + for index in rows[range].iter().copied() { let Some(entry) = app.session.log.get(index) else { continue }; - let text = RichText::new(entry.line()).color(level_color(tk, entry.level)); - let band = ui.painter().add(egui::Shape::Noop); - let response = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); - if app.ui.log_selection.contains(&index) { - let rect = response.rect.expand2(egui::vec2(ui.spacing().item_spacing.x, 0.0)).intersect(ui.max_rect()); - ui.painter().set(band, egui::Shape::rect_filled(rect, 0.0, tk.accent_dim)); - } + let response = log_line(ui, tokens, index, entry, app.ui.log_selection.contains(&index)); if response.clicked() || response.secondary_clicked() && !app.ui.log_selection.contains(&index) { let modifiers = ui.input(|input| input.modifiers); select(app, &rows, index, modifiers); diff --git a/crates/ui-egui/src/log_panel/log_width_cache.rs b/crates/ui-egui/src/log_panel/log_width_cache.rs new file mode 100644 index 00000000..808dd651 --- /dev/null +++ b/crates/ui-egui/src/log_panel/log_width_cache.rs @@ -0,0 +1,88 @@ +use texturecraft_engine::log::{LogEntry, SessionLog}; + +use super::{LogChannel, channel_of}; + +/// The widest line of each Log tab, measuring each line once, when it is new +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LogWidthCache { + log_id: u64, + pixels_per_point: f32, + /// Identifies the fonts the lines were measured with + font_key: u64, + /// The newest measured line's occurrence id (ids are never reused within a log) + last_occurrence: u64, + /// How many lines of both tabs were measured: fewer lines in the log means some were cleared + measured: usize, + widest: [f32; LogChannel::ALL.len()], +} + +impl LogWidthCache { + /// The widest line of `channel`: new lines are measured, a cleared line or a new log, scale or font set measures all again + pub fn widest( + &mut self, + log: &SessionLog, + log_id: u64, + pixels_per_point: f32, + font_key: u64, + channel: LogChannel, + measure: impl Fn(&LogEntry) -> f32, + ) -> f32 { + let added = log.entries_after(self.last_occurrence).count(); + let same_measure = self.pixels_per_point == pixels_per_point && self.font_key == font_key; + if self.log_id != log_id || !same_measure || self.measured + added != log.len() { + *self = LogWidthCache { log_id, pixels_per_point, font_key, ..LogWidthCache::default() }; + } + + for (occurrence, entry) in log.entries_after(self.last_occurrence) { + let widest = &mut self.widest[channel_of(entry) as usize]; + *widest = widest.max(measure(entry)); + self.last_occurrence = occurrence; + self.measured += 1; + } + self.widest[channel as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn width(entry: &LogEntry) -> f32 { + entry.line().len() as f32 + } + + #[test] + fn clearing_the_widest_line_narrows_the_tab() { + let mut log = SessionLog::new(); + log.info("Project", "short"); + log.info("Project", "a much longer line than the other one"); + let mut cache = LogWidthCache::default(); + let wide = cache.widest(&log, 1, 1.0, 1, LogChannel::General, width); + + log.retain(|entry| !entry.line().contains("longer")); + assert!(cache.widest(&log, 1, 1.0, 1, LogChannel::General, width) < wide); + } + + #[test] + fn a_new_log_is_measured_again() { + let mut log = SessionLog::new(); + log.info("Project", "a much longer line than the other one"); + let mut cache = LogWidthCache::default(); + let wide = cache.widest(&log, 1, 1.0, 1, LogChannel::General, width); + + let mut next = SessionLog::new(); + next.info("Project", "short"); + assert!(cache.widest(&next, 2, 1.0, 1, LogChannel::General, width) < wide); + } + + #[test] + fn new_fonts_measure_the_lines_again() { + let mut log = SessionLog::new(); + log.info("Project", "a line"); + let mut cache = LogWidthCache::default(); + let narrow = cache.widest(&log, 1, 1.0, 1, LogChannel::General, width); + + let wider = |entry: &LogEntry| 2.0 * width(entry); + assert!(cache.widest(&log, 1, 1.0, 2, LogChannel::General, wider) > narrow); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b40bf69c..d3a053d2 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -747,6 +747,9 @@ pub struct UiState { /// The History panel's last shown container and steps (done, undone, newest name): a change scrolls to the current step #[serde(skip)] pub history_shown: Option<(egui::Id, usize, usize, Option)>, + /// The widest line of each Log tab, measured once per line + #[serde(skip)] + pub log_widths: crate::log_panel::LogWidthCache, } pub(crate) const MAX_RECENT_PROJECTS: u16 = 100; @@ -916,6 +919,7 @@ impl Default for UiState { log_anchor: None, log_id: 0, history_shown: None, + log_widths: Default::default(), } } } diff --git a/crates/ui-egui/tests/it/log_panel_680.rs b/crates/ui-egui/tests/it/log_panel_680.rs index 62fbe967..3fa9764d 100644 --- a/crates/ui-egui/tests/it/log_panel_680.rs +++ b/crates/ui-egui/tests/it/log_panel_680.rs @@ -7,6 +7,9 @@ use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; +/// Enough lines that the Log cannot show them all at once +const LINES_PAST_THE_PANEL: usize = 100; + fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder() @@ -131,30 +134,85 @@ fn mesh_reimport_clears_log_selection_within_the_same_project() { #[test] fn assets_has_a_greyed_filter_button_with_the_hint() { - let mut h = app(); - assert!(h.query_by_label(egui_phosphor::regular::WARNING).is_none(), "GENERAL has no filter button"); - h.get_by_label("ASSETS").click(); - h.run_steps(3); - let button = h.get_by_label(egui_phosphor::regular::WARNING); + let mut harness = app(); + assert!(harness.query_by_label("Warnings").is_none(), "GENERAL has no filter button"); + + harness.get_by_label("ASSETS").click(); + harness.run_steps(3); + + let button = harness.get_by_label("Warnings"); assert!(button.accesskit_node().is_disabled()); + let at = button.rect().center(); - h.hover_at(egui::pos2(1.0, 1.0)); - h.run_steps(2); - h.hover_at(at); - h.run_steps(30); - assert!(h.query_by_label(texturecraft_ui_egui::unavailable::NOT_AVAILABLE).is_some()); + harness.hover_at(egui::pos2(1.0, 1.0)); + harness.run_steps(2); + harness.hover_at(at); + harness.run_steps(30); + assert!(harness.query_by_label(texturecraft_ui_egui::unavailable::NOT_AVAILABLE).is_some()); } /// The two tabs share the panel's width equally, side by side #[test] fn the_log_tabs_split_the_panel_width() { - let h = app(); - let (general, assets) = (h.get_by_label("GENERAL").rect(), h.get_by_label("ASSETS").rect()); + let harness = app(); + let (general, assets) = (harness.get_by_label("GENERAL").rect(), harness.get_by_label("ASSETS").rect()); assert!((general.width() - assets.width()).abs() < 1.0, "{general:?} {assets:?}"); assert!((general.right() - assets.left()).abs() < 1.0, "{general:?} {assets:?}"); } +/// The list's scrollbar keeps a gap to the list's frame, which ends where the tabs end +#[test] +fn the_log_scroll_bar_stands_clear_of_the_list_frame() { + let harness = app(); + let (general, assets) = (harness.get_by_label("GENERAL").rect(), harness.get_by_label("ASSETS").rect()); + let bars = + harness.get_all_by_role(egui::accesskit::Role::ScrollBar).filter(|bar| bar.rect().left() > general.left() && bar.rect().right() <= assets.right()); + let bar = bars.max_by(|a, b| a.rect().height().total_cmp(&b.rect().height())).expect("the list's scroll bar").rect(); + + // The frame ends where the tab strip ends; its 1 point line and 1 point padding come before its inside + let frame_inside = assets.right() - 2.0; + assert!(bar.right() < frame_inside, "{bar:?} {assets:?}"); +} + +/// How many rows each painted text containing `part` has +fn painted_rows(harness: &Harness<'_, TextureCraftApp>, part: &str) -> Vec { + harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text().contains(part) => Some(text.galley.rows.len()), + _ => None, + }) + .collect() +} + +/// Log `message` and show it painted: the status bar repeats the newest message, so another follows it +fn log_behind_a_newer_line(harness: &mut Harness<'_, TextureCraftApp>, message: &str) { + harness.state_mut().session.log.info("Exporter", message.to_owned()); + harness.state_mut().session.log.info("Exporter", "newest"); + harness.run_steps(3); +} + +/// A line longer than the panel stays on one row +#[test] +fn a_long_line_stays_one_row() { + let mut harness = app(); + log_behind_a_newer_line(&mut harness, &"long ".repeat(400)); + + assert_eq!(painted_rows(&harness, "long long"), vec![1]); +} + +/// A message with a line break is painted on its row, not over the lines around it +#[test] +fn a_message_with_a_line_break_is_painted_on_one_row() { + let mut harness = app(); + log_behind_a_newer_line(&mut harness, "broken\nmessage"); + + assert_eq!(painted_rows(&harness, "broken"), vec![1]); +} + #[test] fn renderer_settings_stays_open_when_opened_in_rendering_mode() { let mut h = app(); @@ -219,3 +277,30 @@ fn the_assets_menu_clears_all_or_only_the_selected_lines() { assert!(h.state().session.log.iter().all(|entry| !entry.is_asset())); assert_eq!(h.state().session.log.len(), 3, "the GENERAL lines stay"); } + +/// Shift+Tab walks from the newest line to the first one, past the lines on screen when the panel opened +#[test] +fn the_keyboard_reaches_lines_scrolled_out_of_view() { + let mut harness = app(); + for number in 0..LINES_PAST_THE_PANEL { + harness.state_mut().session.log.info("Exporter", format!("line {number}")); + } + harness.run_steps(4); + line(&harness, &format!("[Exporter] line {}", LINES_PAST_THE_PANEL - 1)).focus(); + harness.run_steps(2); + + let first_line_focused = |harness: &Harness<'_, TextureCraftApp>| { + let screen = harness.ctx.content_rect(); + harness.query_all_by_label("[Exporter] first").any(|row| row.accesskit_node().is_focused() && screen.y_range().contains(row.rect().top())) + }; + // One press per line is enough to reach the first one + for _ in 0..harness.state().session.log.len() { + if first_line_focused(&harness) { + break; + } + harness.key_press_modifiers(Modifiers::SHIFT, egui::Key::Tab); + harness.run_steps(2); + } + + assert!(first_line_focused(&harness)); +} diff --git a/crates/ui-egui/tests/list_panels.rs b/crates/ui-egui/tests/list_panels.rs index 872215fe..27700d8b 100644 --- a/crates/ui-egui/tests/list_panels.rs +++ b/crates/ui-egui/tests/list_panels.rs @@ -36,9 +36,10 @@ fn dock_in_left_column(harness: &mut Harness<'_, TextureCraftApp>, panel: &str) harness.state_mut().ui.dock = Dock::from_value(serde_json::from_str(&swapped).unwrap()); } -/// The height of the list's scroll bar, which runs the visible height of the list +/// The height of the list's vertical scroll bar (the taller one, as the Log also scrolls sideways), which runs the visible height of the list fn list_height(harness: &Harness<'_, TextureCraftApp>) -> f32 { - let bar = harness.get_all_by_role(Role::ScrollBar).find(|bar| bar.rect().max.x < LEFT_COLUMN_MAX_X).expect("a scroll bar in the left column"); + let bars = harness.get_all_by_role(Role::ScrollBar).filter(|bar| bar.rect().max.x < LEFT_COLUMN_MAX_X); + let bar = bars.max_by(|a, b| a.rect().height().total_cmp(&b.rect().height())).expect("a scroll bar in the left column"); bar.rect().height() } 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 097/128] 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 098/128] 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 099/128] 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 100/128] 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 101/128] 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 102/128] 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 f28d4d8b6439208fa721536be0023853841ad3d4 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:30:56 -0500 Subject: [PATCH 103/128] fix(paths): count each snapshot's tile table against the path cache budget Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 58 ++++++++++++++++++++++++++-------- crates/texel/src/tile.rs | 11 +++++++ 2 files changed, 56 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 5efc1215..15455941 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -173,11 +173,15 @@ pub(crate) struct PathCache { tiles: Vec>, } -/// The identities of the tile buffers `snap` holds, added to `seen`; returns the bytes of those -/// not already there. +/// The identities of the tile buffers and tile tables `snap` holds, added to `seen`; returns the +/// bytes of those not already there. A table (one pointer per tile slot) is shared by clones until +/// one writes, so a snapshot that diverged from the live image holds its own. fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { let mut bytes = 0; for img in snap.values() { + if seen.insert(img.table_id()) { + bytes += img.table_bytes(); + } for ty in 0..img.tiles_y() { for tx in 0..img.tiles_x() { if let Some(t) = img.tile_handle(tx, ty) @@ -239,7 +243,9 @@ impl EvictPacer { /// A snapshot was appended after a path that painted `tiles` tile positions of `state`'s images. fn appended(&mut self, snaps: &mut [Option], edited: usize, state: &Snap, tiles: usize) { let tile_bytes: usize = state.values().map(|image| texturecraft_texel::TILE_AREA * image.comps() * 2).sum(); - self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)); + // The new snapshot may also own a table per image (a write after the clone copies it). + let table_bytes: usize = state.values().map(TileImage::table_bytes).sum(); + self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)).saturating_add(table_bytes); if self.held > CACHE_BYTES { self.held = evict(snaps, CACHE_BYTES, edited); } @@ -1475,10 +1481,11 @@ mod tests { let c = s.path_cache.as_mut().unwrap(); super::evict(&mut c.snaps, usize::MAX, 0); assert_eq!(c.snaps.iter().flatten().count(), 4); - // The paths are on different tiles, so keeping every snapshot costs nothing beyond the live - // pixels: even a zero budget keeps them. - super::evict(&mut c.snaps, 0, 0); - assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels are free"); + // The paths are on different tiles, so a snapshot costs nothing beyond its own tile table + // (the tiles are all shared with the live pixels): a budget of two tables keeps them. + let table: usize = c.snaps[1].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, 2 * table, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels cost only their tables"); // Drop them by hand to test the repaint from the bottom. c.snaps[1] = None; c.snaps[2] = None; @@ -1493,10 +1500,11 @@ mod tests { let c = s.path_cache.as_mut().unwrap(); assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); - // That edit kept the snapshot below path 3 within a zero budget: its next frame starts - // there, and the snapshots above it that cost nothing keep their paths unrepainted. + // That edit kept the snapshot below path 3 within a one-table budget: its next frame starts + // there, and the snapshots above it that cost only a table keep their paths unrepainted. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, 0, 2); + let table: usize = c.snaps[2].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, table, 2); assert!(c.snaps[2].is_some()); assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); } @@ -1533,6 +1541,7 @@ mod tests { #[test] fn appending_paths_scans_the_snapshots_only_when_the_budget_may_be_passed() { let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; let mut snaps = vec![Some(empty.clone()), Some(painted(&empty, &[(0, 0)]))]; let mut pacer = super::EvictPacer::start(&mut snaps, 0); @@ -1540,7 +1549,7 @@ mod tests { // A few small paths add up to an estimate without a scan (a scan would reset it to the exact 0). for n in 1..=3 { pacer.appended(&mut snaps, 0, &empty, 1); - assert_eq!(pacer.held, n * tile_bytes, "after {n} paths"); + assert_eq!(pacer.held, n * (tile_bytes + table), "after {n} paths"); } // Past the budget the estimate gives way to an exact scan. pacer.appended(&mut snaps, 0, &empty, super::CACHE_BYTES / tile_bytes + 1); @@ -1552,6 +1561,7 @@ mod tests { let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); // Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with // the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles. let s1 = painted(&empty, &all); @@ -1563,8 +1573,8 @@ mod tests { super::evict(&mut snaps, usize::MAX, 0); assert_eq!(kept(&snaps), [true; 4]); let mut snaps = fresh(); - super::evict(&mut snaps, tile_bytes, 0); - assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile, snapshot 1 sixteen"); + super::evict(&mut snaps, tile_bytes + table, 0); + assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile and a table, snapshot 1 sixteen"); let mut snaps = fresh(); super::evict(&mut snaps, 0, 0); assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget"); @@ -1574,6 +1584,28 @@ mod tests { assert_eq!(kept(&snaps), [true, true, false, true]); } + #[test] + fn the_tile_table_of_a_diverged_snapshot_counts_once_against_the_budget() { + // Big image: the table (one slot per tile position) outweighs a one-tile stroke. + let empty: super::Snap = [(Some(texturecraft_core::Channel::Roughness), texturecraft_texel::TileImage::new(8192, 8192, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + assert!(table >= 128 * 128 * 8, "table {table}"); + let s1 = painted(&empty, &[(0, 0)]); + let s2 = painted(&s1, &[(1, 0)]); + let s3 = painted(&s2, &[(2, 0)]); + let live = painted(&s3, &[(3, 0)]); + let mut seen = std::collections::BTreeSet::new(); + // Alone, a diverged snapshot holds its own table; charged again with the same table, it is free. + let first = super::charge(&s2, &mut seen); + assert!(first >= table, "charged {first}"); + assert_eq!(super::charge(&s2, &mut seen), 0); + // Tiles alone (8 KiB each) would fit this budget; with tables only one snapshot does. + let tile_only = texturecraft_texel::TILE_AREA * 4 * 2; + let mut snaps = vec![Some(empty.clone()), Some(s1), Some(s2), Some(s3), Some(live)]; + super::evict(&mut snaps, 3 * tile_only, 0); + assert!(snaps.iter().filter(|s| s.is_some()).count() < 5, "tables must evict snapshots"); + } + #[test] fn the_quick_mask_does_not_clip_paths() { let (mut s, eid) = with_paths(&[0.2, 0.8]); diff --git a/crates/texel/src/tile.rs b/crates/texel/src/tile.rs index 31e30349..81c96ac7 100644 --- a/crates/texel/src/tile.rs +++ b/crates/texel/src/tile.rs @@ -62,6 +62,17 @@ impl TileImage { self.tile_index(tx, ty).and_then(|i| self.tiles.get(i)).and_then(Option::as_ref) } + /// Identity of the shared tile table: clones share it until one of them writes, so two images + /// with the same id hold one allocation (for memory accounting). + pub fn table_id(&self) -> usize { + Arc::as_ptr(&self.tiles) as usize + } + + /// Bytes of the tile table itself (one slot per tile position), not counting the tiles. + pub fn table_bytes(&self) -> usize { + self.tiles.len().saturating_mul(std::mem::size_of::>()) + } + /// Replace a tile wholesale (None frees it). pub fn set_tile(&mut self, tx: u32, ty: u32, data: Option) { let len = TILE_AREA * self.comps; From ca4ea4bccff135ca3b843f4e0b3f2921293f5f34 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:43:49 +0000 Subject: [PATCH 104/128] Layers: shorten the enabled-check comment --- crates/engine/src/commands.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 76728ea2..04fc918c 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -193,9 +193,7 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } -/// [`check_enabled`] for a run with `params`: a command that takes `layer` is checked as if the -/// layer it names were the selected one, so a row's own controls work with no layer selected -/// (after an undo, say). +/// [`check_enabled`] for a run with `params`, checking a command that takes `layer` as if the named layer were selected fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { let refused = match check_enabled(spec, s) { Ok(()) => return Ok(()), From 70509468e83ec2bdd3c25b93507a73b630aa14ed Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:52:03 +0000 Subject: [PATCH 105/128] Layers: a generator swapped in place takes its new kind's name --- crates/engine/src/mask_cmds.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 892e50f3..905c1a35 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -1122,6 +1122,13 @@ pub(crate) fn set(session: &mut Session, params: &Value) -> Result { session.edit("Edit effect", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; if let Some(generator) = swapped_generator { + // A name taken from the kind follows the new kind, unless one is given with the change + if let EffectKind::Generator(old) = &edited.kind + && (edited.name == old.kind.label() || edited.name == FORMER_GENERATOR_NAME) + { + edited.name = generator.kind.label().to_string(); + } + edited.kind = EffectKind::Generator(generator); } if let Some((kind, label)) = swapped { @@ -1153,11 +1160,6 @@ pub(crate) fn set(session: &mut Session, params: &Value) -> Result { if let Some(kind) = generator_kind && kind != generator.kind { - // A name taken from the kind follows the new kind - let named_by_kind = edited.name == generator.kind.label() || edited.name == FORMER_GENERATOR_NAME; - if named_by_kind && name_param(params).is_none() { - edited.name = kind.label().to_string(); - } generator.kind = kind; generator.detail = Generator::new(kind).detail; generator.inputs.retain(|map, _| kind.inputs().contains(map)); From 8b1b43246072cdf11ff3d2fde5385a1ccb6783e0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:52:06 +0000 Subject: [PATCH 106/128] Layers: open the effect stack from its thumbnail in the effect row tests --- crates/ui-egui/tests/it/effect_rows.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 663c57e2..27efc47b 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -74,8 +74,12 @@ fn an_effect_rows_menu_moves_it_within_its_stack() { |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); 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)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); let order = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); let menu_item = |harness: &mut Harness<'_, TextureCraftApp>, row: &str, item: &str| { @@ -109,8 +113,12 @@ fn alt_up_and_down_move_the_selected_effect() { |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); 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)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); let order = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); let press = |harness: &mut Harness<'_, TextureCraftApp>, key: egui::Key| { @@ -140,8 +148,12 @@ fn an_effect_rows_cross_removes_it() { let a = add("Effect A"); add("Effect B"); 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)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); let undo_steps = harness.state().session.history_labels().len(); let at = harness.get_by_label("Remove effect Effect B").rect().center(); From 1f4981ea98f9866f505259eff56c8166b795ede4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:22 +0000 Subject: [PATCH 107/128] Layers: flatten folder and R + click build anchor micro heights as the composite does --- crates/compose/src/eval.rs | 3 ++- crates/compose/src/eval/layers_at.rs | 14 +++++++++++--- crates/engine/tests/it/flatten_folder.rs | 24 ++++++++++++++++++++++-- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 2433de66..51dd1b50 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -5630,7 +5630,8 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt } let visible_inputs = Inputs { project: &forced_visible, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; let projectors = ProjectorDepthCache::default(); - let visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + let mut visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + prepare_generators(&mut visible_inputs, Some(id)); let planned_channels = evaluation_channels(&visible_inputs, channels.clone()); let fields = evaluation_fields(&visible_inputs, &planned_channels, tiles); diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs index 4c342707..d078629f 100644 --- a/crates/compose/src/eval/layers_at.rs +++ b/crates/compose/src/eval/layers_at.rs @@ -2,7 +2,7 @@ use super::{ BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, - evaluation_fields, plan, + evaluation_fields, plan, prepare_generators, }; /// Below this weight a layer leaves the texel unchanged (one 16-bit step) @@ -19,8 +19,16 @@ pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32 // A cache built for another mesh would hand out its depth maps let unbound = ProjectorDepthCache::default(); - let projectors = if projectors.serves(inputs.mesh) { projectors } else { &unbound }; - let inputs = &EvaluationInputs::new(inputs, projectors); + let served = projectors.serves(inputs.mesh); + let mut inputs = EvaluationInputs::new(inputs, if served { projectors } else { &unbound }); + + // The viewport's anchor heights are kept for the next query + if served { + inputs = inputs.of_the_session_stack(); + } + prepare_generators(&mut inputs, None); + + let inputs = &inputs; let channels = evaluation_channels(inputs, set.channel_list()); // Filters and anchors can read texels outside this one's tile: the fields cover what it reads diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 77fefc27..4a085bce 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -34,8 +34,8 @@ fn stroke(s: &mut Session, size: u32, points: [[u32; 2]; 2]) { fn composite(s: &mut Session) -> Vec<[f32; 3]> { s.update(); let channels = s.doc.project.texture_set(0).unwrap().channel_list(); - let cache = &s.caches[0]; - channels.iter().flat_map(|c| (0..RESOLUTION).flat_map(move |y| (0..RESOLUTION).map(move |x| cache.composite.value(*c, x, y)))).collect() + let composite = &s.caches[0].composite; + channels.iter().flat_map(|c| (0..composite.height).flat_map(move |y| (0..composite.resolution).map(move |x| composite.value(*c, x, y)))).collect() } fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { @@ -132,3 +132,23 @@ fn a_hidden_folder_flattens_into_a_hidden_layer() { assert!(!s.doc.project.layer(LayerId(flat)).unwrap().visible, "the new layer is hidden like the folder"); assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "the image does not change"); } + +/// A generator whose micro height reads an anchor point bakes as the viewport shows it +#[test] +fn a_flattened_folder_keeps_a_generators_anchor_micro_height() { + let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap()["effect"].as_u64().unwrap(); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap(); + let generator = execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} From 4c2df2a0a0287f75cb18fbf347ec1b8abe42c58c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:24 +0000 Subject: [PATCH 108/128] Layers: R + click reads each compare mask against the layers below its own layer --- crates/compose/src/eval/layers_at.rs | 29 +++++++++++++++++----------- crates/engine/tests/it/layer_pick.rs | 23 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs index d078629f..234247a8 100644 --- a/crates/compose/src/eval/layers_at.rs +++ b/crates/compose/src/eval/layers_at.rs @@ -1,8 +1,8 @@ -//! Which layers lay something down at one texel, for the viewport's Pick layer tool +//! Which layers lay something down at one texel, for R + click on the model use super::{ - BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, - evaluation_fields, plan, prepare_generators, + Acc, BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, + evaluation_fields, mix_group, plan, prepare_generators, }; /// Below this weight a layer leaves the texel unchanged (one 16-bit step) @@ -38,12 +38,9 @@ pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32 let offset = ((y % TILE) * TILE + x % TILE) as usize; let mut texel = Texel::new(inputs, x, y, offset, 0.0); - // The whole stack runs first, so masks and fills that read anchors find them - let mut values = Channel::ALL.map(Channel::default_value); - texel.eval(&nodes, &mut values); - + let mut stack = Channel::ALL.map(Channel::default_value); let mut found = Vec::new(); - texel.layers_laying_down(&nodes, [1.0; NCH], shown, &mut found); + texel.layers_laying_down(&nodes, &mut stack, [1.0; NCH], shown, &mut found); // The stack runs bottom first found.reverse(); @@ -51,11 +48,15 @@ pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32 } impl Texel<'_, '_> { - /// Push the leaf layers among `nodes` (bottom first) that lay something down in a `shown` channel, with those channels, each channel weighted by `weights` (the opacity and mask of the folders holding them) - fn layers_laying_down(&mut self, nodes: &[Node], weights: [f32; NCH], shown: &[Channel], found: &mut Vec<(LayerId, Vec)>) { + /// Composite `nodes` (bottom first) over `stack`, pushing the leaf layers that lay something down in a `shown` channel, with those channels, each channel weighted by `weights` (the opacity and mask of the folders holding them) + fn layers_laying_down(&mut self, nodes: &[Node], stack: &mut Acc, weights: [f32; NCH], shown: &[Channel], found: &mut Vec<(LayerId, Vec)>) { for node in nodes { + // A mask comparing with the layers below reads the stack under its own layer + self.below = Some(*stack); let mask = self.node_mask(node); if mask <= 0.0 { + // A masked-out layer still records its anchor points + self.eval(std::slice::from_ref(node), stack); continue; } @@ -67,7 +68,11 @@ impl Texel<'_, '_> { } match &node.content { - Content::Group(children) => self.layers_laying_down(children, node_weights, shown, found), + Content::Group(children) => { + let mut inner = *stack; + self.layers_laying_down(children, &mut inner, node_weights, shown, found); + mix_group(stack, &inner, &node.chans, mask); + } content => { let changed: Vec = shown .iter() @@ -87,6 +92,8 @@ impl Texel<'_, '_> { if !changed.is_empty() { found.push((node.draw.0, changed)); } + + self.eval(std::slice::from_ref(node), stack); } } } diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs index dcd8d38d..f52d661f 100644 --- a/crates/engine/tests/it/layer_pick.rs +++ b/crates/engine/tests/it/layer_pick.rs @@ -100,3 +100,26 @@ fn a_pick_opens_the_collapsed_folders_holding_the_picked_layer() { let open = |folder| matches!(s.doc.project.layers[&folder].kind, LayerKind::Group { collapsed: false, .. }); assert!(open(inner) && open(outer), "both folders holding the picked layer are open"); } + +/// Each height-combination mask compares with the layers below its own layer, not below another's +#[test] +fn a_height_combination_mask_is_read_against_the_layers_below_its_own_layer() { + let (mut s, ..) = stack(); + let add = |s: &mut Session, height: f32| id(execute(s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "height": height})).unwrap()); + let base = add(&mut s, 0.0); + let lower = add(&mut s, 0.3); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": lower})).unwrap(); + let raised = add(&mut s, 0.6); + let upper = add(&mut s, 0.9); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": upper})).unwrap(); + for layer in [base, raised] { + execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "height", "mode": "Normal"})).unwrap(); + } + execute(&mut s, "layer.blend", &json!({"layer": raised, "channel": "baseColor", "enabled": false})).unwrap(); + s.update(); + + let listed: Vec = layers_at(&mut s, MIDDLE).into_iter().map(|(layer, _)| layer).collect(); + + assert!(listed.contains(&lower), "the lower combination shows over the base: {listed:?}"); + assert!(listed.contains(&upper), "and so does the upper one: {listed:?}"); +} From 03b4c60a75558e48288a7427f81d2d340c92027f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:27 +0000 Subject: [PATCH 109/128] Layers: a folder flattened inside a scaled or turned folder keeps its images in place --- crates/engine/src/layer_ops.rs | 8 +++++++- crates/engine/tests/it/flatten_folder.rs | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 4f1cf4d1..d588adc6 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -3,7 +3,9 @@ use serde_json::{Value, json}; use texturecraft_compose::eval::FlatTile; -use texturecraft_core::{Channel, ChannelKind, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source}; +use texturecraft_core::{ + Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source, +}; use texturecraft_formats::DecodedImage; use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; @@ -257,6 +259,10 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { fill.sources.insert(channel, Source::image(name)); } + // The folders around lay their Scale and Rotation on the new fill too: starting it at the opposite keeps the images in place + let around = s.doc.project.contents_around(folder.id); + fill.projection = ContentsOffset::new(around.scale.recip(), -around.rotation).apply(&fill.projection); + // Only the channels the folder lays down, at its opacity (a folder mixes its result in by opacity alone, whatever its blend mode): a channel without an image would cover the stack with its default let channels: Vec = fill.sources.keys().copied().collect(); let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 4a085bce..1d364d01 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -152,3 +152,20 @@ fn a_flattened_folder_keeps_a_generators_anchor_micro_height() { assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); } + +/// A folder holding this one lays its Scale and Rotation on every fill inside it: the baked images stay where they were baked +#[test] +fn a_folder_flattened_inside_a_scaled_and_turned_folder_looks_the_same() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + stroke(&mut s, 30, [[170, 190], [230, 210]]); + execute(&mut s, "folder.contents.set", &json!({"layer": outer, "scale": 2.0, "rotation": 45.0})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": inner})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} From 7f14dce2529782762607e3b80b068670ff1c336e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:29 +0000 Subject: [PATCH 110/128] Layers: refuse to flatten a folder of a texture set with several UV tiles --- crates/engine/src/layer_ops.rs | 5 +++++ crates/engine/tests/it/flatten_folder.rs | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index d588adc6..587584bc 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -240,6 +240,11 @@ fn flatten(s: &mut Session, p: &Value) -> Result { /// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { + // A fill reads its image again on every UV tile, so an image of several tiles would repeat on each + if s.doc.project.texture_set(ts)?.uv_tiles.len() > 1 { + return Err(EngineError::Other("flattening a folder of a texture set with several UV tiles is not supported yet".into())); + } + s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 1d364d01..4933aa18 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -169,3 +169,24 @@ fn a_folder_flattened_inside_a_scaled_and_turned_folder_looks_the_same() { assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); } + +/// A fill reads one image again on every UV tile, so a folder of a set with several tiles is refused instead of baked wrong +#[test] +fn flattening_a_folder_over_several_uv_tiles_is_refused() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": fill})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": fill, "procedural": "checker", "scale": 3.0})).unwrap(); + assert!(s.doc.project.texture_sets[0].uv_tiles.len() > 1, "the plane spans two UV tiles"); + let before = composite(&mut s); + let steps = s.history_labels().len(); + + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + if flattened.is_ok() { + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before)); + } + assert!(flattened.is_err(), "refused"); + assert_eq!(s.history_labels().len(), steps, "and nothing is changed"); +} From 9a188f4077d39a9f57d9a69589b057b4ff811641 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:32 +0000 Subject: [PATCH 111/128] Layers: layer.pickAt refuses a layer that is no id instead of picking the top one --- crates/engine/src/layer_cmds.rs | 9 +++++++-- crates/engine/tests/it/layer_pick.rs | 11 +++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 9a81da03..8aa84d9e 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Pick layer under the cursor", [], None, - "{x, y, viewport?: [w,h], layer?} a point on the mesh — selects `layer` if it lays something down there, else the top layer laying something down there in the shown channels (R + click)", + "{x, y, viewport?: [w,h], layer?} a point on the mesh — selects the top layer laying something down there in the shown channels, or `layer`, refused when it lays nothing down there (R + click)", always, pick_at ), @@ -303,7 +303,12 @@ fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer { fn pick_at(s: &mut Session, p: &Value) -> Result { let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.pickAt", "`x` and `y` are required")) }; let viewport = crate::tool_cmds::viewport_of(s, p); - let wanted = u64p(p, "layer").map(LayerId); + + // A `layer` that is no id is refused rather than read as none + let wanted = match p.get("layer").filter(|layer| !layer.is_null()) { + Some(_) => Some(u64p(p, "layer").map(LayerId).ok_or_else(|| bad("layer.pickAt", "`layer` must be a layer id"))?), + None => None, + }; let id = s.pick_layer(texturecraft_geom::glam::Vec2::new(x, y), viewport, wanted)?; Ok(json!({ "layer": id.0 })) } diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs index f52d661f..408ecc05 100644 --- a/crates/engine/tests/it/layer_pick.rs +++ b/crates/engine/tests/it/layer_pick.rs @@ -123,3 +123,14 @@ fn a_height_combination_mask_is_read_against_the_layers_below_its_own_layer() { assert!(listed.contains(&lower), "the lower combination shows over the base: {listed:?}"); assert!(listed.contains(&upper), "and so does the upper one: {listed:?}"); } + +#[test] +fn a_pick_of_something_that_is_not_a_layer_id_is_refused() { + let (mut s, ..) = stack(); + let selected = s.selected_layer(); + + let reply = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": "fill"})); + + assert!(reply.is_err(), "not silently replaced by the top layer: {reply:?}"); + assert_eq!(s.selected_layer(), selected); +} From 4b2729ee715916bdc1bf95d56b951e9f2f5246f5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:35 +0000 Subject: [PATCH 112/128] Layers: the R + click list comes before an armed point or focus pick, and its closing press paints nothing in 2D --- crates/ui-egui/src/menus.rs | 5 +- crates/ui-egui/src/viewport.rs | 10 ++-- crates/ui-egui/tests/it/layers_panel.rs | 79 +++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ba37bd5e..2b1712ff 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -557,12 +557,13 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // 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 escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + // The list opens over an armed point pick, so it closes first + app.layer_pick_list = None; } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { cancel_point_pick = true; } else if !escape_is_free { // The picker window handles the key - } else if app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { - app.layer_pick_list = None; } else if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 561002a6..fc23cab0 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -920,14 +920,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::layer_pick_list::click(app, pointer, local(pointer), rect); } + // R + click and the list it opens come before an armed point or focus pick, including the press that closes the list + let layer_pick_takes_click = r_held || crate::layer_pick_list::blocks_view_input(app); + // A 3D generator's armed point pick: a click sets the point there instead of painting let point_pick = crate::generator_point_pick::armed_on(ui.ctx(), &app.session); if let Some(pick) = point_pick { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); - - // R + click still picks a layer while a pick is armed if !alt - && !r_held + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { @@ -947,7 +948,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if picking_focus_distance { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt - && !r_held + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { @@ -2319,6 +2320,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let painting = tool_acts(app) && !projection_hint && app.properties_popup.is_none() + && !crate::layer_pick_list::blocks_view_input(app) && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) && !crate::color_picker::blocks_view_press(ui.ctx()) && !alt diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 8c670db2..fee74407 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -841,3 +841,82 @@ fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_withou assert!(h.state().layer_pick_list.is_none(), "Escape closes the list"); assert_eq!(h.state().session.selected_layer(), Some(upper), "and selects nothing"); } + +/// Two fills over the whole model, so R + click opens the list; returns the 3D view +fn two_fills(h: &mut Harness<'_, TextureCraftApp>) -> egui::Rect { + for name in ["Lower fill", "Upper fill"] { + execute(&mut h.state_mut().session, "layer.add.fill", &json!({"name": name, "color": "#aa3322"})).unwrap(); + } + h.run_steps(SETTLE_FRAMES); + h.state().viewport_rect +} + +/// R + click at the middle of the 3D view +fn open_pick_list(h: &mut Harness<'_, TextureCraftApp>) { + let middle = h.state().viewport_rect.center(); + let key = |pressed| egui::Event::Key { key: egui::Key::R, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + h.event(key(true)); + h.hover_at(middle); + h.run_steps(1); + click(h, middle); + h.event(key(false)); + h.run_steps(SETTLE_FRAMES); + assert!(h.state().layer_pick_list.is_some(), "the list is open"); +} + +/// The list opened over an armed point pick is the innermost thing: Escape closes it first, and a press that closes it sets no point +#[test] +fn the_layer_pick_list_takes_escape_and_its_closing_press_before_an_armed_point_pick() { + let (mut h, _) = harness(); + let view = two_fills(&mut h); + execute(&mut h.state_mut().session, "mask.add.black", &Value::Null).unwrap(); + let effect = id(execute(&mut h.state_mut().session, "effect.add.generator", &json!({"generator": "3dDistance"})).unwrap(), "effect"); + h.run_steps(SETTLE_FRAMES); + let generator = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind.clone(); + let armed = + |h: &Harness<'_, TextureCraftApp>| h.get_by_label("Pick 3D Position on the mesh").accesskit_node().toggled() == Some(egui::accesskit::Toggled::True); + h.get_by_label("Pick 3D Position on the mesh").click(); + h.run_steps(SETTLE_FRAMES); + assert!(armed(&h), "the pick is armed"); + let before = generator(&h); + + open_pick_list(&mut h); + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list"); + assert!(armed(&h), "and leaves the point pick armed"); + + open_pick_list(&mut h); + click(&mut h, view.center() - egui::vec2(60.0, 40.0)); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "a press outside closes the list"); + assert_eq!(generator(&h), before, "and sets no point"); + assert!(armed(&h)); +} + +/// In the split view, a press on the 2D view that closes the list paints nothing there +#[test] +fn a_press_on_the_2d_view_that_closes_the_layer_pick_list_does_not_paint() { + let (mut h, _) = harness(); + two_fills(&mut h); + execute(&mut h.state_mut().session, "layer.add.paint", &Value::Null).unwrap(); + h.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Split; + h.run_steps(SETTLE_FRAMES); + let view = h.state().viewport_rect; + let over_2d = egui::pos2(view.right() + view.width() * 0.5, view.center().y); + let steps = h.state().session.history_labels().len(); + open_pick_list(&mut h); + + click(&mut h, over_2d); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the press closes the list"); + assert_eq!(h.state().session.history_labels().len(), steps, "and paints no stroke"); + + click(&mut h, over_2d); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().session.history_labels().len() > steps, "the next press paints there"); +} From 671cdb3c5b5df80807e37ded3aa320c1eed39408 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:37 +0000 Subject: [PATCH 113/128] Layers: close the R + click list when the document changes --- crates/ui-egui/src/layer_pick_list.rs | 10 +++++++--- crates/ui-egui/tests/it/layers_panel.rs | 13 +++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/layer_pick_list.rs b/crates/ui-egui/src/layer_pick_list.rs index 39558758..ab0f37c9 100644 --- a/crates/ui-egui/src/layer_pick_list.rs +++ b/crates/ui-egui/src/layer_pick_list.rs @@ -46,6 +46,8 @@ pub struct LayerPickList { bounds: Rect, /// The layers there, top first, each with the channels it changes there rows: Vec<(LayerId, Vec)>, + /// The document revision the rows were read at: any change, or another project, closes the list + revision: u64, /// The list's first frame: its top row takes the keyboard focus opening: bool, /// Closed by a press outside it: until every button is up, that press neither paints nor reopens it @@ -59,7 +61,9 @@ type HoverLabel = ((usize, (u32, u32), u64, ViewMode), String); pub(crate) fn click(app: &mut TextureCraftApp, at: Pos2, point: Vec2, bounds: Rect) { let viewport = app.session.viewport; match app.session.layers_under(point, viewport) { - Ok((_, rows)) if rows.len() > 1 => app.layer_pick_list = Some(LayerPickList { at, point, bounds, rows, opening: true, closing: false }), + Ok((_, rows)) if rows.len() > 1 => { + app.layer_pick_list = Some(LayerPickList { at, point, bounds, rows, revision: app.session.revision, opening: true, closing: false }); + } _ => { app.run("layer.pickAt", json!({"x": point.x, "y": point.y, "viewport": [viewport.x, viewport.y]})); } @@ -99,13 +103,13 @@ fn area_id() -> egui::Id { egui::Id::unique("layer_pick_list") } -/// Draws the open list; a row click selects its layer, Esc or a press outside closes it +/// Draws the open list; a row click selects its layer; Esc, a press outside or a document change closes it pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let (any_down, pressed_at, escape) = ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()), input.key_pressed(Key::Escape))); let shown = ctx.memory(|memory| memory.area_rect(area_id())); match &mut app.layer_pick_list { - Some(_) if app.ui.mode != Mode::Painting || escape => app.layer_pick_list = None, + Some(list) if app.ui.mode != Mode::Painting || escape || list.revision != app.session.revision => app.layer_pick_list = None, Some(list) if list.closing => { if !any_down { app.layer_pick_list = None; diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index fee74407..7efe5ba0 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -896,6 +896,19 @@ fn the_layer_pick_list_takes_escape_and_its_closing_press_before_an_armed_point_ assert!(armed(&h)); } +/// The list names layers of the stack it was opened on: an edit, an undo or another project closes it +#[test] +fn the_layer_pick_list_closes_when_the_document_changes() { + let (mut h, _) = harness(); + two_fills(&mut h); + open_pick_list(&mut h); + + execute(&mut h.state_mut().session, "edit.undo", &Value::Null).unwrap(); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none()); +} + /// In the split view, a press on the 2D view that closes the list paints nothing there #[test] fn a_press_on_the_2d_view_that_closes_the_layer_pick_list_does_not_paint() { From 1f79735dcd2ce85ad7eaf6b8ac3927fac3e8e401 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:40 +0000 Subject: [PATCH 114/128] Layers: the smart material picker lists saved materials before the Assets panel has shown --- crates/ui-egui/src/layer_toolbar.rs | 7 ++++++- crates/ui-egui/src/shelf.rs | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index ec6b1eb5..1a80062a 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -489,6 +489,11 @@ fn bitmap_tabs(session: &Session) -> Vec> { /// The smart material picker, hanging under `anchor` at its width while open: a pick adds the material above the selection, as a shelf click on a saved one does fn smart_material_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id) { + // The saved materials are otherwise read only while the Assets panel shows + if egui::Popup::is_id_open(&anchor.ctx, popup) { + crate::shelf::scan_library(app); + } + let tabs = || smart_material_tabs(app.library.as_deref().unwrap_or_default()); match resource_picker::show(anchor, popup, &mut app.thumbs, None, false, tabs) { Some(SmartMaterialChoice::BuiltIn(id)) => { @@ -501,7 +506,7 @@ fn smart_material_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id } } -/// The smart material picker's one tab: the built-in smart materials, then the ones the user saved (once the shelf has read them) +/// The smart material picker's one tab: the built-in smart materials, then the ones the user saved fn smart_material_tabs(library: &[PathBuf]) -> Vec> { let built_in = MATERIALS .iter() diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 75e72846..a7b76133 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -427,7 +427,7 @@ pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { /// Read the user's saved smart materials (desktop library folder and the added library locations) unless they are already listed #[cfg(not(target_arch = "wasm32"))] -fn scan_library(app: &mut TextureCraftApp) { +pub(crate) fn scan_library(app: &mut TextureCraftApp) { if app.library.is_some() { return; } @@ -453,7 +453,7 @@ fn scan_library(app: &mut TextureCraftApp) { } #[cfg(target_arch = "wasm32")] -fn scan_library(_: &mut TextureCraftApp) {} +pub(crate) fn scan_library(_: &mut TextureCraftApp) {} /// A saved smart material's name: its file name without the extension pub(crate) fn saved_material_name(path: &std::path::Path) -> &str { From 62051b42df30501f277677c1d4a1916020527d2a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:43 +0000 Subject: [PATCH 115/128] Layers: document flatten folder, effect moves and the layer commands --- docs/control-protocol.md | 13 +++++++++++-- docs/features.md | 9 +++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9c65e129..2af71ba5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -22,7 +22,8 @@ Submitting the current name leaves history unchanged. The project file keeps its `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. `effect.move {effect, index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies -one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the +one just above itself. `effect.moveUp {effect?}` / `effect.moveDown {effect?}` move the named (or +selected) effect one place and reply `{moved}` (false at that end). `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. `layer.select {layers: [id], layer?}` selects several layers of one texture set at once (`layer` is the active one), and `{layer, range: true}` / `{layer, toggle: true}` do what Shift+click and @@ -37,7 +38,15 @@ layer, the others in stack order; `layer.duplicate` puts the copies in one block topmost selected layer. Without `layer`, `layer.remove`, `layer.duplicate`, `layer.group` and `layer.visible` act on every selected layer; each of them and `layer.move {layers, above | index}` also take an explicit `layers` list. `session.inspect` lists the -selection as `selectedLayers` (top row first). +selection as `selectedLayers` (top row first). A command that takes `layer` is checked against +the named layer of the active texture set, so it runs even with nothing selected. + +`layer.layersAt {x, y, viewport?}` lists the layers laying something down where the mesh is under a +viewport point, top first (`{layers: [{layer, name, channels}]}`, in the shown channels). +`layer.pickAt {x, y, viewport?, layer?}` selects the top one, or `layer` if it is listed there. +`layer.flatten {layer}` on a folder replies with a new fill layer above it holding the folder's +result as image resources, and hides the folder; it is refused for a texture set with several UV +tiles. `mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the texture set's resolution: black where the mesh does not cover the texture, with the orientation diff --git a/docs/features.md b/docs/features.md index cda64d94..ec08683e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -51,6 +51,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and how many more. Click: one layer there is selected; several open a list at the pointer with each one's thumbnail, name and the channels it changes there, to pick from (Up/Down, Enter, Esc work too). Closed folders holding the picked layer open and its row scrolls into view. +- **Flatten folder:** a folder's right-click menu (or Ctrl+M) adds a fill layer holding the + folder's result as one image per channel, with the folder's mask painted into the new layer's + mask; the folder is kept and hidden. Layers that blend over the layers below the folder are baked + as they look over them at that moment. Not available for a texture set with several UV tiles. +- **Effect rows:** a generator is named after its kind; the cross removes an effect; the menu's + Move up / down / to top / to bottom and Alt+Up / Alt+Down reorder its stack. +- **Smart materials from the Layers panel:** the toolbar's button opens a picker of the built-in + and saved smart materials. +- **Height combination masks** (Add mask menus) also set the layer's height to blend Normal. - **Several layers at once:** Shift+click a layer to select the rows from the last clicked one, Ctrl+click (Cmd+click on macOS) to add or take out one layer, Ctrl+A (Cmd+A) with the pointer over the Layers panel to select every shown row (folder rows and the layers of open folders). From aabf759e21255e17c801bfd7095d9ef165160361 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:24:32 +0000 Subject: [PATCH 116/128] Make Ctrl+Shift+Z redo as well as Ctrl+Y --- crates/ui-egui/src/keymap.rs | 73 +++++++++++++++++++----- crates/ui-egui/tests/it/shortcut_keys.rs | 15 +++++ 2 files changed, 74 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index cdf46547..7518e3f0 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -189,22 +189,38 @@ pub fn format_shortcut(sc: &KeyboardShortcut) -> String { s } -/// Every bound shortcut as egui's shortcut type. -fn active(keymap: &Keymap) -> Vec { - bindings().iter().filter_map(|b| Some(parse(shortcut(keymap, b)?)?.to_egui_shortcut())).collect() +/// Second default keys as (item, shortcut); menus and the shortcut lists show the first only +const SECOND_SHORTCUTS: [(&str, &str); 1] = [("edit.redo", "Ctrl+Shift+Z")]; + +/// The second default key of item `id`, unless the stored shortcuts change the item or use the key +fn second_shortcut(keymap: &Keymap, id: &str) -> Option { + let (_, text) = SECOND_SHORTCUTS.iter().find(|(item, _)| *item == id)?; + let chord = parse(text)?; + + let replaced_or_taken = keymap.contains_key(id) || keymap.values().any(|stored| parse(stored) == Some(chord)); + (!replaced_or_taken).then_some(chord) } -/// The catalog as craft-keymap sees it, in `bindings()` order: the first one listed wins a shared -/// shortcut. -fn catalog() -> Vec { +/// Every bound shortcut as egui's shortcut type +fn active(keymap: &Keymap) -> Vec { bindings() .iter() - .map(|b| { - let item = CommandDef::new(b.id, b.label, Scope::app()); - match b.default.and_then(parse) { - Some(chord) => item.with_default(craft_keymap::Binding::new(chord)), - None => item, - } + .flat_map(|binding| [shortcut(keymap, binding).and_then(parse), second_shortcut(keymap, binding.id)]) + .flatten() + .map(|chord| chord.to_egui_shortcut()) + .collect() +} + +/// The catalog for craft-keymap in `bindings()` order: the first one listed wins a shared shortcut +fn catalog(keymap: &Keymap) -> Vec { + bindings() + .iter() + .map(|binding| { + let defaults = [binding.default.and_then(parse), second_shortcut(keymap, binding.id)]; + defaults + .into_iter() + .flatten() + .fold(CommandDef::new(binding.id, binding.label, Scope::app()), |item, chord| item.with_default(craft_keymap::Binding::new(chord))) }) .collect() } @@ -229,9 +245,9 @@ fn overrides(keymap: &Keymap) -> Overrides { out } -/// The keymap with `keymap`'s shortcuts for `platform`. +/// The keymap with `keymap`'s shortcuts for `platform` fn resolved(keymap: &Keymap, platform: Platform) -> craft_keymap::Keymap { - craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap)).with_delete_keys(craft_keymap::DeleteKeys::Apart) + craft_keymap::Keymap::new(catalog(keymap), Scopes::new(), platform).with_overrides(overrides(keymap)).with_delete_keys(craft_keymap::DeleteKeys::Apart) } /// The resolved keymap and the dispatcher that runs it against each frame's keys. @@ -720,12 +736,20 @@ mod tests { fn the_browser_leaves_app_shortcuts_alone_but_keeps_the_clipboard() { let mut keymap = Keymap::new(); keymap.insert("file.close".into(), "Alt+W".into()); + // Ctrl+Z also matches a press with Shift, so without Undo only Redo's own key takes Ctrl+Shift+Z + keymap.insert("edit.undo".into(), String::new()); sync_captured(&keymap); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; assert!(captured(ctrl, Key::S) && captured(ctrl, Key::O) && captured(ctrl, Key::D)); + assert!(captured(Modifiers { shift: true, ..ctrl }, Key::Z), "the second Redo key is taken over too"); assert!(captured(Modifiers::NONE, Key::F9) && captured(Modifiers::ALT, Key::W)); assert!(!captured(ctrl, Key::C) && !captured(ctrl, Key::V) && !captured(ctrl, Key::X), "clipboard keys reach the browser"); assert!(!captured(Modifiers::NONE, Key::M) && !captured(Modifiers::NONE, Key::F), "plain keys need no capture"); + + keymap.insert("edit.redo".into(), String::new()); + sync_captured(&keymap); + assert!(!captured(Modifiers { shift: true, ..ctrl }, Key::Z), "clearing Redo gives its second key back"); } #[test] @@ -884,6 +908,27 @@ mod tests { assert_eq!(run(Modifiers::SHIFT, Key::M), None, "Shift+M is not bound"); } + #[test] + fn a_second_default_key_yields_to_the_stored_shortcuts() { + let second_press = press(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT); + let run = |keymap: &Keymap| bindings_for(keymap).command_of(&second_press); + let mut keymap = Keymap::new(); + assert_eq!(run(&keymap).as_deref(), Some("edit.redo")); + assert_eq!(bindings_for(&keymap).command_of(&press(Key::Y, Modifiers::COMMAND)).as_deref(), Some("edit.redo")); + assert_eq!(shortcut_of(&keymap, "edit.redo"), Some("Ctrl+Y"), "menus keep showing the first key"); + + // Another item the user put on that key keeps it, without a shared-shortcut warning + keymap.insert("file.save".into(), "Ctrl+Shift+Z".into()); + assert_eq!(run(&keymap).as_deref(), Some("file.save")); + assert!(bindings_for(&keymap).conflict(binding("file.save")).is_none()); + + // Changing or clearing Redo replaces both of its keys + for stored in ["F7", ""] { + keymap = Keymap::from([("edit.redo".into(), stored.into())]); + assert_eq!(run(&keymap), None, "Redo stored as {stored:?}"); + } + } + #[test] fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() { let mut keymap = Keymap::new(); diff --git a/crates/ui-egui/tests/it/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs index 80aae4b3..e2053ae8 100644 --- a/crates/ui-egui/tests/it/shortcut_keys.rs +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -56,6 +56,21 @@ fn a_held_key_runs_its_command_again() { assert!(!hidden(&h), "the repeat toggled it back"); } +#[test] +fn ctrl_shift_z_redoes_the_undone_step() { + let mut harness = harness(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &serde_json::Value::Null).unwrap(); + let labels_after_add = harness.state().session.history_labels(); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(2); + assert_ne!(harness.state().session.history_labels(), labels_after_add, "the step is undone"); + + harness.event(press(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT, false)); + harness.run_steps(2); + + assert_eq!(harness.state().session.history_labels(), labels_after_add); +} + #[test] fn a_shortcut_stored_in_the_settings_replaces_the_default() { let mut h = harness(); From b5d9abbb917647d3167e08d381c019a850b7fbbf Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 29 Nov 2026 08:04:24 +0000 Subject: [PATCH 117/128] 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 From 95345879f01c44e19fc1b42c37a8d59a076b0c23 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:47:34 +0000 Subject: [PATCH 118/128] Properties: slider tracks stay put when a value gains a sign or digits The value column was as wide as the widest number on show, so dragging a slider below zero moved every track in the panel. It now reserves the widest value each track can reach, up to a cap so a huge range keeps its tracks, and never narrows while the pointer is held. --- .../ui-egui/src/property_sheet/axis_rows.rs | 8 +- .../src/property_sheet/factor_slider.rs | 13 ++- crates/ui-egui/src/property_sheet/mod.rs | 3 + .../src/property_sheet/property_sheet.rs | 45 ++++++++- crates/ui-egui/src/property_sheet/slider.rs | 18 +++- .../src/property_sheet/stacked_rows.rs | 6 +- crates/ui-egui/src/property_sheet/tests.rs | 91 +++++++++++++++++++ 7 files changed, 170 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index c74a956a..7edf54b9 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -5,7 +5,7 @@ use std::ops::RangeInclusive; 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}; +use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS, shown_value}; use super::switch_control::PILL_SIZE; use super::track::Track; use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; @@ -168,7 +168,11 @@ impl PropertySheet<'_> { } 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); + + // The column fits what the track reaches; a typed value past it widens the column while it is on show + self.measure_track_values(&slider.range, |end| shown_value(end, slider.decimals, slider.suffix)); + let shown = shown_value(*slider.value, slider.decimals, slider.suffix); + let typed = self.column_value_field(id, &slider.label, center_y, &shown, slider.suffix, *slider.value, &slider.typed, slider.decimals); *edit = Self::apply_typed(slider.value, typed, dragged); y += STACK_CAPTION_LINE + STACK_PART_LINE + STACK_GAP; } diff --git a/crates/ui-egui/src/property_sheet/factor_slider.rs b/crates/ui-egui/src/property_sheet/factor_slider.rs index eddf9f72..d789e802 100644 --- a/crates/ui-egui/src/property_sheet/factor_slider.rs +++ b/crates/ui-egui/src/property_sheet/factor_slider.rs @@ -6,20 +6,29 @@ use super::PropertySheet; use super::slider::{KNOB_RADIUS, kept_in}; use super::track::Track; +/// Decimals a factor reads with +const FACTOR_DECIMALS: usize = 2; + impl PropertySheet<'_> { /// A factor (×1.50) on a track `doublings` halvings or doublings each way from ×1 (marked by the zero tick); a typed value may go past the track's ends, within `typed`. `Some(merge)` when it changed pub(crate) fn factor_slider(&mut self, label: &str, factor: &mut f32, doublings: f32, typed: RangeInclusive) -> Option { let (control, center_y) = self.row(label); let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(0.0), ramp: false }; let track_range = -doublings..=doublings; let mut along = kept_in(factor.max(f32::MIN_POSITIVE).log2(), &track_range); + let dragged = self.track(id, label, &track, &mut along, &track_range); if dragged.is_some() { *factor = along.exp2(); } - let shown = format!("×{:.2}", *factor); - let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, 2); + + let show = |factor: f32| format!("×{factor:.FACTOR_DECIMALS$}"); + self.measure_track_values(&track_range, |end| show(end.exp2())); + let shown = show(*factor); + + let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, FACTOR_DECIMALS); Self::apply_typed(factor, entered, dragged) } } diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 3a0b341d..6184cbb4 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -122,6 +122,9 @@ const LOOSE_LABEL_AIR: f32 = 2.0; /// The narrowest value column at a slider's right end const VALUE_MIN_WIDTH: f32 = 26.0; +/// The most the value column reserves for values not on show yet, so a huge range leaves the tracks their length +const TRACK_VALUE_RESERVE_MAX: f32 = 72.0; + /// Air between a slider track's end and the value column, room for the knob and a gap const TRACK_TO_VALUE: f32 = 14.0; diff --git a/crates/ui-egui/src/property_sheet/property_sheet.rs b/crates/ui-egui/src/property_sheet/property_sheet.rs index e1e5b1b6..61b0649c 100644 --- a/crates/ui-egui/src/property_sheet/property_sheet.rs +++ b/crates/ui-egui/src/property_sheet/property_sheet.rs @@ -1,8 +1,10 @@ +use std::ops::RangeInclusive; + use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; use super::{ - CONTROL_HEIGHT, LABEL_COLUMN_MIN, LABEL_TO_CONTROL, SIDE_PADDING_POINTS, TEXT_SIZE, TRACK_TO_VALUE, VALUE_MIN_WIDTH, open_card::OpenCard, section_tabs, - sheet_measure::SheetMeasure, + CONTROL_HEIGHT, LABEL_COLUMN_MIN, LABEL_TO_CONTROL, SIDE_PADDING_POINTS, TEXT_SIZE, TRACK_TO_VALUE, TRACK_VALUE_RESERVE_MAX, VALUE_MIN_WIDTH, + open_card::OpenCard, section_tabs, sheet_measure::SheetMeasure, }; use crate::theme::{Tokens, semibold}; @@ -29,6 +31,9 @@ pub(crate) struct PropertySheet<'u> { pub(super) held: bool, /// Sub-headers so far in the current folding section: a later one takes air above it pub(super) sub_headers: usize, + + /// The value font's widest digit, found on first use + pub(super) widest_digit: Option, } impl<'u> PropertySheet<'u> { @@ -36,8 +41,10 @@ impl<'u> PropertySheet<'u> { pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { let id = ui.make_persistent_id(id_salt); let used = ui.memory_mut(|memory| memory.caches.cache::().get(&id).copied()).unwrap_or_default(); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let rect = ui.available_rect_before_wrap(); + let mut sheet = PropertySheet { tokens: Tokens::get(ui.ctx()), id, @@ -56,8 +63,10 @@ impl<'u> PropertySheet<'u> { info: None, held: false, sub_headers: 0, + widest_digit: None, ui, }; + let result = body(&mut sheet); sheet.close_card(); if !sheet.sections.is_empty() { @@ -66,7 +75,13 @@ impl<'u> PropertySheet<'u> { } // Refresh visible sheets so measurements of closed sheets expire - let seen = sheet.seen; + let mut seen = sheet.seen; + + // A held pointer may be dragging a track: the value column only narrows once it is released + if sheet.ui.input(|input| input.pointer.any_down()) { + seen.value_width = seen.value_width.max(used.value_width); + } + sheet.ui.memory_mut(|memory| memory.caches.cache::().set(id, seen)); if seen != used { sheet.ui.ctx().request_discard("Properties columns changed"); @@ -91,6 +106,30 @@ impl<'u> PropertySheet<'u> { self.seen.value_width = self.seen.value_width.max(width); } + /// Widens the value column for the widest value a track over `range` can read, as `show` writes it, so a drag moves no track + pub(super) fn measure_track_values(&mut self, range: &RangeInclusive, show: impl Fn(f32) -> String) { + let widest_digit = self.widest_digit(); + for end in [*range.start(), *range.end()] { + let shown: String = show(end).chars().map(|character| if character.is_ascii_digit() { widest_digit } else { character }).collect(); + let width = self.text_width(&shown, semibold(TEXT_SIZE)).min(TRACK_VALUE_RESERVE_MAX); + self.seen.value_width = self.seen.value_width.max(width); + } + } + + /// Digits differ in width, so a value between a track's ends can be wider than either end + fn widest_digit(&mut self) -> char { + if let Some(digit) = self.widest_digit { + return digit; + } + + let widest = ('0'..='9') + .map(|digit| (digit, self.text_width(&digit.to_string(), semibold(TEXT_SIZE)))) + .max_by(|one, other| one.1.total_cmp(&other.1)) + .map_or('0', |(digit, _)| digit); + self.widest_digit = Some(widest); + widest + } + pub(super) fn text_width(&self, text: &str, font: FontId) -> f32 { self.ui.painter().layout_no_wrap(text.to_owned(), font, Color32::WHITE).size().x } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 3697880b..a68ddcab 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -130,7 +130,9 @@ impl PropertySheet<'_> { self.paint_dial(pos2(dial_x, center_y), *degrees); - let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; + let show = |angle: f32| if plus { format!("{angle:+.0}°") } else { format!("{angle:.0}°") }; + self.measure_track_values(&range, show); + let shown = show(*degrees); let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); Self::apply_typed(degrees, typed, dragged) } @@ -255,7 +257,7 @@ impl PropertySheet<'_> { edit } - /// The value at the row's end, answering as `label`'s value; a click turns it into a field, which returns the typed value when done + /// The value at the row's end of a track over `range`, answering as `label`'s value; a click turns it into a field, which returns the typed value when done #[allow(clippy::too_many_arguments)] pub(super) fn value_field( &mut self, @@ -267,11 +269,12 @@ impl PropertySheet<'_> { decimals: usize, suffix: &str, ) -> Option { - let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.measure_track_values(range, |end| shown_value(end, decimals, suffix)); + let shown = shown_value(value, decimals, suffix); self.column_value_field(id, &label, center_y, &shown, suffix, value, range, decimals) } - /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it + /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it. A caller with a track measures its range first #[allow(clippy::too_many_arguments)] pub(super) fn column_value_field( &mut self, @@ -303,7 +306,7 @@ impl PropertySheet<'_> { decimals: usize, suffix: &str, ) -> Option { - let shown = format!("{}{suffix}", shown_number(value, decimals)); + let shown = shown_value(value, decimals, suffix); self.value_text_field(id, ValueText { label: &label, right, width, center_y, shown: &shown, suffix }, value, range, decimals) } @@ -363,3 +366,8 @@ impl PropertySheet<'_> { pub(super) fn kept_in(value: f32, range: &RangeInclusive) -> f32 { value.max(*range.start()).min(*range.end()) } + +/// `value` as a slider's end reads it +pub(super) fn shown_value(value: f32, decimals: usize, suffix: &str) -> String { + format!("{}{suffix}", shown_number(value, decimals)) +} diff --git a/crates/ui-egui/src/property_sheet/stacked_rows.rs b/crates/ui-egui/src/property_sheet/stacked_rows.rs index d7934290..6b961630 100644 --- a/crates/ui-egui/src/property_sheet/stacked_rows.rs +++ b/crates/ui-egui/src/property_sheet/stacked_rows.rs @@ -187,13 +187,14 @@ impl PropertySheet<'_> { info: None, held: self.held, sub_headers: self.sub_headers, + widest_digit: self.widest_digit, ui: &mut child, }; let result = body(&mut sheet); - let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, .. } = sheet; + let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, widest_digit, .. } = sheet; (self.named, self.seen, self.card, self.air_at, self.drawn_bottom, self.empty, self.sections) = (named, seen, card, air_at, drawn_bottom, empty, sections); - (self.held, self.sub_headers, self.scope, self.band_scope) = (held, sub_headers, scope, band_scope); + (self.held, self.sub_headers, self.scope, self.band_scope, self.widest_digit) = (held, sub_headers, scope, band_scope, widest_digit); let bottom = child.min_rect().bottom().max(top); let region = Rect::from_min_max(pos2(self.left, top), pos2(self.right, bottom)); @@ -305,6 +306,7 @@ impl PropertySheet<'_> { info: None, held: false, sub_headers: 0, + widest_digit: self.widest_digit, ui: &mut second_ui, }; let second_response = second_sheet.dropdown_button(second, &name(second_value), None::); diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 28b126c4..917449ed 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1017,6 +1017,97 @@ fn a_ramps_value_ends_on_the_linked_tiling_value() { assert_eq!(ramp.right(), tiling.right(), "the ramp's value ends at {}, Tiling's at {}", ramp.right(), tiling.right()); } +/// The row types whose values share a panel's value column +#[derive(Clone, Copy, Debug)] +enum ValueRow { + Signed, + Angle, + Factor, + Captioned, + Unbounded, +} + +/// One row on a sheet of its own, so no other row's value holds the column open +fn value_row(ui: &mut egui::Ui, (row, value): &mut (ValueRow, f32)) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "value row", |sheet| match row { + ValueRow::Signed => { + sheet.signed_slider("Value", value, -1.0..=1.0, 2); + } + ValueRow::Angle => { + sheet.relative_angle("Value", value, -180.0..=180.0); + } + ValueRow::Factor => { + sheet.factor_slider("Value", value, 4.0, 0.0..=2000.0); + } + ValueRow::Captioned => { + sheet.picture_sliders(&swatch(Color32::from_gray(128)), &mut [super::StackSlider::whole("Value", value, -1000.0..=1000.0)]); + } + ValueRow::Unbounded => { + sheet.slider("Value", value, 0.0..=f32::MAX, 2); + } + }); + }); +} + +fn value_row_track(harness: &Harness<'_, (ValueRow, f32)>) -> Rect { + harness.get_by_role_and_label(egui::Role::Slider, "Value").rect() +} + +/// A value gaining a minus sign or digits moves no track (the value column followed the widest number on show) +#[test] +fn tracks_stay_put_as_their_values_gain_a_sign_and_digits() { + let rows = [ + (ValueRow::Signed, [0.0, -0.88, 0.88, -1.0]), + (ValueRow::Angle, [0.0, -88.0, 88.0, -180.0]), + (ValueRow::Factor, [1.0, 16.0, 0.1, 8.0]), + (ValueRow::Captioned, [0.0, -888.0, 888.0, -1000.0]), + ]; + for (row, [first, rest @ ..]) in rows { + let mut harness = builder(Brightness::MediumDark).build_ui_state(value_row, (row, first)); + harness.run_steps(3); + let before = value_row_track(&harness); + + for value in rest { + harness.state_mut().1 = value; + harness.run_steps(3); + assert_eq!(value_row_track(&harness), before, "the {row:?} track moved at {value}"); + } + } +} + +/// A range far past anything readable reserves only so much, and its track still ends in the panel's right half +#[test] +fn a_huge_range_leaves_its_track_its_length() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(value_row, (ValueRow::Unbounded, 1.0)); + harness.run_steps(3); + + // The end, not the width: a squeezed track turns inside out and still reads as wide + let track = value_row_track(&harness); + assert!(track.right() > PANEL_WIDTH / 2.0, "the track ends at {}", track.right()); +} + +/// Dragging back from a value past the track's ends narrows the column only once the drag ends +#[test] +fn a_drag_from_a_typed_value_moves_no_track_until_release() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(value_row, (ValueRow::Factor, 1000.0)); + harness.run_steps(3); + let before = value_row_track(&harness); + + harness.drag_at(before.center()); + + // Past egui's longest click, the press becomes a drag + harness.run_steps(5); + assert!(harness.state().1 < 1000.0, "the press moved no value"); + assert_eq!(value_row_track(&harness), before, "the track moved under the drag"); + + harness.drop_at(before.center()); + harness.run_steps(3); + assert!(value_row_track(&harness).right() > before.right(), "the column stayed wide after the release"); +} + #[test] fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { let context = egui::Context::default(); From 0b0a5337f6bbf01ccfaabe79a8c6aedcd8769c0b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:49:35 +0000 Subject: [PATCH 119/128] Bring the current History step into view when a full history repeats a name --- crates/engine/src/painting.rs | 7 ++---- crates/engine/src/session.rs | 27 +++++++++++++++++++++--- crates/engine/tests/session.rs | 22 +++++++++++++++++++ crates/ui-egui/src/state.rs | 4 ++-- crates/ui-egui/src/windows.rs | 2 +- crates/ui-egui/tests/it/history_panel.rs | 17 ++++++++++++++- 6 files changed, 67 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index f2395365..6d26d432 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -555,7 +555,7 @@ impl Session { self.stroke.is_some() } - /// Commit the active stroke (one undo step). + /// Commit the active stroke as one undo step pub fn end_stroke(&mut self) -> Result<()> { let Some(mut stroke) = self.stroke.take() else { return Ok(()) }; let size = (stroke.canvas.alpha.width(), stroke.canvas.alpha.height()); @@ -586,10 +586,7 @@ impl Session { return Ok(()); } } - self.undo.push((stroke.label.clone(), stroke.before)); - if self.undo.len() > crate::session::MAX_HISTORY { - self.undo.remove(0); - } + self.add_step(stroke.label.clone(), stroke.before); self.redo.clear(); self.mark_modified(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index faf91c9a..9388a3ec 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -440,6 +440,8 @@ pub struct Session { pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, + /// New undo steps so far: it moves even when a full history keeps its length + pub(crate) steps_added: u64, /// Set by [`crate::execute`] from a command's `merge` param: its edits continue the previous /// undo step with the same label (a slider drag is one step however many values it applies). pub(crate) merge_edits: bool, @@ -548,6 +550,7 @@ impl Session { caches, undo: Vec::new(), redo: Vec::new(), + steps_added: 0, merge_edits: false, tool: ToolState::default(), active_set: 0, @@ -757,7 +760,7 @@ impl Session { if !self.painting_paths && let Some(draft) = self.path_draft.take() { - self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base)); + self.add_step(crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base); } // Point changes of an edited path undo only until another step lands @@ -767,11 +770,22 @@ impl Session { self.mark_modified(); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { - self.undo.push((label.to_string(), before)); + self.add_step(label.to_string(), before); } + + self.redo.clear(); + } + + /// Append an undo step, dropping the oldest ones from a full history + pub(crate) fn add_step(&mut self, label: String, before: Document) { + self.undo.push((label, before)); let over = self.undo.len().saturating_sub(MAX_HISTORY); self.undo.drain(..over); - self.redo.clear(); + + // A repaint of paths runs strokes on a temporary history, none of which is a step + if !self.painting_paths { + self.steps_added = self.steps_added.wrapping_add(1); + } } /// A change from `other` to the current document that is not an undo step (a path preview) @@ -975,6 +989,13 @@ impl Session { pub fn redo_labels(&self) -> Vec { self.redo.iter().rev().map(|(l, _)| l.clone()).collect() } + + /// Changes with every new undo step, not when a merged edit continues one + pub fn steps_added(&self) -> u64 { + self.steps_added + } + + /// The done steps, the oldest first pub fn history_labels(&self) -> Vec { self.undo.iter().map(|(l, _)| l.clone()).collect() } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 0fc0b848..d95c4358 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1155,3 +1155,25 @@ fn interleaved_sessions_render_depth_from_their_own_mesh() { assert!((hidden[0] - hidden[1]).abs() < 0.05, "the rear surface is occluded: {hidden:?}"); assert!(visible[0] > visible[1] + 0.5, "the rear surface is exposed: {visible:?}"); } + +/// A full history keeps its length and may repeat its newest name, so views follow the count of steps added +#[test] +fn a_full_history_still_counts_each_new_step() { + let mut s = session(); + for _ in 0..texturecraft_engine::session::MAX_HISTORY { + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + } + let (labels, added) = (s.history_labels(), s.steps_added()); + + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + + assert_eq!(s.history_labels(), labels); + assert!(s.steps_added() > added); + + // A path preview paints through strokes of its own, none of which is a step + let added = s.steps_added(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + + assert_eq!(s.history_labels(), labels); + assert_eq!(s.steps_added(), added); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3a053d2..d52bca3f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -744,9 +744,9 @@ pub struct UiState { /// Identity of the log that owns the selected rows. #[serde(skip)] pub log_id: u64, - /// The History panel's last shown container and steps (done, undone, newest name): a change scrolls to the current step + /// The History panel's last shown container and steps (added so far, done, undone): a change scrolls to the current step #[serde(skip)] - pub history_shown: Option<(egui::Id, usize, usize, Option)>, + pub history_shown: Option<(egui::Id, u64, usize, usize)>, /// The widest line of each Log tab, measured once per line #[serde(skip)] pub log_widths: crate::log_panel::LogWidthCache, diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index dbf29eeb..31299e0f 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -263,7 +263,7 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let total_rows = 1 + done.len() + undone.len(); // Only new steps or a new container (with its own scroll) bring the current one into view; a tool change keeps the user's scroll - let shown = Some((ui.make_persistent_id("history"), done.len(), undone.len(), done.last().cloned())); + let shown = Some((ui.make_persistent_id("history"), app.session.steps_added(), done.len(), undone.len())); let follow = app.ui.history_shown != shown; app.ui.history_shown = shown; diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index f9a82b9a..2880feac 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -293,7 +293,7 @@ fn scrolling_up_is_not_pulled_back() { assert!(!current_shown(&harness, "Rename layer")); } -/// Once the history is full, a new step keeps the step count; its new name still brings it into view +/// Once the history is full, a new step keeps the step count and still comes into view #[test] fn the_newest_step_shows_past_the_history_cap() { let steps = texturecraft_engine::session::MAX_HISTORY + 60; @@ -311,6 +311,21 @@ fn the_newest_step_shows_past_the_history_cap() { assert!(current_shown(&harness, &newest)); } +/// A full history with a new step named like the newest one keeps its counts and names, and still comes into view +#[test] +fn a_repeated_step_shows_past_the_history_cap() { + let mut harness = history_harness(long_session(texturecraft_engine::session::MAX_HISTORY)); + let capped = harness.state().session.history_labels(); + scroll_to_top(&mut harness); + assert!(!current_shown(&harness, "Rename layer")); + + execute(&mut harness.state_mut().session, "layer.rename", &json!({"name": "Once more"})).unwrap(); + harness.run_steps(4); + + assert_eq!(harness.state().session.history_labels(), capped); + assert!(current_shown(&harness, "Rename layer")); +} + /// A History list that moves to another container (rail popup to floating window) still shows the current step #[test] fn an_undocked_history_shows_the_newest_step() { From de7c45bde07391e39160dab2d24b0e90aa065025 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:59:07 +0000 Subject: [PATCH 120/128] Layers: answer review: solo picking, flattened folder anchors and instance opacity, pick list and R key edge cases --- crates/compose/src/eval.rs | 5 +- crates/engine/src/commands.rs | 7 +- crates/engine/src/layer_ops.rs | 36 ++++++- crates/engine/src/layer_pick.rs | 9 +- crates/engine/tests/it/flatten_folder.rs | 99 ++++++++++++++++++++ crates/engine/tests/it/layer_multi_select.rs | 16 ++++ crates/engine/tests/it/layer_pick.rs | 16 +++- crates/ui-egui/src/layer_pick_list.rs | 23 ++++- crates/ui-egui/src/layer_toolbar.rs | 2 +- crates/ui-egui/src/menus.rs | 6 +- crates/ui-egui/src/viewport.rs | 22 +++-- crates/ui-egui/tests/it/layer_toolbar.rs | 20 ++++ crates/ui-egui/tests/it/layers_panel.rs | 73 +++++++++++++++ docs/control-protocol.md | 3 +- docs/features.md | 3 +- 15 files changed, 313 insertions(+), 27 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 51dd1b50..ed437f09 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -5666,6 +5666,9 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt over_below.anchors_below(&below, (id, 0)); let stack_below = over_below.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + // The folder's mask goes first, as in a full render: its children can read its anchor points + let folder_mask = over_below.node_mask(node); + // The layers over an all-0 and an all-1 stack show how much of the stack they hide, and over the real stack what they show there let over = |mut stack: Acc| { let mut texel = over_below.clone(); @@ -5696,7 +5699,7 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt } if let Some(pixel) = mask.as_mut().and_then(|mask| mask.get_mut(offset * 2..offset * 2 + 2)) { - pixel.copy_from_slice(&[to_u16(over_below.node_mask(node)), u16::MAX]); + pixel.copy_from_slice(&[to_u16(folder_mask), u16::MAX]); } } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 04fc918c..82c18f99 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -193,13 +193,16 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } -/// [`check_enabled`] for a run with `params`, checking a command that takes `layer` as if the named layer were selected +/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (the effect's own) were selected fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { let refused = match check_enabled(spec, s) { Ok(()) => return Ok(()), Err(why) => why, }; - let named = u64p(params, "layer").map(texturecraft_core::LayerId).filter(|_| spec.params.contains("layer?")); + let id_param = |key: &str| u64p(params, key).map(texturecraft_core::LayerId); + let named = id_param("layer") + .filter(|_| spec.params.contains("layer?")) + .or_else(|| id_param("effect").filter(|_| spec.params.starts_with("{effect")).and_then(|effect| s.doc.project.effect(effect).map(|(owner, _)| owner))); let Some((id, ts)) = named.and_then(|id| s.doc.project.locate(id).map(|(ts, _, _)| (id, ts))) else { return Err(refused) }; if ts != s.ts() { return Err(refused); diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 587584bc..2a146a0a 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use texturecraft_compose::eval::FlatTile; use texturecraft_core::{ - Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source, + Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Sampling, Source, }; use texturecraft_formats::DecodedImage; use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; @@ -205,7 +205,7 @@ fn flatten(s: &mut Session, p: &Value) -> Result { // An instance flattens what it draws into a plain layer of its own let content = s.doc.project.content_layer(id).cloned().ok_or_else(|| EngineError::Other("the instance's source is missing".into()))?; if content.is_group() { - return flatten_folder(s, ts, &layer); + return flatten_folder(s, ts, &layer, &content); } s.update(); @@ -238,13 +238,18 @@ fn flatten(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": id.0 })) } -/// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did -fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { +/// Flatten `folder` (drawing `drawn`: itself, or an instance's source) of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did +fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> Result { // A fill reads its image again on every UV tile, so an image of several tiles would repeat on each if s.doc.project.texture_set(ts)?.uv_tiles.len() > 1 { return Err(EngineError::Other("flattening a folder of a texture set with several UV tiles is not supported yet".into())); } + // Hiding the folder takes its anchor points with it: whatever reads one from outside would change + if folder.visible && anchor_read_outside(&s.doc.project, folder.id) { + return Err(EngineError::Other("a layer outside the folder reads one of its anchor points: flattening would change it".into())); + } + s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); @@ -273,7 +278,7 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); layer.visible = folder.visible; for (channel, blend) in &mut layer.channels { - blend.opacity = folder.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); + blend.opacity = drawn.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); } if !mask.is_empty() { let paint = s.doc.project.alloc_id(); @@ -295,6 +300,27 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { Ok(json!({ "layer": flat.0 })) } +/// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away +fn anchor_read_outside(project: &Project, folder: LayerId) -> bool { + // An instance inside draws its source, which stays on screen where it is: the source can be such a reader + let mut hidden = std::collections::BTreeSet::new(); + let mut unvisited = vec![folder]; + while let Some(id) = unvisited.pop() { + if hidden.insert(id) { + unvisited.extend(project.layers.get(&id).into_iter().flat_map(|layer| layer.children().iter().copied())); + } + } + + let anchors = project + .render_tree(&[folder]) + .into_iter() + .filter_map(|id| project.layers.get(&id)) + .flat_map(|layer| layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter())) + .filter(|effect| matches!(effect.kind, EffectKind::Anchor)); + + anchors.flat_map(|anchor| project.anchor_readers(anchor.id)).any(|(reader, _)| !hidden.contains(&reader)) +} + /// One flattened tile of a channel: (tile, value + coverage data) type ChannelTile = ((u32, u32), Vec); diff --git a/crates/engine/src/layer_pick.rs b/crates/engine/src/layer_pick.rs index 80f84c7e..404b019c 100644 --- a/crates/engine/src/layer_pick.rs +++ b/crates/engine/src/layer_pick.rs @@ -25,7 +25,14 @@ impl Session { ViewMode::Channel(channel) => vec![channel], _ => self.doc.project.texture_set(ts).map(|set| set.channel_list()).unwrap_or_default(), }; - self.with_inputs(ts, |inputs| Some(texturecraft_compose::layers_at(inputs, &self.projector_depth_cache, texel, &shown))).unwrap_or_default() + // A solo hides layers on screen: they are not there to pick + let solo_view = self.solo_view(); + self.with_inputs(ts, |inputs| { + let inputs = + texturecraft_compose::Inputs { project: solo_view.as_ref().unwrap_or(inputs.project), block_scales: inputs.block_scales.clone(), ..*inputs }; + Some(texturecraft_compose::layers_at(&inputs, &self.projector_depth_cache, texel, &shown)) + }) + .unwrap_or_default() } /// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`]) diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 4933aa18..c97f46d0 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -39,6 +39,8 @@ fn composite(s: &mut Session) -> Vec<[f32; 3]> { } fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { + // `f32::max` drops a NaN operand, so a broken composite would compare as equal + assert!(a.iter().chain(b).flatten().all(|value| value.is_finite()), "the composite holds only finite values"); a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max) } @@ -190,3 +192,100 @@ fn flattening_a_folder_over_several_uv_tiles_is_refused() { assert!(flattened.is_err(), "refused"); assert_eq!(s.history_labels().len(), steps, "and nothing is changed"); } + +/// A child reading an anchor point of the folder's own mask keeps what it read +#[test] +fn a_flattened_folder_keeps_what_a_child_reads_from_the_folder_mask() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": folder, "target": "mask", "value": 0.4})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// An instance of a folder draws at its source's channel opacity, so it flattens at it +#[test] +fn a_flattened_folder_instance_keeps_the_folders_opacity() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.25})).unwrap(); + + // With the folder selected the instance would go inside it + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": instance})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// Hiding a folder takes its anchor points with it, so a layer outside reading one would change: refused, nothing touched +#[test] +fn flattening_a_folder_whose_anchor_point_is_read_outside_it_is_refused() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.0})).unwrap()); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": reader, "above": folder})).unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor, "anchorChannel": "roughness"})).unwrap(); + let project = s.doc.project.clone(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); + assert_eq!(s.doc.project, project, "nothing was added or hidden"); +} + +/// An instance's own mask goes with the hidden instance, and an outside layer stays on screen when only an instance of it sits in the folder +#[test] +fn flattening_is_refused_for_anchor_points_read_through_instances() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + let read = |s: &mut Session, anchor: u64| { + execute(s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap(); + }; + let anchor = |s: &mut Session, layer: u64, target: &str| { + execute(s, "effect.add.anchor", &json!({"layer": layer, "target": target})).unwrap()["effect"].as_u64().unwrap() + }; + + // The anchor point sits in the instance's own mask + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "layer.move", &json!({"layer": reader, "above": instance})).unwrap(); + execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap(); + let own = anchor(&mut s, instance, "mask"); + read(&mut s, own); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": instance})).is_err(), "the instance's own anchor point is read outside it"); + + // The reader is also instanced inside the folder, and reads an anchor point there + execute(&mut s, "layer.remove", &json!({"layer": instance})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": child})).unwrap(); + execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap(); + let inside = anchor(&mut s, child, "content"); + read(&mut s, inside); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err(), "the instanced layer still reads from outside"); +} diff --git a/crates/engine/tests/it/layer_multi_select.rs b/crates/engine/tests/it/layer_multi_select.rs index f6dfe110..9d37db3d 100644 --- a/crates/engine/tests/it/layer_multi_select.rs +++ b/crates/engine/tests/it/layer_multi_select.rs @@ -539,3 +539,19 @@ fn a_rows_controls_act_on_its_layer_with_no_layer_selected() { assert_eq!(s.selected_layer(), None, "the selection stays as it was"); assert!(execute(&mut s, "layer.visible", &Value::Null).is_err(), "with no layer named, nothing is selected to act on"); } + +#[test] +fn an_effect_rows_menu_moves_its_effect_with_no_layer_selected() { + let mut s = session(); + let [a, ..] = four(&mut s); + let add = + |s: &mut Session| execute(s, "effect.add.filter", &json!({"layer": a.0, "target": "content", "filter": "invert"})).unwrap()["effect"].as_u64().unwrap(); + let (lower, upper) = (add(&mut s), add(&mut s)); + s.selected.clear(); + + execute(&mut s, "effect.move", &json!({"effect": lower, "index": 1})).unwrap(); + + let order: Vec = s.doc.project.layer(a).unwrap().content_effects.iter().map(|effect| effect.id.0).collect(); + assert_eq!(order, [upper, lower]); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); +} diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs index 408ecc05..501b2267 100644 --- a/crates/engine/tests/it/layer_pick.rs +++ b/crates/engine/tests/it/layer_pick.rs @@ -1,10 +1,10 @@ //! Picking a layer on the mesh (R + click): the layers laying something down at a spot, top first, and selecting one of them use serde_json::{Value, json}; -use texturecraft_engine::core::LayerKind; +use texturecraft_engine::core::{LayerId, LayerKind}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::{Session, Solo, execute}; /// The middle of the sphere in the test viewport, where the lower paint layer is painted const MIDDLE: [f32; 2] = [200.0, 200.0]; @@ -134,3 +134,15 @@ fn a_pick_of_something_that_is_not_a_layer_id_is_refused() { assert!(reply.is_err(), "not silently replaced by the top layer: {reply:?}"); assert_eq!(s.selected_layer(), selected); } + +#[test] +fn a_soloed_layer_is_the_only_one_listed_and_picked() { + let (mut s, fill, ..) = stack(); + s.set_solo(Some(Solo { layer: LayerId(fill), ignore_mask: false })); + s.update(); + + let order: Vec = layers_at(&mut s, MIDDLE).iter().map(|(layer, _)| *layer).collect(); + + assert_eq!(order, [fill], "the layers solo hides are not on screen"); + assert_eq!(click(&mut s, MIDDLE), Some(fill)); +} diff --git a/crates/ui-egui/src/layer_pick_list.rs b/crates/ui-egui/src/layer_pick_list.rs index ab0f37c9..37165cf6 100644 --- a/crates/ui-egui/src/layer_pick_list.rs +++ b/crates/ui-egui/src/layer_pick_list.rs @@ -4,6 +4,7 @@ use egui::{Color32, Key, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; use serde_json::json; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::OrbitCamera; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::session::ViewMode; @@ -44,6 +45,8 @@ pub struct LayerPickList { point: Vec2, /// The view the list stays inside bounds: Rect, + /// The viewport size and camera `point` was taken in: a change to either closes the list + viewport_and_camera: (Vec2, OrbitCamera), /// The layers there, top first, each with the channels it changes there rows: Vec<(LayerId, Vec)>, /// The document revision the rows were read at: any change, or another project, closes the list @@ -62,7 +65,16 @@ pub(crate) fn click(app: &mut TextureCraftApp, at: Pos2, point: Vec2, bounds: Re let viewport = app.session.viewport; match app.session.layers_under(point, viewport) { Ok((_, rows)) if rows.len() > 1 => { - app.layer_pick_list = Some(LayerPickList { at, point, bounds, rows, revision: app.session.revision, opening: true, closing: false }); + app.layer_pick_list = Some(LayerPickList { + at, + point, + bounds, + viewport_and_camera: (viewport, app.session.camera), + rows, + revision: app.session.revision, + opening: true, + closing: false, + }); } _ => { app.run("layer.pickAt", json!({"x": point.x, "y": point.y, "viewport": [viewport.x, viewport.y]})); @@ -103,7 +115,7 @@ fn area_id() -> egui::Id { egui::Id::unique("layer_pick_list") } -/// Draws the open list; a row click selects its layer; Esc, a press outside or a document change closes it +/// Draws the open list; a row click selects its layer; Esc, a press outside or a document or view change closes it pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let (any_down, pressed_at, escape) = ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()), input.key_pressed(Key::Escape))); @@ -115,6 +127,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { app.layer_pick_list = None; } } + Some(list) if list.viewport_and_camera != (app.session.viewport, app.session.camera) => app.layer_pick_list = None, Some(list) if pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))) => list.closing = true, _ => {} } @@ -193,7 +206,11 @@ fn row(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, channels: &[Chann let thumbnail = Rect::from_min_size(pos2(rect.left() + ROW_PADDING, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); painter.rect_filled(thumbnail, crate::dock::THUMBNAIL_ROUNDING, tokens.field); let target = ThumbTarget::Content { layer, channel: app.ui.layer_channel }; - if let Some(texture) = app.layer_panel.texture_outside(ui.ctx(), &app.session, target) { + + // Rows scrolled out of view ask for no thumbnail + if ui.is_rect_visible(thumbnail) + && let Some(texture) = app.layer_panel.texture_outside(ui.ctx(), &app.session, target) + { painter.image(texture, thumbnail, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 1a80062a..ae07a213 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -275,7 +275,7 @@ fn picker_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, popup: Id if response.clicked() { resource_picker::toggle(ui.ctx(), popup); } - if response.hovered() || egui::Popup::is_id_open(ui.ctx(), popup) { + if response.hovered() || response.has_focus() || egui::Popup::is_id_open(ui.ctx(), popup) { ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_ROUNDING), tokens.button); } button_face(ui.painter(), rect, icon, tokens); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2b1712ff..cf941ff5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -555,11 +555,11 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } else if popup_open || export_input_active { // The open list or export input handles the key + } else if escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + // The list opens over an armed eyedropper or point pick, so it closes first + app.layer_pick_list = None; } else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; - } else if escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { - // The list opens over an armed point pick, so it closes first - app.layer_pick_list = None; } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { cancel_point_pick = true; } else if !escape_is_free { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index fc23cab0..fb846e9c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -920,7 +920,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::layer_pick_list::click(app, pointer, local(pointer), rect); } - // R + click and the list it opens come before an armed point or focus pick, including the press that closes the list + // R + click and the list it opens come before an armed pick (point, focus, eyedropper, ID color), including the press that closes the list let layer_pick_takes_click = r_held || crate::layer_pick_list::blocks_view_input(app); // A 3D generator's armed point pick: a click sets the point there instead of painting @@ -984,6 +984,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::screen_pick::SwatchColor::over_model(ui.ctx(), *color); } if !alt + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(position) = response.interact_pointer_pos() { @@ -1110,11 +1111,14 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.session.continue_stroke(local(pointer), pressure); remember_line_anchor(app, local(pointer)); } - if response.drag_stopped_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } + } + + // A released drag ends its stroke as one undo step, also when a key held meanwhile blocks painting + if response.drag_stopped_by(PointerButton::Primary) + && app.session.stroke_active() + && let Err(error) = app.session.end_stroke() + { + app.toast(error.to_string(), true); } let set_hover = app @@ -1796,7 +1800,7 @@ fn layer_pick_key(app: &TextureCraftApp, ui: &Ui) -> bool { app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(PICK_LAYER_KEY)) && !ui.ctx().egui_wants_keyboard_input() } -/// The pointing hand and a label beside it naming the layer under it while the layer pick key is held +/// The pointing hand and a label beside it naming the layer under it while the layer pick key is held, announced as it changes fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); let tokens = Tokens::get(ui.ctx()); @@ -1813,6 +1817,10 @@ fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { egui::StrokeKind::Inside, ); painter.galley(at, galley, tokens.text); + + let announced = ui.interact(frame, egui::Id::unique("layer_pick_hint"), egui::Sense::empty()); + announced.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, label)); + ui.ctx().accesskit_node_builder(announced.id, |node| node.set_live(egui::accesskit::Live::Polite)); } /// How far the layer pick label sits right of and below the pointer, and the room around its text (points) diff --git a/crates/ui-egui/tests/it/layer_toolbar.rs b/crates/ui-egui/tests/it/layer_toolbar.rs index c71a6670..2fb95c72 100644 --- a/crates/ui-egui/tests/it/layer_toolbar.rs +++ b/crates/ui-egui/tests/it/layer_toolbar.rs @@ -251,3 +251,23 @@ fn the_channel_list_starts_on_material_and_picks_a_channel_or_material_again() { assert!(harness.state().ui.layer_material_view, "Material shows the whole material again"); assert_eq!(harness.state().ui.layer_channel, Channel::Roughness, "the rows keep the last channel's blending"); } + +#[test] +fn add_smart_material_shows_the_keyboard_focus() { + let (mut harness, _) = app(); + let button = harness.get_by_role_and_label(Role::Button, "Add smart material").rect(); + let fills = |harness: &Harness<'_, TextureCraftApp>| { + harness + .output() + .shapes + .iter() + .filter(|clipped| matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.rect == button && shape.fill != egui::Color32::TRANSPARENT)) + .count() + }; + assert_eq!(fills(&harness), 0, "no face at rest"); + + harness.get_by_role_and_label(Role::Button, "Add smart material").focus(); + harness.run_steps(3); + + assert!(fills(&harness) > 0, "the focused button is drawn"); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 7efe5ba0..d057cf51 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -933,3 +933,76 @@ fn a_press_on_the_2d_view_that_closes_the_layer_pick_list_does_not_paint() { assert!(h.state().session.history_labels().len() > steps, "the next press paints there"); } + +/// The list holds the spot it was opened on: a view that changed size or camera no longer has it under that point +#[test] +fn the_layer_pick_list_closes_when_the_view_changes() { + let (mut h, _) = harness(); + two_fills(&mut h); + open_pick_list(&mut h); + + h.state_mut().session.camera.yaw += 0.5; + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the camera turned"); + + open_pick_list(&mut h); + h.set_size(egui::vec2(1300.0, 1000.0)); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the view was resized"); +} + +#[test] +fn r_and_a_click_leaves_an_armed_eyedropper_armed() { + let (mut h, _) = harness(); + two_fills(&mut h); + h.state_mut().picking_color = Some(egui::Id::unique("armed eyedropper")); + h.run_steps(SETTLE_FRAMES); + assert!(h.state().picking_color.is_some(), "armed before the list opens"); + + open_pick_list(&mut h); + + assert!(h.state().picking_color.is_some()); + + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list first"); + assert!(h.state().picking_color.is_some(), "and leaves the eyedropper armed"); +} + +#[test] +fn a_stroke_released_while_r_is_held_ends() { + let (mut h, _) = harness(); + execute(&mut h.state_mut().session, "layer.add.paint", &Value::Null).unwrap(); + h.run_steps(SETTLE_FRAMES); + let middle = h.state().viewport_rect.center(); + let end = middle + egui::vec2(60.0, 0.0); + h.drag_at(middle); + h.run_steps(1); + h.hover_at(middle + egui::vec2(30.0, 0.0)); + h.run_steps(1); + assert!(h.state().session.stroke_active(), "the stroke is under way"); + + h.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.hover_at(end); + h.run_steps(1); + h.drop_at(end); + h.run_steps(SETTLE_FRAMES); + + assert!(!h.state().session.stroke_active()); +} + +#[test] +fn the_label_under_the_pointer_is_announced_while_r_is_held() { + let (mut h, _) = harness(); + let view = two_fills(&mut h); + h.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.hover_at(view.center()); + h.run_steps(SETTLE_FRAMES); + + let announced = h.query_all(by().label_contains("Upper fill +")).any(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite); + + assert!(announced, "the layer's name is announced without moving the focus"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2af71ba5..5c007545 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -44,9 +44,10 @@ the named layer of the active texture set, so it runs even with nothing selected `layer.layersAt {x, y, viewport?}` lists the layers laying something down where the mesh is under a viewport point, top first (`{layers: [{layer, name, channels}]}`, in the shown channels). `layer.pickAt {x, y, viewport?, layer?}` selects the top one, or `layer` if it is listed there. +While a layer is soloed, both see only what the solo shows. `layer.flatten {layer}` on a folder replies with a new fill layer above it holding the folder's result as image resources, and hides the folder; it is refused for a texture set with several UV -tiles. +tiles, and for a visible folder holding an anchor point that a layer outside it reads. `mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the texture set's resolution: black where the mesh does not cover the texture, with the orientation diff --git a/docs/features.md b/docs/features.md index ec08683e..3d380d78 100644 --- a/docs/features.md +++ b/docs/features.md @@ -54,7 +54,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Flatten folder:** a folder's right-click menu (or Ctrl+M) adds a fill layer holding the folder's result as one image per channel, with the folder's mask painted into the new layer's mask; the folder is kept and hidden. Layers that blend over the layers below the folder are baked - as they look over them at that moment. Not available for a texture set with several UV tiles. + as they look over them at that moment. Not available for a texture set with several UV tiles, or + while a layer outside the folder reads one of its anchor points. - **Effect rows:** a generator is named after its kind; the cross removes an effect; the menu's Move up / down / to top / to bottom and Alt+Up / Alt+Down reorder its stack. - **Smart materials from the Layers panel:** the toolbar's button opens a picker of the built-in From 226e2de43a60719fd007035bcfc72dd66ad2f80f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:49:21 +0000 Subject: [PATCH 121/128] Keep the current History step on screen when the list gets shorter --- crates/ui-egui/src/state.rs | 4 +++ crates/ui-egui/src/windows.rs | 19 +++++++--- crates/ui-egui/tests/it/history_panel.rs | 44 ++++++++++++++++++++++-- 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d52bca3f..7429a617 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -747,6 +747,9 @@ pub struct UiState { /// The History panel's last shown container and steps (added so far, done, undone): a change scrolls to the current step #[serde(skip)] pub history_shown: Option<(egui::Id, u64, usize, usize)>, + /// The History list's last height in points and whether the current step was on screen in it + #[serde(skip)] + pub history_view: Option<(f32, bool)>, /// The widest line of each Log tab, measured once per line #[serde(skip)] pub log_widths: crate::log_panel::LogWidthCache, @@ -919,6 +922,7 @@ impl Default for UiState { log_anchor: None, log_id: 0, history_shown: None, + history_view: None, log_widths: Default::default(), } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 31299e0f..6078a4c7 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -262,18 +262,23 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let done_count = done.len() as i64; let total_rows = 1 + done.len() + undone.len(); - // Only new steps or a new container (with its own scroll) bring the current one into view; a tool change keeps the user's scroll + // New steps or a new container (with its own scroll) bring the current one into view; a tool change keeps the user's scroll let shown = Some((ui.make_persistent_id("history"), app.session.steps_added(), done.len(), undone.len())); - let follow = app.ui.history_shown != shown; + // A list made shorter keeps the current step on screen if it was there; one the user scrolled away from it stays put + let height = ui.available_height(); + let shrunk = app.ui.history_view.is_some_and(|(height_before, was_in_view)| was_in_view && height < height_before); + let follow = app.ui.history_shown != shown || shrunk; app.ui.history_shown = shown; // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative let mut jump = 0i64; - let area = egui::ScrollArea::vertical().id_salt("history").auto_shrink([false, false]); - crate::log_panel::panel_rows(ui, area, HISTORY_ROW_HEIGHT, total_rows, |ui, range| { + // Not animated: a scroll request then shows in the offset returned this frame, which a resize by dragging relies on + let area = egui::ScrollArea::vertical().id_salt("history").auto_shrink([false, false]).animated(false); + let current_row_top = done.len() as f32 * HISTORY_ROW_HEIGHT; + let list = crate::log_panel::panel_rows(ui, area, HISTORY_ROW_HEIGHT, total_rows, |ui, range| { if follow { - let top = ui.max_rect().top() + (done.len() as f32 - range.start as f32) * HISTORY_ROW_HEIGHT; + let top = ui.max_rect().top() + current_row_top - range.start as f32 * HISTORY_ROW_HEIGHT; let current = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=top + HISTORY_ROW_HEIGHT); ui.scroll_to_rect_animation(current, None, egui::style::ScrollAnimation::none()); } @@ -295,6 +300,10 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { } }); + let current_top_in_view = current_row_top - list.state.clamped_offset().y; + let current_in_view = current_top_in_view < list.inner_rect.height() && current_top_in_view + HISTORY_ROW_HEIGHT > 0.0; + app.ui.history_view = Some((height, current_in_view)); + if jump > 0 { app.run("edit.undo", json!({ "steps": jump })); } else if jump < 0 { diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index 2880feac..ade144d7 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -1,14 +1,15 @@ //! The History panel: a click on a step goes back or forward to it, the current step is marked and kept in view +use craft_behavior::dock::Action; use egui::accesskit::Toggled; -use egui::{Event, Key, Modifiers, vec2}; +use egui::{Event, Key, Modifiers, Rect, pos2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::docking::{Dock, Panel, permissions}; /// Show document history so row clicks exercise the same command dispatch as the application fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { @@ -326,6 +327,45 @@ fn a_repeated_step_shows_past_the_history_cap() { assert!(current_shown(&harness, "Rename layer")); } +/// A History window short enough to cut many rows off the list +const SHORT_HEIGHT: f32 = 220.0; + +/// Show History in a floating window `height` points tall, as dragging its bottom edge does +fn set_history_height(harness: &mut Harness<'_, TextureCraftApp>, height: f32) { + let rect = Rect::from_min_size(pos2(960.0, 190.0), vec2(300.0, height)); + let mut workspace = harness.state().ui.dock.workspace().clone(); + workspace.apply_all([Action::float(Panel::History, rect)], false, permissions).unwrap(); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); +} + +/// A list shortened on every frame, as a resize by dragging does, keeps the current step on screen without a new step +#[test] +fn a_history_shortened_over_several_frames_keeps_the_current_step_on_screen() { + let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + + // Each height is more than a row shorter than the one before, from the 380 points the window opens at + for height in [340.0, 300.0, 260.0, SHORT_HEIGHT] { + set_history_height(&mut harness, height); + harness.step(); + } + harness.run_steps(4); + + assert!(current_shown(&harness, "Rename layer")); +} + +/// A list the user scrolled away from the current step stays there when it is made shorter +#[test] +fn shortening_a_scrolled_up_history_keeps_the_scroll() { + let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + scroll_to_top(&mut harness); + + set_history_height(&mut harness, SHORT_HEIGHT); + harness.run_steps(4); + + assert!(!current_shown(&harness, "Rename layer")); + assert!(harness.query_by_label("Project opened").is_some()); +} + /// A History list that moves to another container (rail popup to floating window) still shows the current step #[test] fn an_undocked_history_shows_the_newest_step() { From 5a9dbb5340dc71068224f7ca769904f610c479f8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:22:54 +0000 Subject: [PATCH 122/128] Layers: answer review follow-up: instances drawing a folder's anchor readers, effect rows of another set's source --- crates/engine/src/commands.rs | 19 +++++---- crates/engine/src/layer_ops.rs | 52 ++++++++++++++++++++---- crates/engine/tests/it/flatten_folder.rs | 39 ++++++++++++++++++ crates/engine/tests/it/instances.rs | 18 ++++++++ 4 files changed, 113 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 82c18f99..f8ca06ea 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -193,20 +193,23 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } -/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (the effect's own) were selected +/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (one drawing the effect) were selected fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { let refused = match check_enabled(spec, s) { Ok(()) => return Ok(()), Err(why) => why, }; let id_param = |key: &str| u64p(params, key).map(texturecraft_core::LayerId); - let named = id_param("layer") - .filter(|_| spec.params.contains("layer?")) - .or_else(|| id_param("effect").filter(|_| spec.params.starts_with("{effect")).and_then(|effect| s.doc.project.effect(effect).map(|(owner, _)| owner))); - let Some((id, ts)) = named.and_then(|id| s.doc.project.locate(id).map(|(ts, _, _)| (id, ts))) else { return Err(refused) }; - if ts != s.ts() { - return Err(refused); - } + let ts = s.ts(); + let named = id_param("layer").filter(|_| spec.params.contains("layer?")).filter(|id| s.doc.project.locate(*id).is_some_and(|(found, _, _)| found == ts)); + + // An effect's layer may sit in another texture set, drawn here by an instance + let drawing_effect = || { + let effect = id_param("effect").filter(|_| spec.params.starts_with("{effect"))?; + let owner = s.doc.project.effect(effect)?.0; + s.doc.project.walk(ts).into_iter().map(|(id, _)| id).find(|id| s.doc.project.render_tree(&[*id]).contains(&owner)) + }; + let Some(id) = named.or_else(drawing_effect) else { return Err(refused) }; let selected = s.selected.insert(ts, id); let named_refused = check_enabled(spec, s); diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 2a146a0a..d4310282 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -1,6 +1,8 @@ //! Layer clipboard (copy, cut, paste across texture sets), flatten, and resampling of painted //! pixels when a texture set changes size. +use std::collections::BTreeSet; + use serde_json::{Value, json}; use texturecraft_compose::eval::FlatTile; use texturecraft_core::{ @@ -303,7 +305,7 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> /// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away fn anchor_read_outside(project: &Project, folder: LayerId) -> bool { // An instance inside draws its source, which stays on screen where it is: the source can be such a reader - let mut hidden = std::collections::BTreeSet::new(); + let mut hidden = BTreeSet::new(); let mut unvisited = vec![folder]; while let Some(id) = unvisited.pop() { if hidden.insert(id) { @@ -311,14 +313,50 @@ fn anchor_read_outside(project: &Project, folder: LayerId) -> bool { } } - let anchors = project - .render_tree(&[folder]) + // An instance staying on screen draws its source again, there with only the anchor points it draws itself + let drawn_again: Vec<_> = project + .locate(folder) .into_iter() - .filter_map(|id| project.layers.get(&id)) - .flat_map(|layer| layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter())) - .filter(|effect| matches!(effect.kind, EffectKind::Anchor)); + .flat_map(|(ts, _, _)| project.walk(ts)) + .filter(|(id, _)| !hidden.contains(id) && project.layers.get(id).is_some_and(|layer| layer.instance_source().is_some())) + .map(|(id, _)| mask_and_content_owners(project, id)) + .collect(); - anchors.flat_map(|anchor| project.anchor_readers(anchor.id)).any(|(reader, _)| !hidden.contains(&reader)) + let anchors = project.render_tree(&[folder]).into_iter().filter_map(|id| project.layers.get(&id)).flat_map(|layer| { + let effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter()); + effects.filter(|effect| matches!(effect.kind, EffectKind::Anchor)).map(|effect| (layer.id, effect.id)) + }); + + anchors.into_iter().any(|(owner, anchor)| { + project.anchor_readers(anchor).into_iter().any(|(reader, reading)| { + !hidden.contains(&reader) || drawn_again.iter().any(|drawn| draws(project, drawn, reader, reading) && !draws(project, drawn, owner, Some(anchor))) + }) + }) +} + +/// The layers whose masks and the layers whose content drawing layer `root` reads: an instance's own mask stands in for its source's +fn mask_and_content_owners(project: &Project, root: LayerId) -> (BTreeSet, BTreeSet) { + let (mut masks, mut contents, mut visited) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); + let mut unvisited = vec![root]; + while let Some(id) = unvisited.pop() { + if !visited.insert(id) { + continue; + } + + masks.insert(project.mask_owner(id)); + if let Some(content) = project.content_layer(id) { + contents.insert(content.id); + unvisited.extend(content.children().iter().copied()); + } + } + (masks, contents) +} + +/// Whether a draw reading `owners` (see [`mask_and_content_owners`]) includes `effect` of layer `layer`, or the layer's own fill when None +fn draws(project: &Project, (masks, contents): &(BTreeSet, BTreeSet), layer: LayerId, effect: Option) -> bool { + let mask = project.layers.get(&layer).and_then(|layer| layer.mask.as_ref()); + let in_mask = mask.is_some_and(|mask| mask.effects.iter().any(|other| Some(other.id) == effect)); + if in_mask { masks.contains(&layer) } else { contents.contains(&layer) } } /// One flattened tile of a channel: (tile, value + coverage data) diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index c97f46d0..7afb0f3b 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -289,3 +289,42 @@ fn flattening_is_refused_for_anchor_points_read_through_instances() { assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err(), "the instanced layer still reads from outside"); } + +/// An instance above the folder draws a reader from inside it, without the anchor point that reader reads +#[test] +fn flattening_is_refused_when_an_instance_outside_draws_a_reader_from_inside() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": child})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + let project = s.doc.project.clone(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); + assert_eq!(s.doc.project, project, "nothing was added or hidden"); +} + +/// An instance with its own mask draws the folder's children without the folder's mask and its anchor points +#[test] +fn flattening_is_refused_when_a_masked_instance_draws_a_reader_of_the_folder_mask() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.white", &json!({"layer": folder})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); +} diff --git a/crates/engine/tests/it/instances.rs b/crates/engine/tests/it/instances.rs index 099a41b0..d2be8aae 100644 --- a/crates/engine/tests/it/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -276,3 +276,21 @@ fn budgeted_updates_spread_work_and_end_identical() { assert!(s.caches[0].composite == full, "chunked compositing gives the same pixels"); assert!(s.memory().composites > 0); } + +#[test] +fn an_inherited_mask_effect_moves_from_another_texture_set_with_no_layer_selected() { + let mut s = session(); + let source = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &json!({"layer": source.0})).unwrap(); + let add = |s: &mut Session| id(execute(s, "effect.add.fill", &json!({"layer": source.0, "target": "mask", "value": 0.5})).unwrap(), "effect"); + let (lower, upper) = (add(&mut s), add(&mut s)); + execute(&mut s, "layer.instance", &json!({"layer": source.0, "ts": 1})).unwrap(); + s.active_set = 1; + s.selected.clear(); + + execute(&mut s, "effect.move", &json!({"effect": lower.0, "index": 1})).unwrap(); + + let order: Vec = s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(order, [upper, lower]); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); +} From 2f736f3cb8eb212458930c8d5123da7a6b82918d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:28:46 +0000 Subject: [PATCH 123/128] Layers: answer the third review: image alpha once on cropped framed fills, folder flatten keeps compared channels and refuses clipped results, effect row and hover label bounds, nameable library files --- crates/compose/src/eval.rs | 88 ++++++++++++++++++---- crates/compose/src/flatten_folder_error.rs | 8 ++ crates/compose/src/lib.rs | 2 + crates/engine/src/layer_ops.rs | 13 +++- crates/engine/tests/it/flatten_folder.rs | 48 ++++++++++++ crates/ui-egui/src/dock.rs | 7 +- crates/ui-egui/src/layer_toolbar.rs | 28 ++++++- crates/ui-egui/src/viewport.rs | 30 +++++++- crates/ui-egui/tests/it/layers_panel.rs | 3 +- docs/control-protocol.md | 3 +- 10 files changed, 206 insertions(+), 24 deletions(-) create mode 100644 crates/compose/src/flatten_folder_error.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 932ca603..5d8d8120 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -34,6 +34,7 @@ use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_depth::FillDepth; use crate::fill_place::FillPlace; +use crate::flatten_folder_error::FlattenFolderError; use crate::generator_maps::GeneratorMaps; use crate::held_fields::HeldFields; use crate::mask_gray::MaskGray; @@ -3504,7 +3505,8 @@ impl<'a, 'b> Texel<'a, 'b> { }; let (coords, cover) = self.projected(proj); - if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha { + // With alpha coverage each channel's own image alpha covers it, in [`Texel::fill_texel`] + if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha || sampling.alpha_coverage { return cover * self.tile_cover(proj, &coords, sampling); } @@ -5642,11 +5644,17 @@ fn normal_over(under: &[f32; 3], shown: &[f32; 3], coverage: f32, comps: usize, /// One tile of a flattened folder's mask: (tile, mask value + coverage data) pub type FlatMaskTile = ((u32, u32), Vec); -/// Flatten folder `id`: what its visible layers lay down (premultiplied value and coverage tiles per enabled channel, as [`flatten_layer`]) without its mask or opacity, and its mask and submesh limits as mask tiles (none when it has neither); None for a layer that is not a folder -pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<(Vec, Vec)> { - let set = inputs.project.texture_set(inputs.ts).ok()?; - if !inputs.project.content_layer(id)?.is_group() { - return None; +/// How far past its channel's range a folder's result may sit as rounding noise +const RANGE_TOLERANCE: f32 = 1e-3; + +/// A flattened folder: its content tiles and its mask tiles +pub type FlattenedFolder = (Vec, Vec); + +/// Flatten folder `id`: what its visible layers lay down (premultiplied value and coverage tiles per enabled channel and per channel a mask compares, as [`flatten_layer`]) without its mask or opacity, and its mask and submesh limits as mask tiles (none when it has neither) +pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Result { + let set = inputs.project.texture_set(inputs.ts).map_err(|_| FlattenFolderError::NotAFolder)?; + if !inputs.project.content_layer(id).is_some_and(Layer::is_group) { + return Err(FlattenFolderError::NotAFolder); } let channels: Vec = set.channel_list(); @@ -5663,12 +5671,13 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt let planned_channels = evaluation_channels(&visible_inputs, channels.clone()); let fields = evaluation_fields(&visible_inputs, &planned_channels, tiles); - let out: Vec<(Vec, Option)> = tiles + // None for a tile where the folder's result leaves the range its image can hold + let out: Option, Option)>> = tiles .par_iter() .map(|&(tx, ty)| { - let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); - let Some(node) = nodes.first() else { return (Vec::new(), None) }; - let Content::Group(children) = &node.content else { return (Vec::new(), None) }; + let nodes = plan(&visible_inputs, &[id], &planned_channels, tx, ty, 0, Some(&fields)); + let Some(node) = nodes.first() else { return Some((Vec::new(), None)) }; + let Content::Group(children) = &node.content else { return Some((Vec::new(), None)) }; let below = stack_plan_below(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields)); // One value + coverage buffer per channel the folder plans; signed channels start at their middle @@ -5713,7 +5722,22 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt let comps = planned.comps.min(3); let hidden = low.iter().zip(high).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; let range = if channel.kind() == ChannelKind::Signed { (-1.0, 1.0) } else { (0.0, 1.0) }; - let Some(premultiplied) = normal_over(under, shown, hidden.clamp(0.0, 1.0), comps, range) else { continue }; + let premultiplied = normal_over(under, shown, hidden.clamp(0.0, 1.0), comps, range); + + // A change no Normal layer within the channel's range shows; where the folder's mask hides it, nothing is lost + let clipped = match premultiplied { + Some([.., coverage]) => premultiplied + .iter() + .flatten() + .take(comps) + .any(|value| *value < range.0 * coverage - RANGE_TOLERANCE || *value > range.1 * coverage + RANGE_TOLERANCE), + None => shown.iter().zip(under).take(comps).any(|(shown, under)| (shown - under).abs() > RANGE_TOLERANCE), + }; + if clipped && folder_mask > 0.0 { + return None; + } + + let Some(premultiplied) = premultiplied else { continue }; *laid_down = true; let Some(pixel) = buffer.get_mut(offset * (planned.comps + 1)..(offset + 1) * (planned.comps + 1)) else { continue }; @@ -5732,12 +5756,12 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt } let content = buffers.into_iter().filter(|(_, _, laid_down)| *laid_down).map(|(channel, buffer, _)| (channel, (tx, ty), buffer)).collect(); - (content, mask.map(|mask| ((tx, ty), mask))) + Some((content, mask.map(|mask| ((tx, ty), mask)))) }) .collect(); - let (content, masks): (Vec<_>, Vec<_>) = out.into_iter().unzip(); - Some((content.into_iter().flatten().collect(), masks.into_iter().flatten().collect())) + let (content, masks): (Vec<_>, Vec<_>) = out.ok_or(FlattenFolderError::ValueOutOfRange)?.into_iter().unzip(); + Ok((content.into_iter().flatten().collect(), masks.into_iter().flatten().collect())) } #[cfg(test)] @@ -7874,6 +7898,42 @@ soft {soft:?}" assert!(raised.iter().zip(flattened).any(|(raised, flat)| (*raised - flat).abs() > 1e-4)); } + #[test] + fn a_cropped_framed_fill_applies_its_image_alpha_once_with_alpha_coverage() { + let mut f = fixture(); + let mut images = ImageStore::default(); + images.insert("half".to_owned(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 1.0, 1.0, 0.5]], false))); + let id = fill_layer(&mut f.project, [0.0; 3], 0.5); + let LayerKind::Fill(fill) = &mut f.project.layer_mut(id).unwrap().kind else { panic!("fill fixture") }; + fill.sources.insert(Channel::BaseColor, Source::image("half")); + fill.projection = Projection::Planar { + scale: 1.0, + axis: 1, + offset: [0.0; 3], + uv: Default::default(), + projector: texturecraft_core::Projector { crop: texturecraft_core::ShapeCrop::Cropped, ..Default::default() }, + placed: Some(texturecraft_core::Decal { + center: [0.0; 3], + normal: [0.0, 1.0, 0.0], + up: [0.0, 0.0, -1.0], + size: [4.0, 4.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 1.0, + symmetry: None, + flip: [false; 2], + }), + }; + let plain = run_with_images(&f, None, &images).value(Channel::BaseColor, 32, 32); + let LayerKind::Fill(fill) = &mut f.project.layer_mut(id).unwrap().kind else { panic!("fill fixture") }; + fill.sampling.alpha_coverage = true; + + let covered = run_with_images(&f, None, &images).value(Channel::BaseColor, 32, 32); + + assert!(!close(plain, Channel::BaseColor.default_value()), "the fill lands on the plane"); + assert!(close(covered, plain), "alpha coverage {covered:?}, image alpha {plain:?}"); + } + #[test] fn micro_height_uses_the_live_stroke_and_restores_the_committed_anchor_after_cancel() { let (mut fixture, images) = micro_height_fixture(); diff --git a/crates/compose/src/flatten_folder_error.rs b/crates/compose/src/flatten_folder_error.rs new file mode 100644 index 00000000..40b0bac5 --- /dev/null +++ b/crates/compose/src/flatten_folder_error.rs @@ -0,0 +1,8 @@ +/// Why a folder can't be flattened +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlattenFolderError { + NotAFolder, + + /// Its layers add up past what an image holds, which baking would clip + ValueOutOfRange, +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a393a519..b52fade5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -27,6 +27,7 @@ pub mod fill_copies; pub mod fill_copy; mod fill_depth; mod fill_place; +mod flatten_folder_error; pub mod frame_placement; mod fur_lock; mod generator_maps; @@ -81,6 +82,7 @@ pub use eval::{ composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, layers_at, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; +pub use flatten_folder_error::FlattenFolderError; pub use mask_gray::MaskGray; pub use padding_maps::PaddingMaps; pub use pattern_context::PatternContext; diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index d4310282..7a755bae 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -4,6 +4,7 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; +use texturecraft_compose::FlattenFolderError; use texturecraft_compose::eval::FlatTile; use texturecraft_core::{ Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Sampling, Source, @@ -255,9 +256,15 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); - let (content, mask) = s - .with_inputs(ts, |inputs| texturecraft_compose::flatten_folder(inputs, folder.id, &tiles)) - .ok_or_else(|| EngineError::Other("nothing to flatten".into()))?; + let flattened = s + .with_inputs(ts, |inputs| Some(texturecraft_compose::flatten_folder(inputs, folder.id, &tiles))) + .ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let (content, mask) = flattened.map_err(|error| { + EngineError::Other(match error { + FlattenFolderError::NotAFolder => "nothing to flatten".into(), + FlattenFolderError::ValueOutOfRange => "the folder's layers go past what an image holds: flattening would clip them".into(), + }) + })?; let images = channel_images(content, size)?; if images.is_empty() { return Err(EngineError::Other("the folder shows nothing to flatten".into())); diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 7afb0f3b..ca438fb8 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -328,3 +328,51 @@ fn flattening_is_refused_when_a_masked_instance_draws_a_reader_of_the_folder_mas assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); } + +/// A mask comparing a channel the set no longer has reads the folder's layers holding only that channel, before and after +#[test] +fn a_flattened_folder_keeps_what_its_masks_compare_in_a_removed_channel() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap(); + stroke(&mut s, 40, [[160, 200], [240, 200]]); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap()); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": top})).unwrap(); + execute(&mut s, "textureSet.channel.remove", &json!({"channel": "height"})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// Linear dodge can take a folder's result past what an image holds, which the folder's opacity then mixes back: refused, not clipped +#[test] +fn flattening_a_folder_adding_up_past_white_is_refused() { + // The last folder's mask hides everything it adds, so nothing is clipped + for (added, masked, overflows) in [(0.25, false, false), (0.75, false, true), (0.75, true, false)] { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2], "roughness": 0.5})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.1, 0.1, 0.1], "roughness": added})).unwrap()); + execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": "roughness", "mode": "linearDodge"})).unwrap(); + execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.5})).unwrap(); + if masked { + execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap(); + } + let before = composite(&mut s); + let project = s.doc.project.clone(); + + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + if flattened.is_ok() { + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before)); + } + assert_eq!(flattened.is_err(), overflows, "added roughness {added}, masked {masked}: {flattened:?}"); + if overflows { + assert_eq!(s.doc.project, project, "nothing was added or hidden"); + } + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3addda00..4f0f62fc 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -311,7 +311,8 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { /// Preserve the effect eye, preview and a readable name before spending space on nesting. fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 { - (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) + let remove_column = ROW_CONTROL_GAP + EFFECT_REMOVE_WIDTH + ROW_RIGHT_PADDING; + (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - remove_column).max(0.0)) } /// X of the centre of the eye column at indent `level` in a row spanning from `left`. @@ -2746,7 +2747,9 @@ mod layer_layout_tests { let preview_left = 7.0 + indent + 22.0; let name_left = preview_left + preview + 8.0; assert!(eye_right < preview_left); - assert!(name_left + 20.0 <= width - 6.0 + 0.001); + // The cross takes the row's right end, so the name ends before it + let name_end = width - ROW_CONTROL_GAP - EFFECT_REMOVE_WIDTH - ROW_RIGHT_PADDING; + assert!(name_left + MIN_NAME_WIDTH <= name_end + 0.001, "width {width}, level {level}, preview {preview}"); } } } diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 9bb066f4..a47beced 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -534,7 +534,8 @@ fn smart_material_tabs(library: &[PathBuf]) -> Vec = library .iter() - .filter(|path| !crate::shelf::is_saved_mask(path)) + // `material.load` takes the path as text: a file name that isn't text can't be named to it + .filter(|path| !crate::shelf::is_saved_mask(path) && path.to_str().is_some()) .map(|path| ResourcePickerItem { id: SmartMaterialChoice::Saved(path.clone()), label: crate::shelf::saved_material_name(path).to_owned(), @@ -548,3 +549,28 @@ fn smart_material_tabs(library: &[PathBuf]) -> Vec = tabs + .iter() + .flat_map(|tab| &tab.groups) + .flat_map(|group| &group.items) + .filter_map(|item| match &item.id { + SmartMaterialChoice::Saved(path) => Some(path.as_path()), + SmartMaterialChoice::BuiltIn(_) => None, + }) + .collect(); + + assert_eq!(saved, [std::path::Path::new("/library/steel.tcmat")]); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1265143c..56480a65 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1815,8 +1815,8 @@ fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { let painter = ui.painter_at(rect); let font = egui::TextStyle::Small.resolve(ui.style()); let galley = painter.layout_no_wrap(label.to_owned(), font, tokens.text); - let at = hover + vec2(LAYER_PICK_HINT_OFFSET, LAYER_PICK_HINT_OFFSET); - let frame = Rect::from_min_size(at, galley.size()).expand(LAYER_PICK_HINT_PADDING); + let frame = layer_pick_hint_frame(rect, hover, galley.size()); + let at = frame.min + vec2(LAYER_PICK_HINT_PADDING, LAYER_PICK_HINT_PADDING); painter.rect_filled(frame, egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), tokens.panel); painter.rect_stroke( frame, @@ -1831,6 +1831,16 @@ fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { ui.ctx().accesskit_node_builder(announced.id, |node| node.set_live(egui::accesskit::Live::Polite)); } +/// The layer pick label's frame around text of `size`: beside the pointer, slid back inside `view` near its edges +fn layer_pick_hint_frame(view: Rect, hover: Pos2, size: egui::Vec2) -> Rect { + let beside = hover + vec2(LAYER_PICK_HINT_OFFSET, LAYER_PICK_HINT_OFFSET); + let frame = Rect::from_min_size(beside, size).expand(LAYER_PICK_HINT_PADDING); + let frame = frame.translate((view.max - frame.max).min(egui::Vec2::ZERO)); + + // A label wider than the view keeps its start + frame.translate((view.min - frame.min).max(egui::Vec2::ZERO)) +} + /// How far the layer pick label sits right of and below the pointer, and the room around its text (points) const LAYER_PICK_HINT_OFFSET: f32 = 16.0; const LAYER_PICK_HINT_PADDING: f32 = 4.0; @@ -2654,6 +2664,22 @@ fn eyedrop(app: &mut TextureCraftApp, ctx: &egui::Context, bar: egui::Id, pixel: #[cfg(test)] mod tests { use super::*; + + #[test] + fn the_layer_pick_label_stays_inside_the_view_at_its_edges() { + let view = Rect::from_min_size(pos2(100.0, 50.0), vec2(400.0, 300.0)); + let size = vec2(120.0, 14.0); + for hover in [view.min, view.center(), view.right_center() - vec2(2.0, 0.0), view.max - vec2(2.0, 2.0)] { + let frame = layer_pick_hint_frame(view, hover, size); + + assert!(view.contains_rect(frame), "hover {hover:?}: {frame:?}"); + } + + let wide = layer_pick_hint_frame(view, view.center(), vec2(600.0, 14.0)); + + assert_eq!(wide.left(), view.left(), "a label wider than the view starts inside it"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn hovering_a_texture_set_row_previews_it_without_selecting_it() { diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index d057cf51..dd732214 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -238,7 +238,8 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { let row = harness.get_by_label("Effect A").rect(); assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); - let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 6.0).max(0.0); + // The nesting gives way to the row's edge, eye column, preview, gap, name and remove column + let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 27.0).max(0.0); click(&mut harness, egui::pos2(row.left() + 15.0 + indent, row.center().y)); let content = &harness.state().session.doc.project.layers[&layer].content_effects; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3b614921..534cac1e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -47,7 +47,8 @@ viewport point, top first (`{layers: [{layer, name, channels}]}`, in the shown c While a layer is soloed, both see only what the solo shows. `layer.flatten {layer}` on a folder replies with a new fill layer above it holding the folder's result as image resources, and hides the folder; it is refused for a texture set with several UV -tiles, and for a visible folder holding an anchor point that a layer outside it reads. +tiles, for a visible folder holding an anchor point that a layer outside it reads, and for a +folder whose layers' blend modes go past a channel's range (an image would clip the result). `mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the texture set's resolution: black where the mesh does not cover the texture, with the orientation From af41a430744b48e9ca94d505c7a5e7e157689b24 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:42:44 +0000 Subject: [PATCH 124/128] Layers: answer review: a failed folder flatten keeps no decoded images --- crates/engine/src/layer_ops.rs | 10 ++++++++-- crates/engine/tests/it/flatten_folder.rs | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 7a755bae..bc16c1a7 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -305,8 +305,14 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> s.select_one(ts, flat); s.target = StackTarget::Content; Ok(flat) - })?; - Ok(json!({ "layer": flat.0 })) + }); + + // Forget images stored by an edit that rolled back + if flat.is_err() { + s.sync_images(); + } + + Ok(json!({ "layer": flat?.0 })) } /// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index ca438fb8..8ec2da0c 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -193,6 +193,23 @@ fn flattening_a_folder_over_several_uv_tiles_is_refused() { assert_eq!(s.history_labels().len(), steps, "and nothing is changed"); } +/// A flatten that fails once its images are stored keeps none of their decoded pixels +#[test] +fn a_failed_folder_flatten_keeps_no_decoded_images() { + let mut s = session(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + let decoded = s.images.len(); + + // The new layer gets a taken id, so placing it in the stack fails after its images are in + s.doc.project.next_id = folder; + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + let error = flattened.unwrap_err().to_string(); + assert!(error.contains("already exists"), "failed placing the new layer: {error}"); + assert_eq!(s.images.len(), decoded); +} + /// A child reading an anchor point of the folder's own mask keeps what it read #[test] fn a_flattened_folder_keeps_what_a_child_reads_from_the_folder_mask() { From 29cc9738039c207aab8138c472c6d9d19cf9b559 Mon Sep 17 00:00:00 2001 From: Morion Date: Sun, 29 Nov 2026 11:57:38 -0500 Subject: [PATCH 125/128] Announce the autosave failure notice to screen readers --- crates/ui-egui/src/autosave_notice.rs | 5 +++++ crates/ui-egui/tests/autosave_notice.rs | 19 +++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/autosave_notice.rs b/crates/ui-egui/src/autosave_notice.rs index cc37af56..5ca18157 100644 --- a/crates/ui-egui/src/autosave_notice.rs +++ b/crates/ui-egui/src/autosave_notice.rs @@ -68,6 +68,11 @@ pub(crate) fn poll(app: &mut TextureCraftApp) { if let Some(message) = &message { app.session.log.error("Autosave", message.clone()); app.toast_sticky(message.clone()); + + // The user's focus is elsewhere, so a screen reader hears the notice only as a live region + if let Some(toast) = app.toasts.last_mut() { + toast.announce = true; + } } app.autosave_notice.shown = message; diff --git a/crates/ui-egui/tests/autosave_notice.rs b/crates/ui-egui/tests/autosave_notice.rs index 703c13e9..5b735a38 100644 --- a/crates/ui-egui/tests/autosave_notice.rs +++ b/crates/ui-egui/tests/autosave_notice.rs @@ -1,11 +1,23 @@ //! A failed autosave is announced in the interface. This is its own test binary because the data //! folder it breaks is fixed once for the whole process. +use std::path::PathBuf; use std::time::{Duration, Instant}; +use egui::accesskit::Live; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_ui_egui::TextureCraftApp; +/// Removes the test's folder, also when an assertion fails +struct TempFolder(PathBuf); + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + fn notices(harness: &Harness<'_, TextureCraftApp>) -> usize { // Other loaders name the broken data folder too: only the autosave's own notice counts harness.state().toasts.iter().filter(|toast| toast.text.starts_with("Autosave to ") && toast.text.contains("autosave-notice")).count() @@ -23,7 +35,9 @@ fn run_until(harness: &mut Harness<'_, TextureCraftApp>, done: impl Fn(&Harness< #[test] fn a_failing_autosave_is_announced_once_until_it_works_again() { - let root = std::env::temp_dir().join(format!("tc-autosave-notice-{}", std::process::id())); + let folder = TempFolder(std::env::temp_dir().join(format!("tc-autosave-notice-{}", std::process::id()))); + std::fs::create_dir_all(&folder.0).unwrap(); + let root = folder.0.join("data"); // A file where the data folder should be, so the autosave folder cannot be created std::fs::write(&root, b"not a folder").unwrap(); texturecraft_ui_egui::set_data_root(root.clone()); @@ -47,8 +61,9 @@ fn a_failing_autosave_is_announced_once_until_it_works_again() { std::thread::sleep(Duration::from_millis(10)); } assert_eq!(notices(&harness), 1, "the same failure is not announced again"); + let announced = harness.query_all_by_label_contains("Autosave to ").any(|node| node.accesskit_node().live() == Live::Polite); + assert!(announced, "the notice is a live region, so a screen reader reads it"); std::fs::remove_file(&root).unwrap(); run_until(&mut harness, |harness| notices(harness) == 0); - let _ = std::fs::remove_dir_all(&root); } From 5600be65561d9bc38cf6c0fe6df910c2cdbd346f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 13:48:49 -0500 Subject: [PATCH 126/128] Use craft-nightly for nightly profile self-isolation and security fence (#911) --- Cargo.lock | 9 + Cargo.toml | 2 + apps/texturecraft/Cargo.toml | 2 + apps/texturecraft/src/build_flavor.rs | 32 +- apps/texturecraft/src/launch_profile.rs | 255 +++------ apps/texturecraft/src/main.rs | 40 +- apps/texturecraft/src/profile_root.rs | 668 ++++++------------------ 7 files changed, 277 insertions(+), 731 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01e17558..2c2a5d6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1324,6 +1324,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -5949,6 +5957,7 @@ dependencies = [ "craft-host", "craft-image-codecs", "craft-menu", + "craft-nightly", "craft-update", "eframe", "egui", diff --git a/Cargo.toml b/Cargo.toml index bb398c92..2a15ba96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -89,6 +89,8 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs). craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# Nightly profile isolation, launch protocol, and security fence (apps/texturecraft). +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index ab29d036..c9be2510 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -25,6 +25,8 @@ log = { workspace = true } rfd = { workspace = true } # Pass the selected window backend to the title bar and UI runtime craft-host = { workspace = true } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { 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/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs index 294f1e19..9330b7d8 100644 --- a/apps/texturecraft/src/build_flavor.rs +++ b/apps/texturecraft/src/build_flavor.rs @@ -1,14 +1,9 @@ //! The build-time channel, which is distinct from a launch selector: no runtime environment can //! promote a stable build into the Nightly one. -use crate::launch_profile::Profile; use std::ffi::OsString; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; /// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; @@ -17,15 +12,6 @@ pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor /// workspace version (`build.rs` bakes it so both flavors read it the same way). pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION"); -/// A nightly build starts only with its profile, and a stable build only without one. -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } -} - /// A refused nightly start explains itself in a native dialog: a release Windows build has no /// console, and a Dock launch on macOS has none either. pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { @@ -58,22 +44,6 @@ mod tests { assert!(!needs_native_error(BuildFlavor::Stable, false)); } - #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); - } - - #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); - } - #[test] fn the_nightly_version_line_is_exact_and_says_its_channel() { let nightly = version(BuildFlavor::NightlyV1); diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs index 84f5061f..9e29c559 100644 --- a/apps/texturecraft/src/launch_profile.rs +++ b/apps/texturecraft/src/launch_profile.rs @@ -1,126 +1,30 @@ -//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. -//! Stable launches keep their arguments and directory policy unchanged, and no environment is -//! mutated: the profile is a value this process reads, not a variable it exports. +//! The Launcher's nightly-v1 bootstrap and direct-launch self-isolation, backed by `craft-nightly`. +//! +//! Selected before logging, updates, fonts or saved state. Stable launches keep their arguments and +//! directory policy unchanged, and no environment is mutated: the profile is a value this process +//! reads, not a variable it exports. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} - -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } - - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); +pub use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&Profile::Stable) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) -} - -/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a -/// file, even when it looks like a profile flag. No filesystem or startup hook runs here. -pub fn parse(args: Vec) -> Result { - let mut selector = None; - let mut root = None; - let mut other = Vec::new(); - let mut files = Vec::new(); - let mut iter = args.iter(); - let mut delimiter = false; - while let Some(arg) = iter.next() { - if arg == "--" { - delimiter = true; - files.extend(iter.cloned()); - break; - } - if arg == "--launch-profile" || arg == "--profile-root" { - let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; - if slot.is_some() { - return Err("the profile selector and root must each occur exactly once".into()); - } - let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; - if value.to_string_lossy().starts_with("--") { - return Err("the profile selector/root needs a value".into()); - } - *slot = Some(value.clone()); - } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { - return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); - } else { - other.push(arg.clone()); - } - } - match (selector, root) { - (None, None) => Ok(Launch { profile: Profile::Stable, args }), - (Some(version), Some(root)) if version == VERSION => { - if !delimiter || !other.is_empty() { - return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); - } - let root = PathBuf::from(root); - if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { - return Err("the nightly profile root must be absolute and contain no parent traversal".into()); - } - Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) - } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), - _ => Err("--launch-profile and --profile-root must be supplied together".into()), - } -} - -/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), -/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never -/// validated or touched, and `-- --version` stays a file name. -pub fn version_query(args: &[OsString]) -> bool { - let Some((last, pair)) = args.split_last() else { return false }; - if last != "--version" && last != "-V" { - return false; - } - let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); - matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) -} - -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly -/// root validator, so its old directory resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +/// Parse startup arguments for `flavor`, validate and prepare the isolated nightly profile root +/// (self-isolating into `craft_nightly::canonical_profile_root("texturecraft")` on direct nightly +/// launches, or using the explicit `--launch-profile nightly-v1 --profile-root ` pair), and +/// install the resolved [`Profile`] into the process-wide `OnceLock`. +pub fn prepare(flavor: BuildFlavor, args: Vec) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::new()) } #[cfg(test)] mod tests { use super::*; - use std::cell::Cell; + use std::path::PathBuf; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -130,88 +34,93 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() { + let spec = crate::profile_root::spec(); for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + let launch = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + + let nightly_flags = args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]); + let err = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::new()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "model with spaces.glb"])); - let launch = parse(argv).unwrap(); + fn direct_nightly_launch_self_isolates_to_canonical_root_and_preserves_args() { + let spec = crate::profile_root::spec(); + let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).expect("canonical profile root"); + let argv = args(&["model.glb", "--gpu", "nvidia"]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert!(launch.profile.is_nightly()); + assert_eq!(launch.passthrough_args, argv); + assert!(!launch.is_version_query()); + } + + #[test] + fn explicit_launcher_flags_override_canonical_root_and_preserve_files() { + let spec = crate::profile_root::spec(); + let argv = args(&[ + craft_nightly::LAUNCH_PROFILE_FLAG, + craft_nightly::NIGHTLY_V1_CONTRACT, + craft_nightly::PROFILE_ROOT_FLAG, + absolute(), + "--", + "--profile-root", + "model with spaces.glb", + ]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "model with spaces.glb"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn invalid_profile_arguments_are_refused() { + let spec = crate::profile_root::spec(); for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT]), args(&["--profile-root", absolute()]), args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]), + args(&[ + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--profile-root", + absolute(), + "--", + ]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]), + args(&["--gpu", "nvidia", "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]), ] { - assert!(parse(argv.clone()).is_err(), "{argv:?}"); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).is_err(), "{argv:?}"); } } #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + fn version_queries_are_recognized_plain_and_via_launcher() { + let spec = crate::profile_root::spec(); for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } - } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); - } + let plain = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(plain.is_version_query(), "plain {flag}"); - #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } + let launcher = craft_nightly::parse_startup( + BuildFlavor::NightlyV1, + &spec, + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]), + &StartupOptions::new(), + ) + .unwrap(); + assert!(launcher.is_version_query(), "launcher {flag}"); + } - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + let file_named_version = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); + assert!(!file_named_version.is_version_query()); } } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 678c0a8c..0255487b 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -291,33 +291,31 @@ fn report_launch_profile_error(error: &str) { } } -/// Select the immutable launch profile before any startup service or side effect, and answer the -/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the -/// launch is already answered and the process returns. +/// Select the immutable launch profile before any startup service or side effect, and answer +/// version queries before root validation, logging, IPC or a window. `None` means the launch is +/// already answered and the process returns. fn prepare_launch() -> Option> { let argv: Vec = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`: both are answered here, with nothing but standard output written. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + // Plain `--version` / `-V` is answered immediately with nothing but standard output written, + // even in a minimal environment without home/data variables. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); + return None; + } + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // Launcher's `--launch-profile nightly-v1 --profile-root --version`: `craft-nightly` + // skips root validation and profile installation for version queries. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_process_identity().map_err(|error| error.to_string())?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }; - if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + if let Err(error) = initialize_nightly_process_identity().map_err(|error| error.to_string()).and_then(|()| os_window::select_identity(identity)) { report_launch_profile_error(&error); std::process::exit(2); } @@ -326,7 +324,7 @@ fn prepare_launch() -> Option> { texturecraft_ui_egui::set_data_root(root.clone()); texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned()); } - Some(early.args) + Some(early.passthrough_args) } /// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs index db10fdae..7ab39c60 100644 --- a/apps/texturecraft/src/profile_root.rs +++ b/apps/texturecraft/src/profile_root.rs @@ -1,567 +1,223 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! App-owned nightly profile specification backed by `craft-nightly`. //! -//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error -//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export -//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the -//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it, -//! or when it is not writable. +//! A Nightly profile holds *all* of its user state: eframe's `app.ron`/`ui.json`, the error log, +//! session logs, autosave copies, smart materials, layouts, templates, brush and export presets. +//! `craft-nightly` enforces the security fence, symlink/hardlink checks, `0o700` hardening, and +//! writability probe using the TextureCraft-specific boundaries declared here. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::PathBuf; -/// The folder names the launch checks use for this app in each platform's location. +use craft_nightly::AppProfileSpec; + +/// Canonical lowercase app identifier used for the default nightly profile path. +pub const APP_ID: &str = "texturecraft"; +/// Human-readable application name and stable folder name. const BRAND: &str = "TextureCraft"; -/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). -const STABLE_ID: &str = "ai.storyteller.texturecraft"; -/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that -/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts. -const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder /// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called. const LINUX_STORAGE_BRAND: &str = "texturecraft"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, -} - -impl Platform { - fn current() -> Result { - match std::env::consts::OS { - "windows" => Ok(Self::Windows), - "linux" => Ok(Self::Linux), - "macos" => Ok(Self::Mac), - _ => Err("nightly-v1 is not defined for this operating system".into()), - } - } - - fn ignores_case(self) -> bool { - self != Self::Linux - } -} - -fn absolute(path: PathBuf, label: &str) -> Result { - if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!("{label} must be absolute and contain no parent traversal")); - } - Ok(path) -} - -fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { - let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; - absolute(PathBuf::from(value), key) -} - -fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { - match env(key).filter(|v| !v.is_empty()) { - Some(value) => absolute(PathBuf::from(value), key), - None => Ok(required_base(env, "HOME")?.join(fallback)), - } -} - -/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor -/// is not a missing directory that may be replaced or followed later. -fn canonical_future(path: &Path) -> Result { - let mut parent = path; - let mut missing = Vec::new(); - loop { - match std::fs::symlink_metadata(parent) { - Ok(_) => break, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); - parent = parent.parent().ok_or("the profile root has no existing ancestor")?; - } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), - } - } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -/// Whether one path is the other or contains it (in either direction), compared component by -/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not -/// inside `TextureCraft`. -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -/// The running install: never let the profile live inside it (it would be replaced or removed by -/// the next update). -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or("cannot establish the installation boundary")?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned bundle, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it -/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`. -fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option) -> Result { - let home = match platform { - Platform::Windows => required_base(env, "USERPROFILE")?, - _ => required_base(env, "HOME")?, - }; - Ok(home.join("Documents").join(BRAND)) -} - -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - // eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's - // per-machine and any per-user install folders. A custom install folder is covered by the - // executable's own folder below. - let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::, _>>()?; - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND)); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - if let Some(base) = env(key).filter(|v| !v.is_empty()) { - roots.push(absolute(PathBuf::from(base), key)?.join(BRAND)); - } - } - roots - } - Platform::Linux => { - // The four XDG roots carry eframe's settings, caches and state under the app's name. - let mut roots = - [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] - .into_iter() - .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND))) - .collect::, _>>()?; - // eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`, - // `ui.json` and `errors.log`: it folds the name, so it is the lowercase one. - roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND)); - roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); - // The stable Flatpak keeps its own per-app data folder. - roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}"))); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support").join(BRAND), - library.join("Caches").join(BRAND), - library.join("Caches").join(STABLE_ID), - library.join("Preferences").join(BRAND), - library.join("Preferences").join(format!("{STABLE_ID}.plist")), - library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")), - home.join("Applications").join(format!("{BRAND}.app")), - PathBuf::from("/Applications").join(format!("{BRAND}.app")), - ] - } - }; - // The user's own documents folder is Stable's default data folder on every platform; a profile - // there would share autosaves, smart materials and presets with it. - roots.push(default_data_folder(platform, env)?); - roots.push(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() -} - -/// An entry inside the profile must resolve inside it, so a link planted there cannot point -/// 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 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) -} +/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). +const STABLE_ID: &str = "ai.storyteller.texturecraft"; +/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// 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"]; +const PROFILE_FOLDERS: &[&str] = &["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> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - 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(()) +/// Build TextureCraft's `craft_nightly::AppProfileSpec` from the current process environment. +pub fn spec() -> AppProfileSpec { + spec_with_env(|key| std::env::var_os(key)) } -/// 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()); - } +/// Build TextureCraft's `craft_nightly::AppProfileSpec` using a custom environment lookup. +pub fn spec_with_env(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: BRAND, + stable_dir_names: &[BRAND, LINUX_STORAGE_BRAND], + stable_package_id: STABLE_ID, + nightly_package_id: NIGHTLY_ID, + profile_root_env: None, + forbidden_env_vars: &[], + portable_markers: &[], + folder_only_entries: PROFILE_FOLDERS, + extra_forbidden_roots: extra_forbidden_roots(&env), } - #[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"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) +fn non_empty_abs_env(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key).filter(|v| !v.is_empty())?; + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only -/// access where the platform has it, and return the resolved root to use. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} +/// Platform-specific stable data and install roots beyond the OS config/data/cache dirs that +/// `craft-nightly` already fences from `stable_dir_names` and `stable_package_id`. +fn extra_forbidden_roots(env: &impl Fn(&str) -> Option) -> Vec { + let mut roots = Vec::new(); -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - // A native package must not carry another app's Flatpak namespace, and the Nightly bundle must - // be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its - // `~/.var/app/` sandbox is separate from stable's, so only other ids are refused. - if platform != Platform::Windows - && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) - && id != NIGHTLY_ID + // The user's own Documents folder is Stable's default data folder on every platform; a profile + // there would share autosaves, smart materials and presets with it. + #[cfg(target_os = "windows")] + if let Some(home) = non_empty_abs_env(env, "USERPROFILE") { + roots.push(home.join("Documents").join(BRAND)); + } + #[cfg(not(target_os = "windows"))] + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join("Documents").join(BRAND)); + } + + #[cfg(target_os = "windows")] { - return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + if let Some(local) = non_empty_abs_env(env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join(BRAND)); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs_env(env, key) { + roots.push(base.join(BRAND)); + } + } } - let chosen = canonical_future(root)?; - let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".into()); - } - // Existing aliases under the profile must not redirect any of its folders elsewhere. - entries_stay_inside(&chosen)?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] + + #[cfg(target_os = "linux")] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join(format!(".var/app/{STABLE_ID}"))); + } } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); + + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs_env(env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences").join(format!("{STABLE_ID}.plist"))); + roots.push(library.join("Saved Application State").join(format!("{STABLE_ID}.savedState"))); + roots.push(home.join("Applications").join(format!("{BRAND}.app"))); + } + roots.push(PathBuf::from("/Applications").join(format!("{BRAND}.app"))); } - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) + + roots } #[cfg(test)] mod tests { use super::*; + use craft_nightly::{ProfileError, validate_and_prepare_root}; use std::collections::BTreeMap; + use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, + struct TempDir { + path: PathBuf, } - impl Fixture { - fn new() -> Self { + impl TempDir { + fn new(label: &str) -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let path = loop { + let candidate = base.join(format!("texturecraft-profile-spec-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Ok(()) => break candidate, Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => panic!("cannot create owned fixture: {error}"), } }; - let home = root.join("home"); - let exe = root.join("install/texturecraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } + Self { path } } - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - - fn profile(&self, name: &str) -> PathBuf { - self.root.join("profiles").join(name) + fn path(&self) -> &Path { + &self.path } } - impl Drop for Fixture { + impl Drop for TempDir { fn drop(&mut self) { - // Only the directory this fixture created is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + let _ = std::fs::remove_dir_all(&self.path); } } #[test] - fn a_fresh_private_profile_is_created_and_returned_resolved() { - let fixture = Fixture::new(); - let profile = fixture.profile("nightly"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert_eq!(fixture.check(platform, &profile).unwrap(), profile); - assert!(profile.is_dir()); - std::fs::remove_dir_all(&profile).ok(); + fn spec_declares_texturecraft_ids_folders_and_extra_forbidden_roots() { + let tmp = TempDir::new("spec"); + let home = tmp.path().join("home"); + let mut env = BTreeMap::new(); + env.insert("HOME", home.clone().into_os_string()); + env.insert("USERPROFILE", home.clone().into_os_string()); + env.insert("LOCALAPPDATA", tmp.path().join("local").into_os_string()); + env.insert("ProgramFiles", tmp.path().join("Program Files").into_os_string()); + + let spec = spec_with_env(|key| env.get(key).cloned()); + assert_eq!(spec.app_id, "texturecraft"); + assert_eq!(spec.display_name, "TextureCraft"); + assert_eq!(spec.stable_dir_names, &["TextureCraft", "texturecraft"]); + assert_eq!(spec.stable_package_id, "ai.storyteller.texturecraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.texturecraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert!(spec.forbidden_env_vars.is_empty()); + assert!(spec.portable_markers.is_empty()); + assert_eq!(spec.folder_only_entries, PROFILE_FOLDERS); + assert!(spec.extra_forbidden_roots.contains(&home.join("Documents").join(BRAND))); + + #[cfg(target_os = "linux")] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!(".var/app/{STABLE_ID}")))); + } + #[cfg(target_os = "macos")] + { + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Preferences/{STABLE_ID}.plist")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Saved Application State/{STABLE_ID}.savedState")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Applications/{BRAND}.app")))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(format!("/Applications/{BRAND}.app")))); + } + #[cfg(target_os = "windows")] + { + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("local/Programs/ArtCraft").join(BRAND))); + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("Program Files").join(BRAND))); } } #[test] - fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() { - let fixture = Fixture::new(); - let home = fixture.home(); - let candidates: Vec<(Platform, PathBuf)> = vec![ - (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)), - (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)), - (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)), - (Platform::Windows, home.join("Documents").join(BRAND)), - (Platform::Linux, home.join(".config").join(BRAND)), - (Platform::Linux, home.join(".local/share").join(BRAND)), - (Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)), - (Platform::Linux, home.join(".cache").join(BRAND)), - (Platform::Linux, home.join(".local/state").join(BRAND)), - (Platform::Linux, home.join("Documents").join(BRAND)), - (Platform::Linux, PathBuf::from("/usr/bin/texturecraft")), - (Platform::Linux, PathBuf::from("/opt/texturecraft")), - (Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))), - (Platform::Mac, home.join("Library/Application Support").join(BRAND)), - (Platform::Mac, home.join("Library/Caches").join(BRAND)), - (Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))), - (Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))), - (Platform::Mac, home.join("Documents").join(BRAND)), - (Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))), - ]; - for (platform, stable) in candidates { - for candidate in [stable.clone(), stable.join("nested nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "{platform:?} accepted {}", candidate.display()); - assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display()); - } + fn nightly_profile_reopens_and_enforces_folder_only_entries() { + let tmp = TempDir::new("reopen"); + let private = tmp.path().join("nightly-profile"); + let spec = spec_with_env(|_| None); + + let canonical = validate_and_prepare_root(&private, &spec).expect("fresh private profile"); + assert_eq!(canonical, 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!(validate_and_prepare_root(&private, &spec).expect("reopen populated profile"), 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!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); } } #[test] - fn the_running_install_is_fenced_on_every_platform() { - let fixture = Fixture::new(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - let inside = fixture.exe.parent().unwrap().join("profile"); - assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install"); - } - } + fn documents_data_folder_is_refused() { + let tmp = TempDir::new("documents"); + let home = tmp.path().join("home"); + let documents_stable = home.join("Documents").join(BRAND); + let spec = spec_with_env(|key| matches!(key, "HOME" | "USERPROFILE").then(|| home.clone().into_os_string())); - #[test] - fn lookalike_names_are_not_overlaps_but_case_folding_is() { - let fixture = Fixture::new(); - let documents = fixture.home().join("Documents"); - assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder"); - assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly"); - for platform in [Platform::Windows, Platform::Mac] { - assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case"); - } - } - - #[test] - fn relative_parent_traversal_and_empty_roots_are_refused() { - let fixture = Fixture::new(); - for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] { - assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display()); - } - } - - #[test] - fn only_the_nightly_flatpak_may_start_with_its_own_id() { - let fixture = Fixture::new(); - let profile = fixture.profile("flatpak"); - assert!(fixture.check(Platform::Linux, &profile).is_ok()); - std::fs::remove_dir_all(&profile).ok(); - let check_with = |id: &str, candidate: &Path| { - let id = OsString::from(id); - validate_for( - Platform::Linux, - candidate, - |key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) }, - Some(&fixture.exe), - ensure_writable, - ) - }; - // Stable's id, its window id and an unrelated app's id are all refusals. - for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] { - assert!(check_with(id, &profile).is_err(), "{id} was accepted"); - } - // The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the - // profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`). - let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}")); - let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly"); - assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed); - std::fs::remove_dir_all(&sandbox).ok(); - } - - #[test] - #[cfg(unix)] - fn an_entry_that_leaves_the_profile_is_refused() { - let fixture = Fixture::new(); - let profile = fixture.profile("aliased"); - let outside = fixture.root.join("somewhere else"); - std::fs::create_dir_all(&profile).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused"); - // A dangling link is not a missing folder that may be created. - std::fs::remove_file(profile.join("autosave")).unwrap(); - std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err()); - std::fs::remove_file(profile.join("logs")).unwrap(); - // A plain folder inside it is fine. - std::fs::create_dir(profile.join("autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_ok()); - } - - #[test] - fn a_failed_write_probe_never_falls_back_to_stable() { - let fixture = Fixture::new(); - let profile = fixture.profile("read only"); - let reached = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &profile, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - reached.set(true); - Err(std::io::Error::other("read-only filesystem")) - }, - ); - assert!(result.is_err()); - assert!(reached.get()); - assert!(result.unwrap_err().contains("not writable")); - // The app must not then use the stable folder: it simply refuses to start. - 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() { - let fixture = Fixture::new(); - let real = fixture.root.join("real profiles"); - std::fs::create_dir_all(&real).unwrap(); - let link = fixture.root.join("linked"); - std::os::unix::fs::symlink(&real, &link).unwrap(); - // A link to a private folder is fine, and the resolved root is what the app uses. - let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap(); - assert_eq!(resolved, real.join("nightly")); + assert!(matches!(validate_and_prepare_root(&documents_stable, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(matches!(validate_and_prepare_root(&documents_stable.join("nested"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); } } From a42d053c3e68a8ccac3de282e716de958ed06c53 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 15:29:32 -0500 Subject: [PATCH 127/128] test(nightly): retain exact launcher query and profile coverage (#913) --- apps/texturecraft/src/launch_profile.rs | 24 ++++++++++++++++-------- apps/texturecraft/src/profile_root.rs | 4 +++- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs index 9e29c559..b75287fd 100644 --- a/apps/texturecraft/src/launch_profile.rs +++ b/apps/texturecraft/src/launch_profile.rs @@ -110,14 +110,22 @@ mod tests { let plain = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap(); assert!(plain.is_version_query(), "plain {flag}"); - let launcher = craft_nightly::parse_startup( - BuildFlavor::NightlyV1, - &spec, - args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]), - &StartupOptions::new(), - ) - .unwrap(); - assert!(launcher.is_version_query(), "launcher {flag}"); + for header in [ + ["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()], + ["--profile-root", absolute(), "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT], + ] { + let mut query = args(&header); + query.push(flag.into()); + assert!( + craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, query, &StartupOptions::new()).unwrap().is_version_query(), + "launcher {flag}" + ); + let mut gpu = args(&header); + gpu.extend(args(&["--gpu", "nvidia", flag])); + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, gpu, &StartupOptions::new()).unwrap(); + assert!(!launch.is_version_query()); + assert_eq!(launch.passthrough_args, args(&["--gpu", "nvidia", flag])); + } } let file_named_version = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs index 7ab39c60..b2c53f2b 100644 --- a/apps/texturecraft/src/profile_root.rs +++ b/apps/texturecraft/src/profile_root.rs @@ -198,7 +198,9 @@ mod tests { } assert_eq!(validate_and_prepare_root(&private, &spec).expect("reopen populated profile"), private); - assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); + for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] { + assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen"); + } for name in PROFILE_FOLDERS { let path = private.join(name); From 8c4bf602e88a8fd2cfa8717840ef31c036a85654 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 16:16:21 -0500 Subject: [PATCH 128/128] ci(nightly): enable automated 06:00 UTC schedule and signer dispatch (#898) --- .github/nightly-signing-policy.json | 4 ++- .github/workflows/nightly-dispatch.yml | 4 +-- .github/workflows/nightly.yml | 5 ++-- packaging/nightly-release-tests.py | 35 +++++++++++++++++--------- 4 files changed, 31 insertions(+), 17 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 61714f01..58445c26 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -88,7 +88,9 @@ } }, "max_artifact_bytes": 2147483648, - "automatic_signer_actors": [], + "automatic_signer_actors": [ + "github-actions[bot]" + ], "platforms": { "windows-x86_64": { "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml index bd40f765..2445bdd2 100644 --- a/.github/workflows/nightly-dispatch.yml +++ b/.github/workflows/nightly-dispatch.yml @@ -11,9 +11,9 @@ permissions: {} jobs: dispatch: - # SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification. + # Exact context guard only; admission belongs to the protected signer branch. if: >- - false && github.repository == 'storytold/texturecraft' && + github.repository == 'storytold/texturecraft' && github.event_name == 'workflow_run' runs-on: ubuntu-latest timeout-minutes: 5 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index c05c2e31..173ba6cc 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,8 +1,9 @@ name: TextureCraft unsigned nightly -# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. -# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +# Automated daily schedule at 06:00 UTC plus supervised manual runs by reviewed manual actors. on: + schedule: + - cron: '0 6 * * *' workflow_dispatch: permissions: diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 55c08d86..840110b8 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -217,15 +217,21 @@ class TrustedSourcePreparation(unittest.TestCase): (indicator, expression), = job_conditions(jobs) self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) - def test_no_nightly_schedule_is_registered(self): - for name, event in (("nightly.yml", "workflow_dispatch"), - ("nightly-sign.yml", "workflow_dispatch")): + def test_nightly_triggers_match_reviewed_schedule_and_dispatch(self): + expected = { + "nightly.yml": [" schedule:", " workflow_dispatch:"], + "nightly-sign.yml": [" workflow_dispatch:"], + } + for name, expected_triggers in expected.items(): source = (ROOT / ".github/workflows" / name).read_text() events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] triggers = [line for line in events.splitlines() if line.startswith(" ") and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] with self.subTest(workflow=name): - self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + self.assertEqual(triggers, expected_triggers, "schedule/activation needs explicit review") + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + self.assertEqual(re.findall(r"(?m)^ - cron: '([^']+)'$", producer), ["0 6 * * *"], + "nightly schedule must remain pinned to the reviewed 06:00 UTC cron") def test_signer_serialization_contract_is_enforced(self): assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) @@ -360,7 +366,8 @@ class NightlyEnabledCallers(unittest.TestCase): source = (ROOT / ".github/workflows/nightly.yml").read_text() policy = json.loads(INSTALLED_POLICY.read_text()) self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) - self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"], + "automatic signer is limited to github-actions[bot]") def test_an_actor_outside_the_release_managers_is_refused(self): source = (ROOT / ".github/workflows/nightly.yml").read_text() @@ -824,19 +831,23 @@ def dispatch_triggers(source): class NightlyDispatchTransport(unittest.TestCase): - """The scheduled transport stays literally off and can only reach the signer branch.""" + """The scheduled transport runs only in its exact context and can only reach the signer branch.""" + + DISPATCH_GUARD = "github.repository == 'storytold/texturecraft' && github.event_name == 'workflow_run'" def setUp(self): self.source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() - def test_every_dispatch_job_is_literal_off(self): + def test_dispatch_job_keeps_exact_context_guard(self): jobs = self.source.split("\njobs:\n", 1)[1] - headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs) + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), ["dispatch"]) conditions = job_conditions(jobs) - self.assertTrue(headers) - self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition") - for _, expression in conditions: - self.assertTrue(literal_off(expression), "nightly activation requires reviewed test update") + self.assertEqual(len(conditions), 1) + indicator, expression = conditions[0] + self.assertEqual(indicator, ">-") + self.assertFalse(literal_off(expression), "scheduled dispatch transport must be enabled") + self.assertEqual(" ".join(expression.split()), self.DISPATCH_GUARD, + "dispatch guard may only change with review") def test_only_a_completed_scheduled_producer_is_transported(self): self.assertEqual(re.findall(r"(?m)^ workflows: (.+)$", self.source),