From 77d5edbce6aef32b021fe6bb3b9ace044ae4cd31 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 03:53:58 +0000 Subject: [PATCH 01/42] Tool availability: which tools can act on the selection Session::tool_usable answers per tool: brushes and Path act on paint layer content, paint sublayers, masks and the quick mask while it is edited; fill content, filters, generators, folders, instances and an empty selection take none of them. Smudge and Clone can't paint mask values yet. Path also edits a selected path sublayer, wherever it is. The color picker always acts; the geometry mask needs a layer. --- crates/engine/src/lib.rs | 1 + crates/engine/src/tool_availability.rs | 46 ++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/tool_availability.rs | 250 ++++++++++++++++++++ 4 files changed, 298 insertions(+) create mode 100644 crates/engine/src/tool_availability.rs create mode 100644 crates/engine/tests/it/tool_availability.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a8ea034a..e7fbefde 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -55,6 +55,7 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod thumbs; +mod tool_availability; pub mod tool_cmds; mod triangle_partition; mod uv_stroke_state; diff --git a/crates/engine/src/tool_availability.rs b/crates/engine/src/tool_availability.rs new file mode 100644 index 00000000..392388e3 --- /dev/null +++ b/crates/engine/src/tool_availability.rs @@ -0,0 +1,46 @@ +//! Which tools can act on the current selection: the tool shelf and its shortcuts grey the rest + +use texturecraft_core::{EffectKind, LayerKind}; + +use crate::{Session, StackTarget, Tool}; + +impl Session { + /// Whether `tool` can act on the selection (or on the quick mask while it is being edited) + pub fn tool_usable(&self, tool: Tool) -> bool { + match tool { + // The picker reads the composite under the cursor, whatever is selected + Tool::ColorPicker => return true, + Tool::GeometryMask => return self.selected_layer().is_some(), + _ => {} + } + + // Brushes paint the quick mask whatever is selected; paths can't edit it + if self.quick_mask.editing { + return tool != Tool::Path; + } + + let project = &self.doc.project; + let Some(layer) = self.selected_layer().and_then(|id| project.layers.get(&id)) else { return false }; + + // Smudge and Clone read layer content, so they can't yet paint mask values + let reads_content = matches!(tool, Tool::Smudge | Tool::Clone); + match self.target { + StackTarget::Content => matches!(layer.kind, LayerKind::Paint), + StackTarget::Mask => !reads_content, + StackTarget::Effect(effect) => { + let Some((owner, found)) = project.effect(effect) else { return false }; + let Some(owner_layer) = project.layers.get(&owner) else { return false }; + let in_content = owner_layer.content_effects.iter().any(|candidate| candidate.id == effect); + let in_fill_content = in_content && matches!(owner_layer.kind, LayerKind::Fill(_)); + + match found.kind { + // Paths saved in a fill layer before paths there were removed stay editable + EffectKind::Path(_) => tool == Tool::Path, + EffectKind::Paint if tool == Tool::Path => !in_fill_content, + EffectKind::Paint => in_content || !reads_content, + _ => false, + } + } + } + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index e6157332..42d6ac61 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -24,6 +24,7 @@ mod polygon_fill; mod project_recovery; mod sample; mod thumbs; +mod tool_availability; mod tools; mod udim; mod uv_strokes; diff --git a/crates/engine/tests/it/tool_availability.rs b/crates/engine/tests/it/tool_availability.rs new file mode 100644 index 00000000..3e1526fe --- /dev/null +++ b/crates/engine/tests/it/tool_availability.rs @@ -0,0 +1,250 @@ +//! Which tools can act on each selection + +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; +use texturecraft_engine::{Session, StackTarget, Tool, execute}; + +/// Two triangles side by side, each a mesh part with its own corner of the UV square +const PARTS_OBJ: &str = "o Lid\nv 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 0.5 0\nvt 0 0.5\nf 1/1 2/2 3/3\n\ +o Body\nv 2 2 0\nv 4 2 0\nv 2 4 0\nvt 0.5 0.5\nvt 1 0.5\nvt 0.5 1\nf 4/4 5/5 6/6\n"; + +const VIEWPORT_PIXELS: f32 = 400.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Selection { + PaintContent, + FillContent, + PaintMask, + FillMask, + FolderMask, + InstanceOwnMask, + PaintSublayer, + PaintSublayerInMask, + PaintSublayerInFill, + PathSublayer, + FilterInPaint, + FilterInFill, + FilterInMask, + FillEffectInPaint, + GeneratorInFillMask, + FolderContent, + InstanceOfPaint, + InstanceOfFill, + Nothing, + QuickMaskOverFill, + QuickMaskOverNothing, +} + +impl Selection { + const ALL: [Selection; 21] = [ + Selection::PaintContent, + Selection::FillContent, + Selection::PaintMask, + Selection::FillMask, + Selection::FolderMask, + Selection::InstanceOwnMask, + Selection::PaintSublayer, + Selection::PaintSublayerInMask, + Selection::PaintSublayerInFill, + Selection::PathSublayer, + Selection::FilterInPaint, + Selection::FilterInFill, + Selection::FilterInMask, + Selection::FillEffectInPaint, + Selection::GeneratorInFillMask, + Selection::FolderContent, + Selection::InstanceOfPaint, + Selection::InstanceOfFill, + Selection::Nothing, + Selection::QuickMaskOverFill, + Selection::QuickMaskOverNothing, + ]; + + /// Whether the shelf offers `tool` for this selection + fn offers(self, tool: Tool) -> bool { + let reads_content = matches!(tool, Tool::Smudge | Tool::Clone); + match tool { + Tool::ColorPicker => true, + Tool::GeometryMask => !matches!(self, Selection::Nothing | Selection::QuickMaskOverNothing), + _ => match self { + Selection::PaintContent | Selection::PaintSublayer => true, + Selection::PaintSublayerInFill => tool != Tool::Path, + Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => { + !reads_content + } + Selection::PathSublayer => tool == Tool::Path, + Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path, + _ => false, + }, + } + } +} + +fn stencil_png() -> Vec { + let mut out = Vec::new(); + let green = image::RgbaImage::from_fn(8, 8, |_, _| image::Rgba([0, 255, 0, 255])); + green.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +fn base_session() -> Session { + let mut session = Session::from_mesh_bytes("parts.obj", PARTS_OBJ.as_bytes(), 256, "parts").unwrap(); + session.viewport = Vec2::splat(VIEWPORT_PIXELS); + (session.camera.yaw, session.camera.pitch) = (0.0, 0.0); + let (low, high) = session.mesh.bounds(); + session.camera.frame(low, high); + session.update(); + + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap(); + let stencil = session.import_resource_bytes("stencil.png", stencil_png()).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": stencil})).unwrap(); + session +} + +fn screen(session: &Session, point: [f32; 3]) -> Vec2 { + let ndc = session.camera.project(Vec3::from(point), 1.0).unwrap(); + Vec2::new((ndc.x + 1.0) * VIEWPORT_PIXELS / 2.0, (1.0 - ndc.y) * VIEWPORT_PIXELS / 2.0) +} + +fn add_layer(session: &mut Session, command: &str) -> u64 { + execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap() +} + +fn select(session: &mut Session, layer: u64, target: Value) { + execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap(); +} + +fn select_nothing(session: &mut Session) { + let set = session.ts(); + session.selected.remove(&set); + session.target = StackTarget::Content; +} + +/// Adds an effect with `command` to the layer's content or mask and selects it +fn select_new_effect(session: &mut Session, layer: u64, mask: bool, command: &str, params: Value) { + if mask { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + } + + let target = if mask { "mask" } else { "content" }; + let mut params = params; + params["layer"] = json!(layer); + params["target"] = json!(target); + execute(session, command, ¶ms).unwrap(); + + let owner = session.doc.project.layer(LayerId(layer)).unwrap(); + let effects = if mask { &owner.mask.as_ref().unwrap().effects } else { &owner.content_effects }; + let effect = effects.last().unwrap().id.0; + select(session, layer, json!(effect)); +} + +fn select_new_mask(session: &mut Session, layer: u64) { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + select(session, layer, json!("mask")); +} + +fn session_with(selection: Selection) -> Session { + let mut session = base_session(); + match selection { + Selection::PaintContent => { + let layer = add_layer(&mut session, "layer.add.paint"); + select(&mut session, layer, json!("content")); + } + Selection::FillContent => { + let layer = add_layer(&mut session, "layer.add.fill"); + select(&mut session, layer, json!("content")); + } + Selection::PaintMask => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_mask(&mut session, layer); + } + Selection::FillMask => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_mask(&mut session, layer); + } + Selection::FolderMask => { + let folder = add_layer(&mut session, "layer.add.group"); + select_new_mask(&mut session, folder); + } + Selection::InstanceOwnMask => { + let source = add_layer(&mut session, "layer.add.paint"); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + select_new_mask(&mut session, instance); + } + Selection::PaintSublayer => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, false, "effect.add.paint", json!({})); + } + Selection::PaintSublayerInMask => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, true, "effect.add.paint", json!({})); + } + Selection::PaintSublayerInFill => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_effect(&mut session, layer, false, "effect.add.paint", json!({})); + } + Selection::PathSublayer => { + let layer = add_layer(&mut session, "layer.add.paint"); + select(&mut session, layer, json!("content")); + let (start, end) = (screen(&session, [0.2, 0.2, 0.0]), screen(&session, [1.0, 0.4, 0.0])); + execute(&mut session, "tool.path", &json!({"points": [[start.x, start.y], [end.x, end.y]]})).unwrap(); + execute(&mut session, "tool.path", &json!({"commit": true})).unwrap(); + let path = session.doc.project.layer(LayerId(layer)).unwrap().content_effects.last().unwrap().id.0; + select(&mut session, layer, json!(path)); + } + Selection::FilterInPaint | Selection::FilterInFill | Selection::FilterInMask => { + let command = if selection == Selection::FilterInFill { "layer.add.fill" } else { "layer.add.paint" }; + let layer = add_layer(&mut session, command); + select_new_effect(&mut session, layer, selection == Selection::FilterInMask, "effect.add.filter", json!({"filter": "invert"})); + } + Selection::FillEffectInPaint => { + let layer = add_layer(&mut session, "layer.add.paint"); + select_new_effect(&mut session, layer, false, "effect.add.fill", json!({})); + } + Selection::GeneratorInFillMask => { + let layer = add_layer(&mut session, "layer.add.fill"); + select_new_effect(&mut session, layer, true, "effect.add.generator", json!({})); + } + Selection::FolderContent => { + let folder = add_layer(&mut session, "layer.add.group"); + select(&mut session, folder, json!("content")); + } + Selection::InstanceOfPaint | Selection::InstanceOfFill => { + let command = if selection == Selection::InstanceOfFill { "layer.add.fill" } else { "layer.add.paint" }; + let source = add_layer(&mut session, command); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + select(&mut session, instance, json!("content")); + } + Selection::Nothing => select_nothing(&mut session), + Selection::QuickMaskOverFill => { + let layer = add_layer(&mut session, "layer.add.fill"); + select(&mut session, layer, json!("content")); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + } + Selection::QuickMaskOverNothing => { + select_nothing(&mut session); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + } + } + session +} + +#[test] +fn every_selection_offers_the_tools_that_can_act_on_it() { + let mut wrong = Vec::new(); + for selection in Selection::ALL { + let session = session_with(selection); + for tool in Tool::ALL { + let usable = session.tool_usable(tool); + if usable != selection.offers(tool) { + wrong.push(format!("{selection:?} {tool:?}: usable {usable}")); + } + } + } + + assert!(wrong.is_empty(), "{wrong:#?}"); +} From fc2f62656e378dbff42e1ea846c71087b8ee594a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 03:53:58 +0000 Subject: [PATCH 02/42] No new paths in fill layers or the quick mask; quick mask Edit needs the mask on A path committed on a fill layer (its content, an effect in it or an instance of it) or while the quick mask is edited is refused; paths already saved in a fill layer stay editable through their sublayer. Edit and Invert quick mask are enabled only while the quick mask is on, and turning it off stops editing it. --- crates/engine/src/path_tool.rs | 43 +++--- crates/engine/src/quick_mask.rs | 33 ++-- crates/engine/tests/it/tool_availability.rs | 145 +++++++++++++++++- crates/engine/tests/it/tools.rs | 53 ++++--- .../tests/it/color_selection_editor.rs | 7 + crates/ui-egui/tests/it/tool_availability.rs | 81 ++++++++++ 6 files changed, 303 insertions(+), 59 deletions(-) create mode 100644 crates/ui-egui/tests/it/tool_availability.rs diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 1607636c..0cf8e2e8 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use texturecraft_compose::{PaintTarget, PixelStore}; -use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; +use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape}; use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments}; @@ -706,33 +706,40 @@ impl Session { self.path_steps = Default::default(); } - /// The selected path sublayer, or a new one on the selected layer's content or mask - /// (whichever is selected). + /// The selected path sublayer, or a new one on the selected paint layer's content or mask fn path_effect(&mut self) -> Result { - let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?; - let p = &self.doc.project; + if self.quick_mask.editing { + return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); + } + + let selected = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?; + let project = &self.doc.project; let mask = match self.target { - StackTarget::Effect(e) => match p.effect(e) { - Some((_, x)) if matches!(x.kind, EffectKind::Path(_)) => return Ok(e), - Some((owner, _)) => !p.layer(owner)?.content_effects.iter().any(|x| x.id == e), + StackTarget::Effect(effect) => match project.effect(effect) { + // Paths saved in a fill layer before paths there were removed stay editable + Some((_, found)) if matches!(found.kind, EffectKind::Path(_)) => return Ok(effect), + Some((owner, _)) => !project.layer(owner)?.content_effects.iter().any(|candidate| candidate.id == effect), None => false, }, StackTarget::Mask => true, StackTarget::Content => false, }; - // An instance's content and (unless it has its own) mask belong to its source. - let owner = if mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) }; - let eid = self.doc.project.alloc_id(); - let l = self.doc.project.layer_mut(owner)?; - let e = Effect::new(eid, EffectKind::Path(Vec::new())); + + // An instance's content and (unless it has its own) mask belong to its source + let owner = if mask { project.mask_owner(selected) } else { project.content_layer(selected).map_or(selected, |layer| layer.id) }; + let path_id = self.doc.project.alloc_id(); + let layer = self.doc.project.layer_mut(owner)?; + let path = Effect::new(path_id, EffectKind::Path(Vec::new())); if mask { - l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(e); - } else if l.is_group() { - return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", l.name))); + layer.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(path); + } else if layer.is_group() { + return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", layer.name))); + } else if matches!(layer.kind, LayerKind::Paint) { + layer.content_effects.push(path); } else { - l.content_effects.push(e); + return Err(EngineError::Other(format!("\"{}\" is not a paint layer: add the path to a paint layer or a mask", layer.name))); } - Ok(eid) + Ok(path_id) } /// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 93087c14..f6bbafe9 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -35,14 +35,18 @@ pub fn specs() -> Vec { "Edit quick mask", ["Viewport"], Some("U"), - "{editing?: bool} — toggles when omitted; editing enables the mask", - always, + "{editing?: bool} — toggles when omitted; needs the quick mask enabled", + mask_enabled, edit ), - cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", always, invert), + cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", mask_enabled, invert), ] } +fn mask_enabled(session: &Session) -> std::result::Result<(), String> { + if session.quick_mask.enabled { Ok(()) } else { Err("enable the quick mask first".into()) } +} + fn state(s: &Session) -> Value { let q = &s.quick_mask; json!({ @@ -57,17 +61,22 @@ fn changed(s: &mut Session) -> Result { Ok(state(s)) } -fn enable(s: &mut Session, p: &Value) -> Result { - s.quick_mask.enabled = boolp(p, "enabled").unwrap_or(!s.quick_mask.enabled); - changed(s) +fn enable(session: &mut Session, params: &Value) -> Result { + let enabled = boolp(params, "enabled").unwrap_or(!session.quick_mask.enabled); + if !enabled && session.quick_mask.editing { + session.cancel_stroke(); + session.quick_mask.editing = false; + } + + session.quick_mask.enabled = enabled; + changed(session) } -fn edit(s: &mut Session, p: &Value) -> Result { - s.cancel_stroke(); - let q = &mut s.quick_mask; - q.editing = boolp(p, "editing").unwrap_or(!q.editing); - q.enabled |= q.editing; - changed(s) +fn edit(session: &mut Session, params: &Value) -> Result { + session.cancel_stroke(); + let quick_mask = &mut session.quick_mask; + quick_mask.editing = boolp(params, "editing").unwrap_or(!quick_mask.editing); + changed(session) } fn invert(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/tests/it/tool_availability.rs b/crates/engine/tests/it/tool_availability.rs index 3e1526fe..a91ec9f0 100644 --- a/crates/engine/tests/it/tool_availability.rs +++ b/crates/engine/tests/it/tool_availability.rs @@ -1,7 +1,7 @@ -//! Which tools can act on each selection +//! Which tools can act on each selection, and that every usable tool acts there in both views use serde_json::{Value, json}; -use texturecraft_engine::core::LayerId; +use texturecraft_engine::core::{Effect, EffectKind, LayerId}; use texturecraft_engine::geom::glam::{Vec2, Vec3}; use texturecraft_engine::{Session, StackTarget, Tool, execute}; @@ -32,12 +32,13 @@ enum Selection { InstanceOfPaint, InstanceOfFill, Nothing, + QuickMaskOverPaint, QuickMaskOverFill, QuickMaskOverNothing, } impl Selection { - const ALL: [Selection; 21] = [ + const ALL: [Selection; 22] = [ Selection::PaintContent, Selection::FillContent, Selection::PaintMask, @@ -57,6 +58,7 @@ impl Selection { Selection::InstanceOfPaint, Selection::InstanceOfFill, Selection::Nothing, + Selection::QuickMaskOverPaint, Selection::QuickMaskOverFill, Selection::QuickMaskOverNothing, ]; @@ -74,11 +76,19 @@ impl Selection { !reads_content } Selection::PathSublayer => tool == Tool::Path, - Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path, + Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path, _ => false, }, } } + + /// Greyed in the shelf, but scripts still paint here: below the effect, or the instance's source + fn scripts_still_paint(self) -> bool { + matches!( + self, + Selection::FilterInPaint | Selection::FillEffectInPaint | Selection::FilterInMask | Selection::GeneratorInFillMask | Selection::InstanceOfPaint + ) + } } fn stencil_png() -> Vec { @@ -218,8 +228,9 @@ fn session_with(selection: Selection) -> Session { select(&mut session, instance, json!("content")); } Selection::Nothing => select_nothing(&mut session), - Selection::QuickMaskOverFill => { - let layer = add_layer(&mut session, "layer.add.fill"); + Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill => { + let command = if selection == Selection::QuickMaskOverFill { "layer.add.fill" } else { "layer.add.paint" }; + let layer = add_layer(&mut session, command); select(&mut session, layer, json!("content")); execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); @@ -233,6 +244,49 @@ fn session_with(selection: Selection) -> Session { session } +/// Uses `tool` once the way the viewport does: a stroke, a click or a committed path +fn use_tool(session: &mut Session, tool: Tool, in_2d_view: bool) -> texturecraft_engine::Result<()> { + session.tool.tool = tool; + if tool == Tool::Clone { + let source = screen(session, [1.2, 0.3, 0.0]); + execute(session, "tool.cloneSource", &json!({"x": source.x, "y": source.y}))?; + } + + let points = [screen(session, [0.3, 0.3, 0.0]), screen(session, [0.6, 0.4, 0.0]), screen(session, [0.9, 0.5, 0.0])]; + let uv_points = [Vec2::new(0.05, 0.95), Vec2::new(0.1, 0.92), Vec2::new(0.15, 0.9)]; + if tool == Tool::Path { + let params = if in_2d_view { + json!({"uvPoints": uv_points.iter().map(|uv| [uv.x, uv.y]).collect::>()}) + } else { + json!({"points": points.iter().map(|point| [point.x, point.y]).collect::>()}) + }; + execute(session, "tool.path", ¶ms)?; + execute(session, "tool.path", &json!({"commit": true}))?; + return Ok(()); + } + + let single_click = matches!(tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask); + let viewport = session.viewport; + if in_2d_view { + session.begin_stroke_uv(uv_points[0], 1.0)?; + } else { + session.begin_stroke(points[0], viewport, 1.0)?; + } + + if single_click { + return Ok(()); + } + + for (point, uv) in points.iter().zip(&uv_points).skip(1) { + if in_2d_view { + session.continue_stroke_uv(*uv, 1.0); + } else { + session.continue_stroke(*point, 1.0); + } + } + session.end_stroke() +} + #[test] fn every_selection_offers_the_tools_that_can_act_on_it() { let mut wrong = Vec::new(); @@ -248,3 +302,82 @@ fn every_selection_offers_the_tools_that_can_act_on_it() { assert!(wrong.is_empty(), "{wrong:#?}"); } + +#[test] +fn every_usable_tool_acts_in_both_views() { + let mut wrong = Vec::new(); + for in_2d_view in [false, true] { + for selection in Selection::ALL { + for tool in Tool::ALL { + // The picker and the geometry mask read the 3D view only, whatever is selected + if in_2d_view && matches!(tool, Tool::ColorPicker | Tool::GeometryMask) { + continue; + } + + let mut session = session_with(selection); + let usable = session.tool_usable(tool); + + let result = use_tool(&mut session, tool, in_2d_view); + + let view = if in_2d_view { "2D" } else { "3D" }; + match result { + Err(error) if usable => wrong.push(format!("{view} {selection:?} {tool:?}: usable but {error}")), + Ok(()) if !usable && !selection.scripts_still_paint() => wrong.push(format!("{view} {selection:?} {tool:?}: greyed but acts")), + _ => {} + } + } + } + } + + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +fn commit_path(session: &mut Session) -> texturecraft_engine::Result { + execute(session, "tool.path", &json!({"uvPoints": [[0.05, 0.95], [0.15, 0.9]], "commit": true})) +} + +fn path_count(session: &Session, path_sublayer: LayerId) -> usize { + match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Path(paths)) => paths.len(), + _ => 0, + } +} + +#[test] +fn paths_are_refused_on_fill_layers_and_the_quick_mask_but_saved_ones_stay_editable() { + let mut session = session_with(Selection::FillContent); + let fill = session.selected_layer().unwrap(); + + assert!(commit_path(&mut session).is_err(), "no new paths in a fill layer"); + assert!(session.doc.project.layer(fill).unwrap().content_effects.is_empty()); + + let mut session = session_with(Selection::QuickMaskOverPaint); + assert!(commit_path(&mut session).is_err(), "paths can't edit the quick mask"); + + // A project saved while paths could go into fill layers + let mut session = session_with(Selection::FillContent); + let fill = session.selected_layer().unwrap(); + let saved_path = session.doc.project.alloc_id(); + session.doc.project.layer_mut(fill).unwrap().content_effects.push(Effect::new(saved_path, EffectKind::Path(Vec::new()))); + select(&mut session, fill.0, json!(saved_path.0)); + + assert!(session.tool_usable(Tool::Path)); + + commit_path(&mut session).unwrap(); + + assert_eq!(path_count(&session, saved_path), 1, "the saved path sublayer takes the new path"); +} + +#[test] +fn quick_mask_edit_and_invert_need_the_mask_on() { + let mut session = base_session(); + + assert!(execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).is_err()); + assert!(execute(&mut session, "viewport.quickMask.invert", &json!({})).is_err()); + + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap(); + + assert!(!session.quick_mask.editing, "turning the mask off stops editing it"); +} diff --git a/crates/engine/tests/it/tools.rs b/crates/engine/tests/it/tools.rs index afadf0b3..1277202c 100644 --- a/crates/engine/tests/it/tools.rs +++ b/crates/engine/tests/it/tools.rs @@ -153,32 +153,39 @@ fn library_alphas_shape_the_stamp() { #[test] fn quick_mask_limits_painting() { - let mut s = session(); - paint_red(&mut s, 20.0); - let r = execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap(); - assert_eq!(r["editing"], json!(true)); - assert_eq!(r["enabled"], json!(true), "editing enables the mask"); - let undo = s.history_labels().len(); - dab(&mut s, 150.0, 200.0); - assert!(!red(color_at(&s, 150.0, 200.0)), "mask strokes do not paint the layer"); - assert_eq!(s.history_labels().len(), undo, "mask strokes stay out of the history"); - assert!(s.quick_mask_rgba(0, 64).is_some_and(|v| v.len() == 64 * 64 * 4)); - execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap(); + let mut session = session(); + paint_red(&mut session, 20.0); + execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); - execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); - dab(&mut s, 150.0, 200.0); - dab(&mut s, 250.0, 200.0); - assert!(red(color_at(&s, 150.0, 200.0)), "inside the mask"); - assert!(!red(color_at(&s, 250.0, 200.0)), "outside the mask"); + let state = execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap(); + let undo = session.history_labels().len(); + dab(&mut session, 150.0, 200.0); - execute(&mut s, "viewport.quickMask.invert", &Value::Null).unwrap(); - dab(&mut s, 250.0, 200.0); - assert!(red(color_at(&s, 250.0, 200.0)), "inverted: outside is open"); + assert_eq!(state["editing"], json!(true)); + assert!(!red(color_at(&session, 150.0, 200.0)), "mask strokes do not paint the layer"); + assert_eq!(session.history_labels().len(), undo, "mask strokes stay out of the history"); + let overlay_size: u32 = 64; + let rgba_bytes = (overlay_size * overlay_size * 4) as usize; + assert!(session.quick_mask_rgba(0, overlay_size).is_some_and(|pixels| pixels.len() == rgba_bytes), "an RGBA8 overlay of the requested size"); - execute(&mut s, "viewport.quickMask", &json!({"enabled": false})).unwrap(); - execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap(); - dab(&mut s, 150.0, 200.0); - assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); + execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap(); + dab(&mut session, 150.0, 200.0); + dab(&mut session, 250.0, 200.0); + + assert!(red(color_at(&session, 150.0, 200.0)), "inside the mask"); + assert!(!red(color_at(&session, 250.0, 200.0)), "outside the mask"); + + execute(&mut session, "viewport.quickMask.invert", &Value::Null).unwrap(); + dab(&mut session, 250.0, 200.0); + + assert!(red(color_at(&session, 250.0, 200.0)), "inverted: outside is open"); + + execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap(); + dab(&mut session, 150.0, 200.0); + + assert!(color_at(&session, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); } /// How much redder than green a texel must be to count as painted (faded edges included) diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index eb80adf6..360dca82 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -272,8 +272,11 @@ fn color_selection_snapshots_and_quick_mask_pick() { let center = harness.state().viewport_rect.center(); harness.hover_at(center + egui::vec2(80.0, 0.0)); let expected = save(&mut harness, "color-selection-picking"); + + 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(); let with_quick_mask = save(&mut harness, "color-selection-picking-quick-mask"); + assert_eq!( with_quick_mask.get_pixel(center.x as u32, center.y as u32), expected.get_pixel(center.x as u32, center.y as u32), @@ -281,14 +284,18 @@ fn color_selection_snapshots_and_quick_mask_pick() { ); click_at(&mut harness, center); + assert!(harness.state().session.quick_mask.editing, "picking preserves quick-mask editing"); save(&mut harness, "color-selection-quick-mask-restored"); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D; harness.get_by_label(&pick_color_label()).click(); save(&mut harness, "color-selection-picking-2d"); click_at(&mut harness, center); + assert!(harness.state().picking_id_color.is_none()); + execute(&mut harness.state_mut().session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); save(&mut harness, "color-selection-no-id-map"); } diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs new file mode 100644 index 00000000..49851d82 --- /dev/null +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -0,0 +1,81 @@ +//! The shelf greys tools that can't act on the selection; the top bar and Properties follow it + +use egui_kittest::Harness; +use serde_json::{Value, json}; +use texturecraft_engine::{Session, StackTarget, Tool, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; +use texturecraft_ui_egui::theme::Brightness; + +fn add_layer(session: &mut Session, command: &str) -> u64 { + execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap() +} + +fn select(session: &mut Session, layer: u64, target: Value) { + execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap(); +} + +fn select_nothing(session: &mut Session) { + let set = session.ts(); + session.selected.remove(&set); + session.target = StackTarget::Content; +} + +#[test] +#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"] +fn tool_availability_snapshots() { + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { + return; + }; + + std::fs::create_dir_all(&directory).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + for (brightness, suffix) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(8); + harness.render().unwrap().save(directory.join(format!("{name}-{suffix}.png"))).unwrap(); + } + }; + + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + session.tool.tool = Tool::Paint; + save(&mut harness, "01-paint-layer"); + + let session = &mut harness.state_mut().session; + let fill = add_layer(session, "layer.add.fill"); + select(session, fill, json!("content")); + session.tool.tool = Tool::PolygonFill; + save(&mut harness, "04-fill-content-polygon-fill"); + + let session = &mut harness.state_mut().session; + execute(session, "effect.add.filter", &json!({"layer": paint, "target": "content", "filter": "blur"})).unwrap(); + let filter = session.doc.project.layer(texturecraft_engine::core::LayerId(paint)).unwrap().content_effects.last().unwrap().id.0; + select(session, paint, json!(filter)); + session.tool.tool = Tool::Paint; + save(&mut harness, "07-filter"); + + let session = &mut harness.state_mut().session; + execute(session, "mask.add.black", &json!({"layer": paint})).unwrap(); + select(session, paint, json!("mask")); + session.tool.tool = Tool::Smudge; + save(&mut harness, "05-mask-smudge"); + + let session = &mut harness.state_mut().session; + let folder = add_layer(session, "layer.add.group"); + select(session, folder, json!("content")); + session.tool.tool = Tool::Paint; + save(&mut harness, "09-folder"); + + select_nothing(&mut harness.state_mut().session); + save(&mut harness, "12-nothing-selected"); + + harness.state_mut().ui.mode = Mode::Baking; + save(&mut harness, "15-bake"); + + harness.state_mut().ui.mode = Mode::Rendering; + save(&mut harness, "16-render"); +} From 8039420a2b75b776ed8c60186a7e6e504cddca74 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 06:50:27 +0000 Subject: [PATCH 03/42] Assets: tiles on the reference's 68 x 78 grid step with 60 pt thumbnails --- crates/ui-egui/src/shelf.rs | 13 +++++++------ crates/ui-egui/src/thumbs.rs | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9a36df2a..609e5878 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -27,14 +27,15 @@ use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; -/// A shelf tile's size in points -const TILE_WIDTH: f32 = 72.0; -const TILE_HEIGHT: f32 = 86.0; +/// A shelf tile's size and the gap between tiles in points: a 68 x 78 grid step, as in the reference +const TILE_WIDTH: f32 = 66.0; +const TILE_HEIGHT: f32 = 76.0; +const TILE_GAP: f32 = 2.0; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; /// The thumbnail's size in a tile and its center below the tile's top, in points -const THUMBNAIL_SIZE: f32 = 56.0; -const THUMBNAIL_CENTER_Y: f32 = 32.0; +const THUMBNAIL_SIZE: f32 = 60.0; +const THUMBNAIL_CENTER_Y: f32 = 31.0; /// Loading icon size relative to the thumbnail width, and its opacity over the dim text color const LOADING_ICON_SCALE: f32 = 0.9; const LOADING_ICON_OPACITY: f32 = 0.5; @@ -303,7 +304,7 @@ pub(crate) fn header(ui: &mut Ui, text: &str) { pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + ui.spacing_mut().item_spacing = vec2(TILE_GAP, TILE_GAP); body(ui); }); ui.add_space(6.0); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index d0067411..059cc0a3 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -21,7 +21,7 @@ const PER_FRAME: usize = 2; /// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; /// Shelf procedural swatch size in pixels -const PROCEDURAL_PX: usize = 56; +const PROCEDURAL_PX: usize = 64; /// Shelf alpha and brush stroke swatch size in pixels const SWATCH_PX: usize = 64; /// Image resource preview size in pixels From a3eac9d2fb8d5fdd45dfa0ddb92706c6041754b2 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 06:50:35 +0000 Subject: [PATCH 04/42] Assets: one-line tile labels cut with an ellipsis --- crates/ui-egui/src/shelf.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 609e5878..51700285 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -633,13 +633,20 @@ pub(crate) fn tile( } let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); thumbnail(painter, tex, image_rect, &tk); - let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN); + let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) } +/// A tile label on one line, cut with "…" past `width` points (the hover popup shows the whole name) +fn one_line(label: &str, width: f32, color: Color32) -> egui::text::LayoutJob { + let mut job = egui::text::LayoutJob::single_section(label.to_string(), egui::TextFormat::simple(egui::FontId::proportional(LABEL_FONT_SIZE), color)); + job.wrap = egui::text::TextWrapping::truncate_at_width(width); + job +} + /// Start rendering during the popup delay once the pointer rests fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { let ctx = ui.ctx(); From e64385f331a0f2285103104e93bdcb42db2d86be Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 03:53:59 +0000 Subject: [PATCH 05/42] Tool shelf: grey the tools that can't act on the selection The shelf follows the reference order (Paint, Eraser, Path, Projection, Polygon fill, Smudge, Clone, picker, geometry mask; keys unchanged), greys each tool the selection can't take, with its name on hover, and greys quick mask Edit and Invert while the mask is off. Their shortcuts and menu items follow. Rendering hides the paint tools; baking keeps them greyed. --- crates/ui-egui/src/docking.rs | 62 +++++++----- crates/ui-egui/src/menus.rs | 12 ++- crates/ui-egui/src/toolbar.rs | 101 ++++++++++++++----- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/tool_availability.rs | 16 +-- 5 files changed, 133 insertions(+), 59 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 5bebfd98..d20fe45d 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -215,6 +215,9 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> { // --------------------------------------------------------------------------------------------- // The live dock +/// Height of a panel group's tab strip, in points +pub(crate) const TAB_HEIGHT: f32 = 30.0; + /// Width of the bake layout's texture set and mesh map bakers column, in points const BAKERS_COLUMN_WIDTH: f32 = 200.0; /// Width of the bake layout's common and mesh map settings column, in points @@ -367,29 +370,42 @@ fn area_id() -> Id { Id::unique("texturecraft-docking") } -/// The dock look: every panel group is a card on the window's frame colour, its tab strip -/// without hard lines, the shown tab a pill. -fn style(ui: &Ui, t: &Tokens) -> DockStyle { - let mut s = DockStyle::from_ui(ui); - s.gap = f32::from(crate::theme::GUTTER); - // Smallest panel extent a divider drag leaves. - s.min_pane = 60.0; - s.background = t.panel; - s.tab_background = t.panel; - s.active_background = t.button; - s.text = t.text_strong; - s.inactive_text = t.text_dim; - s.border = egui::Stroke::NONE; - s.accent = t.accent; - s.floating_background = t.panel; - s.floating_stroke = egui::Stroke::new(1.0, t.button_border); - s.font = egui::FontId::proportional(12.5); - s.min_tab_width = 54.0; - s.tab_height = 30.0; - // Panels arrange in a split tree around the viewport; floating title bars only move windows. - s.new_dock_zones = false; - s.title_bar_docks = false; - s +/// Smallest panel extent a divider drag leaves, in points +const MIN_PANE_EXTENT: f32 = 60.0; + +/// Border width of a floating panel, in points +const FLOATING_BORDER_WIDTH: f32 = 1.0; + +/// Text size of the panel tabs, in points +const TAB_TEXT_SIZE: f32 = 12.5; + +/// Narrowest panel tab, in points +const MIN_TAB_WIDTH: f32 = 54.0; + +/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill +fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { + let mut dock_style = DockStyle::from_ui(ui); + dock_style.gap = f32::from(crate::theme::GUTTER); + dock_style.min_pane = MIN_PANE_EXTENT; + + dock_style.background = tokens.panel; + dock_style.tab_background = tokens.panel; + dock_style.active_background = tokens.button; + dock_style.text = tokens.text_strong; + dock_style.inactive_text = tokens.text_dim; + dock_style.border = egui::Stroke::NONE; + dock_style.accent = tokens.accent; + dock_style.floating_background = tokens.panel; + dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border); + + dock_style.font = egui::FontId::proportional(TAB_TEXT_SIZE); + dock_style.min_tab_width = MIN_TAB_WIDTH; + dock_style.tab_height = TAB_HEIGHT; + + // Panels arrange in a split tree around the viewport; floating title bars only move windows + dock_style.new_dock_zones = false; + dock_style.title_bar_docks = false; + dock_style } /// Whether a modal layer or update dialog holds the input, so the panels, floating ones included, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 72d78b34..b5bafea5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -4,6 +4,7 @@ use egui::{Key, Modifiers}; use serde_json::{Value, json}; +use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::i18n::tr; @@ -110,7 +111,7 @@ fn is_ui(id: &str) -> bool { id.starts_with("ui.") } -/// Whether an item can run now. +/// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { if let Some(panel) = crate::docking::view_panel(id) { return panel.available_in(app.ui.mode); @@ -123,7 +124,14 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { if is_ui(id) { return true; } - texturecraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok()) + + // Scripts may pick any tool, but the shelf and its shortcuts offer only those that can act + let tool = id.strip_prefix("tool.").and_then(|tool_id| Tool::ALL.into_iter().find(|tool| tool.id() == tool_id)); + if tool.is_some_and(|tool| !app.session.tool_usable(tool)) { + return false; + } + + texturecraft_engine::find(id).is_some_and(|command| (command.enabled)(&app.session).is_ok()) } /// Whether an id is implemented at all (parity report). diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 9c0013bc..a592f2ef 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -344,41 +344,90 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } } +/// Shelf order of the tools; their shortcut keys follow `Tool::ALL` +const SHELF_TOOLS: [Tool; 9] = + [Tool::Paint, Tool::Eraser, Tool::Path, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::GeometryMask]; + +/// The tools Baking keeps on its shelf, greyed +const BAKING_SHELF_TOOLS: [Tool; 3] = [Tool::Paint, Tool::Eraser, Tool::PolygonFill]; + +/// Width of the tool shelf, in points +const SHELF_WIDTH: f32 = 40.0; + +/// Size of a shelf button, in points +const SHELF_BUTTON_SIZE: f32 = 28.0; + +/// Vertical gap between shelf buttons, in points +const SHELF_BUTTON_SPACING: f32 = 3.0; + +/// Space on each side of the lines between shelf groups, in points +const SHELF_GROUP_GAP: f32 = 6.0; + +/// Padding inside the shelf card around its buttons, in points (sides, then top and bottom) +const SHELF_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); + pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); - egui::Panel::left("tool_shelf").resizable(false).exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { - ui.spacing_mut().item_spacing.y = 3.0; - ui.add_enabled_ui(app.ui.mode == Mode::Painting, |ui| { - for tool in Tool::ALL { - let selected = app.ui.mode == Mode::Painting && app.session.tool.tool == tool; - let hint = tip(&app.ui.keymap, tr(tool.label()), &format!("tool.{}", tool.id())); - if icon_button(ui, tool_icon(tool), &hint, selected, 28.0).clicked() { + egui::Panel::left("tool_shelf").resizable(false).exact_size(SHELF_WIDTH).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + // The tools start level with the panels' contents, below their tab strips + let top = GUTTER + crate::docking::TAB_HEIGHT as i8; + card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top, bottom: GUTTER }, SHELF_PADDING, |ui| { + ui.spacing_mut().item_spacing.y = SHELF_BUTTON_SPACING; + + // Rendering has nothing to paint, so its shelf keeps only the buttons below the tools + let tools: &[Tool] = match app.ui.mode { + Mode::Painting => &SHELF_TOOLS, + Mode::Baking => &BAKING_SHELF_TOOLS, + Mode::Rendering => &[], + }; + if !tools.is_empty() { + for &tool in tools { + let command = format!("tool.{}", tool.id()); + let hint = tip(&app.ui.keymap, tr(tool.label()), &command); + let (usable, selected) = match app.ui.mode { + // In bake mode Paint is the cage or skew brush while one of them is being painted + Mode::Baking => { + 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); + (usable, usable && app.session.tool.tool == tool) + } + }; + let button = ui.add_enabled_ui(usable, |ui| icon_button(ui, tool_icon(tool), &hint, selected, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(tr(tool.label())).clicked() && app.ui.mode == Mode::Painting { app.run("tool.select", json!({"tool": tool.id()})); } } - ui.add_space(6.0); + ui.add_space(SHELF_GROUP_GAP); ui.separator(); - ui.add_space(6.0); - let quick_mask = &app.session.quick_mask; - for (command, icon, label, selected) in [ - ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled), - ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing), - ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), selected, 28.0).clicked() { - app.run(command, json!({})); - } - } + ui.add_space(SHELF_GROUP_GAP); + } - ui.add_space(6.0); - ui.separator(); - ui.add_space(6.0); - if icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, 28.0).clicked() { - app.ui.dock.focus(Panel::Assets); + let quick_mask = &app.session.quick_mask; + for (command, icon, label, selected) in [ + ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled), + ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing), + ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted), + ] { + let hint = tip(&app.ui.keymap, label, command); + let button = ui.add_enabled_ui(crate::menus::enabled(app, command), |ui| icon_button(ui, icon, &hint, selected, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(label).clicked() { + app.run(command, json!({})); } - }); + } + + ui.add_space(SHELF_GROUP_GAP); + ui.separator(); + ui.add_space(SHELF_GROUP_GAP); + let painting = app.ui.mode == Mode::Painting; + if ui.add_enabled_ui(painting, |ui| icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, SHELF_BUTTON_SIZE)).inner.clicked() + { + app.ui.dock.focus(Panel::Assets); + } }); }); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..2bf7b314 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -34,6 +34,7 @@ mod shortcut_keys; mod skew_paint; mod split_divider; mod start_window; +mod tool_availability; mod toolbar; mod symmetry; diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index 49851d82..f201280a 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -43,39 +43,39 @@ fn tool_availability_snapshots() { let paint = add_layer(session, "layer.add.paint"); select(session, paint, json!("content")); session.tool.tool = Tool::Paint; - save(&mut harness, "01-paint-layer"); + save(&mut harness, "paint-layer"); let session = &mut harness.state_mut().session; let fill = add_layer(session, "layer.add.fill"); select(session, fill, json!("content")); session.tool.tool = Tool::PolygonFill; - save(&mut harness, "04-fill-content-polygon-fill"); + save(&mut harness, "fill-content-polygon-fill"); let session = &mut harness.state_mut().session; execute(session, "effect.add.filter", &json!({"layer": paint, "target": "content", "filter": "blur"})).unwrap(); let filter = session.doc.project.layer(texturecraft_engine::core::LayerId(paint)).unwrap().content_effects.last().unwrap().id.0; select(session, paint, json!(filter)); session.tool.tool = Tool::Paint; - save(&mut harness, "07-filter"); + save(&mut harness, "filter"); let session = &mut harness.state_mut().session; execute(session, "mask.add.black", &json!({"layer": paint})).unwrap(); select(session, paint, json!("mask")); session.tool.tool = Tool::Smudge; - save(&mut harness, "05-mask-smudge"); + save(&mut harness, "mask-smudge"); let session = &mut harness.state_mut().session; let folder = add_layer(session, "layer.add.group"); select(session, folder, json!("content")); session.tool.tool = Tool::Paint; - save(&mut harness, "09-folder"); + save(&mut harness, "folder"); select_nothing(&mut harness.state_mut().session); - save(&mut harness, "12-nothing-selected"); + save(&mut harness, "nothing-selected"); harness.state_mut().ui.mode = Mode::Baking; - save(&mut harness, "15-bake"); + save(&mut harness, "baking"); harness.state_mut().ui.mode = Mode::Rendering; - save(&mut harness, "16-render"); + save(&mut harness, "rendering"); } From 3e0d70bbf003806f6cae6074c7f59a81ec59978a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 03:53:59 +0000 Subject: [PATCH 06/42] Properties shows the selection while the active tool can't act Polygon fill keeps its own properties only where it can fill, so a fill layer's settings show with any tool. A mask with Smudge or Clone shows its height section only, and with nothing selected the panel says to select a layer to paint on. --- crates/ui-egui/src/dock.rs | 29 ++++++++++++++++++++--------- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + 10 files changed, 29 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 53932f4e..e40873c5 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1121,17 +1121,21 @@ fn mesh_map_color(map: BakedMap) -> Color32 { // --------------------------------------------------------------------------------------------- // Properties -/// The Properties tab title: what the panel edits. +/// The Properties tab title: what the panel edits pub(crate) fn properties_title(app: &TextureCraftApp) -> String { let project = &app.session.doc.project; + let tool = app.session.tool.tool; + let tool_usable = app.session.tool_usable(tool); let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { - // Polygon fill keeps its own properties whatever is selected - _ if app.session.tool.tool == Tool::PolygonFill => tr(app.session.tool.tool.label()).to_string(), + // Polygon fill keeps its own properties wherever it can fill + _ if tool == Tool::PolygonFill && tool_usable => tr(tool.label()).to_string(), (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), (Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(), (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(), - _ => tr(app.session.tool.tool.label()).to_string(), + (Some(_), StackTarget::Mask) if !tool_usable => tr("Mask").to_string(), + (None, _) if !tool_usable => return tr("Properties").to_string(), + _ => tr(tool.label()).to_string(), }; format!("{} - {what}", tr("Properties")) } @@ -1142,14 +1146,16 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); } -/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder or instance, else the tool +/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder, instance or mask, else the tool (or a hint to select a layer when it can't act) pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); + let tool = app.session.tool.tool; + let tool_usable = app.session.tool_usable(tool); match (&selected, app.session.target) { - // Polygon fill shows its own settings and says what it fills into, whatever is selected - _ if app.session.tool.tool == Tool::PolygonFill => polygon_fill_properties(app, ui), + // Polygon fill shows its own settings and says what it fills into, wherever it can fill + _ if tool == Tool::PolygonFill && tool_usable => polygon_fill_properties(app, ui), (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => { @@ -1158,8 +1164,13 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => instance_properties(app, ui, layer), (Some(layer), StackTarget::Mask) => { height_mask_section(app, ui, layer); - ui.separator(); - tool_properties(app, ui); + if tool_usable { + ui.separator(); + tool_properties(app, ui); + } + } + (None, _) if !tool_usable => { + ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); } _ => tool_properties(app, ui), } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 95373f3d..773514cf 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -701,6 +701,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), ("Seed", "البذرة العشوائية (Seed)"), ("Select a layer", "تحديد طبقة"), + ("Select a layer to paint on", "حدد طبقة للرسم عليها"), ("Select an output template", "تحديد قالب إخراج"), ("Select source", "تحديد المصدر"), ("Select the mask (Alt+click: show it in the viewport)", "تحديد القناع (Alt+نقر: عرضه في منفذ العرض)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f7e7c35..a46b660b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -737,6 +737,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "Befehle oder Tasten suchen"), ("Seed", "Startwert"), ("Select a layer", "Ebene auswählen"), + ("Select a layer to paint on", "Ebene zum Malen auswählen"), ("Select an output template", "Ausgabevorlage auswählen"), ("Select source", "Quelle auswählen"), ("Select the mask (Alt+click: show it in the viewport)", "Maske auswählen (Alt+Klick: im Ansichtsfenster anzeigen)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b5361801..cde2dbc6 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -728,6 +728,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "Buscar comandos o teclas"), ("Seed", "Semilla"), ("Select a layer", "Selecciona una capa"), + ("Select a layer to paint on", "Selecciona una capa para pintar"), ("Select an output template", "Selecciona una plantilla de salida"), ("Select source", "Seleccionar origen"), ("Select the mask (Alt+click: show it in the viewport)", "Seleccionar la máscara (Alt+clic: mostrarla en la ventana gráfica)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 00b8c2af..3f4625c0 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -746,6 +746,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "Rechercher des commandes ou des touches"), ("Seed", "Graine"), ("Select a layer", "Sélectionnez un calque"), + ("Select a layer to paint on", "Sélectionnez un calque à peindre"), ("Select an output template", "Sélectionnez un modèle de sortie"), ("Select source", "Sélectionner la source"), ("Select the mask (Alt+click: show it in the viewport)", "Sélectionner le masque (Alt+clic : l'afficher dans la fenêtre d'affichage)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index e067cf67..c60fa049 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -734,6 +734,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "Cerca comandi o tasti"), ("Seed", "Seme"), ("Select a layer", "Seleziona un livello"), + ("Select a layer to paint on", "Seleziona un livello su cui dipingere"), ("Select an output template", "Seleziona un modello di output"), ("Select source", "Seleziona sorgente"), ("Select the mask (Alt+click: show it in the viewport)", "Seleziona la maschera (Alt+clic: mostrala nella viewport)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 0e60e132..d932757e 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -719,6 +719,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "コマンドまたはキーを検索"), ("Seed", "シード"), ("Select a layer", "レイヤーを選択"), + ("Select a layer to paint on", "ペイントするレイヤーを選択"), ("Select an output template", "出力テンプレートを選択"), ("Select source", "ソースを選択"), ("Select the mask (Alt+click: show it in the viewport)", "マスクを選択 (Alt+クリック: ビューポートに表示)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 7f80b6be..d636deaf 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -710,6 +710,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "명령 또는 키 검색"), ("Seed", "시드"), ("Select a layer", "레이어를 선택하세요"), + ("Select a layer to paint on", "페인트할 레이어를 선택하세요"), ("Select an output template", "출력 템플릿을 선택하세요"), ("Select source", "소스 선택"), ("Select the mask (Alt+click: show it in the viewport)", "마스크를 선택합니다 (Alt+클릭: 뷰포트에 표시)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e5b023af..31545043 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -725,6 +725,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "Pesquisar comandos ou teclas"), ("Seed", "Semente"), ("Select a layer", "Selecione uma camada"), + ("Select a layer to paint on", "Selecione uma camada para pintar"), ("Select an output template", "Selecione um modelo de saída"), ("Select source", "Selecionar origem"), ("Select the mask (Alt+click: show it in the viewport)", "Selecionar a máscara (Alt+clique: exibi-la na viewport)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index ef4209e4..c875d82e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -668,6 +668,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Search commands or keys", "搜索命令或按键"), ("Seed", "随机种子"), ("Select a layer", "选择图层"), + ("Select a layer to paint on", "选择要绘制的图层"), ("Select an output template", "选择输出模板"), ("Select source", "选择来源"), ("Select the mask (Alt+click: show it in the viewport)", "选择遮罩(Alt+单击:在视口中显示)"), From f12cb68332848005a6319677afbb0ab097622c23 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 03:53:59 +0000 Subject: [PATCH 07/42] Top bar: no tool controls while the active tool can't act --- crates/ui-egui/src/toolbar.rs | 24 +++- crates/ui-egui/tests/it/tool_availability.rs | 112 +++++++++++++++++++ 2 files changed, 131 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a592f2ef..054b1d83 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -17,6 +17,12 @@ const BAR_SPACING: f32 = 10.0; const COMPACT_BAR_SPACING: f32 = 4.0; const BAR_SEPARATOR_WIDTH: f32 = 6.0; +/// Height of the top bar, in points +const BAR_HEIGHT: f32 = 40.0; + +/// Padding inside the top bar card on its left and right, in points +const BAR_PADDING: egui::Margin = egui::Margin::symmetric(8, 0); + pub fn tool_icon(t: Tool) -> &'static str { match t { Tool::Paint => ic::PAINT_BRUSH, @@ -34,8 +40,8 @@ pub fn tool_icon(t: Tool) -> &'static str { /// Keep mode buttons visible, with painting controls scrolling as space runs out pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); - egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { + egui::Panel::top("paint_bar").exact_size(BAR_HEIGHT).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, BAR_PADDING, |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let button_size = ui.spacing().interact_size.y; let mode_width = 3.0 * button_size + 2.0 * BAR_SPACING; @@ -54,7 +60,9 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); if !scroll_views { view_buttons(app, ui); - ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + if app.session.tool_usable(app.session.tool.tool) { + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + } } ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { @@ -183,9 +191,15 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: scroll_area.show(ui, |ui| { ui.scroll_with_delta(vec2(scroll_delta, 0.0)); ui.horizontal_centered(|ui| { - tool_controls(app, ui, tokens); + // A tool that can't act on the selection leaves the bar, as the shelf greys it + let tool_usable = app.session.tool_usable(app.session.tool.tool); + if tool_usable { + tool_controls(app, ui, tokens); + } if scroll_views { - ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + if tool_usable { + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + } let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height()); ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| view_buttons(app, ui)); } diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index f201280a..6b9775ea 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -1,6 +1,7 @@ //! The shelf greys tools that can't act on the selection; the top bar and Properties follow it use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use texturecraft_engine::{Session, StackTarget, Tool, execute}; use texturecraft_ui_egui::TextureCraftApp; @@ -21,6 +22,117 @@ fn select_nothing(session: &mut Session) { session.target = StackTarget::Content; } +fn app_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + harness +} + +/// Selects a new fill layer's content with `tool` equipped +fn select_fill_content(harness: &mut Harness<'_, TextureCraftApp>, tool: Tool) { + let session = &mut harness.state_mut().session; + let fill = add_layer(session, "layer.add.fill"); + select(session, fill, json!("content")); + session.tool.tool = tool; + harness.run_steps(4); +} + +fn shelf_button_disabled(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.get_by_label(label).accesskit_node().is_disabled() +} + +fn shelf_button_selected(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +fn shows_text(harness: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + harness.output().shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(found) if found.galley.text() == text)) +} + +#[test] +fn a_fill_layer_greys_the_paint_tools_and_shows_its_own_properties() { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + harness.run_steps(4); + + assert!(!shelf_button_disabled(&harness, "Paint (1)")); + assert!(shelf_button_selected(&harness, "Paint (1)")); + assert!(shows_text(&harness, "Size"), "the brush controls are in the top bar"); + + select_fill_content(&mut harness, Tool::PolygonFill); + + assert!(shelf_button_disabled(&harness, "Paint (1)")); + assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); + assert!(!shelf_button_selected(&harness, "Polygon fill (4)"), "the equipped tool doesn't show as selected while greyed"); + assert!(!shelf_button_disabled(&harness, "Geometry mask (8)")); + assert!(shows_text(&harness, "Properties - Fill"), "a fill layer shows its fill whatever the tool"); + assert!(!shows_text(&harness, "Size"), "a tool that can't act leaves the top bar"); +} + +#[test] +fn shortcuts_skip_the_tools_the_shelf_greys() { + let mut harness = app_harness(); + select_fill_content(&mut harness, Tool::Paint); + + harness.key_press(egui::Key::Num2); + harness.run_steps(2); + + assert_eq!(harness.state().session.tool.tool, Tool::Paint, "Eraser can't act on a fill layer"); + + harness.key_press(egui::Key::P); + harness.run_steps(2); + + assert_eq!(harness.state().session.tool.tool, Tool::ColorPicker); +} + +#[test] +fn bake_painting_turns_on_the_shelf_paint_tool() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + assert!(shelf_button_disabled(&harness, "Paint (1)"), "nothing is being painted yet"); + + harness.state_mut().ui.bake_paint_brush.on = true; + harness.run_steps(4); + + assert!(harness.state().ui.bake_paint_brush.on, "the high poly allows bake painting"); + assert!(!shelf_button_disabled(&harness, "Paint (1)"), "Paint is the bake brush while it paints"); + assert!(shelf_button_disabled(&harness, "Eraser (2)")); + assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); +} + +#[test] +fn nothing_selected_asks_for_a_layer() { + let mut harness = app_harness(); + select_nothing(&mut harness.state_mut().session); + harness.run_steps(4); + + assert!(shows_text(&harness, "Select a layer to paint on")); + assert!(shelf_button_disabled(&harness, "Geometry mask (8)")); +} + +#[test] +fn baking_keeps_three_greyed_tools_and_rendering_none() { + let mut harness = app_harness(); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + + for label in ["Paint (1)", "Eraser (2)", "Polygon fill (4)"] { + assert!(shelf_button_disabled(&harness, label), "{label}"); + } + assert!(harness.query_by_label("Path (7)").is_none()); + + harness.state_mut().ui.mode = Mode::Rendering; + harness.run_steps(4); + + assert!(harness.query_by_label("Paint (1)").is_none()); +} + #[test] #[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"] fn tool_availability_snapshots() { From e020080bde4fbf34de6aee543fe10483d548178d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 05:07:51 +0000 Subject: [PATCH 08/42] Shelf icons and the material picker's name Path gets a pen nib, so it no longer looks like Polygon fill's polygon; Projection takes the cube-focus icon and Geometry mask a crossed selection. The color picker copies every channel of the material under the cursor, so it is now called the material picker (its command id and key stay). --- ROADMAP.md | 2 +- crates/engine/src/painting.rs | 26 ++++++++++++++------------ crates/engine/src/session.rs | 2 +- crates/engine/src/tool_cmds.rs | 4 ++-- crates/ui-egui/src/i18n/ar.rs | 2 +- crates/ui-egui/src/i18n/de.rs | 2 +- crates/ui-egui/src/i18n/es.rs | 2 +- crates/ui-egui/src/i18n/fr.rs | 2 +- crates/ui-egui/src/i18n/it.rs | 2 +- crates/ui-egui/src/i18n/ja.rs | 2 +- crates/ui-egui/src/i18n/ko.rs | 2 +- crates/ui-egui/src/i18n/pt_br.rs | 2 +- crates/ui-egui/src/i18n/zh_hans.rs | 2 +- crates/ui-egui/src/toolbar.rs | 10 +++++----- docs/features.md | 2 +- 15 files changed, 33 insertions(+), 31 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 654f5c35..1a70d26d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -14,7 +14,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — | | Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | -| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | +| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, material picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | | Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing | diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6344311f..cf5c9565 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -1,5 +1,5 @@ //! Interactive painting on the session: strokes (begin / continue / end / cancel), polygon fill -//! and the color picker. The UI, CLI and agents all go through these. +//! and the material picker. The UI, CLI and agents all go through these. use std::collections::{BTreeMap, BTreeSet}; @@ -555,20 +555,22 @@ impl Session { Ok(()) } - /// Color picker: copy the material under the cursor into the tool's paint values. + /// Material picker: copy the material under the cursor into the tool's paint values pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result> { let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); - let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; - let (w, h) = (cache.size.0 as f32, cache.size.1 as f32); - let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32); - let mut out = BTreeMap::new(); - for c in cache.composite.channels.keys() { - let v = cache.composite.value(*c, x, y); - self.tool.values.insert(*c, v); - out.insert(*c, v); + let texture_set = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); + let cache = self.caches.get(texture_set).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + + let (width, height) = (cache.size.0 as f32, cache.size.1 as f32); + let (x, y) = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32); + + let mut picked = BTreeMap::new(); + for channel in cache.composite.channels.keys() { + let value = cache.composite.value(*channel, x, y); + self.tool.values.insert(*channel, value); + picked.insert(*channel, value); } - Ok(out) + Ok(picked) } /// The stroke canvas alpha of the active stroke (for overlays and tests). diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 41bfacbb..98490d57 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -109,7 +109,7 @@ impl Tool { Tool::PolygonFill => "Polygon fill", Tool::Smudge => "Smudge", Tool::Clone => "Clone", - Tool::ColorPicker => "Color picker", + Tool::ColorPicker => "Material picker", Tool::Path => "Path", Tool::GeometryMask => "Geometry mask", } diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 6a390866..4e588ea9 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { cmd!("tool.polygonFill", "Polygon fill", ["Tools"], Some("4"), "{}", always, |s, _| set_tool(s, Tool::PolygonFill)), cmd!("tool.smudge", "Smudge", ["Tools"], Some("5"), "{}", always, |s, _| set_tool(s, Tool::Smudge)), cmd!("tool.clone", "Clone", ["Tools"], Some("6"), "{}", always, |s, _| set_tool(s, Tool::Clone)), - cmd!("tool.colorPicker", "Color picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)), + cmd!("tool.colorPicker", "Material picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)), cmd!( "tool.geometryMask", "Geometry mask", @@ -105,7 +105,7 @@ pub fn specs() -> Vec { "Tool click", [], None, - "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}", + "{x, y, viewport?: [w,h]} — polygon fill / material picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}", always, click ), diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 773514cf..4fa44d5a 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -174,7 +174,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color burn", "حرق لوني (Color Burn)"), ("Color dodge", "تفتيح لوني (Color Dodge)"), ("Color of the light that travels under the surface (each channel goes as far as its value)", "لون الضوء المنتقل تحت السطح (تصل كل قناة بقدر قيمتها)"), - ("Color picker", "منتقي الألوان"), ("Color selection", "تحديد لوني"), ("Color to replace", "اللون المراد استبداله"), ("Colors near the first shift towards the second, keeping their shading.", "الألوان القريبة من الأولى تتحول نحو الثانية مع الحفاظ على تظليلها."), @@ -484,6 +483,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "إنهاء المادة: خام"), ("MatFinish Sanded", "إنهاء المادة: مصنفر"), ("Material", "المادة"), + ("Material picker", "منتقي المواد"), ("Material ball", "كرة المادة"), ("Material finish", "إنهاء المادة"), ("Materials", "المواد"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index a46b660b..deff726b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -180,7 +180,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Color of the light that travels under the surface (each channel goes as far as its value)", "Farbe des Lichts, das unter der Oberfläche wandert (jeder Kanal reicht so weit wie sein Wert)", ), - ("Color picker", "Farbpipette"), ("Color selection", "Farbauswahl"), ("Color to replace", "Zu ersetzende Farbe"), ( @@ -511,6 +510,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "MatFinish Roh"), ("MatFinish Sanded", "MatFinish Geschmirgelt"), ("Material", "Material"), + ("Material picker", "Materialpipette"), ("Material ball", "Materialkugel"), ("Material finish", "Materialoberfläche"), ("Materials", "Materialien"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index cde2dbc6..c08a7ff5 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -177,7 +177,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Color of the light that travels under the surface (each channel goes as far as its value)", "Color de la luz que viaja bajo la superficie (cada canal llega tan lejos como su valor)", ), - ("Color picker", "Cuentagotas"), ("Color selection", "Selección de color"), ("Color to replace", "Color a reemplazar"), ( @@ -502,6 +501,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "Acabado en bruto"), ("MatFinish Sanded", "Acabado lijado"), ("Material", "Material"), + ("Material picker", "Cuentagotas de material"), ("Material ball", "Bola de material"), ("Material finish", "Acabado de material"), ("Materials", "Materiales"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 3f4625c0..82038edf 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -183,7 +183,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Color of the light that travels under the surface (each channel goes as far as its value)", "Couleur de la lumière qui se propage sous la surface (chaque canal va aussi loin que sa valeur)", ), - ("Color picker", "Pipette"), ("Color selection", "Sélection de couleur"), ("Color to replace", "Couleur à remplacer"), ( @@ -517,6 +516,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "MatFinish Brut"), ("MatFinish Sanded", "MatFinish Poncé"), ("Material", "Matériau"), + ("Material picker", "Pipette de matériau"), ("Material ball", "Boule de matériau"), ("Material finish", "Finition du matériau"), ("Materials", "Matériaux"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index c60fa049..c88a1788 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -183,7 +183,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Color of the light that travels under the surface (each channel goes as far as its value)", "Colore della luce che viaggia sotto la superficie (ogni canale arriva fino al proprio valore)", ), - ("Color picker", "Contagocce"), ("Color selection", "Selezione colore"), ("Color to replace", "Colore da sostituire"), ( @@ -508,6 +507,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "MatFinish Grezzo"), ("MatFinish Sanded", "MatFinish Carteggiato"), ("Material", "Materiale"), + ("Material picker", "Contagocce materiale"), ("Material ball", "Sfera materiale"), ("Material finish", "Finitura materiale"), ("Materials", "Materiali"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index d932757e..0770b619 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -186,7 +186,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Color of the light that travels under the surface (each channel goes as far as its value)", "表面下を伝わる光の色 (各チャンネルは値に応じた距離まで届く)", ), - ("Color picker", "カラーピッカー"), ("Color selection", "カラー選択"), ("Color to replace", "置き換える色"), ("Colors near the first shift towards the second, keeping their shading.", "最初の色に近い色が、陰影を保ったまま2番目の色へ移ります。"), @@ -496,6 +495,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "MatFinish 未加工"), ("MatFinish Sanded", "MatFinish サンディング"), ("Material", "マテリアル"), + ("Material picker", "マテリアルピッカー"), ("Material ball", "マテリアルボール"), ("Material finish", "マテリアル仕上げ"), ("Materials", "マテリアル"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index d636deaf..7ee076da 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -177,7 +177,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Color of the light that travels under the surface (each channel goes as far as its value)", "표면 아래로 이동하는 빛의 색상입니다 (각 채널은 값만큼 멀리 이동)", ), - ("Color picker", "색상 피커"), ("Color selection", "색상 선택"), ("Color to replace", "바꿀 색상"), ("Colors near the first shift towards the second, keeping their shading.", "첫 번째 색상에 가까운 색상이 음영을 유지한 채 두 번째 색상으로 바뀝니다."), @@ -490,6 +489,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "마감 - 원재료"), ("MatFinish Sanded", "마감 - 샌딩"), ("Material", "머티리얼"), + ("Material picker", "머티리얼 피커"), ("Material ball", "머티리얼 볼"), ("Material finish", "머티리얼 마감"), ("Materials", "머티리얼"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 31545043..ddc2e70c 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -180,7 +180,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Color of the light that travels under the surface (each channel goes as far as its value)", "Cor da luz que viaja sob a superfície (cada canal vai tão longe quanto seu valor)", ), - ("Color picker", "Conta-gotas"), ("Color selection", "Seleção de cor"), ("Color to replace", "Cor a substituir"), ("Colors near the first shift towards the second, keeping their shading.", "As cores próximas da primeira passam para a segunda, mantendo o sombreamento."), @@ -499,6 +498,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "MatFinish Bruto"), ("MatFinish Sanded", "MatFinish Lixado"), ("Material", "Material"), + ("Material picker", "Conta-gotas de material"), ("Material ball", "Esfera de material"), ("Material finish", "Acabamento de material"), ("Materials", "Materiais"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index c875d82e..d1a4bca9 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -162,7 +162,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color burn", "颜色加深"), ("Color dodge", "颜色减淡"), ("Color of the light that travels under the surface (each channel goes as far as its value)", "在表面下传播的光的颜色(各通道的传播距离取决于其值)"), - ("Color picker", "拾色器"), ("Color selection", "颜色选择"), ("Color to replace", "要替换的颜色"), ("Colors near the first shift towards the second, keeping their shading.", "接近第一种颜色的颜色会在保留明暗的同时转向第二种颜色。"), @@ -454,6 +453,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Raw", "表面处理:原始"), ("MatFinish Sanded", "表面处理:砂磨"), ("Material", "材质"), + ("Material picker", "材质拾取器"), ("Material ball", "材质球"), ("Material finish", "材质表面处理"), ("Materials", "材质"), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 054b1d83..0be16695 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -23,17 +23,17 @@ const BAR_HEIGHT: f32 = 40.0; /// Padding inside the top bar card on its left and right, in points const BAR_PADDING: egui::Margin = egui::Margin::symmetric(8, 0); -pub fn tool_icon(t: Tool) -> &'static str { - match t { +pub fn tool_icon(tool: Tool) -> &'static str { + match tool { Tool::Paint => ic::PAINT_BRUSH, Tool::Eraser => ic::ERASER, - Tool::Projection => ic::PROJECTOR_SCREEN, + Tool::Projection => ic::CUBE_FOCUS, Tool::PolygonFill => ic::POLYGON, Tool::Smudge => ic::FINGERPRINT, Tool::Clone => ic::STAMP, Tool::ColorPicker => ic::EYEDROPPER, - Tool::Path => ic::PATH, - Tool::GeometryMask => ic::CUBE_FOCUS, + Tool::Path => ic::PEN_NIB_STRAIGHT, + Tool::GeometryMask => ic::SELECTION_SLASH, } } diff --git a/docs/features.md b/docs/features.md index a51352da..4a95356d 100644 --- a/docs/features.md +++ b/docs/features.md @@ -16,7 +16,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA stroke and keep the size; save your own brushes there too. - **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** and **lasso fill**, a - **particle brush**, **smudge**, **clone** (V + click sets the source), color picker, Shift+click + **particle brush**, **smudge**, **clone** (V + click sets the source), material picker, Shift+click straight lines, and painting directly in the **2D UV view**. - **Geometry decals:** drop an image on the surface, then move, scale and turn its frame; it stays an editable fill layer. From e15f01ccd83e02249760d4f247ed2b35ff9d639e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:10:14 +0000 Subject: [PATCH 09/42] Views ignore a tool that can't act on the selection While the active tool can't act, the 3D and 2D views take no stroke, fill, path point or error toast from it, show no brush cursor, stencil or symmetry planes, and leave Ctrl+drag, V+click and the path keys alone. --- crates/ui-egui/src/symmetry/mod.rs | 5 +- crates/ui-egui/src/viewport.rs | 135 ++++++++++++------- crates/ui-egui/tests/it/tool_availability.rs | 46 +++++++ 3 files changed, 136 insertions(+), 50 deletions(-) diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index 9c492896..a3964660 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -29,9 +29,10 @@ pub(crate) fn applies_to(tool: Tool) -> bool { matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Clone | Tool::Path) } -/// Whether the 3D view shows symmetry now +/// Whether the 3D view shows symmetry now: not while the active tool can't act on the selection pub(crate) fn shown(app: &TextureCraftApp) -> bool { - app.ui.mode == crate::state::Mode::Painting && applies_to(app.session.tool.tool) && app.session.tool.brush.symmetry.any() + let tool = app.session.tool.tool; + app.ui.mode == crate::state::Mode::Painting && applies_to(tool) && app.session.tool_usable(tool) && app.session.tool.brush.symmetry.any() } /// The world axes any active mirror plane or radial axis can move along, even while symmetry is disabled diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4ac469eb..0ee5f73d 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -178,9 +178,30 @@ const RUBBER_BAND_GAP: f32 = 4.0; /// Opacity of the UV tile outlines in the 2D view const UV_TILE_OUTLINE_ALPHA: u8 = 40; +/// Width of the UV tile outlines, in points +const UV_TILE_OUTLINE_WIDTH: f32 = 1.0; + +/// The texture set name in the 2D view's bottom-right corner: its inset from the corner and its text size, in points +const SET_NAME_INSET: egui::Vec2 = vec2(10.0, 10.0); +const SET_NAME_TEXT_SIZE: f32 = 11.0; + /// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; +/// The bake brush cursor's outline: width in points and white alpha +const BAKE_PAINT_CURSOR_STROKE: f32 = 1.0; +const BAKE_PAINT_CURSOR_ALPHA: u8 = 200; + +/// A UDIM tile label: its offset from the tile's top-left corner and its text size, in points +const UV_TILE_LABEL_OFFSET: egui::Vec2 = vec2(6.0, 4.0); +const UV_TILE_LABEL_SIZE: f32 = 11.0; + +/// The projection 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; +const STENCIL_OUTLINE_GAP: f32 = 4.0; + /// The 2D view's width when the split divider is at `divider_x` fn uv_view_width(full: Rect, divider_x: f32) -> f32 { (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) @@ -219,18 +240,24 @@ fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) { ui.interact(zone, split_divider_id(ui), Sense::drag()).on_hover_and_drag_cursor(egui::CursorIcon::ResizeHorizontal); } +/// The shader's view modes (`Shade::view_mode`): the material, one channel, the aux texture (mesh map, mask or quick mask), the UV checker +const VIEW_MODE_MATERIAL: u32 = 0; +const VIEW_MODE_CHANNEL: u32 = 1; +const VIEW_MODE_AUX_TEXTURE: u32 = 2; +const VIEW_MODE_UV_CHECKER: u32 = 3; + fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { - _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (2, 0), - ViewMode::Material => (0, 0), - ViewMode::Channel(selected_channel) => (1, selected_channel.index() as u32), - ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0), - ViewMode::UvChecker => (3, 0), + _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (VIEW_MODE_AUX_TEXTURE, 0), + ViewMode::Material => (VIEW_MODE_MATERIAL, 0), + ViewMode::Channel(selected_channel) => (VIEW_MODE_CHANNEL, selected_channel.index() as u32), + ViewMode::MeshMap(_) | ViewMode::Mask(_) => (VIEW_MODE_AUX_TEXTURE, 0), + ViewMode::UvChecker => (VIEW_MODE_UV_CHECKER, 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); // Polygon fill shows the polygons it fills without changing the saved wireframe toggles - let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; + let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, @@ -488,7 +515,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Navigation; S + drag moves the projection 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(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); - let stencil_drag = s_held && app.session.tool.stencil.is_some(); + // 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; + let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some(); if stencil_drag || adjusting { // The stencil or the brush changes instead of the camera } else if response.dragged_by(PointerButton::Middle) { @@ -510,8 +539,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { if shift && app.ui.mode == crate::state::Mode::Painting { - let brush = &mut app.session.tool.brush; - brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + // A tool that can't act keeps its size: its controls are hidden + if tool_acts(app) { + let brush = &mut app.session.tool.brush; + brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + } } else { app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT); } @@ -537,7 +569,10 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Stencil: S + left drag turns it, S + right drag scales it, S + middle drag moves it - if s_held && let Some(stencil) = app.session.tool.stencil.as_mut() { + if s_held + && stencil_moves + && let Some(stencil) = app.session.tool.stencil.as_mut() + { if response.dragged_by(PointerButton::Primary) { stencil.rotation = (stencil.rotation + delta.x * STENCIL_DEGREES_PER_POINT).rem_euclid(360.0); } else if response.dragged_by(PointerButton::Secondary) { @@ -636,7 +671,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let symmetry_handle = !app.session.stroke_active() && crate::symmetry::manipulator_hovered(app, ui, rect); // Painting - let painting = app.ui.mode == crate::state::Mode::Painting + let painting = tool_acts(app) && !popup && !alt && !adjusting @@ -716,7 +751,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began let mut symmetry_cursor = None; - if app.ui.mode == crate::state::Mode::Painting + if tool_acts(app) && !navigating && response.hovered() && brush_tool(app.session.tool.tool) @@ -746,7 +781,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - if app.ui.mode == crate::state::Mode::Painting && path_tool { + if tool_acts(app) && path_tool { path_overlay(app, ui, rect, &response, false, show); } crate::symmetry::overlay(app, ui, rect, symmetry_cursor); @@ -1008,12 +1043,13 @@ fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { /// Draw the projection stencil in Paint Mode fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { - if app.ui.mode != crate::state::Mode::Painting || app.session.tool.tool != Tool::Projection { + if !tool_acts(app) || app.session.tool.tool != Tool::Projection { return; } let Some(stencil) = app.session.tool.stencil.clone() else { return }; let Some(image) = app.session.images.get(&stencil.image).cloned() else { return }; + // Where the stencil's corners land on screen let texture = app.thumbs.stencil(ui.ctx(), &stencil.image, &image); let aspect = rect.width() / rect.height().max(1.0); let (center, half_size, rotation) = stencil.placement(image.width as f32 / image.height.max(1) as f32, aspect); @@ -1023,7 +1059,8 @@ fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { let (x, y) = (x * half_size[0], y * half_size[1]); to_screen(center[0] + x * cosine - y * sine, center[1] + x * sine + y * cosine) }; - let tint = Color32::from_white_alpha((stencil.opacity * 255.0) as u8); + + let tint = Color32::from_white_alpha((stencil.opacity * f32::from(u8::MAX)) as u8); let mut mesh = egui::Mesh::with_texture(texture.id()); 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), uv: pos2(u, v), color: tint }); @@ -1031,8 +1068,10 @@ fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]); let painter = ui.painter_at(rect); painter.add(egui::Shape::mesh(mesh)); + let outline = vec![corner(-1.0, 1.0), corner(1.0, 1.0), corner(1.0, -1.0), corner(-1.0, -1.0), corner(-1.0, 1.0)]; - painter.add(egui::Shape::dashed_line(&outline, Stroke::new(1.0, Color32::from_white_alpha(120)), 5.0, 4.0)); + let outline_stroke = Stroke::new(STENCIL_OUTLINE_STROKE, Color32::from_white_alpha(STENCIL_OUTLINE_ALPHA)); + painter.add(egui::Shape::dashed_line(&outline, outline_stroke, STENCIL_OUTLINE_DASH, STENCIL_OUTLINE_GAP)); } /// A world point on screen in the 3D view `rect` (None behind the camera) @@ -1080,19 +1119,16 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { return; } - if app.ui.mode != crate::state::Mode::Painting - || app.session.tool.tool != Tool::Path - || app.session.tool.path.points.is_empty() - || ui.ctx().egui_wants_keyboard_input() - { + if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || ui.ctx().egui_wants_keyboard_input() { return; } - let (enter, back) = ui.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::Enter), i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace))); + let (enter, backspace) = + ui.input_mut(|input| (input.consume_key(egui::Modifiers::NONE, egui::Key::Enter), input.consume_key(egui::Modifiers::NONE, egui::Key::Backspace))); if enter { app.run("tool.path", json!({"commit": true})); } - if back { + if backspace { app.session.remove_selected_path_point(); } } @@ -1482,12 +1518,9 @@ fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option) { ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside); } -/// V held with the Clone tool in painting mode: clicks set the clone source. +/// V held with the Clone tool in painting mode: clicks set the clone source fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { - app.ui.mode == crate::state::Mode::Painting - && app.session.tool.tool == Tool::Clone - && ui.input(|i| i.key_down(egui::Key::V)) - && !ui.ctx().egui_wants_keyboard_input() + tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(egui::Key::V)) && !ui.ctx().egui_wants_keyboard_input() } /// Crosshair where the Clone tool reads from. @@ -1502,20 +1535,23 @@ fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { } } +/// 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) +} + /// Tools that paint with the brush (and show its cursor). fn brush_tool(t: Tool) -> bool { matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) } -/// Ctrl (Cmd on macOS) + drag in a view changes the brush instead of painting or navigating: a -/// right drag its size (left/right) and hardness (up/down), a left drag its flow and angle. True -/// while Ctrl is held with a brush tool and no stroke is under way. -fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response) -> bool { - let held = - app.ui.mode == crate::state::Mode::Painting && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|i| i.modifiers.command); - if held && let Some(right) = brush_drag_button(resp) { - adjust_brush(&mut app.session.tool.brush, right, ui.input(|i| i.pointer.delta())); +/// Ctrl (Cmd on macOS) + drag changes the brush instead of painting: true while it applies (see `adjust_brush`) +fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) -> bool { + let held = tool_acts(app) && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|input| input.modifiers.command); + if held && let Some(right) = brush_drag_button(response) { + adjust_brush(&mut app.session.tool.brush, right, ui.input(|input| input.pointer.delta())); } + held } @@ -1660,8 +1696,8 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Conversions between the view's points and the texture set's UV space - let ts = app.session.ts(); - let set = app.session.doc.project.texture_sets.get(ts); + let texture_set_index = app.session.ts(); + let set = app.session.doc.project.texture_sets.get(texture_set_index); let [scale_x, scale_y] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |texture_set| texture_set.size())); let pan = app.ui.uv_pan; let to_uv = |pointer: egui::Pos2| { @@ -1708,7 +1744,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Painting in UV space - let painting = app.ui.mode == crate::state::Mode::Painting + let painting = tool_acts(app) && app.properties_popup.is_none() && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) && !alt @@ -1738,7 +1774,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let frame = Frame { view_id: VIEW_2D, size: frame_size_in_pixels(ui, rect), - kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, + kind: ViewKind::Uv { ts: texture_set_index, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, camera: app.session.camera, shade: shade(app), visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), @@ -1750,8 +1786,10 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); - let set = app.session.doc.project.texture_sets.get(ts); - let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside); + let set = app.session.doc.project.texture_sets.get(texture_set_index); + let outline = |tile: Rect| { + painter.rect_stroke(tile, 0.0, Stroke::new(UV_TILE_OUTLINE_WIDTH, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside) + }; match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { Some((texture_set, grid)) => { for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { @@ -1761,10 +1799,10 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let tile = Rect::from_two_pos(to_screen(u0, v0), to_screen(u0 + tile_scale / grid.cols as f32, v0 + tile_scale / grid.rows as f32)); outline(tile); painter.text( - tile.left_top() + vec2(6.0, 4.0), + tile.left_top() + UV_TILE_LABEL_OFFSET, egui::Align2::LEFT_TOP, udim.to_string(), - egui::FontId::proportional(11.0), + egui::FontId::proportional(UV_TILE_LABEL_SIZE), tokens.viewport_text, ); } @@ -1773,7 +1811,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin outline(Rect::from_two_pos(to_screen(0.0, 0.0), to_screen(1.0, 1.0))); } } - if app.ui.mode == crate::state::Mode::Painting && path_tool { + if tool_acts(app) && path_tool { path_overlay(app, ui, rect, &response, true, show); } @@ -1792,15 +1830,16 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); if bake_paint_on && let Some(hover) = response.hover_pos() { let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS); - painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); + painter.circle_stroke(hover, radius, Stroke::new(BAKE_PAINT_CURSOR_STROKE, Color32::from_white_alpha(BAKE_PAINT_CURSOR_ALPHA))); } } brush_readout(app, ui, &response, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); - let name = app.session.doc.project.texture_sets.get(ts).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); - ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); + let name = app.session.doc.project.texture_sets.get(texture_set_index).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); + let name_position = rect.right_bottom() - SET_NAME_INSET; + ui.painter().text(name_position, egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(SET_NAME_TEXT_SIZE), tokens.viewport_text); } /// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke. diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index 6b9775ea..094e858a 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -88,6 +88,52 @@ fn shortcuts_skip_the_tools_the_shelf_greys() { assert_eq!(harness.state().session.tool.tool, Tool::ColorPicker); } +/// Drag with the left button across the middle of the 3D view, as a stroke would +fn drag_across_the_view(harness: &mut Harness<'_, TextureCraftApp>) { + const STEPS: usize = 4; + const STEP_POINTS: f32 = 15.0; + + let center = harness.state().viewport_rect.center(); + let modifiers = egui::Modifiers::NONE; + harness.hover_at(center); + harness.event(egui::Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(2); + + for step in 1..=STEPS { + harness.hover_at(center + egui::vec2(STEP_POINTS * step as f32, 0.0)); + harness.run_steps(1); + } + + let end = center + egui::vec2(STEP_POINTS * STEPS as f32, 0.0); + harness.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(3); +} + +#[test] +fn a_tool_that_cant_act_ignores_the_view() { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + select(session, paint, json!("content")); + harness.run_steps(4); + + let steps_before = harness.state().session.history_labels().len(); + drag_across_the_view(&mut harness); + + assert!(harness.state().session.history_labels().len() > steps_before, "the drag reaches the mesh and paints a paint layer"); + + for tool in [Tool::Paint, Tool::PolygonFill, Tool::Path] { + select_fill_content(&mut harness, tool); + let steps_before = harness.state().session.history_labels().len(); + drag_across_the_view(&mut harness); + + let state = harness.state(); + assert!(state.toasts.is_empty(), "{tool:?} on a fill layer: no error toast, got {:?}", state.toasts.first().map(|toast| &toast.text)); + assert_eq!(state.session.history_labels().len(), steps_before, "{tool:?} on a fill layer changes nothing"); + assert!(state.session.tool.path.points.is_empty(), "{tool:?} places no path points"); + } +} + #[test] fn bake_painting_turns_on_the_shelf_paint_tool() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); From 4ac09bf4f702599dc735f9d2f39f13028481d113 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 06:59:40 +0000 Subject: [PATCH 10/42] Assets: one grid per tab sorted by name, without category headers; search results in one grid --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 255 ++++-------------- crates/ui-egui/src/shelf_entry.rs | 150 +++++++++++ .../ui-egui/tests/it/shelf_hover_preview.rs | 14 +- 4 files changed, 217 insertions(+), 203 deletions(-) create mode 100644 crates/ui-egui/src/shelf_entry.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..c47ddd4f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -47,6 +47,7 @@ mod resource_picker; mod resource_picker_item; mod running_bake; pub mod shelf; +mod shelf_entry; pub mod shelf_preview; mod soft_box; pub mod state; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 51700285..7afff1f2 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -1,27 +1,23 @@ //! The asset shelf (the Assets dock tab): tabs (materials, smart materials, smart //! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. -//! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas +//! Each tab is one grid sorted by name; a search shows the matches of every tab in one grid. +//! Materials (built in and saved), smart masks, filters, alphas //! and textures drag onto the layer stack, a layer row, the viewport or the brush properties //! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::core::ProceduralKind; -use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; -use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; -use texturecraft_engine::paint::alphas; -use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; -use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; +use crate::shelf_entry::ShelfEntry; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; use crate::thumbs::Thumbs; @@ -248,28 +244,30 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(4.0); let filter = app.ui.shelf_filter.to_lowercase(); - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - // Searching shows matches from every tab, each under its tab's name - for (i, (t, _, title)) in TABS.iter().enumerate() { - if filter.is_empty() && i != tab { - continue; - } + let shown_tab = TABS[tab].0; + // Searching shows matches from every tab in one grid + let mut entries: Vec = + ShelfEntry::all(app).into_iter().filter(|entry| (searching || entry.tab() == shown_tab) && entry.matches(&filter)).collect(); + entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); - let title = tr(title); - match t { - Tab::Materials => materials(app, ui, &ctx, &filter, false, title), - Tab::Smart => { - materials(app, ui, &ctx, &filter, true, title); - library(app, ui, &filter); - } - Tab::Masks => smart_masks(app, ui, &ctx, &filter, title), - Tab::Filters => filters(app, ui, &ctx, &filter, title), - Tab::Brushes => brushes(app, ui, &ctx, &filter, title), - Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title), - Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title), - Tab::Environments => environments(app, ui, &filter, title), - Tab::Textures => textures(app, ui, &ctx, &filter, title), + egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { + if !searching && shown_tab == Tab::Textures { + import_images(app, ui, &ctx, entries.is_empty()); + } + tiles(ui, |ui| { + for entry in &entries { + entry_tile(app, ui, &ctx, entry); } + }); + + if searching || shown_tab == Tab::Smart { + library(app, ui, &filter); + } + if searching || shown_tab == Tab::Brushes { + my_brushes(app, ui, &filter); + } + if searching || shown_tab == Tab::Environments { + environments(app, ui, &filter); } }); drag_preview(&ctx); @@ -291,11 +289,6 @@ pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } -fn title(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(text).strong().color(tk.text_strong)); -} - pub(crate) fn header(ui: &mut Ui, text: &str) { let tk = Tokens::get(ui.ctx()); ui.add_space(2.0); @@ -321,29 +314,6 @@ pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) out } -/// Built-in materials or smart materials, grouped by category -fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) { - let shown: Vec<_> = - MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect(); - if shown.is_empty() { - return; - } - - title(ui, name); - for category in categories(&shown, |material| material.category) { - header(ui, category); - tiles(ui, |ui| { - for material in shown.iter().filter(|material| material.category == category) { - let texture = app.thumbs.material(ctx, material.id); - let asset = Asset::Material(material.id); - if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); - } -} - /// The user's saved smart materials (desktop library folder). #[cfg(not(target_arch = "wasm32"))] fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { @@ -393,66 +363,6 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<_> = SMART_MASKS.iter().filter(|m| matches(filter, &[m.label, m.id])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - tiles(ui, |ui| { - for m in shown { - let tex = app.thumbs.smart_mask(ctx, m.id); - let asset = Asset::SmartMask(m.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); -} - -/// The filter library, grouped: a click adds the filter to the selected layer's content (or its -/// mask when the mask is selected), a drop onto a layer to that layer's content. -fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<_> = FILTERS.iter().filter(|f| matches(filter, &[f.label, f.group, f.id, tr(f.label), tr(f.group)])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - for group in categories(&shown, |f| f.group) { - header(ui, tr(group)); - tiles(ui, |ui| { - for f in shown.iter().filter(|f| f.group == group) { - let tex = app.thumbs.filter(ctx, f.id); - let asset = Asset::Filter(f.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); - } -} - -/// Brush presets, grouped by category, then the user's own: a click sets the brush's stroke -/// (alpha, spacing, flow, jitters…) and keeps its size. -fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<&BrushPreset> = PRESETS.iter().filter(|p| matches(filter, &[p.label, p.category, p.id])).collect(); - if !shown.is_empty() { - title(ui, name); - for cat in categories(&shown, |p| p.category) { - header(ui, cat); - tiles(ui, |ui| { - for p in shown.iter().filter(|p| p.category == cat) { - let tex = app.thumbs.brush_preset(ctx, p); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() { - app.run("brush.preset.apply", json!({"preset": p.id})); - } - } - }); - } - } - my_brushes(app, ui, filter); -} - /// The user's saved brush presets (desktop brushes folder) and saving the current brush there. #[cfg(not(target_arch = "wasm32"))] fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { @@ -508,57 +418,8 @@ fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -/// The built-in alpha library, grouped by category; the brush's alpha is outlined. -fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let tk = Tokens::get(ctx); - let shown: Vec<&'static alphas::LibraryAlpha> = alphas::library().iter().filter(|a| matches(filter, &[&a.label, a.category, &a.id])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - let brush = &app.session.tool.brush; - let current = if brush.alpha_image.is_none() { brush.alpha_library.clone() } else { None }; - for cat in categories(&shown, |a| a.category) { - header(ui, cat); - tiles(ui, |ui| { - for &a in shown.iter().filter(|a| a.category == cat) { - let tex = app.thumbs.alpha(ctx, a); - let asset = Asset::Alpha(&a.id); - let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset)); - if current.as_deref() == Some(a.id.as_str()) { - ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } - if r.clicked() { - apply(app, &asset); - } - } - }); - } -} - -fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec = ProceduralKind::ALL.into_iter().filter(|k| matches(filter, &[k.label(), tr(k.label())])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - tiles(ui, |ui| { - for k in shown { - let tex = app.thumbs.procedural(ctx, k); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() { - app.run("layer.add.fill", json!({"name": k.label()})); - app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); - } - } - }); -} - -fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, name: &str) { +fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { let shown: Vec<&&str> = ENVIRONMENTS.iter().filter(|e| matches(filter, &[e])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); for env in shown { let on = app.session.doc.project.display.environment == **env; if ui.selectable_label(on, format!("{} {env}", ic::SUN_HORIZON)).clicked() { @@ -568,44 +429,44 @@ fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, name: &str ui.add_space(6.0); } -fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { +/// The Textures tab's import button, and a hint while the project has no images +fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { let tk = Tokens::get(ctx); - let names: Vec = app.session.doc.resources.keys().filter(|n| matches(filter, &[n])).cloned().collect(); - if !filter.is_empty() && names.is_empty() { - return; + if ui.small_button(tr("Import...")).clicked() { + crate::menus::invoke(app, ctx, "resource.import"); } - ui.horizontal(|ui| { - title(ui, name); - if ui.small_button(tr("Import...")).clicked() { - crate::menus::invoke(app, ctx, "resource.import"); - } - }); - if names.is_empty() { + if empty { ui.label(RichText::new(tr("Import images to use them in fills and masks")).size(10.0).color(tk.text_dim)); } - tiles(ui, |ui| { - for name in names { - let Some(img) = app.session.images.get(&name).cloned() else { continue }; +} - let tex = app.thumbs.image(ctx, &name, &img); - let asset = Asset::Texture(name.clone()); - let preview = || ShelfPreview::Image(name.clone(), img); - let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset)); - if r.clicked() { - apply(app, &asset); +/// The tile of `entry`: a click applies it, an image resource has a context menu +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry) { + // An image removed this frame has nothing to show + let (Some(preview), texture) = (entry.preview(app), entry.thumbnail(app, ctx)) else { return }; + + let asset = entry.asset(); + let response = tile(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref()); + if entry.in_use(app) { + let tk = Tokens::get(ctx); + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + entry.activate(app); + } + + if let ShelfEntry::Image(name) = entry { + response.context_menu(|ui| { + if ui.button(tr("Add as decal (view center)")).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); } - r.context_menu(|ui| { - if ui.button(tr("Add as decal (view center)")).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); - } - if ui.button(tr("Remove resource")).clicked() { - app.run("resource.remove", json!({"name": name})); - ui.close(); - } - }); - } - }); + if ui.button(tr("Remove resource")).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); + } + }); + } } /// Asset tile with optional dragging and a larger hover preview diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs new file mode 100644 index 00000000..554cc6a4 --- /dev/null +++ b/crates/ui-egui/src/shelf_entry.rs @@ -0,0 +1,150 @@ +//! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies + +use serde_json::json; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::filter_lib::{FILTERS, FilterDef}; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; +use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; +use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf::{Asset, Tab, apply}; +use crate::shelf_preview::ShelfPreview; + +/// A shelf tile's asset +#[derive(Clone)] +pub(crate) enum ShelfEntry { + Material(&'static SmartMaterial), + SmartMask(&'static SmartMask), + Filter(&'static FilterDef), + Brush(&'static BrushPreset), + Alpha(&'static LibraryAlpha), + Procedural(ProceduralKind), + /// An image resource of the project, by name + Image(String), +} + +impl ShelfEntry { + /// Every built-in asset and the project's images + pub(crate) fn all(app: &TextureCraftApp) -> Vec { + let built_in = MATERIALS + .iter() + .map(ShelfEntry::Material) + .chain(SMART_MASKS.iter().map(ShelfEntry::SmartMask)) + .chain(FILTERS.iter().map(ShelfEntry::Filter)) + .chain(PRESETS.iter().map(ShelfEntry::Brush)) + .chain(alphas::library().iter().map(ShelfEntry::Alpha)) + .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)); + built_in.chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() + } + + /// The tab that lists the asset + pub(crate) fn tab(&self) -> Tab { + match self { + ShelfEntry::Material(material) if material.smart => Tab::Smart, + ShelfEntry::Material(_) => Tab::Materials, + ShelfEntry::SmartMask(_) => Tab::Masks, + ShelfEntry::Filter(_) => Tab::Filters, + ShelfEntry::Brush(_) => Tab::Brushes, + ShelfEntry::Alpha(_) => Tab::Alphas, + ShelfEntry::Procedural(_) => Tab::Procedurals, + ShelfEntry::Image(_) => Tab::Textures, + } + } + + /// The name under the tile, translated where the asset's name is + pub(crate) fn label(&self) -> &str { + match self { + ShelfEntry::Material(material) => material.label, + ShelfEntry::SmartMask(mask) => mask.label, + ShelfEntry::Filter(filter) => tr(filter.label), + ShelfEntry::Brush(preset) => preset.label, + ShelfEntry::Alpha(alpha) => &alpha.label, + ShelfEntry::Procedural(kind) => tr(kind.label()), + ShelfEntry::Image(name) => name, + } + } + + /// Whether `filter` (lowercase) matches the asset's name, id or category, in English or translated + pub(crate) fn matches(&self, filter: &str) -> bool { + let texts: &[&str] = match self { + ShelfEntry::Material(material) => &[material.label, material.category, material.id], + ShelfEntry::SmartMask(mask) => &[mask.label, mask.id], + ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)], + ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], + ShelfEntry::Alpha(alpha) => &[&alpha.label, alpha.category, &alpha.id], + ShelfEntry::Procedural(kind) => &[kind.label(), tr(kind.label())], + ShelfEntry::Image(name) => &[name], + }; + crate::shelf::matches(filter, texts) + } + + /// The thumbnail, or None while it renders + pub(crate) fn thumbnail(&self, app: &mut TextureCraftApp, ctx: &egui::Context) -> Option { + match self { + ShelfEntry::Material(material) => app.thumbs.material(ctx, material.id), + ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), + ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), + ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), + ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), + ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), + ShelfEntry::Image(name) => { + let image = app.session.images.get(name).cloned()?; + Some(app.thumbs.image(ctx, name, &image)) + } + } + } + + /// What the hover popup renders; None for an image that is gone + pub(crate) fn preview(&self, app: &TextureCraftApp) -> Option { + Some(match self { + ShelfEntry::Material(material) => ShelfPreview::material(material.id), + ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), + ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), + ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), + ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), + ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), + ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), app.session.images.get(name).cloned()?), + }) + } + + /// The drag payload's asset; brushes and procedurals don't drag + pub(crate) fn asset(&self) -> Option { + match self { + ShelfEntry::Material(material) => Some(Asset::Material(material.id)), + ShelfEntry::SmartMask(mask) => Some(Asset::SmartMask(mask.id)), + ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), + ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), + ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), + ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) => None, + } + } + + /// Whether the tile is outlined as in use: the brush's library alpha + pub(crate) fn in_use(&self, app: &TextureCraftApp) -> bool { + let ShelfEntry::Alpha(alpha) = self else { return false }; + + let brush = &app.session.tool.brush; + brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str()) + } + + /// What a click on the tile does + pub(crate) fn activate(&self, app: &mut TextureCraftApp) { + match self { + ShelfEntry::Brush(preset) => { + app.run("brush.preset.apply", json!({"preset": preset.id})); + } + ShelfEntry::Procedural(kind) => { + app.run("layer.add.fill", json!({"name": kind.label()})); + app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); + } + entry => { + if let Some(asset) = entry.asset() { + apply(app, &asset); + } + } + } + } +} diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index c7ad071a..4deda09a 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -20,20 +20,22 @@ const REST: f32 = 0.1; /// Real time the worker gets to render const WORKER_TIMEOUT: Duration = Duration::from_secs(60); -/// Open the Materials tab and find two labels unique to shelf tiles +/// Open the Materials tab and find the first two labels (the grid is sorted by name) unique to shelf tiles fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder() + let mut harness = Harness::builder() .with_size(egui::vec2(1600.0, 960.0)) .with_step_dt(step_seconds) .with_pixels_per_point(pixels_per_point) .build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.state_mut().ui.shelf_tab = MATERIALS_TAB; - h.run_steps(4); + harness.state_mut().ui.shelf_tab = MATERIALS_TAB; + harness.run_steps(4); - let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect(); + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + let unique: Vec<_> = plain.into_iter().filter(|material| harness.query_all_by_label(material.label).count() == 1).take(2).collect(); assert_eq!(unique.len(), 2, "two materials with unique names"); - (h, unique) + (harness, unique) } /// Largest drawn texture in pixels, excluding fonts and images below `min_width` points From 3bcd57de006c3e361da190eb0e3375e3a8119374 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 06:59:51 +0000 Subject: [PATCH 11/42] Assets: a wider default panel, four tile columns in a 1920 px window; the right column gives up the width --- crates/ui-egui/src/docking.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 5bebfd98..1b6e9b2a 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -133,7 +133,7 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node Workspace { use Panel::*; let column = split( @@ -143,7 +143,7 @@ pub fn default_workspace() -> Workspace { split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), ); let root = - split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column)); + split(SplitAxis::Horizontal, SplitSize::Ratio(0.16), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.80), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); for panel in Panel::ALL { From 0a327746c6303059000fd85e6baa73eeef7c6c06 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:02:42 +0000 Subject: [PATCH 12/42] Assets: outline the last clicked or right-clicked tile --- crates/ui-egui/src/shelf.rs | 17 +++++++++++++++-- crates/ui-egui/src/shelf_entry.rs | 13 +++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 7afff1f2..1890c30e 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -29,6 +29,11 @@ const TILE_HEIGHT: f32 = 76.0; const TILE_GAP: f32 = 2.0; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; +/// The last clicked or right-clicked tile's [`ShelfEntry::key`], kept in egui's memory under this id +const SELECTED_TILE: &str = "shelf_selected_tile"; +/// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points +const SELECTED_OUTLINE_WIDTH: f32 = 1.5; +const IN_USE_OUTLINE_WIDTH: f32 = 1.0; /// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 60.0; const THUMBNAIL_CENTER_Y: f32 = 31.0; @@ -447,9 +452,17 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry let asset = entry.asset(); let response = tile(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref()); - if entry.in_use(app) { + let selected_id = egui::Id::unique(SELECTED_TILE); + let key = entry.key(); + let selected = ctx.data(|data| data.get_temp::(selected_id)).is_some_and(|selected| selected == key); + if selected || entry.in_use(app) { let tk = Tokens::get(ctx); - ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + let width = if selected { SELECTED_OUTLINE_WIDTH } else { IN_USE_OUTLINE_WIDTH }; + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tk.accent), egui::StrokeKind::Inside); + } + + if response.clicked() || response.secondary_clicked() { + ctx.data_mut(|data| data.insert_temp(selected_id, key)); } if response.clicked() { entry.activate(app); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 554cc6a4..be43977b 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -54,6 +54,19 @@ impl ShelfEntry { } } + /// The asset's identity across frames: its kind and id + pub(crate) fn key(&self) -> String { + match self { + ShelfEntry::Material(material) => format!("material:{}", material.id), + ShelfEntry::SmartMask(mask) => format!("mask:{}", mask.id), + ShelfEntry::Filter(filter) => format!("filter:{}", filter.id), + ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), + ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), + ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), + ShelfEntry::Image(name) => format!("image:{name}"), + } + } + /// The name under the tile, translated where the asset's name is pub(crate) fn label(&self) -> &str { match self { From 1be96b8248d6d23eeba5c281b672c8d700d68076 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:10:52 +0000 Subject: [PATCH 13/42] Assets: environments as tiles with their panorama, the shown one outlined --- crates/ui-egui/src/preview_image.rs | 17 ++++++++++++++++ crates/ui-egui/src/shelf.rs | 15 -------------- crates/ui-egui/src/shelf_entry.rs | 31 ++++++++++++++++++++++------- crates/ui-egui/src/shelf_preview.rs | 7 ++++++- crates/ui-egui/src/thumbs.rs | 5 +++++ 5 files changed, 52 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 9b753b74..16709385 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -194,3 +194,20 @@ pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { } ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) } + +/// Environment `name`'s panorama across a `size²` swatch, transparent above and below +pub fn environment_image(name: &str, size: usize) -> ColorImage { + let panorama = texturecraft_render::ibl::environment(name, u32::try_from(size).unwrap_or(u32::MAX)); + let (width, height) = (panorama.width as usize, panorama.height as usize); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let top = size.saturating_sub(height) / 2; + for (y, row) in panorama.data.chunks(width.max(1)).enumerate() { + for (x, linear) in row.iter().enumerate().take(size) { + let Some(pixel) = image.pixels.get_mut((top + y) * size + x) else { continue }; + + let [r, g, b] = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + *pixel = Color32::from_rgb(r, g, b); + } + } + image +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 1890c30e..0ff1cc6a 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -12,7 +12,6 @@ use serde_json::json; use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; -use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::decal_drop::DecalDrop; @@ -271,9 +270,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if searching || shown_tab == Tab::Brushes { my_brushes(app, ui, &filter); } - if searching || shown_tab == Tab::Environments { - environments(app, ui, &filter); - } }); drag_preview(&ctx); } @@ -423,17 +419,6 @@ fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { - let shown: Vec<&&str> = ENVIRONMENTS.iter().filter(|e| matches(filter, &[e])).collect(); - for env in shown { - let on = app.session.doc.project.display.environment == **env; - if ui.selectable_label(on, format!("{} {env}", ic::SUN_HORIZON)).clicked() { - app.run("display.set", json!({"environment": env})); - } - } - ui.add_space(6.0); -} - /// The Textures tab's import button, and a hint while the project has no images fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { let tk = Tokens::get(ctx); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index be43977b..c44ecb1c 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -2,6 +2,7 @@ use serde_json::json; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::project::ENVIRONMENTS; use texturecraft_engine::filter_lib::{FILTERS, FilterDef}; use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; @@ -22,6 +23,8 @@ pub(crate) enum ShelfEntry { Brush(&'static BrushPreset), Alpha(&'static LibraryAlpha), Procedural(ProceduralKind), + /// A built-in lighting environment, by name + Environment(&'static str), /// An image resource of the project, by name Image(String), } @@ -36,7 +39,8 @@ impl ShelfEntry { .chain(FILTERS.iter().map(ShelfEntry::Filter)) .chain(PRESETS.iter().map(ShelfEntry::Brush)) .chain(alphas::library().iter().map(ShelfEntry::Alpha)) - .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)); + .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) + .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); built_in.chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() } @@ -50,6 +54,7 @@ impl ShelfEntry { ShelfEntry::Brush(_) => Tab::Brushes, ShelfEntry::Alpha(_) => Tab::Alphas, ShelfEntry::Procedural(_) => Tab::Procedurals, + ShelfEntry::Environment(_) => Tab::Environments, ShelfEntry::Image(_) => Tab::Textures, } } @@ -63,6 +68,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), + ShelfEntry::Environment(name) => format!("environment:{name}"), ShelfEntry::Image(name) => format!("image:{name}"), } } @@ -76,6 +82,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => preset.label, ShelfEntry::Alpha(alpha) => &alpha.label, ShelfEntry::Procedural(kind) => tr(kind.label()), + ShelfEntry::Environment(name) => name, ShelfEntry::Image(name) => name, } } @@ -89,6 +96,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], ShelfEntry::Alpha(alpha) => &[&alpha.label, alpha.category, &alpha.id], ShelfEntry::Procedural(kind) => &[kind.label(), tr(kind.label())], + ShelfEntry::Environment(name) => &[name], ShelfEntry::Image(name) => &[name], }; crate::shelf::matches(filter, texts) @@ -103,6 +111,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), + ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), ShelfEntry::Image(name) => { let image = app.session.images.get(name).cloned()?; Some(app.thumbs.image(ctx, name, &image)) @@ -119,6 +128,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), + ShelfEntry::Environment(name) => ShelfPreview::Environment(name), ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), app.session.images.get(name).cloned()?), }) } @@ -131,16 +141,20 @@ impl ShelfEntry { ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), - ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) => None, + ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, } } - /// Whether the tile is outlined as in use: the brush's library alpha + /// Whether the tile is outlined as in use: the brush's library alpha, the shown environment pub(crate) fn in_use(&self, app: &TextureCraftApp) -> bool { - let ShelfEntry::Alpha(alpha) = self else { return false }; - - let brush = &app.session.tool.brush; - brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str()) + match self { + ShelfEntry::Alpha(alpha) => { + let brush = &app.session.tool.brush; + brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str()) + } + ShelfEntry::Environment(name) => app.session.doc.project.display.environment == *name, + _ => false, + } } /// What a click on the tile does @@ -153,6 +167,9 @@ impl ShelfEntry { app.run("layer.add.fill", json!({"name": kind.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); } + ShelfEntry::Environment(name) => { + app.run("display.set", json!({"environment": name})); + } entry => { if let Some(asset) = entry.asset() { apply(app, &asset); diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index b512f250..c4b4ae36 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -11,7 +11,7 @@ use texturecraft_engine::paint::alphas::LibraryAlpha; use texturecraft_engine::paint::presets::BrushPreset; use texturecraft_engine::preview; -use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; +use crate::preview_image::{alpha_image, environment_image, image_preview, procedural_image, sphere_image, stroke_preview}; /// The asset a shelf tile previews pub enum ShelfPreview { @@ -31,6 +31,8 @@ pub enum ShelfPreview { Brush(&'static BrushPreset), /// An image resource by name Image(String, Arc), + /// A built-in lighting environment's panorama + Environment(&'static str), } impl ShelfPreview { @@ -53,6 +55,7 @@ impl ShelfPreview { ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), ShelfPreview::Image(name, _) => format!("image:{name}"), + ShelfPreview::Environment(name) => format!("environment:{name}"), } } @@ -67,6 +70,7 @@ impl ShelfPreview { ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), ShelfPreview::Image(_, image) => Some(image_preview(image, size)), + ShelfPreview::Environment(name) => Some(environment_image(name, size)), } } } @@ -93,6 +97,7 @@ mod tests { ShelfPreview::Alpha(&alphas::library()[0]), ShelfPreview::Brush(&PRESETS[0]), ShelfPreview::Image("image".into(), Arc::new(image)), + ShelfPreview::Environment(texturecraft_engine::core::project::ENVIRONMENTS[0]), ]; for preview in previews { let key = preview.key(); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 059cc0a3..3aa97413 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -212,6 +212,11 @@ impl Thumbs { self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } + /// A lighting environment's panorama + pub fn environment(&mut self, ctx: &egui::Context, name: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX) + } + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) From 73e15193decc79776e37eba8ca835c6c2ca047e3 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:11:53 +0000 Subject: [PATCH 14/42] =?UTF-8?q?Assets:=20saved=20brushes=20as=20tiles;?= =?UTF-8?q?=20saving=20the=20current=20brush=20moves=20to=20Properties=20?= =?UTF-8?q?=E2=80=BA=20Brush=20=E2=80=BA=20Preset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/brush_preset_save.rs | 34 ++++++++++++++ crates/ui-egui/src/dock.rs | 4 ++ crates/ui-egui/src/i18n/ar.rs | 2 - crates/ui-egui/src/i18n/de.rs | 2 - crates/ui-egui/src/i18n/es.rs | 2 - crates/ui-egui/src/i18n/fr.rs | 2 - crates/ui-egui/src/i18n/it.rs | 2 - crates/ui-egui/src/i18n/ja.rs | 2 - crates/ui-egui/src/i18n/ko.rs | 2 - crates/ui-egui/src/i18n/pt_br.rs | 2 - crates/ui-egui/src/i18n/zh_hans.rs | 2 - crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/shelf.rs | 62 +++++-------------------- crates/ui-egui/src/shelf_entry.rs | 24 ++++++++-- crates/ui-egui/src/shelf_preview.rs | 28 +++++++++++ crates/ui-egui/src/thumbs.rs | 5 ++ 16 files changed, 105 insertions(+), 72 deletions(-) create mode 100644 crates/ui-egui/src/brush_preset_save.rs diff --git a/crates/ui-egui/src/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs new file mode 100644 index 00000000..7bc0faaa --- /dev/null +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -0,0 +1,34 @@ +//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab + +use egui::Ui; +use serde_json::json; +use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// The preset name field's width in points +const NAME_WIDTH: f32 = 110.0; + +/// A name field and a button that saves the current brush under that name +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { + let dir = crate::user_dir("brushes"); + ui.horizontal(|ui| { + let name_id = ui.make_persistent_id("brush_preset_name"); + let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); + ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH)); + + let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); + if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { + let path = dir.join(format!("{file}.{BRUSH_EXT}")); + // A folder that can't be made fails the save, which reports it + let _ = std::fs::create_dir_all(&dir); + if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { + new_name.clear(); + app.brushes = None; + } + } + + ui.data_mut(|data| data.insert_temp(name_id, new_name)); + }); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 53932f4e..61d39ced 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1583,6 +1583,10 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { } *brush = brush.sanitized(); + + // Presets are files, which the browser doesn't have + #[cfg(not(target_arch = "wasm32"))] + section(ui, "sec_brush_preset", tr("Preset"), false, |ui| crate::brush_preset_save::row(app, ui)); } /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 95373f3d..68e95d5c 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -919,8 +919,6 @@ pub const TABLE: &[(&str, &str)] = &[ "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), ("Brushes", "الفرش"), - ("My brushes", "فرشي"), - ("Use this brush (keeps its size)", "استخدام هذه الفرشاة (مع الحفاظ على حجمها)"), ("Brush name", "اسم الفرشاة"), ("Save current brush", "حفظ الفرشاة الحالية"), ("Start window", "نافذة البدء"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f7e7c35..e0f15ab8 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -959,8 +959,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), ("Brushes", "Pinsel"), - ("My brushes", "Meine Pinsel"), - ("Use this brush (keeps its size)", "Diesen Pinsel verwenden (Größe bleibt)"), ("Brush name", "Pinselname"), ("Save current brush", "Aktuellen Pinsel speichern"), ("Start window", "Startfenster"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b5361801..2bd6fc75 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -947,8 +947,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), ("Brushes", "Pinceles"), - ("My brushes", "Mis pinceles"), - ("Use this brush (keeps its size)", "Usar este pincel (conserva su tamaño)"), ("Brush name", "Nombre del pincel"), ("Save current brush", "Guardar el pincel actual"), ("Start window", "Ventana de inicio"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 00b8c2af..73c6b199 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -968,8 +968,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), ("Brushes", "Pinceaux"), - ("My brushes", "Mes pinceaux"), - ("Use this brush (keeps its size)", "Utiliser ce pinceau (garde sa taille)"), ("Brush name", "Nom du pinceau"), ("Save current brush", "Enregistrer le pinceau actuel"), ("Start window", "Fenêtre de démarrage"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index e067cf67..d785fb4a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -953,8 +953,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), ("Brushes", "Pennelli"), - ("My brushes", "I miei pennelli"), - ("Use this brush (keeps its size)", "Usa questo pennello (mantiene la dimensione)"), ("Brush name", "Nome del pennello"), ("Save current brush", "Salva il pennello attuale"), ("Start window", "Finestra iniziale"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 0e60e132..c437a9a5 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -941,8 +941,6 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), ("Brushes", "ブラシ一覧"), - ("My brushes", "マイブラシ"), - ("Use this brush (keeps its size)", "このブラシを使用(サイズはそのまま)"), ("Brush name", "ブラシ名"), ("Save current brush", "現在のブラシを保存"), ("Start window", "スタートウィンドウ"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 7f80b6be..df46e2f1 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -929,8 +929,6 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), ("Brushes", "브러시 목록"), - ("My brushes", "내 브러시"), - ("Use this brush (keeps its size)", "이 브러시 사용 (크기 유지)"), ("Brush name", "브러시 이름"), ("Save current brush", "현재 브러시 저장"), ("Start window", "시작 창"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e5b023af..87b0fc93 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -944,8 +944,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), ("Brushes", "Pincéis"), - ("My brushes", "Meus pincéis"), - ("Use this brush (keeps its size)", "Usar este pincel (mantém o tamanho)"), ("Brush name", "Nome do pincel"), ("Save current brush", "Salvar o pincel atual"), ("Start window", "Janela inicial"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index ef4209e4..3f1e89f7 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -884,8 +884,6 @@ pub const TABLE: &[(&str, &str)] = &[ "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), ("Brushes", "笔刷库"), - ("My brushes", "我的笔刷"), - ("Use this brush (keeps its size)", "使用此笔刷(保留大小)"), ("Brush name", "笔刷名称"), ("Save current brush", "保存当前笔刷"), ("Start window", "启动窗口"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c47ddd4f..cbfc80a8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,6 +10,8 @@ mod bake_job; pub mod bake_mode; mod bake_scene; +#[cfg(not(target_arch = "wasm32"))] +mod brush_preset_save; mod color_selection_editor; pub mod control; mod decal_drop; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 0ff1cc6a..2e8f6a82 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -249,6 +249,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let filter = app.ui.shelf_filter.to_lowercase(); let shown_tab = TABS[tab].0; + scan_brushes(app); // Searching shows matches from every tab in one grid let mut entries: Vec = ShelfEntry::all(app).into_iter().filter(|entry| (searching || entry.tab() == shown_tab) && entry.matches(&filter)).collect(); @@ -267,9 +268,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if searching || shown_tab == Tab::Smart { library(app, ui, &filter); } - if searching || shown_tab == Tab::Brushes { - my_brushes(app, ui, &filter); - } }); drag_preview(&ctx); } @@ -364,60 +362,24 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -/// The user's saved brush presets (desktop brushes folder) and saving the current brush there. +/// Read the user's saved brush presets (desktop brushes folder) unless they are already listed #[cfg(not(target_arch = "wasm32"))] -fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { +fn scan_brushes(app: &mut TextureCraftApp) { use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; - let dir = crate::user_dir("brushes"); - if app.brushes.is_none() { - let mut files: Vec = std::fs::read_dir(&dir) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.brushes = Some(files); - } - let files = app.brushes.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); - if !filter.is_empty() && shown.is_empty() { + + if app.brushes.is_some() { return; } - ui.horizontal(|ui| { - header(ui, tr("My brushes")); - if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { - app.brushes = None; - } - }); - for f in shown { - if ui - .add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f)))) - .on_hover_text(tr("Use this brush (keeps its size)")) - .clicked() - { - app.run("brush.preset.load", json!({"path": f.display().to_string()})); - } - } - ui.horizontal(|ui| { - let id = ui.make_persistent_id("brush_preset_name"); - let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); - ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0)); - let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); - if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { - let path = dir.join(format!("{file}.{BRUSH_EXT}")); - // A folder that can't be made fails the save, which reports it. - let _ = std::fs::create_dir_all(&dir); - if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { - new_name.clear(); - app.brushes = None; - } - } - ui.data_mut(|d| d.insert_temp(id, new_name)); - }); - ui.add_space(6.0); + + let mut files: Vec = std::fs::read_dir(crate::user_dir("brushes")) + .map(|dir| dir.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|extension| extension == BRUSH_EXT)).collect()) + .unwrap_or_default(); + files.sort(); + app.brushes = Some(files); } #[cfg(target_arch = "wasm32")] -fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} +fn scan_brushes(_: &mut TextureCraftApp) {} /// The Textures tab's import button, and a hint while the project has no images fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index c44ecb1c..a8d4cacc 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -1,5 +1,7 @@ //! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies +use std::path::PathBuf; + use serde_json::json; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::core::project::ENVIRONMENTS; @@ -14,6 +16,9 @@ use crate::i18n::tr; use crate::shelf::{Asset, Tab, apply}; use crate::shelf_preview::ShelfPreview; +/// The name of a saved brush whose file name isn't text +const SAVED_BRUSH_NAME: &str = "brush"; + /// A shelf tile's asset #[derive(Clone)] pub(crate) enum ShelfEntry { @@ -21,6 +26,8 @@ pub(crate) enum ShelfEntry { SmartMask(&'static SmartMask), Filter(&'static FilterDef), Brush(&'static BrushPreset), + /// A brush preset file the user saved + SavedBrush(PathBuf), Alpha(&'static LibraryAlpha), Procedural(ProceduralKind), /// A built-in lighting environment, by name @@ -30,7 +37,7 @@ pub(crate) enum ShelfEntry { } impl ShelfEntry { - /// Every built-in asset and the project's images + /// Every built-in asset, the user's saved brushes and the project's images pub(crate) fn all(app: &TextureCraftApp) -> Vec { let built_in = MATERIALS .iter() @@ -41,7 +48,8 @@ impl ShelfEntry { .chain(alphas::library().iter().map(ShelfEntry::Alpha)) .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); - built_in.chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() + let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush); + built_in.chain(saved).chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() } /// The tab that lists the asset @@ -51,7 +59,7 @@ impl ShelfEntry { ShelfEntry::Material(_) => Tab::Materials, ShelfEntry::SmartMask(_) => Tab::Masks, ShelfEntry::Filter(_) => Tab::Filters, - ShelfEntry::Brush(_) => Tab::Brushes, + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes, ShelfEntry::Alpha(_) => Tab::Alphas, ShelfEntry::Procedural(_) => Tab::Procedurals, ShelfEntry::Environment(_) => Tab::Environments, @@ -66,6 +74,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => format!("mask:{}", mask.id), ShelfEntry::Filter(filter) => format!("filter:{}", filter.id), ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), + ShelfEntry::SavedBrush(path) => format!("saved-brush:{}", path.display()), ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), ShelfEntry::Environment(name) => format!("environment:{name}"), @@ -77,6 +86,7 @@ impl ShelfEntry { pub(crate) fn label(&self) -> &str { match self { ShelfEntry::Material(material) => material.label, + ShelfEntry::SavedBrush(path) => path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_BRUSH_NAME), ShelfEntry::SmartMask(mask) => mask.label, ShelfEntry::Filter(filter) => tr(filter.label), ShelfEntry::Brush(preset) => preset.label, @@ -91,6 +101,7 @@ impl ShelfEntry { pub(crate) fn matches(&self, filter: &str) -> bool { let texts: &[&str] = match self { ShelfEntry::Material(material) => &[material.label, material.category, material.id], + ShelfEntry::SavedBrush(_) => &[self.label()], ShelfEntry::SmartMask(mask) => &[mask.label, mask.id], ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)], ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], @@ -109,6 +120,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), + ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path), ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), @@ -126,6 +138,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), + ShelfEntry::SavedBrush(path) => ShelfPreview::SavedBrush(path.clone()), ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), ShelfEntry::Environment(name) => ShelfPreview::Environment(name), @@ -141,7 +154,7 @@ impl ShelfEntry { ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), - ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, } } @@ -163,6 +176,9 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => { app.run("brush.preset.apply", json!({"preset": preset.id})); } + ShelfEntry::SavedBrush(path) => { + app.run("brush.preset.load", json!({"path": path.display().to_string()})); + } ShelfEntry::Procedural(kind) => { app.run("layer.add.fill", json!({"name": kind.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index c4b4ae36..076ea14f 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -1,5 +1,6 @@ //! Shelf assets and their preview renderers +use std::path::PathBuf; use std::sync::Arc; use egui::ColorImage; @@ -13,6 +14,10 @@ use texturecraft_engine::preview; use crate::preview_image::{alpha_image, environment_image, image_preview, procedural_image, sphere_image, stroke_preview}; +/// Larger brush preset files aren't read (the `brush.preset.load` command's limit) +#[cfg(not(target_arch = "wasm32"))] +const MAX_SAVED_BRUSH_BYTES: u64 = 1 << 20; + /// The asset a shelf tile previews pub enum ShelfPreview { /// A built-in plain material on a sphere @@ -29,6 +34,8 @@ pub enum ShelfPreview { Alpha(&'static LibraryAlpha), /// A brush preset's stroke along an S curve Brush(&'static BrushPreset), + /// A brush preset file the user saved, its stroke along an S curve + SavedBrush(PathBuf), /// An image resource by name Image(String, Arc), /// A built-in lighting environment's panorama @@ -54,6 +61,7 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), + ShelfPreview::SavedBrush(path) => format!("saved-brush:{}", path.display()), ShelfPreview::Image(name, _) => format!("image:{name}"), ShelfPreview::Environment(name) => format!("environment:{name}"), } @@ -69,12 +77,32 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), + ShelfPreview::SavedBrush(path) => Some(stroke_preview(&saved_brush(path)?, size)), ShelfPreview::Image(_, image) => Some(image_preview(image, size)), ShelfPreview::Environment(name) => Some(environment_image(name, size)), } } } +/// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files) +#[cfg(not(target_arch = "wasm32"))] +fn saved_brush(path: &std::path::Path) -> Option { + use std::io::Read as _; + + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|file| file.take(MAX_SAVED_BRUSH_BYTES + 1).read_to_end(&mut bytes)).ok()?; + if bytes.len() as u64 > MAX_SAVED_BRUSH_BYTES { + return None; + } + + serde_json::from_slice::(&bytes).ok().map(|settings| settings.sanitized()) +} + +#[cfg(target_arch = "wasm32")] +fn saved_brush(_: &std::path::Path) -> Option { + None +} + #[cfg(test)] mod tests { use texturecraft_engine::filter_lib::FILTERS; diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 3aa97413..a6bd93cb 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -217,6 +217,11 @@ impl Thumbs { self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX) } + /// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable + pub fn saved_brush(&mut self, ctx: &egui::Context, path: &std::path::Path) -> Option { + self.shelf(ctx, ShelfPreview::SavedBrush(path.to_path_buf()), SWATCH_PX) + } + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) From e8fd3b0074abbbf260a2fdb99007d08e39b59692 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:12:48 +0000 Subject: [PATCH 15/42] Assets: a dots badge on procedurals whose result depends on the random seed --- crates/ui-egui/src/shelf.rs | 27 ++++++++++++++++++- crates/ui-egui/src/shelf_entry.rs | 43 +++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 2e8f6a82..33cac185 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -33,6 +33,14 @@ const SELECTED_TILE: &str = "shelf_selected_tile"; /// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points const SELECTED_OUTLINE_WIDTH: f32 = 1.5; const IN_USE_OUTLINE_WIDTH: f32 = 1.0; +/// The randomness badge's dot radius, dot spacing and inset from the thumbnail's corner, in points +const BADGE_DOT_RADIUS: f32 = 1.3; +const BADGE_DOT_SPACING: f32 = 3.6; +const BADGE_INSET: f32 = 2.5; +/// The randomness badge's dot colour and its rim's width (points) and colour +const BADGE_DOT_FILL: Color32 = Color32::from_gray(205); +const BADGE_DOT_RIM: f32 = 0.8; +const BADGE_DOT_RIM_COLOR: Color32 = Color32::from_black_alpha(170); /// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 60.0; const THUMBNAIL_CENTER_Y: f32 = 31.0; @@ -408,6 +416,10 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tk.accent), egui::StrokeKind::Inside); } + if entry.includes_randomness() { + randomness_badge(ui.painter(), response.rect); + } + if response.clicked() || response.secondary_clicked() { ctx.data_mut(|data| data.insert_temp(selected_id, key)); } @@ -452,7 +464,7 @@ pub(crate) fn tile( if resp.hovered() || resp.dragged() { painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); } - let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + let image_rect = thumbnail_rect(rect); thumbnail(painter, tex, image_rect, &tk); let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); @@ -461,6 +473,19 @@ pub(crate) fn tile( resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) } +/// Where a tile's thumbnail goes in the tile's `rect` +fn thumbnail_rect(rect: egui::Rect) -> egui::Rect { + egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)) +} + +/// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness +fn randomness_badge(painter: &egui::Painter, tile: egui::Rect) { + let corner = thumbnail_rect(tile).right_bottom() - vec2(BADGE_INSET, BADGE_INSET); + for offset in [vec2(0.0, 0.0), vec2(-BADGE_DOT_SPACING, 0.0), vec2(-BADGE_DOT_SPACING * 0.5, -BADGE_DOT_SPACING)] { + painter.circle(corner + offset, BADGE_DOT_RADIUS, BADGE_DOT_FILL, Stroke::new(BADGE_DOT_RIM, BADGE_DOT_RIM_COLOR)); + } +} + /// A tile label on one line, cut with "…" past `width` points (the hover popup shows the whole name) fn one_line(label: &str, width: f32, color: Color32) -> egui::text::LayoutJob { let mut job = egui::text::LayoutJob::single_section(label.to_string(), egui::TextFormat::simple(egui::FontId::proportional(LABEL_FONT_SIZE), color)); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index a8d4cacc..cd147fde 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -19,6 +19,12 @@ use crate::shelf_preview::ShelfPreview; /// The name of a saved brush whose file name isn't text const SAVED_BRUSH_NAME: &str = "brush"; +/// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines +const SEED_PROBES: usize = 4; +const SEED_PROBE_OFFSET: f32 = 0.13; +/// A smaller difference between the two seeds' samples is rounding +const SEED_TOLERANCE: f32 = 1e-4; + /// A shelf tile's asset #[derive(Clone)] pub(crate) enum ShelfEntry { @@ -170,6 +176,14 @@ impl ShelfEntry { } } + /// Whether applying the asset gives a different result per random seed (the tile's dots badge) + pub(crate) fn includes_randomness(&self) -> bool { + match self { + ShelfEntry::Procedural(kind) => SEEDED_PROCEDURALS.contains(kind), + _ => false, + } + } + /// What a click on the tile does pub(crate) fn activate(&self, app: &mut TextureCraftApp) { match self { @@ -194,3 +208,32 @@ impl ShelfEntry { } } } + +/// The procedurals whose pattern depends on the seed, worked out once +static SEEDED_PROCEDURALS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| ProceduralKind::ALL.into_iter().filter(|kind| seed_changes(*kind)).collect()); + +/// Whether procedural `kind` samples differently under two seeds +fn seed_changes(kind: ProceduralKind) -> bool { + use texturecraft_engine::compose::pattern::{Coords, procedural}; + use texturecraft_engine::core::{Procedural, Projection}; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + let sample = |seed: u32, i: usize| { + let uv = Vec2::new((i % SEED_PROBES) as f32 / SEED_PROBES as f32, (i / SEED_PROBES) as f32 / SEED_PROBES as f32) + SEED_PROBE_OFFSET; + procedural(&Procedural { seed, ..Procedural::new(kind) }, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }) + }; + (0..SEED_PROBES * SEED_PROBES).any(|i| (sample(1, i) - sample(2, i)).abs() > SEED_TOLERANCE) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_seeded_procedurals_include_randomness() { + let seeded = &*SEEDED_PROCEDURALS; + assert!(seeded.contains(&ProceduralKind::Clouds), "{seeded:?}"); + assert!(!seeded.contains(&ProceduralKind::Checker), "{seeded:?}"); + } +} From 0ec76bb05e4f3042a11d650656c167d39eff68cf Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 02:38:21 +0000 Subject: [PATCH 16/42] Assets: procedurals and the project's images share one Textures tab --- crates/ui-egui/src/i18n/ar.rs | 1 - crates/ui-egui/src/i18n/de.rs | 1 - crates/ui-egui/src/i18n/es.rs | 1 - crates/ui-egui/src/i18n/fr.rs | 1 - crates/ui-egui/src/i18n/it.rs | 1 - crates/ui-egui/src/i18n/ja.rs | 1 - crates/ui-egui/src/i18n/ko.rs | 1 - crates/ui-egui/src/i18n/pt_br.rs | 1 - crates/ui-egui/src/i18n/zh_hans.rs | 1 - crates/ui-egui/src/shelf.rs | 16 +++++----------- crates/ui-egui/src/shelf_entry.rs | 2 +- 11 files changed, 6 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 68e95d5c..46a167de 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -615,7 +615,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "اضطراب الموضع"), ("Posterize", "تبسيط الألوان (Posterize)"), ("Press a key...", "اضغط على مفتاح..."), - ("Procedurals", "إجرائيات"), ("Project", "المشروع"), ("Project Configuration...", "تكوين المشروع..."), ("Project opened", "تم فتح المشروع"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index e0f15ab8..7ad71027 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -651,7 +651,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Positionsstreuung"), ("Posterize", "Tontrennung"), ("Press a key...", "Taste drücken..."), - ("Procedurals", "Prozedurale"), ("Project", "Projekt"), ("Project Configuration...", "Projektkonfiguration..."), ("Project opened", "Projekt geöffnet"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 2bd6fc75..d1c35108 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -642,7 +642,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variación de posición"), ("Posterize", "Posterizar"), ("Press a key...", "Pulsa una tecla..."), - ("Procedurals", "Procedurales"), ("Project", "Proyecto"), ("Project Configuration...", "Configuración del proyecto..."), ("Project opened", "Proyecto abierto"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 73c6b199..182e71e8 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -657,7 +657,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variation de position"), ("Posterize", "Postérisation"), ("Press a key...", "Appuyez sur une touche..."), - ("Procedurals", "Procéduraux"), ("Project", "Projet"), ("Project Configuration...", "Configuration du projet..."), ("Project opened", "Projet ouvert"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index d785fb4a..1e243196 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -648,7 +648,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variazione posizione"), ("Posterize", "Posterizza"), ("Press a key...", "Premi un tasto..."), - ("Procedurals", "Procedurali"), ("Project", "Progetto"), ("Project Configuration...", "Configurazione progetto..."), ("Project opened", "Progetto aperto"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index c437a9a5..c705d024 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -633,7 +633,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "位置ジッター"), ("Posterize", "ポスタリゼーション"), ("Press a key...", "キーを押してください..."), - ("Procedurals", "プロシージャル"), ("Project", "プロジェクト"), ("Project Configuration...", "プロジェクト構成..."), ("Project opened", "プロジェクトを開きました"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index df46e2f1..20e114da 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -624,7 +624,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "위치 지터"), ("Posterize", "포스터화"), ("Press a key...", "키를 누르세요..."), - ("Procedurals", "프로시저럴"), ("Project", "프로젝트"), ("Project Configuration...", "프로젝트 구성..."), ("Project opened", "프로젝트를 열었습니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 87b0fc93..2de14047 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -639,7 +639,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variação de posição"), ("Posterize", "Posterizar"), ("Press a key...", "Pressione uma tecla..."), - ("Procedurals", "Procedurais"), ("Project", "Projeto"), ("Project Configuration...", "Configuração do projeto..."), ("Project opened", "Projeto aberto"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3f1e89f7..c1925515 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -582,7 +582,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "位置抖动"), ("Posterize", "色调分离"), ("Press a key...", "请按下一个键..."), - ("Procedurals", "程序纹理"), ("Project", "项目"), ("Project Configuration...", "项目配置..."), ("Project opened", "项目已打开"), diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 33cac185..6543b230 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -1,9 +1,4 @@ -//! The asset shelf (the Assets dock tab): tabs (materials, smart materials, smart -//! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. -//! Each tab is one grid sorted by name; a search shows the matches of every tab in one grid. -//! Materials (built in and saved), smart masks, filters, alphas -//! and textures drag onto the layer stack, a layer row, the viewport or the brush properties -//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu +//! The Assets panel: built-in, saved and project assets in one grid by type, library and search, dragged onto the layer stack, the views or the brush use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; @@ -65,22 +60,21 @@ pub(crate) enum Tab { Filters, Brushes, Alphas, - Procedurals, - Environments, + /// Procedural patterns and the project's images Textures, + Environments, } /// The shelf tabs: icon and (English, translated where shown) name. -pub(crate) const TABS: [(Tab, &str, &str); 9] = [ +pub(crate) const TABS: [(Tab, &str, &str); 8] = [ (Tab::Materials, ic::SPHERE, "Materials"), (Tab::Smart, ic::STACK, "Smart materials"), (Tab::Masks, ic::CIRCLE_HALF, "Smart masks"), (Tab::Filters, ic::FUNNEL, "Filters"), (Tab::Brushes, ic::PAINT_BRUSH_BROAD, "Brushes"), (Tab::Alphas, ic::SHAPES, "Alphas"), - (Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"), - (Tab::Environments, ic::SUN_HORIZON, "Environments"), (Tab::Textures, ic::IMAGE, "Textures"), + (Tab::Environments, ic::SUN_HORIZON, "Environments"), ]; /// A shelf asset: built in (by id), a saved smart material (file path) or an image resource. diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index cd147fde..0def726c 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -67,7 +67,7 @@ impl ShelfEntry { ShelfEntry::Filter(_) => Tab::Filters, ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes, ShelfEntry::Alpha(_) => Tab::Alphas, - ShelfEntry::Procedural(_) => Tab::Procedurals, + ShelfEntry::Procedural(_) => Tab::Textures, ShelfEntry::Environment(_) => Tab::Environments, ShelfEntry::Image(_) => Tab::Textures, } From 6077efb3adfde8c8117d3f0cd512173da25a9735 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 02:44:17 +0000 Subject: [PATCH 17/42] Assets: type tab row: a click on the picked type shows every type again, types with nothing matching greyed, one dropdown when narrow --- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 34 +++++--------- crates/ui-egui/src/shelf_tabs.rs | 71 ++++++++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 2 +- 13 files changed, 94 insertions(+), 23 deletions(-) create mode 100644 crates/ui-egui/src/shelf_tabs.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 46a167de..e1f581d2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1129,4 +1129,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "الحد الأقصى لبيانات المشروع بعد فك الضغط. ارفع هذا الحد لفتح مشاريع أكبر.", ), + ("Filter by type", "تصفية حسب النوع"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 7ad71027..8064b888 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1175,4 +1175,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Maximale entpackte Projektdaten. Erhöhen Sie diesen Grenzwert, um größere Projekte zu öffnen.", ), + ("Filter by type", "Nach Typ filtern"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d1c35108..8fb206d4 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1166,4 +1166,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Máximo de datos descomprimidos del proyecto. Aumenta este límite para abrir proyectos más grandes.", ), + ("Filter by type", "Filtrar por tipo"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 182e71e8..da1da090 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1190,4 +1190,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Volume maximal des données décompressées du projet. Augmentez cette limite pour ouvrir des projets plus volumineux.", ), + ("Filter by type", "Filtrer par type"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1e243196..82437ae6 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1172,4 +1172,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Quantità massima di dati decompressi del progetto. Aumenta questo limite per aprire progetti più grandi.", ), + ("Filter by type", "Filtra per tipo"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index c705d024..92ceb5c1 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1157,4 +1157,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "展開後のプロジェクトデータの上限です。大きなプロジェクトを開くには、この上限を引き上げてください。", ), + ("Filter by type", "種類で絞り込む"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 20e114da..6bb57959 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1142,4 +1142,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "압축 해제된 프로젝트 데이터의 최대 크기입니다. 더 큰 프로젝트를 열려면 이 한도를 높이세요.", ), + ("Filter by type", "유형별 필터"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 2de14047..8ba06687 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1160,4 +1160,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Limite de dados descompactados do projeto. Aumente este limite para abrir projetos maiores.", ), + ("Filter by type", "Filtrar por tipo"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index c1925515..3842e2c7 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1085,4 +1085,5 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Max project size on open", "打开项目的大小上限"), ("Maximum decompressed project data. Increase this limit to open larger projects.", "解压后项目数据的大小上限。提高此限制以打开更大的项目。"), + ("Filter by type", "按类型筛选"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cbfc80a8..5b87b257 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -51,6 +51,7 @@ mod running_bake; pub mod shelf; mod shelf_entry; pub mod shelf_preview; +mod shelf_tabs; mod soft_box; pub mod state; pub mod symmetry; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 6543b230..fd085ad8 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -15,7 +15,7 @@ use crate::shelf_entry::ShelfEntry; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; use crate::thumbs::Thumbs; -use crate::widgets::{dnd_release, icon_button}; +use crate::widgets::dnd_release; /// A shelf tile's size and the gap between tiles in points: a 68 x 78 grid step, as in the reference const TILE_WIDTH: f32 = 66.0; @@ -65,7 +65,7 @@ pub(crate) enum Tab { Environments, } -/// The shelf tabs: icon and (English, translated where shown) name. +/// The shelf tabs: icon and (English, translated where shown) name pub(crate) const TABS: [(Tab, &str, &str); 8] = [ (Tab::Materials, ic::SPHERE, "Materials"), (Tab::Smart, ic::STACK, "Smart materials"), @@ -228,20 +228,12 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); - let mut tab = app.ui.shelf_tab.min(TABS.len() - 1); let searching = !app.ui.shelf_filter.is_empty(); - - ui.horizontal_wrapped(|ui| { - let button_size = ui.spacing().interact_size.y; - ui.spacing_mut().item_spacing = vec2(2.0, 2.0); - for (i, (_, icon, label)) in TABS.iter().enumerate() { - if icon_button(ui, icon, tr(label), i == tab && !searching, button_size).clicked() { - tab = i; - app.ui.shelf_filter.clear(); - } - } - }); - app.ui.shelf_tab = tab; + let filter = app.ui.shelf_filter.to_lowercase(); + scan_brushes(app); + let matching: Vec = ShelfEntry::all(app).into_iter().filter(|entry| entry.matches(&filter)).collect(); + let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + crate::shelf_tabs::row(app, ui, &counts, |_, _, _| {}); ui.horizontal(|ui| { ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); @@ -249,16 +241,14 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { }); ui.add_space(4.0); - let filter = app.ui.shelf_filter.to_lowercase(); - let shown_tab = TABS[tab].0; - scan_brushes(app); + let tab = app.ui.shelf_tab; + let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); // Searching shows matches from every tab in one grid - let mut entries: Vec = - ShelfEntry::all(app).into_iter().filter(|entry| (searching || entry.tab() == shown_tab) && entry.matches(&filter)).collect(); + let mut entries: Vec = matching.into_iter().filter(|entry| searching || crate::shelf_tabs::shows(tab, entry.tab())).collect(); entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - if !searching && shown_tab == Tab::Textures { + if !searching && shown_tab == Some(Tab::Textures) { import_images(app, ui, &ctx, entries.is_empty()); } tiles(ui, |ui| { @@ -267,7 +257,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - if searching || shown_tab == Tab::Smart { + if searching || shown_tab.is_none_or(|shown| shown == Tab::Smart) { library(app, ui, &filter); } }); diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs new file mode 100644 index 00000000..4e2c3e07 --- /dev/null +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -0,0 +1,71 @@ +//! The shelf's type row: one icon per type (none picked shows every type), greyed without matches, one dropdown when narrow + +use egui::{Ui, vec2}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf::{TABS, Tab}; +use crate::widgets::{icon_button, icon_dropdown_button}; + +/// The gap between the row's icons in points +const ICON_GAP: f32 = 2.0; +/// The size of the dot that marks the collapsed row's dropdown while a type is picked, in points +const FILTER_DOT_RADIUS: f32 = 2.5; + +/// `app.ui.shelf_tab` while no type is picked: every type shows +pub(crate) const NO_TYPE: usize = TABS.len(); + +/// The row, then `trailing` at its right end; `counts[i]` is how many assets of `TABS[i]` match the search +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) { + let size = ui.spacing().interact_size.y; + // The type icons and one icon after them + let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP); + let mut picked = app.ui.shelf_tab.min(NO_TYPE); + + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(ICON_GAP, ICON_GAP); + if ui.available_width() >= row_width { + for (i, (_, icon, label)) in TABS.iter().enumerate() { + // The picked type stays clickable so it can be unpicked + let empty = i != picked && counts.get(i).is_none_or(|count| *count == 0); + if ui.add_enabled_ui(!empty, |ui| icon_button(ui, icon, tr(label), i == picked, size)).inner.clicked() { + picked = if i == picked { NO_TYPE } else { i }; + } + } + } else { + collapsed(ui, &mut picked, counts, size); + } + + let rest = ui.available_width() - size; + ui.add_space(rest.max(0.0)); + trailing(app, ui, size); + }); + app.ui.shelf_tab = picked; +} + +/// One dropdown listing the types, dotted while one is picked +fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) { + let filtering = *picked != NO_TYPE; + let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size); + let response = response.on_hover_text(tr("Filter by type")); + if filtering { + let tk = crate::theme::Tokens::get(ui.ctx()); + let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS); + ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tk.accent); + } + + egui::Popup::menu(&response).show(|ui| { + for (i, (_, icon, label)) in TABS.iter().enumerate() { + let empty = i != *picked && counts.get(i).is_none_or(|count| *count == 0); + if ui.add_enabled(!empty, egui::Button::selectable(i == *picked, format!("{icon} {}", tr(label)))).clicked() { + *picked = if i == *picked { NO_TYPE } else { i }; + ui.close(); + } + } + }); +} + +/// Whether `tab` (an index into [`TABS`], or [`NO_TYPE`]) shows assets of type `kind` +pub(crate) fn shows(tab: usize, kind: Tab) -> bool { + TABS.get(tab).is_none_or(|(shown, _, _)| *shown == kind) +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e52a2907..2c03dc45 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -297,7 +297,7 @@ pub struct UiState { /// Channel whose blending the layer rows show. pub layer_channel: Channel, pub shelf_filter: String, - /// The asset shelf's open tab. + /// The asset shelf's picked type: an index into the shelf's types, or past them for every type #[serde(default)] pub shelf_tab: usize, pub props_tab: PropsTab, From a401d36f9ccd64b5131280687304275ecd74b5ce Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 02:56:58 +0000 Subject: [PATCH 18/42] Assets: search above the tabs, with a clear button; the search narrows the picked tab and a tab click keeps it --- crates/ui-egui/src/i18n/ar.rs | 1 - crates/ui-egui/src/i18n/de.rs | 1 - crates/ui-egui/src/i18n/es.rs | 1 - crates/ui-egui/src/i18n/fr.rs | 1 - crates/ui-egui/src/i18n/it.rs | 1 - crates/ui-egui/src/i18n/ja.rs | 1 - crates/ui-egui/src/i18n/ko.rs | 1 - crates/ui-egui/src/i18n/pt_br.rs | 1 - crates/ui-egui/src/i18n/zh_hans.rs | 1 - crates/ui-egui/src/shelf.rs | 29 ++++++++++++++++++----------- 10 files changed, 18 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index e1f581d2..de036796 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -696,7 +696,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "شاشة (Screen)"), ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), ("Search", "بحث"), - ("Search all assets", "البحث في جميع الأصول"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), ("Seed", "البذرة العشوائية (Seed)"), ("Select a layer", "تحديد طبقة"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 8064b888..dab5a9fc 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -732,7 +732,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Negativ multiplizieren"), ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), ("Search", "Suchen"), - ("Search all assets", "Alle Assets durchsuchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), ("Seed", "Startwert"), ("Select a layer", "Ebene auswählen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 8fb206d4..b7869bbf 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -723,7 +723,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Trama"), ("Screenshot of the viewport", "Captura de la ventana gráfica"), ("Search", "Buscar"), - ("Search all assets", "Buscar en todos los recursos"), ("Search commands or keys", "Buscar comandos o teclas"), ("Seed", "Semilla"), ("Select a layer", "Selecciona una capa"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index da1da090..84e49d0c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -741,7 +741,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Superposition"), ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), ("Search", "Rechercher"), - ("Search all assets", "Rechercher dans toutes les ressources"), ("Search commands or keys", "Rechercher des commandes ou des touches"), ("Seed", "Graine"), ("Select a layer", "Sélectionnez un calque"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 82437ae6..44047bf9 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -729,7 +729,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Scolora"), ("Screenshot of the viewport", "Screenshot della viewport"), ("Search", "Cerca"), - ("Search all assets", "Cerca in tutte le risorse"), ("Search commands or keys", "Cerca comandi o tasti"), ("Seed", "Seme"), ("Select a layer", "Seleziona un livello"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 92ceb5c1..c2b07952 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -714,7 +714,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "スクリーン"), ("Screenshot of the viewport", "ビューポートのスクリーンショット"), ("Search", "検索"), - ("Search all assets", "すべてのアセットを検索"), ("Search commands or keys", "コマンドまたはキーを検索"), ("Seed", "シード"), ("Select a layer", "レイヤーを選択"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 6bb57959..27aab276 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -705,7 +705,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "스크린"), ("Screenshot of the viewport", "뷰포트 스크린샷"), ("Search", "검색"), - ("Search all assets", "모든 에셋 검색"), ("Search commands or keys", "명령 또는 키 검색"), ("Seed", "시드"), ("Select a layer", "레이어를 선택하세요"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 8ba06687..7ad61770 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -720,7 +720,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Tela"), ("Screenshot of the viewport", "Captura de tela da viewport"), ("Search", "Pesquisar"), - ("Search all assets", "Pesquisar em todos os recursos"), ("Search commands or keys", "Pesquisar comandos ou teclas"), ("Seed", "Semente"), ("Select a layer", "Selecione uma camada"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3842e2c7..4e407b12 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -663,7 +663,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "滤色"), ("Screenshot of the viewport", "视口截图"), ("Search", "搜索"), - ("Search all assets", "搜索所有资产"), ("Search commands or keys", "搜索命令或按键"), ("Seed", "随机种子"), ("Select a layer", "选择图层"), diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index fd085ad8..74a4ad83 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -226,29 +226,22 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response /// The Assets panel body (a dock tab) pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); - let searching = !app.ui.shelf_filter.is_empty(); let filter = app.ui.shelf_filter.to_lowercase(); scan_brushes(app); let matching: Vec = ShelfEntry::all(app).into_iter().filter(|entry| entry.matches(&filter)).collect(); let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + search_field(app, ui); crate::shelf_tabs::row(app, ui, &counts, |_, _, _| {}); - - ui.horizontal(|ui| { - ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); - ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search all assets")).desired_width(f32::INFINITY)); - }); ui.add_space(4.0); let tab = app.ui.shelf_tab; let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); - // Searching shows matches from every tab in one grid - let mut entries: Vec = matching.into_iter().filter(|entry| searching || crate::shelf_tabs::shows(tab, entry.tab())).collect(); + let mut entries: Vec = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect(); entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - if !searching && shown_tab == Some(Tab::Textures) { + if filter.is_empty() && shown_tab == Some(Tab::Textures) { import_images(app, ui, &ctx, entries.is_empty()); } tiles(ui, |ui| { @@ -257,13 +250,27 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - if searching || shown_tab.is_none_or(|shown| shown == Tab::Smart) { + if shown_tab.is_none_or(|shown| shown == Tab::Smart) { library(app, ui, &filter); } }); drag_preview(&ctx); } +/// The search field: a live filter on names (and categories) with a clear button while it has text +fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { + let tk = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); + let clear_width = if app.ui.shelf_filter.is_empty() { 0.0 } else { ui.spacing().interact_size.y + ui.spacing().item_spacing.x }; + let field = egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search")).desired_width(ui.available_width() - clear_width); + ui.add(field); + if !app.ui.shelf_filter.is_empty() && ui.add(egui::Button::new(ic::X).frame(false)).on_hover_text(tr("Clear")).clicked() { + app.ui.shelf_filter.clear(); + } + }); +} + /// The dragged asset's name next to the pointer. fn drag_preview(ctx: &egui::Context) { let tk = Tokens::get(ctx); From 3277ef725324fb6138afe11c79da715fcd4fe23d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:05:16 +0000 Subject: [PATCH 19/42] Assets: a library breadcrumb above the search (All libraries, Project, Starter assets, Your assets, then folders) --- crates/ui-egui/src/i18n/ar.rs | 4 ++ crates/ui-egui/src/i18n/de.rs | 4 ++ crates/ui-egui/src/i18n/es.rs | 4 ++ crates/ui-egui/src/i18n/fr.rs | 4 ++ crates/ui-egui/src/i18n/it.rs | 4 ++ crates/ui-egui/src/i18n/ja.rs | 4 ++ crates/ui-egui/src/i18n/ko.rs | 4 ++ crates/ui-egui/src/i18n/pt_br.rs | 4 ++ crates/ui-egui/src/i18n/zh_hans.rs | 4 ++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 16 ++++- crates/ui-egui/src/shelf_entry.rs | 30 ++++++++++ crates/ui-egui/src/shelf_folders.rs | 92 +++++++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 4 ++ 14 files changed, 177 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/shelf_folders.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index de036796..65caff11 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1129,4 +1129,8 @@ pub const TABLE: &[(&str, &str)] = &[ "الحد الأقصى لبيانات المشروع بعد فك الضغط. ارفع هذا الحد لفتح مشاريع أكبر.", ), ("Filter by type", "تصفية حسب النوع"), + ("All libraries", "كل المكتبات"), + ("Browse folders", "تصفح المجلدات"), + ("Starter assets", "الأصول المضمّنة"), + ("Your assets", "أصولك"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index dab5a9fc..477792d7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1175,4 +1175,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximale entpackte Projektdaten. Erhöhen Sie diesen Grenzwert, um größere Projekte zu öffnen.", ), ("Filter by type", "Nach Typ filtern"), + ("All libraries", "Alle Bibliotheken"), + ("Browse folders", "Ordner durchsuchen"), + ("Starter assets", "Mitgelieferte Assets"), + ("Your assets", "Eigene Assets"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b7869bbf..639d4dbc 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1166,4 +1166,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Máximo de datos descomprimidos del proyecto. Aumenta este límite para abrir proyectos más grandes.", ), ("Filter by type", "Filtrar por tipo"), + ("All libraries", "Todas las bibliotecas"), + ("Browse folders", "Explorar carpetas"), + ("Starter assets", "Recursos incluidos"), + ("Your assets", "Tus recursos"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 84e49d0c..00ef31a2 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1190,4 +1190,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Volume maximal des données décompressées du projet. Augmentez cette limite pour ouvrir des projets plus volumineux.", ), ("Filter by type", "Filtrer par type"), + ("All libraries", "Toutes les bibliothèques"), + ("Browse folders", "Parcourir les dossiers"), + ("Starter assets", "Ressources fournies"), + ("Your assets", "Vos ressources"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 44047bf9..9a7831d7 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1172,4 +1172,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Quantità massima di dati decompressi del progetto. Aumenta questo limite per aprire progetti più grandi.", ), ("Filter by type", "Filtra per tipo"), + ("All libraries", "Tutte le librerie"), + ("Browse folders", "Sfoglia cartelle"), + ("Starter assets", "Risorse incluse"), + ("Your assets", "Le tue risorse"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index c2b07952..2e86d12b 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1157,4 +1157,8 @@ pub const TABLE: &[(&str, &str)] = &[ "展開後のプロジェクトデータの上限です。大きなプロジェクトを開くには、この上限を引き上げてください。", ), ("Filter by type", "種類で絞り込む"), + ("All libraries", "すべてのライブラリ"), + ("Browse folders", "フォルダーを参照"), + ("Starter assets", "付属アセット"), + ("Your assets", "マイアセット"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 27aab276..8c4b29f1 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1142,4 +1142,8 @@ pub const TABLE: &[(&str, &str)] = &[ "압축 해제된 프로젝트 데이터의 최대 크기입니다. 더 큰 프로젝트를 열려면 이 한도를 높이세요.", ), ("Filter by type", "유형별 필터"), + ("All libraries", "모든 라이브러리"), + ("Browse folders", "폴더 찾아보기"), + ("Starter assets", "기본 에셋"), + ("Your assets", "내 에셋"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7ad61770..e13f812d 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1160,4 +1160,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Limite de dados descompactados do projeto. Aumente este limite para abrir projetos maiores.", ), ("Filter by type", "Filtrar por tipo"), + ("All libraries", "Todas as bibliotecas"), + ("Browse folders", "Navegar pelas pastas"), + ("Starter assets", "Recursos incluídos"), + ("Your assets", "Seus recursos"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 4e407b12..4160195e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1085,4 +1085,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Max project size on open", "打开项目的大小上限"), ("Maximum decompressed project data. Increase this limit to open larger projects.", "解压后项目数据的大小上限。提高此限制以打开更大的项目。"), ("Filter by type", "按类型筛选"), + ("All libraries", "所有库"), + ("Browse folders", "浏览文件夹"), + ("Starter assets", "内置资源"), + ("Your assets", "我的资源"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b87b257..51848cdb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -50,6 +50,7 @@ mod resource_picker_item; mod running_bake; pub mod shelf; mod shelf_entry; +mod shelf_folders; pub mod shelf_preview; mod shelf_tabs; mod soft_box; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 74a4ad83..d4648c97 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -229,8 +229,19 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let ctx = ui.ctx().clone(); let filter = app.ui.shelf_filter.to_lowercase(); scan_brushes(app); - let matching: Vec = ShelfEntry::all(app).into_iter().filter(|entry| entry.matches(&filter)).collect(); + let all = ShelfEntry::all(app); + let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all)); + + // A folder that is gone (its last image removed) shows everything again + if !paths.iter().any(|path| path.starts_with(&app.ui.shelf_path)) { + app.ui.shelf_path.clear(); + } + + let folder = app.ui.shelf_path.clone(); + let matching: Vec = all.into_iter().filter(|entry| entry.in_folder(&folder) && entry.matches(&filter)).collect(); let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + + crate::shelf_folders::breadcrumb(app, ui, &paths); search_field(app, ui); crate::shelf_tabs::row(app, ui, &counts, |_, _, _| {}); ui.add_space(4.0); @@ -250,7 +261,8 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - if shown_tab.is_none_or(|shown| shown == Tab::Smart) { + let in_user_library = folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + if in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart) { library(app, ui, &filter); } }); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 0def726c..e9bbcbec 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -25,6 +25,13 @@ const SEED_PROBE_OFFSET: f32 = 0.13; /// A smaller difference between the two seeds' samples is rounding const SEED_TOLERANCE: f32 = 1e-4; +/// The libraries' ids: the open project's images, the built-in assets, the user's saved assets +pub(crate) const PROJECT: &str = "project"; +pub(crate) const STARTER: &str = "starter"; +pub(crate) const USER: &str = "user"; +/// The libraries in the picker's order: id and (English, translated where shown) name +pub(crate) const LIBRARIES: [(&str, &str); 3] = [(PROJECT, "Project"), (STARTER, "Starter assets"), (USER, "Your assets")]; + /// A shelf tile's asset #[derive(Clone)] pub(crate) enum ShelfEntry { @@ -88,6 +95,29 @@ impl ShelfEntry { } } + /// Where the asset lives: its library id ([`LIBRARIES`]), its type's folder, then its category if it has one (names in English, shown through `tr`) + pub(crate) fn path(&self) -> Vec<&str> { + let (library, folder, category) = match self { + ShelfEntry::Material(material) if material.smart => (STARTER, "Smart materials", Some(material.category)), + ShelfEntry::Material(material) => (STARTER, "Materials", Some(material.category)), + ShelfEntry::SmartMask(_) => (STARTER, "Smart masks", None), + ShelfEntry::Filter(filter) => (STARTER, "Filters", Some(filter.group)), + ShelfEntry::Brush(preset) => (STARTER, "Brushes", Some(preset.category)), + ShelfEntry::SavedBrush(_) => (USER, "Brushes", None), + ShelfEntry::Alpha(alpha) => (STARTER, "Alphas", Some(alpha.category)), + ShelfEntry::Procedural(_) => (STARTER, "Procedurals", None), + ShelfEntry::Environment(_) => (STARTER, "Environments", None), + ShelfEntry::Image(_) => (PROJECT, "Textures", None), + }; + [library, folder].into_iter().chain(category).collect() + } + + /// Whether the asset is in folder `path` (a library id, then folder names) or below it + pub(crate) fn in_folder(&self, path: &[String]) -> bool { + let own = self.path(); + path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have) + } + /// The name under the tile, translated where the asset's name is pub(crate) fn label(&self) -> &str { match self { diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs new file mode 100644 index 00000000..de8c2144 --- /dev/null +++ b/crates/ui-egui/src/shelf_folders.rs @@ -0,0 +1,92 @@ +//! The shelf's library folders ([`ShelfEntry::path`]) for the breadcrumb above the search and the Filter by path tree + +use egui::{RichText, Ui}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf_entry::{LIBRARIES, ShelfEntry}; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The breadcrumb arrows' size relative to an icon button +const ARROW_SCALE: f32 = 0.8; + +/// The folder paths of `entries`, each a library id then folder names +pub(crate) fn paths(entries: &[ShelfEntry]) -> Vec> { + let mut paths: Vec> = entries.iter().map(|entry| entry.path().into_iter().map(str::to_string).collect()).collect(); + paths.sort(); + paths.dedup(); + paths +} + +/// `paths` and every library, even one with nothing in it (the picker always lists them all) +pub(crate) fn with_every_library(mut paths: Vec>) -> Vec> { + paths.extend(LIBRARIES.iter().map(|(id, _)| vec![id.to_string()])); + paths.sort(); + paths.dedup(); + paths +} + +/// The folders right below `prefix` (libraries in their usual order, folders by name) +pub(crate) fn children(paths: &[Vec], prefix: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for path in paths.iter().filter(|path| path.len() > prefix.len() && path.starts_with(prefix)) { + if let Some(next) = path.get(prefix.len()) + && !out.contains(next) + { + out.push(next.clone()); + } + } + if prefix.is_empty() { + out.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library)); + } + out +} + +/// A folder's shown name: libraries by their name, folders (type and category names) translated +pub(crate) fn name(level: usize, segment: &str) -> &str { + match LIBRARIES.iter().find(|(id, _)| *id == segment) { + Some((_, library)) if level == 0 => tr(library), + _ => tr(segment), + } +} + +/// "› All libraries › …": each arrow lists the folders at its level, the names are plain text, a last arrow lists the folders inside +pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { + let tk = Tokens::get(ui.ctx()); + let size = ui.spacing().interact_size.y * ARROW_SCALE; + let mut picked: Option> = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = ui.spacing().item_spacing.x * 0.5; + let path = app.ui.shelf_path.clone(); + for level in 0..=path.len() { + let options = children(paths, &path[..level]); + if level > 0 && options.is_empty() { + break; + } + + let current = path.get(level); + let response = icon_button(ui, egui_phosphor::regular::CARET_RIGHT, tr("Browse folders"), false, size); + egui::Popup::menu(&response).show(|ui| { + if level == 0 && ui.selectable_label(current.is_none(), tr("All libraries")).clicked() { + picked = Some(Vec::new()); + } + for option in &options { + if ui.selectable_label(current == Some(option), name(level, option)).clicked() { + picked = Some(path[..level].iter().cloned().chain([option.clone()]).collect()); + } + } + }); + + let shown = match current { + Some(segment) => name(level, segment), + None if level == 0 => tr("All libraries"), + None => continue, + }; + ui.label(RichText::new(shown).strong().color(tk.text_strong)); + } + }); + if let Some(path) = picked { + app.ui.shelf_path = path; + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2c03dc45..f9b75653 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -300,6 +300,9 @@ pub struct UiState { /// The asset shelf's picked type: an index into the shelf's types, or past them for every type #[serde(default)] pub shelf_tab: usize, + /// The asset shelf's library folder: a library id, then folder names (empty: all libraries) + #[serde(default)] + pub shelf_path: Vec, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -390,6 +393,7 @@ impl Default for UiState { layer_channel: Channel::BaseColor, shelf_filter: String::new(), shelf_tab: 0, + shelf_path: Vec::new(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, From 8223882c99e17d53db0b4ede190df07d4a5791be Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:07:29 +0000 Subject: [PATCH 20/42] Assets: a bottom toolbar with refresh, reset query and import; the Textures tab's import button moves there --- crates/ui-egui/src/brush_preset_save.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 3 +- crates/ui-egui/src/i18n/de.rs | 3 +- crates/ui-egui/src/i18n/es.rs | 3 +- crates/ui-egui/src/i18n/fr.rs | 3 +- crates/ui-egui/src/i18n/it.rs | 3 +- crates/ui-egui/src/i18n/ja.rs | 3 +- crates/ui-egui/src/i18n/ko.rs | 3 +- crates/ui-egui/src/i18n/pt_br.rs | 3 +- crates/ui-egui/src/i18n/zh_hans.rs | 3 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 40 +++++++++----------- crates/ui-egui/src/shelf_toolbar.rs | 49 +++++++++++++++++++++++++ crates/ui-egui/src/thumbs.rs | 10 +++++ 14 files changed, 97 insertions(+), 32 deletions(-) create mode 100644 crates/ui-egui/src/shelf_toolbar.rs diff --git a/crates/ui-egui/src/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs index 7bc0faaa..1372e0e5 100644 --- a/crates/ui-egui/src/brush_preset_save.rs +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -25,7 +25,9 @@ pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { let _ = std::fs::create_dir_all(&dir); if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { new_name.clear(); + // Saving over a preset keeps its file name, so its tile must redraw app.brushes = None; + app.thumbs.forget_saved_files(); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 65caff11..8b575955 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -412,7 +412,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "استيراد HDR..."), ("Import a template (.json)", "استيراد قالب (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "استورد صورة (ملف > استيراد الموارد) لإسقاطها على المجسم."), - ("Import images to use them in fills and masks", "استورد الصور لاستخدامها في التعبئة والأقنعة"), ("Import resources...", "استيراد الموارد..."), ("Import MaterialX material...", "استيراد مادة MaterialX..."), ("MaterialX materials", "مواد MaterialX"), @@ -1133,4 +1132,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "تصفح المجلدات"), ("Starter assets", "الأصول المضمّنة"), ("Your assets", "أصولك"), + ("Reset query", "إعادة تعيين الاستعلام"), + ("Refresh", "تحديث"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 477792d7..c06ab830 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -439,7 +439,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Ein Bild importieren (Datei > Ressourcen importieren), um es auf das Mesh zu projizieren.", ), - ("Import images to use them in fills and masks", "Bilder importieren, um sie in Füllungen und Masken zu verwenden"), ("Import resources...", "Ressourcen importieren..."), ("Import MaterialX material...", "MaterialX-Material importieren..."), ("MaterialX materials", "MaterialX-Materialien"), @@ -1179,4 +1178,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Ordner durchsuchen"), ("Starter assets", "Mitgelieferte Assets"), ("Your assets", "Eigene Assets"), + ("Reset query", "Abfrage zurücksetzen"), + ("Refresh", "Aktualisieren"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 639d4dbc..587d098a 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -430,7 +430,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Importa una imagen (Archivo > Importar recursos) para proyectarla sobre la malla.", ), - ("Import images to use them in fills and masks", "Importar imágenes para usarlas en rellenos y máscaras"), ("Import resources...", "Importar recursos..."), ("Import MaterialX material...", "Importar material MaterialX..."), ("MaterialX materials", "Materiales MaterialX"), @@ -1170,4 +1169,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Explorar carpetas"), ("Starter assets", "Recursos incluidos"), ("Your assets", "Tus recursos"), + ("Reset query", "Restablecer consulta"), + ("Refresh", "Actualizar"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 00ef31a2..62540c43 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -442,7 +442,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Importez une image (Fichier > Importer des ressources) pour la projeter sur le maillage.", ), - ("Import images to use them in fills and masks", "Importez des images pour les utiliser dans les remplissages et les masques"), ("Import resources...", "Importer des ressources..."), ("Import MaterialX material...", "Importer un matériau MaterialX..."), ("MaterialX materials", "Matériaux MaterialX"), @@ -1194,4 +1193,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Parcourir les dossiers"), ("Starter assets", "Ressources fournies"), ("Your assets", "Vos ressources"), + ("Reset query", "Réinitialiser la requête"), + ("Refresh", "Actualiser"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9a7831d7..6923de3f 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -433,7 +433,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "Importa HDR..."), ("Import a template (.json)", "Importa un modello (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "Importa un'immagine (File > Importa risorse) per proiettarla sulla mesh."), - ("Import images to use them in fills and masks", "Importa immagini per usarle in riempimenti e maschere"), ("Import resources...", "Importa risorse..."), ("Import MaterialX material...", "Importa materiale MaterialX..."), ("MaterialX materials", "Materiali MaterialX"), @@ -1176,4 +1175,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Sfoglia cartelle"), ("Starter assets", "Risorse incluse"), ("Your assets", "Le tue risorse"), + ("Reset query", "Reimposta query"), + ("Refresh", "Aggiorna"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2e86d12b..58dcfdee 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -424,7 +424,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "画像をインポートすると (ファイル > リソースをインポート)、メッシュに投影できます。", ), - ("Import images to use them in fills and masks", "画像をインポートして塗りつぶしやマスクで使用"), ("Import resources...", "リソースをインポート..."), ("Import MaterialX material...", "MaterialX マテリアルをインポート..."), ("MaterialX materials", "MaterialX マテリアル"), @@ -1161,4 +1160,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "フォルダーを参照"), ("Starter assets", "付属アセット"), ("Your assets", "マイアセット"), + ("Reset query", "クエリをリセット"), + ("Refresh", "更新"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8c4b29f1..2905d226 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -418,7 +418,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "HDR 가져오기..."), ("Import a template (.json)", "템플릿을 가져옵니다 (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "메시에 투영할 이미지를 가져오세요 (파일 > 리소스 가져오기)."), - ("Import images to use them in fills and masks", "채우기와 마스크에 사용할 이미지를 가져옵니다"), ("Import resources...", "리소스 가져오기..."), ("Import MaterialX material...", "MaterialX 머티리얼 가져오기..."), ("MaterialX materials", "MaterialX 머티리얼"), @@ -1146,4 +1145,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "폴더 찾아보기"), ("Starter assets", "기본 에셋"), ("Your assets", "내 에셋"), + ("Reset query", "쿼리 초기화"), + ("Refresh", "새로 고침"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e13f812d..e6edc0f4 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -427,7 +427,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "Importar HDR..."), ("Import a template (.json)", "Importar um modelo (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "Importe uma imagem (Arquivo > Importar recursos) para projetá-la na malha."), - ("Import images to use them in fills and masks", "Importe imagens para usá-las em preenchimentos e máscaras"), ("Import resources...", "Importar recursos..."), ("Import MaterialX material...", "Importar material MaterialX..."), ("MaterialX materials", "Materiais MaterialX"), @@ -1164,4 +1163,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Navegar pelas pastas"), ("Starter assets", "Recursos incluídos"), ("Your assets", "Seus recursos"), + ("Reset query", "Redefinir consulta"), + ("Refresh", "Atualizar"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 4160195e..5e07fb3b 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -382,7 +382,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "导入 HDR..."), ("Import a template (.json)", "导入模板(.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "导入图像(文件 > 导入资源)以将其投影到网格上。"), - ("Import images to use them in fills and masks", "导入图像以在填充和遮罩中使用"), ("Import resources...", "导入资源..."), ("Import MaterialX material...", "导入 MaterialX 材质..."), ("MaterialX materials", "MaterialX 材质"), @@ -1089,4 +1088,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "浏览文件夹"), ("Starter assets", "内置资源"), ("Your assets", "我的资源"), + ("Reset query", "重置查询"), + ("Refresh", "刷新"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 51848cdb..e1d42983 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -53,6 +53,7 @@ mod shelf_entry; mod shelf_folders; pub mod shelf_preview; mod shelf_tabs; +mod shelf_toolbar; mod soft_box; pub mod state; pub mod symmetry; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index d4648c97..ebd4cc0d 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -251,21 +251,26 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let mut entries: Vec = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect(); entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - if filter.is_empty() && shown_tab == Some(Tab::Textures) { - import_images(app, ui, &ctx, entries.is_empty()); - } - tiles(ui, |ui| { - for entry in &entries { - entry_tile(app, ui, &ctx, entry); + // The toolbar has its own strip at the panel's bottom, so nothing above it can push it out + let area = ui.available_rect_before_wrap(); + let toolbar_top = (area.bottom() - crate::shelf_toolbar::height(ui)).max(area.top()); + let grid_rect = egui::Rect::from_min_max(area.min, egui::pos2(area.right(), toolbar_top)); + let toolbar_rect = egui::Rect::from_min_max(egui::pos2(area.left(), toolbar_top), area.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect), |ui| { + egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).max_height(grid_rect.height()).show(ui, |ui| { + tiles(ui, |ui| { + for entry in &entries { + entry_tile(app, ui, &ctx, entry); + } + }); + + let in_user_library = folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + if in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart) { + library(app, ui, &filter); } }); - - let in_user_library = folder.first().is_none_or(|library| library == crate::shelf_entry::USER); - if in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart) { - library(app, ui, &filter); - } }); + ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui)); drag_preview(&ctx); } @@ -392,17 +397,6 @@ fn scan_brushes(app: &mut TextureCraftApp) { #[cfg(target_arch = "wasm32")] fn scan_brushes(_: &mut TextureCraftApp) {} -/// The Textures tab's import button, and a hint while the project has no images -fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { - let tk = Tokens::get(ctx); - if ui.small_button(tr("Import...")).clicked() { - crate::menus::invoke(app, ctx, "resource.import"); - } - if empty { - ui.label(RichText::new(tr("Import images to use them in fills and masks")).size(10.0).color(tk.text_dim)); - } -} - /// The tile of `entry`: a click applies it, an image resource has a context menu fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry) { // An image removed this frame has nothing to show diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs new file mode 100644 index 00000000..93a5afcd --- /dev/null +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -0,0 +1,49 @@ +//! The shelf's bottom toolbar: refresh, reset query and import on the right + +use egui::Ui; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::icon_button; + +/// The gap above the toolbar in points +const GAP_ABOVE: f32 = 4.0; + +/// The toolbar's height for a `ui` (one icon button and the gap above it) +pub(crate) fn height(ui: &Ui) -> f32 { + ui.spacing().interact_size.y + GAP_ABOVE +} + +/// The toolbar +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + let size = ui.spacing().interact_size.y; + ui.add_space(GAP_ABOVE); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), "resource.import"); + } + if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() { + reset_query(app); + } + if icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Refresh"), false, size).clicked() { + refresh(app); + } + }); + }); +} + +/// Show every asset again: no search, no type picked, all libraries +pub(crate) fn reset_query(app: &mut TextureCraftApp) { + app.ui.shelf_filter.clear(); + app.ui.shelf_tab = crate::shelf_tabs::NO_TYPE; + app.ui.shelf_path.clear(); +} + +/// Read the user's saved assets from disk again and redraw their thumbnails +fn refresh(app: &mut TextureCraftApp) { + app.library = None; + app.brushes = None; + app.thumbs.forget_saved_files(); +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a6bd93cb..4c7bab4b 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -26,6 +26,8 @@ const PROCEDURAL_PX: usize = 64; const SWATCH_PX: usize = 64; /// Image resource preview size in pixels const IMAGE_PX: usize = 64; +/// The [`ShelfPreview::key`] prefix of the user's saved files +const SAVED_FILE_KEY_PREFIX: &str = "saved-"; /// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; @@ -192,6 +194,14 @@ impl Thumbs { } } + /// Drop the thumbnails and hover previews of the user's saved files, which may have changed on disk + pub fn forget_saved_files(&mut self) { + let current = |key: &String| !key.starts_with(SAVED_FILE_KEY_PREFIX); + self.shelf.retain(|key, _| current(key)); + self.rendered.retain(|key, _| current(key)); + self.big_shown.retain(current); + } + /// Smart mask thumbnail; None until the worker returns it pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) From 77cf7a8d33b948de8ed98dc81e85ae31c324ee97 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:11:21 +0000 Subject: [PATCH 21/42] Assets: a Saved searches pane: All, then saved queries (search, tab and folder), saved from its header --- crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/de.rs | 3 + crates/ui-egui/src/i18n/es.rs | 3 + crates/ui-egui/src/i18n/fr.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 3 + crates/ui-egui/src/i18n/ko.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 3 + crates/ui-egui/src/i18n/zh_hans.rs | 3 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/saved_search.rs | 12 ++++ crates/ui-egui/src/shelf.rs | 37 ++++++---- crates/ui-egui/src/shelf_panes.rs | 102 ++++++++++++++++++++++++++++ crates/ui-egui/src/shelf_toolbar.rs | 3 +- crates/ui-egui/src/state.rs | 32 ++++++++- 15 files changed, 199 insertions(+), 16 deletions(-) create mode 100644 crates/ui-egui/src/saved_search.rs create mode 100644 crates/ui-egui/src/shelf_panes.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 8b575955..b43d7e94 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1134,4 +1134,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "أصولك"), ("Reset query", "إعادة تعيين الاستعلام"), ("Refresh", "تحديث"), + ("Saved searches", "عمليات البحث المحفوظة"), + ("Save the current search", "حفظ البحث الحالي"), + ("Delete", "حذف"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index c06ab830..9caa8d4f 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1180,4 +1180,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Eigene Assets"), ("Reset query", "Abfrage zurücksetzen"), ("Refresh", "Aktualisieren"), + ("Saved searches", "Gespeicherte Suchen"), + ("Save the current search", "Aktuelle Suche speichern"), + ("Delete", "Löschen"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 587d098a..b80856ba 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1171,4 +1171,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Tus recursos"), ("Reset query", "Restablecer consulta"), ("Refresh", "Actualizar"), + ("Saved searches", "Búsquedas guardadas"), + ("Save the current search", "Guardar la búsqueda actual"), + ("Delete", "Eliminar"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 62540c43..5ee27626 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1195,4 +1195,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Vos ressources"), ("Reset query", "Réinitialiser la requête"), ("Refresh", "Actualiser"), + ("Saved searches", "Recherches enregistrées"), + ("Save the current search", "Enregistrer la recherche actuelle"), + ("Delete", "Supprimer"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 6923de3f..ca3f7186 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1177,4 +1177,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Le tue risorse"), ("Reset query", "Reimposta query"), ("Refresh", "Aggiorna"), + ("Saved searches", "Ricerche salvate"), + ("Save the current search", "Salva la ricerca attuale"), + ("Delete", "Elimina"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 58dcfdee..285401bf 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1162,4 +1162,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "マイアセット"), ("Reset query", "クエリをリセット"), ("Refresh", "更新"), + ("Saved searches", "保存した検索"), + ("Save the current search", "現在の検索を保存"), + ("Delete", "削除"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 2905d226..39933670 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1147,4 +1147,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "내 에셋"), ("Reset query", "쿼리 초기화"), ("Refresh", "새로 고침"), + ("Saved searches", "저장된 검색"), + ("Save the current search", "현재 검색 저장"), + ("Delete", "삭제"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e6edc0f4..4c3be582 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1165,4 +1165,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Seus recursos"), ("Reset query", "Redefinir consulta"), ("Refresh", "Atualizar"), + ("Saved searches", "Pesquisas salvas"), + ("Save the current search", "Salvar a pesquisa atual"), + ("Delete", "Excluir"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 5e07fb3b..d9a04f78 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1090,4 +1090,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "我的资源"), ("Reset query", "重置查询"), ("Refresh", "刷新"), + ("Saved searches", "已保存的搜索"), + ("Save the current search", "保存当前搜索"), + ("Delete", "删除"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e1d42983..e57b5189 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -48,9 +48,11 @@ pub mod render_mode; mod resource_picker; mod resource_picker_item; mod running_bake; +pub mod saved_search; pub mod shelf; mod shelf_entry; mod shelf_folders; +pub mod shelf_panes; pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; diff --git a/crates/ui-egui/src/saved_search.rs b/crates/ui-egui/src/saved_search.rs new file mode 100644 index 00000000..ec6181b8 --- /dev/null +++ b/crates/ui-egui/src/saved_search.rs @@ -0,0 +1,12 @@ +//! A shelf query the user saved in the Saved searches pane + +use serde::{Deserialize, Serialize}; + +/// The search text, tab and library folder of a saved shelf query, under the name it lists as +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SavedSearch { + pub name: String, + pub filter: String, + pub tab: usize, + pub path: Vec, +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index ebd4cc0d..a5eed2d0 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -256,24 +256,37 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let toolbar_top = (area.bottom() - crate::shelf_toolbar::height(ui)).max(area.top()); let grid_rect = egui::Rect::from_min_max(area.min, egui::pos2(area.right(), toolbar_top)); let toolbar_rect = egui::Rect::from_min_max(egui::pos2(area.left(), toolbar_top), area.max); - ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect), |ui| { - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).max_height(grid_rect.height()).show(ui, |ui| { - tiles(ui, |ui| { - for entry in &entries { - entry_tile(app, ui, &ctx, entry); - } + ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect).layout(egui::Layout::left_to_right(egui::Align::Min)), |ui| { + if let Some(width) = crate::shelf_panes::column_width(app, ui.available_width()) { + ui.allocate_ui_with_layout(vec2(width, grid_rect.height()), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(vec2(width, grid_rect.height())); + crate::shelf_panes::column(app, ui); }); - - let in_user_library = folder.first().is_none_or(|library| library == crate::shelf_entry::USER); - if in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart) { - library(app, ui, &filter); - } - }); + ui.separator(); + } + // Saved smart materials are files in the user's library, without folders of their own + let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); + grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter); }); ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui)); drag_preview(&ctx); } +/// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` +fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { + egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).max_height(height).show(ui, |ui| { + tiles(ui, |ui| { + for entry in entries { + entry_tile(app, ui, ctx, entry); + } + }); + if saved_materials { + library(app, ui, filter); + } + }); +} + /// The search field: a live filter on names (and categories) with a clear button while it has text fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs new file mode 100644 index 00000000..eb02b3e7 --- /dev/null +++ b/crates/ui-egui/src/shelf_panes.rs @@ -0,0 +1,102 @@ +//! The shelf's side panes, toggled from the bottom toolbar and stacked left of the grid: saved +//! searches (one click restores a query) + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::saved_search::SavedSearch; +use crate::shelf::TABS; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The panes' column width as a fraction of the panel, and its least width in points +const COLUMN_FRACTION: f32 = 0.45; +const COLUMN_MIN_WIDTH: f32 = 110.0; +/// The pane header's caption size in points +const HEADER_SIZE: f32 = 10.0; + +/// Which side panes are open +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfPanes { + pub saved_searches: bool, +} + +/// The toolbar's buttons that open and close the panes +pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let panes = &mut app.ui.shelf_panes; + if icon_button(ui, ic::BOOKMARKS_SIMPLE, tr("Saved searches"), panes.saved_searches, size).clicked() { + panes.saved_searches = !panes.saved_searches; + } +} + +/// The width of the panes' column in a panel `width` wide, or None while no pane is open +pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option { + app.ui.shelf_panes.saved_searches.then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width)) +} + +/// The open panes, top to bottom +pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui) { + // Names past the narrow column end in "…" rather than breaking mid-word + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + if app.ui.shelf_panes.saved_searches { + saved_searches(app, ui); + } +} + +/// A pane's caption with a button at its right +fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { + let tk = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tk.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button); + }); +} + +/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one +fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { + let size = ui.spacing().interact_size.y; + let current = current_query(app); + header(ui, tr("Saved searches"), |ui| { + if icon_button(ui, ic::FLOPPY_DISK, tr("Save the current search"), false, size).clicked() && !app.ui.shelf_saved_searches.contains(¤t) { + app.ui.shelf_saved_searches.push(current.clone()); + } + }); + + let everything = current.filter.is_empty() && current.path.is_empty() && current.tab == crate::shelf_tabs::NO_TYPE; + if ui.selectable_label(everything, tr("All")).clicked() { + crate::shelf_toolbar::reset_query(app); + } + let mut deleted = None; + for (i, saved) in app.ui.shelf_saved_searches.iter().enumerate() { + let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path; + let response = ui.selectable_label(same, &saved.name); + if response.clicked() { + (app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone()); + } + response.context_menu(|ui| { + if ui.button(tr("Delete")).clicked() { + deleted = Some(i); + ui.close(); + } + }); + } + if let Some(i) = deleted { + app.ui.shelf_saved_searches.remove(i); + } +} + +/// The shelf's query, named after its search text, else its folder, else its tab +fn current_query(app: &TextureCraftApp) -> SavedSearch { + let (filter, tab, path) = (app.ui.shelf_filter.clone(), app.ui.shelf_tab, app.ui.shelf_path.clone()); + let name = if !filter.is_empty() { + filter.clone() + } else if let Some(folder) = path.last() { + crate::shelf_folders::name(path.len() - 1, folder).to_string() + } else { + TABS.get(tab).map_or(tr("All"), |(_, _, label)| tr(label)).to_string() + }; + SavedSearch { name, filter, tab, path } +} diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index 93a5afcd..5e185bf9 100644 --- a/crates/ui-egui/src/shelf_toolbar.rs +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -1,4 +1,4 @@ -//! The shelf's bottom toolbar: refresh, reset query and import on the right +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right use egui::Ui; use egui_phosphor::regular as ic; @@ -20,6 +20,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let size = ui.spacing().interact_size.y; ui.add_space(GAP_ABOVE); ui.horizontal(|ui| { + crate::shelf_panes::toggles(app, ui, size); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), "resource.import"); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f9b75653..0d2acd6f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -5,6 +5,8 @@ use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; +use crate::saved_search::SavedSearch; +use crate::shelf_panes::ShelfPanes; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { @@ -303,6 +305,12 @@ pub struct UiState { /// The asset shelf's library folder: a library id, then folder names (empty: all libraries) #[serde(default)] pub shelf_path: Vec, + /// The asset shelf's open side panes + #[serde(default)] + pub shelf_panes: ShelfPanes, + /// The asset shelf's saved queries, in the order they were saved + #[serde(default)] + pub shelf_saved_searches: Vec, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -360,17 +368,21 @@ impl UiState { self.bake_layout_version = BAKE_LAYOUT_VERSION; } - /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export - /// settings and recent files. + /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, settings, files and shelf query pub fn adopt_layout(&mut self, layout: UiState) { let keep = std::mem::replace(self, layout); self.new_project = keep.new_project; self.export = keep.export; self.recent = keep.recent; - self.shelf_filter = keep.shelf_filter; self.prefs = keep.prefs; self.keymap = keep.keymap; self.rename = None; + + // The shelf's search, type and folder are one query, and saved searches are the user's own + self.shelf_filter = keep.shelf_filter; + self.shelf_tab = keep.shelf_tab; + self.shelf_path = keep.shelf_path; + self.shelf_saved_searches = keep.shelf_saved_searches; } } @@ -394,6 +406,8 @@ impl Default for UiState { shelf_filter: String::new(), shelf_tab: 0, shelf_path: Vec::new(), + shelf_panes: ShelfPanes::default(), + shelf_saved_searches: Vec::new(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, @@ -430,6 +444,18 @@ mod tests { assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); } + #[test] + fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() { + let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; + let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], ..UiState::default() }; + ui.shelf_saved_searches.push(saved.clone()); + + ui.adopt_layout(UiState::default()); + + assert_eq!((ui.shelf_filter.as_str(), ui.shelf_tab, ui.shelf_path.as_slice()), ("rust", 2, ["starter".to_string()].as_slice())); + assert_eq!(ui.shelf_saved_searches, [saved]); + } + #[test] fn the_data_folder_is_an_absolute_choice_or_documents_texturecraft() { let default = crate::data_folder(""); From 880da2706166a66c2fd56df712d5655a8c3bd80e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:15:04 +0000 Subject: [PATCH 22/42] Assets: a Filter by path pane: the library folders as a tree, optionally only those with matching assets --- crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/zh_hans.rs | 2 + crates/ui-egui/src/shelf.rs | 4 +- crates/ui-egui/src/shelf_folders.rs | 4 +- crates/ui-egui/src/shelf_panes.rs | 72 +++++++++++++++++++++++++++-- 12 files changed, 90 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index b43d7e94..5f58de6a 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1137,4 +1137,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "عمليات البحث المحفوظة"), ("Save the current search", "حفظ البحث الحالي"), ("Delete", "حذف"), + ("Filter by path", "تصفية حسب المسار"), + ("Hide non-applicable folders", "إخفاء المجلدات غير المطابقة"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 9caa8d4f..d9cf04a3 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1183,4 +1183,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Gespeicherte Suchen"), ("Save the current search", "Aktuelle Suche speichern"), ("Delete", "Löschen"), + ("Filter by path", "Nach Pfad filtern"), + ("Hide non-applicable folders", "Nicht zutreffende Ordner ausblenden"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b80856ba..029d56c2 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1174,4 +1174,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Búsquedas guardadas"), ("Save the current search", "Guardar la búsqueda actual"), ("Delete", "Eliminar"), + ("Filter by path", "Filtrar por ruta"), + ("Hide non-applicable folders", "Ocultar carpetas no aplicables"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 5ee27626..6ef7af9b 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1198,4 +1198,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Recherches enregistrées"), ("Save the current search", "Enregistrer la recherche actuelle"), ("Delete", "Supprimer"), + ("Filter by path", "Filtrer par chemin"), + ("Hide non-applicable folders", "Masquer les dossiers non applicables"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index ca3f7186..40e041b1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1180,4 +1180,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Ricerche salvate"), ("Save the current search", "Salva la ricerca attuale"), ("Delete", "Elimina"), + ("Filter by path", "Filtra per percorso"), + ("Hide non-applicable folders", "Nascondi le cartelle non pertinenti"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 285401bf..b890c371 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1165,4 +1165,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "保存した検索"), ("Save the current search", "現在の検索を保存"), ("Delete", "削除"), + ("Filter by path", "パスで絞り込む"), + ("Hide non-applicable folders", "該当しないフォルダーを隠す"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 39933670..8b93a6ab 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1150,4 +1150,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "저장된 검색"), ("Save the current search", "현재 검색 저장"), ("Delete", "삭제"), + ("Filter by path", "경로별 필터"), + ("Hide non-applicable folders", "해당 없는 폴더 숨기기"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 4c3be582..3514e942 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1168,4 +1168,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Pesquisas salvas"), ("Save the current search", "Salvar a pesquisa atual"), ("Delete", "Excluir"), + ("Filter by path", "Filtrar por caminho"), + ("Hide non-applicable folders", "Ocultar pastas não aplicáveis"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d9a04f78..aeca1b5e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1093,4 +1093,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "已保存的搜索"), ("Save the current search", "保存当前搜索"), ("Delete", "删除"), + ("Filter by path", "按路径筛选"), + ("Hide non-applicable folders", "隐藏不适用的文件夹"), ]; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index a5eed2d0..9e8d2390 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -238,6 +238,8 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } let folder = app.ui.shelf_path.clone(); + let picked_tab = app.ui.shelf_tab; + let applicable = crate::shelf_folders::paths(all.iter().filter(|entry| entry.matches(&filter) && crate::shelf_tabs::shows(picked_tab, entry.tab()))); let matching: Vec = all.into_iter().filter(|entry| entry.in_folder(&folder) && entry.matches(&filter)).collect(); let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); @@ -260,7 +262,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(width) = crate::shelf_panes::column_width(app, ui.available_width()) { ui.allocate_ui_with_layout(vec2(width, grid_rect.height()), egui::Layout::top_down(egui::Align::Min), |ui| { ui.set_min_size(vec2(width, grid_rect.height())); - crate::shelf_panes::column(app, ui); + crate::shelf_panes::column(app, ui, &paths, &applicable); }); ui.separator(); } diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs index de8c2144..0f029033 100644 --- a/crates/ui-egui/src/shelf_folders.rs +++ b/crates/ui-egui/src/shelf_folders.rs @@ -12,8 +12,8 @@ use crate::widgets::icon_button; const ARROW_SCALE: f32 = 0.8; /// The folder paths of `entries`, each a library id then folder names -pub(crate) fn paths(entries: &[ShelfEntry]) -> Vec> { - let mut paths: Vec> = entries.iter().map(|entry| entry.path().into_iter().map(str::to_string).collect()).collect(); +pub(crate) fn paths<'a>(entries: impl IntoIterator) -> Vec> { + let mut paths: Vec> = entries.into_iter().map(|entry| entry.path().into_iter().map(str::to_string).collect()).collect(); paths.sort(); paths.dedup(); paths diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index eb02b3e7..dee1eb62 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -1,5 +1,4 @@ -//! The shelf's side panes, toggled from the bottom toolbar and stacked left of the grid: saved -//! searches (one click restores a query) +//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree use egui::{RichText, Ui}; use egui_phosphor::regular as ic; @@ -22,6 +21,9 @@ const HEADER_SIZE: f32 = 10.0; #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ShelfPanes { pub saved_searches: bool, + pub filter_by_path: bool, + /// Filter by path lists only the folders with assets matching the search and tab + pub hide_non_applicable: bool, } /// The toolbar's buttons that open and close the panes @@ -30,20 +32,80 @@ pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { if icon_button(ui, ic::BOOKMARKS_SIMPLE, tr("Saved searches"), panes.saved_searches, size).clicked() { panes.saved_searches = !panes.saved_searches; } + if icon_button(ui, ic::TREE_STRUCTURE, tr("Filter by path"), panes.filter_by_path, size).clicked() { + panes.filter_by_path = !panes.filter_by_path; + } } /// The width of the panes' column in a panel `width` wide, or None while no pane is open pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option { - app.ui.shelf_panes.saved_searches.then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width)) + let panes = &app.ui.shelf_panes; + (panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width)) } -/// The open panes, top to bottom -pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The open panes, top to bottom; the tree shows `paths`, or `applicable` while it hides folders with nothing matching +pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec], applicable: &[Vec]) { // Names past the narrow column end in "…" rather than breaking mid-word ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); if app.ui.shelf_panes.saved_searches { saved_searches(app, ui); } + if app.ui.shelf_panes.filter_by_path { + if app.ui.shelf_panes.saved_searches { + ui.separator(); + } + let shown = if app.ui.shelf_panes.hide_non_applicable { applicable } else { paths }; + filter_by_path(app, ui, shown); + } +} + +/// "All libraries", then each library's folders as a tree; a click shows that folder +fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { + let size = ui.spacing().interact_size.y; + header(ui, tr("Filter by path"), |ui| { + let hiding = app.ui.shelf_panes.hide_non_applicable; + if icon_button(ui, ic::EYE_SLASH, tr("Hide non-applicable folders"), hiding, size).clicked() { + app.ui.shelf_panes.hide_non_applicable = !hiding; + } + }); + + let mut picked = None; + egui::ScrollArea::vertical().id_salt("shelf_path_tree").auto_shrink([false, true]).show(ui, |ui| { + if ui.selectable_label(app.ui.shelf_path.is_empty(), tr("All libraries")).clicked() { + picked = Some(Vec::new()); + } + folders(ui, paths, &[], &app.ui.shelf_path, &mut picked); + }); + if let Some(path) = picked { + app.ui.shelf_path = path; + } +} + +/// The folders below `prefix`: one with folders inside opens and closes, a click on a name picks it +fn folders(ui: &mut Ui, paths: &[Vec], prefix: &[String], current: &[String], picked: &mut Option>) { + for child in crate::shelf_folders::children(paths, prefix) { + let path: Vec = prefix.iter().cloned().chain([child.clone()]).collect(); + let name = crate::shelf_folders::name(prefix.len(), &child); + let selected = current == path.as_slice(); + if crate::shelf_folders::children(paths, &path).is_empty() { + ui.indent(("shelf_path_leaf", &path), |ui| { + if ui.selectable_label(selected, name).clicked() { + *picked = Some(path.clone()); + } + }); + continue; + } + + let id = ui.make_persistent_id(("shelf_path", &path)); + let open_by_default = current.starts_with(&path); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, open_by_default) + .show_header(ui, |ui| { + if ui.selectable_label(selected, name).clicked() { + *picked = Some(path.clone()); + } + }) + .body(|ui| folders(ui, paths, &path, current, picked)); + } } /// A pane's caption with a button at its right From 0fb7d9205772445341d809c32dc8dad508acdbd5 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:16:34 +0000 Subject: [PATCH 23/42] Assets: the grid's scrollbar always shows --- crates/ui-egui/src/shelf.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9e8d2390..aa753acd 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -277,16 +277,21 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).max_height(height).show(ui, |ui| { - tiles(ui, |ui| { - for entry in entries { - entry_tile(app, ui, ctx, entry); + egui::ScrollArea::vertical() + .id_salt("shelf_scroll") + .auto_shrink([false, false]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible) + .max_height(height) + .show(ui, |ui| { + tiles(ui, |ui| { + for entry in entries { + entry_tile(app, ui, ctx, entry); + } + }); + if saved_materials { + library(app, ui, filter); } }); - if saved_materials { - library(app, ui, filter); - } - }); } /// The search field: a live filter on names (and categories) with a clear button while it has text From 751f7937442dda2a06fe13dfddcd4ded634d07ff Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:33:11 +0000 Subject: [PATCH 24/42] Assets: a thumbnail size menu at the end of the type row: small, medium or large tiles, or a list --- crates/ui-egui/src/grid_tile.rs | 9 ++++ crates/ui-egui/src/i18n/ar.rs | 6 +++ crates/ui-egui/src/i18n/de.rs | 6 +++ crates/ui-egui/src/i18n/es.rs | 6 +++ crates/ui-egui/src/i18n/fr.rs | 6 +++ crates/ui-egui/src/i18n/it.rs | 6 +++ crates/ui-egui/src/i18n/ja.rs | 6 +++ crates/ui-egui/src/i18n/ko.rs | 6 +++ crates/ui-egui/src/i18n/pt_br.rs | 6 +++ crates/ui-egui/src/i18n/zh_hans.rs | 6 +++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/shelf.rs | 73 +++++++++++++++----------- crates/ui-egui/src/shelf_view.rs | 83 ++++++++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 5 ++ 14 files changed, 196 insertions(+), 30 deletions(-) create mode 100644 crates/ui-egui/src/grid_tile.rs create mode 100644 crates/ui-egui/src/shelf_view.rs diff --git a/crates/ui-egui/src/grid_tile.rs b/crates/ui-egui/src/grid_tile.rs new file mode 100644 index 00000000..45fd9bf6 --- /dev/null +++ b/crates/ui-egui/src/grid_tile.rs @@ -0,0 +1,9 @@ +//! A grid tile's measurements in the shelf's small, medium and large views + +/// A grid tile's size and its thumbnail's size and center below the tile's top, in points +pub(crate) struct GridTile { + pub(crate) width: f32, + pub(crate) height: f32, + pub(crate) thumbnail_size: f32, + pub(crate) thumbnail_center_y: f32, +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 5f58de6a..b63df18c 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1139,4 +1139,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "حذف"), ("Filter by path", "تصفية حسب المسار"), ("Hide non-applicable folders", "إخفاء المجلدات غير المطابقة"), + ("Thumbnail size", "حجم الصورة المصغّرة"), + ("Small", "صغير"), + ("Medium", "متوسط"), + ("Large", "كبير"), + ("List", "قائمة"), + ("Procedurals", "إجرائيات"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index d9cf04a3..81e62b2c 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1185,4 +1185,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Löschen"), ("Filter by path", "Nach Pfad filtern"), ("Hide non-applicable folders", "Nicht zutreffende Ordner ausblenden"), + ("Thumbnail size", "Vorschaugröße"), + ("Small", "Klein"), + ("Medium", "Mittel"), + ("Large", "Groß"), + ("List", "Liste"), + ("Procedurals", "Prozedurale"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 029d56c2..ed759054 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1176,4 +1176,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Eliminar"), ("Filter by path", "Filtrar por ruta"), ("Hide non-applicable folders", "Ocultar carpetas no aplicables"), + ("Thumbnail size", "Tamaño de miniatura"), + ("Small", "Pequeño"), + ("Medium", "Mediano"), + ("Large", "Grande"), + ("List", "Lista"), + ("Procedurals", "Procedurales"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 6ef7af9b..ebcb248a 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1200,4 +1200,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Supprimer"), ("Filter by path", "Filtrer par chemin"), ("Hide non-applicable folders", "Masquer les dossiers non applicables"), + ("Thumbnail size", "Taille des miniatures"), + ("Small", "Petit"), + ("Medium", "Moyen"), + ("Large", "Grand"), + ("List", "Liste"), + ("Procedurals", "Procéduraux"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 40e041b1..55fe9abd 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1182,4 +1182,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Elimina"), ("Filter by path", "Filtra per percorso"), ("Hide non-applicable folders", "Nascondi le cartelle non pertinenti"), + ("Thumbnail size", "Dimensione miniature"), + ("Small", "Piccolo"), + ("Medium", "Medio"), + ("Large", "Grande"), + ("List", "Elenco"), + ("Procedurals", "Procedurali"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index b890c371..bb4f5152 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1167,4 +1167,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "削除"), ("Filter by path", "パスで絞り込む"), ("Hide non-applicable folders", "該当しないフォルダーを隠す"), + ("Thumbnail size", "サムネイルのサイズ"), + ("Small", "小"), + ("Medium", "中"), + ("Large", "大"), + ("List", "リスト"), + ("Procedurals", "プロシージャル"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8b93a6ab..4273f92c 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1152,4 +1152,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "삭제"), ("Filter by path", "경로별 필터"), ("Hide non-applicable folders", "해당 없는 폴더 숨기기"), + ("Thumbnail size", "썸네일 크기"), + ("Small", "작게"), + ("Medium", "보통"), + ("Large", "크게"), + ("List", "목록"), + ("Procedurals", "프로시저럴"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 3514e942..70d68d21 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1170,4 +1170,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Excluir"), ("Filter by path", "Filtrar por caminho"), ("Hide non-applicable folders", "Ocultar pastas não aplicáveis"), + ("Thumbnail size", "Tamanho da miniatura"), + ("Small", "Pequeno"), + ("Medium", "Médio"), + ("Large", "Grande"), + ("List", "Lista"), + ("Procedurals", "Procedurais"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index aeca1b5e..0b582484 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1095,4 +1095,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "删除"), ("Filter by path", "按路径筛选"), ("Hide non-applicable folders", "隐藏不适用的文件夹"), + ("Thumbnail size", "缩略图大小"), + ("Small", "小"), + ("Medium", "中"), + ("Large", "大"), + ("List", "列表"), + ("Procedurals", "程序纹理"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e57b5189..efdfbf65 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -23,6 +23,7 @@ pub mod file_dialogs; mod filter_slot; pub mod fonts; pub mod gpu; +mod grid_tile; pub mod i18n; pub mod id_color_pick; pub mod keymap; @@ -56,6 +57,7 @@ pub mod shelf_panes; pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; +pub mod shelf_view; mod soft_box; pub mod state; pub mod symmetry; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index aa753acd..5902452b 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -13,13 +13,12 @@ use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; use crate::shelf_entry::ShelfEntry; use crate::shelf_preview::ShelfPreview; +use crate::shelf_view::ShelfView; use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::dnd_release; -/// A shelf tile's size and the gap between tiles in points: a 68 x 78 grid step, as in the reference -const TILE_WIDTH: f32 = 66.0; -const TILE_HEIGHT: f32 = 76.0; +/// The gap between tiles in points (their sizes are [`ShelfView`]'s) const TILE_GAP: f32 = 2.0; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; @@ -36,9 +35,6 @@ const BADGE_INSET: f32 = 2.5; const BADGE_DOT_FILL: Color32 = Color32::from_gray(205); const BADGE_DOT_RIM: f32 = 0.8; const BADGE_DOT_RIM_COLOR: Color32 = Color32::from_black_alpha(170); -/// The thumbnail's size in a tile and its center below the tile's top, in points -const THUMBNAIL_SIZE: f32 = 60.0; -const THUMBNAIL_CENTER_Y: f32 = 31.0; /// Loading icon size relative to the thumbnail width, and its opacity over the dim text color const LOADING_ICON_SCALE: f32 = 0.9; const LOADING_ICON_OPACITY: f32 = 0.5; @@ -245,7 +241,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { crate::shelf_folders::breadcrumb(app, ui, &paths); search_field(app, ui); - crate::shelf_tabs::row(app, ui, &counts, |_, _, _| {}); + crate::shelf_tabs::row(app, ui, &counts, crate::shelf_view::menu); ui.add_space(4.0); let tab = app.ui.shelf_tab; @@ -277,6 +273,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { + let view = app.ui.shelf_view; egui::ScrollArea::vertical() .id_salt("shelf_scroll") .auto_shrink([false, false]) @@ -285,7 +282,7 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ .show(ui, |ui| { tiles(ui, |ui| { for entry in entries { - entry_tile(app, ui, ctx, entry); + entry_tile(app, ui, ctx, entry, view); } }); if saved_materials { @@ -418,12 +415,13 @@ fn scan_brushes(app: &mut TextureCraftApp) { fn scan_brushes(_: &mut TextureCraftApp) {} /// The tile of `entry`: a click applies it, an image resource has a context menu -fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry) { +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView) { // An image removed this frame has nothing to show let (Some(preview), texture) = (entry.preview(app), entry.thumbnail(app, ctx)) else { return }; let asset = entry.asset(); - let response = tile(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref()); + let response = tile_in_view(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref(), view); + let selected_id = egui::Id::unique(SELECTED_TILE); let key = entry.key(); let selected = ctx.data(|data| data.get_temp::(selected_id)).is_some_and(|selected| selected == key); @@ -434,7 +432,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry } if entry.includes_randomness() { - randomness_badge(ui.painter(), response.rect); + randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); } if response.clicked() || response.secondary_clicked() { @@ -458,46 +456,61 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry } } -/// Asset tile with optional dragging and a larger hover preview +/// Asset tile with optional dragging and a larger hover preview, at the medium size pub(crate) fn tile( ui: &mut Ui, thumbs: &mut Thumbs, - tex: Option<&egui::TextureHandle>, + texture: Option<&egui::TextureHandle>, preview: impl FnOnce() -> ShelfPreview, label: &str, drag: Option<&Asset>, +) -> egui::Response { + tile_in_view(ui, thumbs, texture, preview, label, drag, ShelfView::Medium) +} + +/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside +fn tile_in_view( + ui: &mut Ui, + thumbs: &mut Thumbs, + texture: Option<&egui::TextureHandle>, + preview: impl FnOnce() -> ShelfPreview, + label: &str, + drag: Option<&Asset>, + view: ShelfView, ) -> egui::Response { let tk = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; - let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if let Some(asset) = drag - && resp.drag_started() + && response.drag_started() { - resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); } let painter = ui.painter(); - if resp.hovered() || resp.dragged() { + if response.hovered() || response.dragged() { painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); } - let image_rect = thumbnail_rect(rect); - thumbnail(painter, tex, image_rect, &tk); - let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); - painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); - let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; - resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) -} + let image_rect = view.thumbnail_rect(rect); + thumbnail(painter, texture, image_rect, &tk); + if view.name_beside() { + let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP; + let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tk.text)); + painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tk.text); + } else { + let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); + } -/// Where a tile's thumbnail goes in the tile's `rect` -fn thumbnail_rect(rect: egui::Rect) -> egui::Rect { - egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)) + let big = if response.hovered() { big_preview(ui, thumbs, preview) } else { None }; + response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) } /// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness -fn randomness_badge(painter: &egui::Painter, tile: egui::Rect) { - let corner = thumbnail_rect(tile).right_bottom() - vec2(BADGE_INSET, BADGE_INSET); +fn randomness_badge(painter: &egui::Painter, thumbnail: egui::Rect) { + let corner = thumbnail.right_bottom() - vec2(BADGE_INSET, BADGE_INSET); for offset in [vec2(0.0, 0.0), vec2(-BADGE_DOT_SPACING, 0.0), vec2(-BADGE_DOT_SPACING * 0.5, -BADGE_DOT_SPACING)] { painter.circle(corner + offset, BADGE_DOT_RADIUS, BADGE_DOT_FILL, Stroke::new(BADGE_DOT_RIM, BADGE_DOT_RIM_COLOR)); } diff --git a/crates/ui-egui/src/shelf_view.rs b/crates/ui-egui/src/shelf_view.rs new file mode 100644 index 00000000..036c498b --- /dev/null +++ b/crates/ui-egui/src/shelf_view.rs @@ -0,0 +1,83 @@ +//! How the shelf shows its assets: small, medium or large tiles, or a list (the menu at the type row's end) + +use egui::{Rect, Ui, Vec2, vec2}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::grid_tile::GridTile; +use crate::i18n::tr; +use crate::widgets::icon_button; + +/// A list row's height and its thumbnail's size, in points +const LIST_ROW_HEIGHT: f32 = 30.0; +const LIST_THUMBNAIL_SIZE: f32 = 26.0; +/// The gap between a list row's thumbnail and its name, in points +pub(crate) const LIST_NAME_GAP: f32 = 6.0; + +/// The shelf's tile size, or the list +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ShelfView { + Small, + /// A 68 x 78 grid step, as in the reference + #[default] + Medium, + Large, + List, +} + +/// The views in the menu's order: icon and (English, translated where shown) name +const VIEWS: [(ShelfView, &str, &str); 4] = [ + (ShelfView::Small, ic::GRID_NINE, "Small"), + (ShelfView::Medium, ic::GRID_FOUR, "Medium"), + (ShelfView::Large, ic::SQUARE, "Large"), + (ShelfView::List, ic::LIST, "List"), +]; + +impl ShelfView { + /// A grid tile's measurements; None for the list + fn grid(self) -> Option { + match self { + ShelfView::Small => Some(GridTile { width: 50.0, height: 58.0, thumbnail_size: 44.0, thumbnail_center_y: 23.0 }), + ShelfView::Medium => Some(GridTile { width: 66.0, height: 76.0, thumbnail_size: 60.0, thumbnail_center_y: 31.0 }), + ShelfView::Large => Some(GridTile { width: 88.0, height: 100.0, thumbnail_size: 82.0, thumbnail_center_y: 42.0 }), + ShelfView::List => None, + } + } + + /// A tile's size in a grid `width` points wide (a list row spans it) + pub(crate) fn tile_size(self, width: f32) -> Vec2 { + match self.grid() { + Some(tile) => vec2(tile.width, tile.height), + None => vec2(width.max(LIST_ROW_HEIGHT), LIST_ROW_HEIGHT), + } + } + + /// Where the thumbnail goes in the tile `rect` + pub(crate) fn thumbnail_rect(self, rect: Rect) -> Rect { + match self.grid() { + Some(tile) => Rect::from_center_size(rect.center_top() + vec2(0.0, tile.thumbnail_center_y), vec2(tile.thumbnail_size, tile.thumbnail_size)), + None => Rect::from_center_size(rect.left_center() + vec2(LIST_ROW_HEIGHT * 0.5, 0.0), vec2(LIST_THUMBNAIL_SIZE, LIST_THUMBNAIL_SIZE)), + } + } + + /// Whether the name sits right of the thumbnail (a list) rather than under it + pub(crate) fn name_beside(self) -> bool { + self == ShelfView::List + } +} + +/// The view menu button: its icon is the current view's +pub(crate) fn menu(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let current = app.ui.shelf_view; + let icon = VIEWS.iter().find(|(view, _, _)| *view == current).map_or(ic::GRID_FOUR, |(_, icon, _)| icon); + let response = icon_button(ui, icon, tr("Thumbnail size"), false, size); + egui::Popup::menu(&response).show(|ui| { + for (view, icon, label) in VIEWS { + if ui.selectable_label(view == current, format!("{icon} {}", tr(label))).clicked() { + app.ui.shelf_view = view; + ui.close(); + } + } + }); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0d2acd6f..a8b43813 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -7,6 +7,7 @@ use crate::docking::Dock; use crate::keymap::Keymap; use crate::saved_search::SavedSearch; use crate::shelf_panes::ShelfPanes; +use crate::shelf_view::ShelfView; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { @@ -305,6 +306,9 @@ pub struct UiState { /// The asset shelf's library folder: a library id, then folder names (empty: all libraries) #[serde(default)] pub shelf_path: Vec, + /// The asset shelf's tile size, or its list + #[serde(default)] + pub shelf_view: ShelfView, /// The asset shelf's open side panes #[serde(default)] pub shelf_panes: ShelfPanes, @@ -406,6 +410,7 @@ impl Default for UiState { shelf_filter: String::new(), shelf_tab: 0, shelf_path: Vec::new(), + shelf_view: ShelfView::default(), shelf_panes: ShelfPanes::default(), shelf_saved_searches: Vec::new(), props_tab: PropsTab::Brush, From accfb51aba74332e3d99c037dccbd8352880a6ff Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:56:10 +0000 Subject: [PATCH 25/42] Assets: tests for the panel layout: columns at the reference width, one-line labels, type row, breadcrumb, size menu, panes and toolbar --- crates/ui-egui/src/shelf.rs | 21 +++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_panel.rs | 239 +++++++++++++++++++++++++ 3 files changed, 261 insertions(+) create mode 100644 crates/ui-egui/tests/it/shelf_panel.rs diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 5902452b..75958d99 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -573,3 +573,24 @@ fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<& ui.label(label); }); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_long_label_stays_on_one_line_ending_in_an_ellipsis() { + let width = 60.0; + let mut laid_out = None; + let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + laid_out = Some(ui.painter().layout_job(one_line("Steel Painted Rust Leaks Extra", width, Color32::WHITE))); + }); + // The font atlas upload is not under test + output.textures_delta.clear(); + let galley = laid_out.unwrap(); + + assert_eq!(galley.rows.len(), 1); + assert!(galley.size().x <= width); + assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…')); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..da067f4d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -29,6 +29,7 @@ mod properties_popup; mod rail; mod shelf_drop; mod shelf_hover_preview; +mod shelf_panel; mod shift_lines_2d; mod shortcut_keys; mod skew_paint; diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs new file mode 100644 index 00000000..94e3edd7 --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -0,0 +1,239 @@ +//! The Assets panel's layout: columns at the reference width, type row, size menu, breadcrumb, side panes and toolbar + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::project::ENVIRONMENTS; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_view::ShelfView; + +/// The reference's capture window: its Assets panel shows four columns there +const REFERENCE_WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0); +/// A window whose default Assets panel is too narrow for the full type row +const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0); +/// The shelf's Materials and Smart masks types +const MATERIALS_TYPE: usize = 0; +const SMART_MASKS_TYPE: usize = 2; +const BRUSHES_TYPE: usize = 4; +const TEXTURES_TYPE: usize = 6; +const ENVIRONMENTS_TYPE: usize = 7; +/// Tile columns the reference shows at its panel width +const REFERENCE_COLUMNS: usize = 4; + +/// The sample project with the shelf on the Materials type +fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; + harness.run_steps(4); + harness +} + +/// The plain materials in the grid's order (by name) +fn plain_materials() -> Vec<&'static SmartMaterial> { + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + plain +} + +/// A clickable node labelled `label` (its tooltip, once shown, has the same label) +fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")) +} + +#[test] +fn the_default_panel_shows_the_reference_column_count() { + let harness = shelf(REFERENCE_WINDOW); + let tops: Vec = plain_materials().iter().take(REFERENCE_COLUMNS + 1).map(|material| harness.get_by_label(material.label).rect().top()).collect(); + + assert!(tops[..REFERENCE_COLUMNS].iter().all(|top| *top == tops[0]), "the first {REFERENCE_COLUMNS} tiles share a row: {tops:?}"); + assert!(tops[REFERENCE_COLUMNS] > tops[0], "the next tile starts a row: {tops:?}"); +} + +#[test] +fn a_click_on_the_picked_type_shows_every_type() { + let mut harness = shelf(REFERENCE_WINDOW); + let mask = SMART_MASKS[0].label; + assert!(harness.query_by_label(mask).is_none(), "the Materials type hides smart masks"); + + button(&harness, "Materials").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(mask).is_some(), "no type picked shows smart masks too"); +} + +#[test] +fn the_search_narrows_the_picked_type_and_greys_types_without_matches() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials().into_iter().find(|material| material.label.to_lowercase().contains("rust")).unwrap(); + let mask = SMART_MASKS.iter().find(|mask| mask.label.to_lowercase().contains("rust")).unwrap(); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE; + harness.run_steps(3); + + assert!(harness.query_by_label(mask.label).is_some(), "the matching mask shows"); + assert!(harness.query_by_label(material.label).is_none(), "a matching material of another type does not"); + assert!(button(&harness, "Environments").accesskit_node().is_disabled(), "no environment matches"); + assert!(!button(&harness, "Materials").accesskit_node().is_disabled()); + + button(&harness, "Materials").click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.shelf_filter, "rust", "picking a type keeps the search"); + assert!(harness.query_by_label(material.label).is_some()); +} + +#[test] +fn the_breadcrumb_arrow_picks_a_library() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials()[0].label; + + button(&harness, "Browse folders").click(); + harness.run_steps(2); + for library in ["Project", "Starter assets", "Your assets"] { + assert!(harness.query_by_label(library).is_some(), "the list offers {library}"); + } + harness.get_by_label("Project").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_path, ["project"]); + assert!(harness.query_by_label(material).is_none(), "built-in materials are not in the project"); +} + +#[test] +fn the_thumbnail_size_menu_switches_to_the_list() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials()[0].label; + let tile_width = harness.get_by_label(material).rect().width(); + + button(&harness, "Thumbnail size").click(); + harness.run_steps(2); + harness.get_by_label_contains("List").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_view, ShelfView::List); + assert!(harness.get_by_label(material).rect().width() > tile_width * 2.0, "a list row spans the panel"); +} + +#[test] +fn reset_query_shows_every_asset_again() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.state_mut().ui.shelf_path = vec!["starter".into()]; + harness.run_steps(2); + + button(&harness, "Reset query").click(); + harness.run_steps(3); + + let ui = &harness.state().ui; + assert!(ui.shelf_filter.is_empty() && ui.shelf_path.is_empty()); + assert!(harness.query_by_label(SMART_MASKS[0].label).is_some(), "every type shows"); +} + +#[test] +fn refresh_reads_the_saved_brushes_again() { + let mut harness = shelf(REFERENCE_WINDOW); + let stale = vec![std::path::PathBuf::from("gone.tcbrush")]; + harness.state_mut().brushes = Some(stale.clone()); + harness.run_steps(1); + + button(&harness, "Refresh").click(); + harness.run_steps(3); + + assert_ne!(harness.state().brushes, Some(stale), "the brushes folder was read again"); + assert!(harness.query_by_label("Import resources...").is_some(), "the toolbar has the import button"); +} + +#[test] +fn a_saved_search_restores_its_query() { + let mut harness = shelf(REFERENCE_WINDOW); + button(&harness, "Saved searches").click(); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.run_steps(3); + + button(&harness, "Save the current search").click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1); + harness.state_mut().ui.shelf_filter.clear(); + harness.run_steps(2); + + harness.get_by_label("rust").click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.shelf_filter, "rust"); + + harness.get_by_label("rust").click_secondary(); + harness.run_steps(2); + // The context menu opens last, so its Delete is the newest node with that label + harness.get_all_by_label("Delete").last().unwrap().click(); + harness.run_steps(2); + assert!(harness.state().ui.shelf_saved_searches.is_empty()); +} + +#[test] +fn filter_by_path_picks_a_folder() { + let mut harness = shelf(REFERENCE_WINDOW); + button(&harness, "Filter by path").click(); + harness.run_steps(3); + + harness.get_by_label("Starter assets").click(); + harness.run_steps(2); + + assert_eq!(harness.state().ui.shelf_path, ["starter"]); +} + +#[test] +fn a_narrow_panel_keeps_the_toolbar_and_folds_the_type_row() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.run_steps(3); + + for label in ["Refresh", "Reset query", "Import resources...", "Saved searches", "Filter by path"] { + let rect = button(&harness, label).rect(); + assert!(rect.bottom() <= NARROW_WINDOW.y, "{label} is inside the window: {rect:?}"); + } + assert!(harness.query_by_label("Filter by type").is_some(), "the type row folds into one dropdown"); + assert!(harness.query_by_label("Environments").is_none()); +} + +#[test] +fn an_environment_tile_switches_the_lighting() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_tab = ENVIRONMENTS_TYPE; + harness.run_steps(3); + let shown = harness.state().session.doc.project.display.environment.clone(); + let other = ENVIRONMENTS.iter().find(|name| **name != shown).unwrap(); + + harness.get_by_label(other).click(); + harness.run_steps(2); + + assert_eq!(harness.state().session.doc.project.display.environment, *other); +} + +#[test] +fn a_saved_brush_is_a_tile_that_loads_the_preset() { + let mut harness = shelf(REFERENCE_WINDOW); + let mut saved = harness.state().session.tool.brush.clone(); + saved.spacing = (saved.spacing + 0.25).min(1.0); + let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id())); + std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); + harness.state_mut().brushes = Some(vec![path.clone()]); + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + harness.run_steps(3); + + harness.get_by_label(path.file_stem().unwrap().to_str().unwrap()).click(); + harness.run_steps(2); + std::fs::remove_file(&path).unwrap(); + + assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke"); +} + +#[test] +fn procedurals_are_in_the_textures_type() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_tab = TEXTURES_TYPE; + harness.run_steps(3); + + assert!(harness.query_by_label(ProceduralKind::ALL[0].label()).is_some()); +} From 49e9de6be509c7ec22e266324f014bed55d55176 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 07:19:33 +0000 Subject: [PATCH 26/42] Assets: saved smart materials count toward the Smart materials type and Your assets, so neither greys out while they match --- crates/ui-egui/src/shelf.rs | 88 ++++++++++++++++++-------- crates/ui-egui/tests/it/shelf_panel.rs | 27 +++++++- 2 files changed, 88 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 75958d99..9d9e3628 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -20,6 +20,11 @@ use crate::widgets::dnd_release; /// The gap between tiles in points (their sizes are [`ShelfView`]'s) const TILE_GAP: f32 = 2.0; +/// The gap after a grid or a list of rows, and the size of a hint under a header, in points +const SECTION_GAP: f32 = 6.0; +const HINT_SIZE: f32 = 10.0; +/// The name of a saved material whose file name isn't text +const SAVED_MATERIAL_NAME: &str = "material"; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; /// The last clicked or right-clicked tile's [`ShelfEntry::key`], kept in egui's memory under this id @@ -224,6 +229,7 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let ctx = ui.ctx().clone(); let filter = app.ui.shelf_filter.to_lowercase(); + scan_library(app); scan_brushes(app); let all = ShelfEntry::all(app); let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all)); @@ -235,9 +241,19 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let folder = app.ui.shelf_path.clone(); let picked_tab = app.ui.shelf_tab; - let applicable = crate::shelf_folders::paths(all.iter().filter(|entry| entry.matches(&filter) && crate::shelf_tabs::shows(picked_tab, entry.tab()))); + let mut applicable = crate::shelf_folders::paths(all.iter().filter(|entry| entry.matches(&filter) && crate::shelf_tabs::shows(picked_tab, entry.tab()))); let matching: Vec = all.into_iter().filter(|entry| entry.in_folder(&folder) && entry.matches(&filter)).collect(); - let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + + // Saved smart materials list under the grid rather than as tiles, so they count apart + let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + let saved_materials_matching = saved_materials_matching(app, &filter); + if in_user_library && let Some(smart) = TABS.iter().position(|(tab, _, _)| *tab == Tab::Smart).and_then(|smart| counts.get_mut(smart)) { + *smart += saved_materials_matching; + } + if saved_materials_matching > 0 && crate::shelf_tabs::shows(picked_tab, Tab::Smart) { + applicable.push(vec![crate::shelf_entry::USER.to_string()]); + } crate::shelf_folders::breadcrumb(app, ui, &paths); search_field(app, ui); @@ -263,7 +279,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); } // Saved smart materials are files in the user's library, without folders of their own - let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter); }); @@ -291,6 +306,11 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ }); } +/// How many of the user's saved smart materials match `filter` (none until the library is read) +fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize { + app.library.iter().flatten().filter(|path| matches(filter, &[saved_material_name(path)])).count() +} + /// The search field: a live filter on names (and categories) with a clear button while it has text fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); @@ -332,7 +352,7 @@ pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.spacing_mut().item_spacing = vec2(TILE_GAP, TILE_GAP); body(ui); }); - ui.add_space(6.0); + ui.add_space(SECTION_GAP); } /// The distinct categories of `items`, in order of first appearance. @@ -346,23 +366,38 @@ pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) out } -/// The user's saved smart materials (desktop library folder). +/// Read the user's saved smart materials (desktop library folder) unless they are already listed +#[cfg(not(target_arch = "wasm32"))] +fn scan_library(app: &mut TextureCraftApp) { + if app.library.is_some() { + return; + } + + let saved_material = |path: &std::path::PathBuf| path.extension().is_some_and(|extension| extension == "tcmat" || extension == MCMAT_EXT); + let mut files: Vec = + std::fs::read_dir(crate::library_dir()).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_material).collect()).unwrap_or_default(); + files.sort(); + app.library = Some(files); +} + +#[cfg(target_arch = "wasm32")] +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 { + path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME) +} + +/// The user's saved smart materials matching `filter`, as rows under the grid #[cfg(not(target_arch = "wasm32"))] fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { - let tk = Tokens::get(ui.ctx()); - if app.library.is_none() { - let mut files: Vec = std::fs::read_dir(crate::library_dir()) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tcmat" || x == MCMAT_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.library = Some(files); - } + let tokens = Tokens::get(ui.ctx()); let files = app.library.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("material").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); + let shown: Vec<_> = files.iter().filter(|path| matches(filter, &[saved_material_name(path)])).collect(); if !filter.is_empty() && shown.is_empty() { return; } + ui.horizontal(|ui| { header(ui, tr("My smart materials")); if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { @@ -370,26 +405,27 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { } }); if files.is_empty() { - ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(10.0).color(tk.text_dim)); + ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(HINT_SIZE).color(tokens.text_dim)); } - for f in shown { - let (label, asset) = (name(f), Asset::Library(f.display().to_string())); - // MaterialCraft materials (sent from MaterialCraft) show a graph. - let glyph = if f.extension().is_some_and(|x| x == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; - let r = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { + + for path in shown { + let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string())); + // MaterialCraft materials (sent from MaterialCraft) show a graph + let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; + let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { ui.label(crate::i18n::trf( "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", - &[("file", &f.display())], + &[("file", &path.display())], )); }); - if r.drag_started() { - r.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); + if response.drag_started() { + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); } - if r.clicked() { + if response.clicked() { apply(app, &asset); } } - ui.add_space(6.0); + ui.add_space(SECTION_GAP); } #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 94e3edd7..47c61410 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -19,6 +19,8 @@ const SMART_MASKS_TYPE: usize = 2; const BRUSHES_TYPE: usize = 4; const TEXTURES_TYPE: usize = 6; const ENVIRONMENTS_TYPE: usize = 7; +/// How far the saved brush's spacing differs from the current brush's, so loading it shows +const SAVED_SPACING_CHANGE: f32 = 0.25; /// Tile columns the reference shows at its panel width const REFERENCE_COLUMNS: usize = 4; @@ -215,7 +217,7 @@ fn an_environment_tile_switches_the_lighting() { fn a_saved_brush_is_a_tile_that_loads_the_preset() { let mut harness = shelf(REFERENCE_WINDOW); let mut saved = harness.state().session.tool.brush.clone(); - saved.spacing = (saved.spacing + 0.25).min(1.0); + saved.spacing += SAVED_SPACING_CHANGE; let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id())); std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); harness.state_mut().brushes = Some(vec![path.clone()]); @@ -229,6 +231,29 @@ fn a_saved_brush_is_a_tile_that_loads_the_preset() { assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke"); } +#[test] +fn saved_smart_materials_keep_their_type_pickable_in_your_assets() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().library = Some(vec![std::path::PathBuf::from("Mine.tcmat")]); + harness.state_mut().ui.shelf_path = vec!["user".into()]; + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + harness.run_steps(3); + + assert!(!button(&harness, "Smart materials").accesskit_node().is_disabled(), "a saved smart material is in Your assets"); + assert!(button(&harness, "Materials").accesskit_node().is_disabled(), "no plain material is"); +} + +#[test] +fn saved_smart_materials_are_read_whatever_the_type_and_after_a_refresh() { + let mut harness = shelf(REFERENCE_WINDOW); + assert!(harness.state().library.is_some(), "read on the Materials type"); + + button(&harness, "Refresh").click(); + harness.run_steps(2); + + assert!(harness.state().library.is_some(), "read again after a refresh"); +} + #[test] fn procedurals_are_in_the_textures_type() { let mut harness = shelf(REFERENCE_WINDOW); From 3bb40ccce7e82c6514df6d445f4abe2476d1e1a2 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 07:19:33 +0000 Subject: [PATCH 27/42] Assets: tiles build their hover preview only on hover, read the selection once per frame and search each asset once --- crates/ui-egui/src/shelf.rs | 61 ++++++++++++++------------ crates/ui-egui/src/shelf_entry.rs | 26 +++++------ crates/ui-egui/src/shelf_folders.rs | 4 +- crates/ui-egui/src/shelf_panes.rs | 5 ++- crates/ui-egui/src/shelf_tabs.rs | 4 +- crates/ui-egui/tests/it/shelf_panel.rs | 2 +- 6 files changed, 55 insertions(+), 47 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9d9e3628..0209b61c 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -27,7 +27,7 @@ const HINT_SIZE: f32 = 10.0; const SAVED_MATERIAL_NAME: &str = "material"; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; -/// The last clicked or right-clicked tile's [`ShelfEntry::key`], kept in egui's memory under this id +/// The last clicked or right-clicked tile's [`ShelfEntry::identity`], kept in egui's memory under this id const SELECTED_TILE: &str = "shelf_selected_tile"; /// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points const SELECTED_OUTLINE_WIDTH: f32 = 1.5; @@ -241,8 +241,9 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let folder = app.ui.shelf_path.clone(); let picked_tab = app.ui.shelf_tab; - let mut applicable = crate::shelf_folders::paths(all.iter().filter(|entry| entry.matches(&filter) && crate::shelf_tabs::shows(picked_tab, entry.tab()))); - let matching: Vec = all.into_iter().filter(|entry| entry.in_folder(&folder) && entry.matches(&filter)).collect(); + let searched: Vec = all.into_iter().filter(|entry| entry.matches(&filter)).collect(); + let mut applicable = crate::shelf_folders::paths(searched.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))); + let matching: Vec = searched.into_iter().filter(|entry| entry.in_folder(&folder)).collect(); let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); // Saved smart materials list under the grid rather than as tiles, so they count apart @@ -289,6 +290,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { let view = app.ui.shelf_view; + let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE))); egui::ScrollArea::vertical() .id_salt("shelf_scroll") .auto_shrink([false, false]) @@ -297,7 +299,8 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ .show(ui, |ui| { tiles(ui, |ui| { for entry in entries { - entry_tile(app, ui, ctx, entry, view); + let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str())); + entry_tile(app, ui, ctx, entry, view, is_selected); } }); if saved_materials { @@ -313,9 +316,9 @@ fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize { /// The search field: a live filter on names (and categories) with a clear button while it has text fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); ui.horizontal(|ui| { - ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); + ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); let clear_width = if app.ui.shelf_filter.is_empty() { 0.0 } else { ui.spacing().interact_size.y + ui.spacing().item_spacing.x }; let field = egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search")).desired_width(ui.available_width() - clear_width); ui.add(field); @@ -450,21 +453,24 @@ fn scan_brushes(app: &mut TextureCraftApp) { #[cfg(target_arch = "wasm32")] fn scan_brushes(_: &mut TextureCraftApp) {} -/// The tile of `entry`: a click applies it, an image resource has a context menu -fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView) { +/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) { // An image removed this frame has nothing to show - let (Some(preview), texture) = (entry.preview(app), entry.thumbnail(app, ctx)) else { return }; + if let ShelfEntry::Image(name) = entry + && !app.session.images.contains_key(name) + { + return; + } + let texture = entry.thumbnail(app, ctx); let asset = entry.asset(); - let response = tile_in_view(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref(), view); + let session = &app.session; + let response = tile_in_view(ui, &mut app.thumbs, texture.as_ref(), || entry.preview(session), entry.label(), asset.as_ref(), view); - let selected_id = egui::Id::unique(SELECTED_TILE); - let key = entry.key(); - let selected = ctx.data(|data| data.get_temp::(selected_id)).is_some_and(|selected| selected == key); if selected || entry.in_use(app) { - let tk = Tokens::get(ctx); + let tokens = Tokens::get(ctx); let width = if selected { SELECTED_OUTLINE_WIDTH } else { IN_USE_OUTLINE_WIDTH }; - ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tk.accent), egui::StrokeKind::Inside); + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tokens.accent), egui::StrokeKind::Inside); } if entry.includes_randomness() { @@ -472,7 +478,8 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry } if response.clicked() || response.secondary_clicked() { - ctx.data_mut(|data| data.insert_temp(selected_id, key)); + let (kind, id) = entry.identity(); + ctx.data_mut(|data| data.insert_temp(egui::Id::unique(SELECTED_TILE), (kind.to_string(), id.to_string()))); } if response.clicked() { entry.activate(app); @@ -501,20 +508,20 @@ pub(crate) fn tile( label: &str, drag: Option<&Asset>, ) -> egui::Response { - tile_in_view(ui, thumbs, texture, preview, label, drag, ShelfView::Medium) + tile_in_view(ui, thumbs, texture, || Some(preview()), label, drag, ShelfView::Medium) } -/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside +/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside; `preview` runs on hover fn tile_in_view( ui: &mut Ui, thumbs: &mut Thumbs, texture: Option<&egui::TextureHandle>, - preview: impl FnOnce() -> ShelfPreview, + preview: impl FnOnce() -> Option, label: &str, drag: Option<&Asset>, view: ShelfView, ) -> egui::Response { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); @@ -526,21 +533,21 @@ fn tile_in_view( let painter = ui.painter(); if response.hovered() || response.dragged() { - painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); + painter.rect_filled(rect, TILE_ROUNDING, tokens.row_hover); } let image_rect = view.thumbnail_rect(rect); - thumbnail(painter, texture, image_rect, &tk); + thumbnail(painter, texture, image_rect, &tokens); if view.name_beside() { let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP; - let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tk.text)); - painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tk.text); + let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tokens.text)); + painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); } else { - let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); - painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); + let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tokens.text)); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tokens.text); } - let big = if response.hovered() { big_preview(ui, thumbs, preview) } else { None }; + let big = if response.hovered() { preview().and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) } diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index e9bbcbec..cad9e30a 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -3,6 +3,7 @@ use std::path::PathBuf; use serde_json::json; +use texturecraft_engine::Session; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::core::project::ENVIRONMENTS; use texturecraft_engine::filter_lib::{FILTERS, FilterDef}; @@ -33,7 +34,6 @@ pub(crate) const USER: &str = "user"; pub(crate) const LIBRARIES: [(&str, &str); 3] = [(PROJECT, "Project"), (STARTER, "Starter assets"), (USER, "Your assets")]; /// A shelf tile's asset -#[derive(Clone)] pub(crate) enum ShelfEntry { Material(&'static SmartMaterial), SmartMask(&'static SmartMask), @@ -81,17 +81,17 @@ impl ShelfEntry { } /// The asset's identity across frames: its kind and id - pub(crate) fn key(&self) -> String { + pub(crate) fn identity(&self) -> (&'static str, &str) { match self { - ShelfEntry::Material(material) => format!("material:{}", material.id), - ShelfEntry::SmartMask(mask) => format!("mask:{}", mask.id), - ShelfEntry::Filter(filter) => format!("filter:{}", filter.id), - ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), - ShelfEntry::SavedBrush(path) => format!("saved-brush:{}", path.display()), - ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), - ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), - ShelfEntry::Environment(name) => format!("environment:{name}"), - ShelfEntry::Image(name) => format!("image:{name}"), + ShelfEntry::Material(material) => ("material", material.id), + ShelfEntry::SmartMask(mask) => ("mask", mask.id), + ShelfEntry::Filter(filter) => ("filter", filter.id), + ShelfEntry::Brush(preset) => ("brush", preset.id), + ShelfEntry::SavedBrush(path) => ("saved-brush", path.to_str().unwrap_or_default()), + ShelfEntry::Alpha(alpha) => ("alpha", &alpha.id), + ShelfEntry::Procedural(kind) => ("procedural", kind.label()), + ShelfEntry::Environment(name) => ("environment", name), + ShelfEntry::Image(name) => ("image", name), } } @@ -168,7 +168,7 @@ impl ShelfEntry { } /// What the hover popup renders; None for an image that is gone - pub(crate) fn preview(&self, app: &TextureCraftApp) -> Option { + pub(crate) fn preview(&self, session: &Session) -> Option { Some(match self { ShelfEntry::Material(material) => ShelfPreview::material(material.id), ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), @@ -178,7 +178,7 @@ impl ShelfEntry { ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), ShelfEntry::Environment(name) => ShelfPreview::Environment(name), - ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), app.session.images.get(name).cloned()?), + ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), session.images.get(name).cloned()?), }) } diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs index 0f029033..317d109b 100644 --- a/crates/ui-egui/src/shelf_folders.rs +++ b/crates/ui-egui/src/shelf_folders.rs @@ -53,7 +53,7 @@ pub(crate) fn name(level: usize, segment: &str) -> &str { /// "› All libraries › …": each arrow lists the folders at its level, the names are plain text, a last arrow lists the folders inside pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let size = ui.spacing().interact_size.y * ARROW_SCALE; let mut picked: Option> = None; ui.horizontal(|ui| { @@ -83,7 +83,7 @@ pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec tr("All libraries"), None => continue, }; - ui.label(RichText::new(shown).strong().color(tk.text_strong)); + ui.label(RichText::new(shown).strong().color(tokens.text_strong)); } }); if let Some(path) = picked { diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index dee1eb62..9368bddc 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -110,9 +110,9 @@ fn folders(ui: &mut Ui, paths: &[Vec], prefix: &[String], current: &[Str /// A pane's caption with a button at its right fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); ui.horizontal(|ui| { - ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tk.text_dim)); + ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tokens.text_dim)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button); }); } @@ -131,6 +131,7 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { if ui.selectable_label(everything, tr("All")).clicked() { crate::shelf_toolbar::reset_query(app); } + let mut deleted = None; for (i, saved) in app.ui.shelf_saved_searches.iter().enumerate() { let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path; diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs index 4e2c3e07..cb620500 100644 --- a/crates/ui-egui/src/shelf_tabs.rs +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -49,9 +49,9 @@ fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) { let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size); let response = response.on_hover_text(tr("Filter by type")); if filtering { - let tk = crate::theme::Tokens::get(ui.ctx()); + let tokens = crate::theme::Tokens::get(ui.ctx()); let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS); - ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tk.accent); + ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tokens.accent); } egui::Popup::menu(&response).show(|ui| { diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 47c61410..e241293f 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -13,7 +13,7 @@ use texturecraft_ui_egui::shelf_view::ShelfView; const REFERENCE_WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0); /// A window whose default Assets panel is too narrow for the full type row const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0); -/// The shelf's Materials and Smart masks types +/// The types' positions in the shelf's type row (its table is crate-private) const MATERIALS_TYPE: usize = 0; const SMART_MASKS_TYPE: usize = 2; const BRUSHES_TYPE: usize = 4; From 7bd6c0ef2bdd327f58e027677c4dad3965c4a96d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:09:31 +0000 Subject: [PATCH 28/42] Generators: global adjustments, output resolution and image inputs - Global blur, balance and contrast on every generator (GeneratorGlobal). The blur blurs only the generator's own value, up to a 64-texel radius at 2K, weighted by mesh coverage; balance picks the input range that is stretched to 0..1 and contrast narrows it; invert stays last. - Output resolution (OutputResolution, ResolutionMode): Auto or UV tile, Texture set or a custom size, times a factor from 1/8 to x8, never coarser than one value per 64 texels. Below the UV tile's resolution the generator is averaged over cells and read back bilinearly. - Image inputs: each mesh map a generator reads can read an image, a uniform value or an anchor point instead. Generator inputs count as anchor and image readers (compositing order, paste, remove unused). - Blur and resolution run as a neighbourhood stage of the mask, listed the same way by every caller and only in masks. - Commands: blur, balance, contrast, resolution, customResolution, resolutionFactor on effect.add.generator / effect.set, and input with inputImage / inputValue / inputAnchor / inputBaked on effect.set. New fields are skipped when they hold their defaults and neutral settings return the value untouched, so saved projects load, save and render as before. --- crates/compose/src/eval.rs | 478 ++++++++++++++++----- crates/core/src/layer.rs | 102 ++++- crates/core/src/layer/generator_global.rs | 96 +++++ crates/core/src/layer/output_resolution.rs | 110 +++++ crates/core/src/layer/resolution_mode.rs | 32 ++ crates/core/src/lib.rs | 6 +- crates/engine/src/effect_clipboard.rs | 99 +++-- crates/engine/src/inspect.rs | 11 +- crates/engine/src/mask_cmds.rs | 80 +++- crates/engine/src/material_lib.rs | 27 +- crates/engine/tests/it/generator_inputs.rs | 77 ++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/session.rs | 42 ++ 13 files changed, 990 insertions(+), 171 deletions(-) create mode 100644 crates/core/src/layer/generator_global.rs create mode 100644 crates/core/src/layer/output_resolution.rs create mode 100644 crates/core/src/layer/resolution_mode.rs create mode 100644 crates/engine/tests/it/generator_inputs.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index fe0bdb23..f7debf8f 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -278,12 +278,24 @@ fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { neighbourhood_filters(effects, res).last() } +/// Below this a coverage weight counts as no coverage at all. +const MIN_COVERAGE_WEIGHT: f32 = 1e-6; +/// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. +const FILTER_SIZE_RESOLUTION: f32 = 2048.0; +/// The smallest radius a filter runs at, in texels. +const MIN_FILTER_RADIUS: f32 = 0.5; +/// Sharpen's blur radius at [`FILTER_SIZE_RESOLUTION`], and the smallest it runs at, in texels. +const SHARPEN_RADIUS: f32 = 1.5; +const MIN_SHARPEN_RADIUS: f32 = 0.75; + /// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does. fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { - let texels = move |size: f32| (size * res as f32 / 2048.0).max(0.5); + let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind { EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), - EffectKind::Filter(Filter::Sharpen { amount }) => Some((index, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), + EffectKind::Filter(Filter::Sharpen { amount }) => { + Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount)))) + } EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) @@ -297,6 +309,10 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator Some((index, texels(*width * 0.5), Op::Bevel)), EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)), + // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them + EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { + Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + } EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) } @@ -597,59 +613,73 @@ fn is_box_blur(op: Op) -> bool { /// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. #[allow(clippy::too_many_arguments)] fn filter_region( - inp: &Inputs, + inputs: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, effects: &[Effect], (index, radius, op): (usize, f32, Op), - (rx0, ry0, w, h): (u32, u32, u32, u32), + (region_x, region_y, width, height): (u32, u32, u32, u32), start: Option<(usize, &Field)>, ) -> Option { - let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height)); - let comps = match job { + let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); + let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); + + // A generator stage also keeps the generator's own ramp per texel, beside the stack below it (generators only act in masks) + let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) { + (Job::Mask(_), Some((EffectKind::Generator(generator), blend))) => Some((generator, blend)), + _ => None, + }; + let components = match job { + Job::Mask(_) if generator.is_some() => 2, Job::Mask(_) => 1, Job::Content(_) => 4, }; // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) - let (rx1, ry1) = (rx0 + w, ry0 + h); - let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect(); + let (region_right, region_bottom) = (region_x + width, region_y + height); + let region_tiles: Vec<(u32, u32)> = + (region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect(); let parts: Vec> = region_tiles .par_iter() - .map(|&(tx, ty)| { - let full = anchor_plan(inp, id, channels, tx, ty, Some(below)); - let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); + .map(|&(tile_x, tile_y)| { + let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below)); + let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); let mut mask = None; let mut nodes = Vec::new(); + let mut generator_sizes = None; match job { Job::Mask(layer_mask) => { - let Some(mut mask_stack) = mask_plan(inp, id, layer_mask, tx, ty, None) else { return Vec::new() }; + let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() }; + generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); mask_stack.effects.truncate(index); mask_stack.start = start; mask = Some(mask_stack); } Job::Content(channel) => { - nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below)); - if let Some(chan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { - chan.effects.truncate(index); - chan.start = start; + nodes = plan(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below)); + if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { + channel_plan.effects.truncate(index); + channel_plan.start = start; } } } - tile_texels(inp.gbuf, tx, ty) + tile_texels(inputs.gbuf, tile_x, tile_y) .map(|(x, y, offset)| { - let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); - if !full.is_empty() { - texel.anchors_below(&full, id); + let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchor_nodes.is_empty() { + texel.anchors_below(&anchor_nodes, id); } let value = match (&mask, nodes.first()) { - (Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0], - (None, Some(node)) => match node.chans.first().and_then(|chan| texel.content(&node.content, chan)) { - Some((color, cov)) => [color[0] * cov, color[1] * cov, color[2] * cov, cov], + (Some(mask_stack), _) => { + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); + [texel.mask(mask_stack), ramp, 0.0, 0.0] + } + (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { + Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], None => [0.0; 4], }, (None, None) => [0.0; 4], @@ -661,55 +691,59 @@ fn filter_region( .collect(); // Scatter into the region, a row of tiles at a time (the region is tile aligned) - let texel_count = (w * h) as usize; - let mut orig = vec![0.0f32; texel_count * comps]; + let texel_count = (width * height) as usize; + let mut stack_values = vec![0.0f32; texel_count * components]; let mut cover = vec![0.0f32; texel_count]; - let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize; - let band = (TILE * w) as usize; - orig.par_chunks_mut(band * comps).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((orig, cover), row)| { + let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize; + let band = (TILE * width) as usize; + stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| { for &(x, y, value) in row.iter().flatten() { - let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize; - if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), orig.get_mut(texel * comps..(texel + 1) * comps)) { + let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; + if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) { *covered = 1.0; - pixel.copy_from_slice(&value[..comps]); + pixel.copy_from_slice(&value[..components]); } } }); - // High pass centers on the channel's mid value (0 for signed channels like height) - let mid = match job { + // High pass centers on the channel's middle value (0 for signed channels like height) + let middle = match job { Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let filtered = |scale: f32| -> Vec { - let res = ((inp.tile_res() as f32 * scale).round() as u32).max(1); - let scaled_radius = neighbourhood_filters(effects, res) + let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1); + if let Some((generator, blend)) = generator { + let texture_set = inputs.project.texture_set(inputs.ts).map_or(inputs.tile_res(), |set| set.resolution); + return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set)); + } + let scaled_radius = neighbourhood_filters(effects, tile_resolution) .find(|filter| filter.0 == index) .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); if !is_box_blur(op) { - return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), scaled_radius as f32, res, opacity); + return gather(op, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity); } // Weighted so uncovered texels don't bleed in - let (width, height, blur_radius) = (w as usize, h as usize, scaled_radius as usize); + let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize); let mut weights = cover.clone(); - blur(&mut weights, width, height, blur_radius); - let mut data = orig.clone(); - for component in 0..comps { - let mut sums: Vec = orig.par_chunks(comps).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); - blur(&mut sums, width, height, blur_radius); - data.par_chunks_mut(comps).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { - // Content is premultiplied, so the mid value is too (coverage itself is kept) - let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *weight > 1e-6 + blur(&mut weights, columns, rows, blur_radius); + let mut filtered_values = stack_values.clone(); + for component in 0..components { + let mut sums: Vec = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); + blur(&mut sums, columns, rows, blur_radius); + filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { + // Content is premultiplied, so the middle value is too (coverage itself is kept) + let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + if *weight > MIN_COVERAGE_WEIGHT && let Some(slot) = pixel.get_mut(component) { let (original, blurred) = (*slot, sum / weight); let result = match op { Op::Blur(Some(amount)) => original + amount * (original - blurred), - Op::HighPass if component < 3 => original - blurred + mid * cov, + Op::HighPass if component < 3 => original - blurred + middle * coverage, // Away from 0 by at most the value itself: 0 at the edge, full inside Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), Op::Glow(amount) if component < 3 => original + amount * blurred, @@ -720,31 +754,148 @@ fn filter_region( } }); } - data + filtered_values }; // Each block keeps the result at its tile's scale (blocks are TILE aligned) - let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default(); - let mut levels: Vec = - (ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect(); + let scales = inputs.project.texture_set(inputs.ts).map(TextureSet::block_scales).unwrap_or_default(); + let mut levels: Vec = (region_y..region_bottom) + .step_by(TILE as usize) + .flat_map(|y| (region_x..region_right).step_by(TILE as usize).map(move |x| (x, y))) + .map(|(x, y)| scales.at(x, y)) + .collect(); levels.sort_by(f32::total_cmp); levels.dedup(); let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest)); - let mut data = filtered(first); + + // A generator stage's field is the mask alone + let field_components = if generator.is_some() { 1 } else { components }; + let mut result = filtered(first); for &scale in rest { - let other = filtered(scale); - let row = w as usize * comps; - data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| { - for (x, (target, source)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { - if scales.at(rx0 + x as u32, ry0 + y as u32) == scale { + let rescaled = filtered(scale); + let row = width as usize * field_components; + result.par_chunks_mut(row).zip(rescaled.par_chunks(row)).enumerate().for_each(|(y, (target_row, source_row))| { + for (x, (target, source)) in target_row.chunks_mut(field_components).zip(source_row.chunks(field_components)).enumerate() { + if scales.at(region_x + x as u32, region_y + y as u32) == scale { target.copy_from_slice(source); } } }); } - unpremultiply(&mut data, comps); - Some(Field { x0: rx0, y0: ry0, w, h, comps, data }) + unpremultiply(&mut result, field_components); + Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result }) +} + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +fn generator_region( + generator: &Generator, + blend: BlendMode, + opacity: f32, + stack: &[f32], + cover: &[f32], + (region_x, region_y, width, height): (u32, u32, u32, u32), + (uv_tile, texture_set): (u32, u32), +) -> Vec { + let (columns, rows) = (width as usize, height as usize); + let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + + // Coarser than the UV tile: averaged over cells, then the blur around them + let cell = generator.resolution.cell(uv_tile, texture_set) as usize; + if cell > 1 { + ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); + } + + let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; + if blur_radius > 0 { + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, blur_radius); + let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); + blur(&mut sums, columns, rows, blur_radius); + ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { + if *weight > MIN_COVERAGE_WEIGHT { + *ramp = sum / weight; + } + }); + } + + // Finished and blended over the stack below, like the generator effect itself + stack + .par_chunks(2) + .zip(ramps.par_iter()) + .map(|(texel, ramp)| { + let below = texel.first().copied().unwrap_or(0.0); + let generated = finish_generator(generator, *ramp); + below + (blend1(blend, below, generated) - below) * opacity + }) + .collect() +} + +/// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. +fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { + // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region + let (first_column, first_row) = (region_x / cell, region_y / cell); + let columns = (region_x + width).div_ceil(cell) - first_column; + let rows = (region_y + height).div_ceil(cell) - first_row; + + // Each cell's coverage-weighted average, a row of cells at a time + let averages: Vec> = (0..rows) + .into_par_iter() + .flat_map_iter(|row| { + let mut sums = vec![(0.0f32, 0.0f32); columns]; + let first_y = ((first_row + row) * cell).saturating_sub(region_y); + let last_y = ((first_row + row + 1) * cell).saturating_sub(region_y).min(height); + for y in first_y..last_y { + for x in 0..width { + let texel = y * width + x; + let covered = cover.get(texel).copied().unwrap_or(0.0); + if let Some((sum, weight)) = sums.get_mut((region_x + x) / cell - first_column) { + *sum += values.get(texel).copied().unwrap_or(0.0) * covered; + *weight += covered; + } + } + } + sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight)) + }) + .collect(); + let average = |column: isize, row: isize| -> Option { + let column = column.clamp(0, columns as isize - 1) as usize; + let row = row.clamp(0, rows as isize - 1) as usize; + averages.get(row * columns + column).copied().flatten() + }; + + let cell_size = cell as f32; + (0..height) + .into_par_iter() + .flat_map_iter(|y| (0..width).map(move |x| (x, y))) + .map(|(x, y)| { + // Position in cells, relative to the first cell's center + let cell_x = ((region_x + x) as f32 + 0.5) / cell_size - 0.5 - first_column as f32; + let cell_y = ((region_y + y) as f32 + 0.5) / cell_size - 0.5 - first_row as f32; + let (left, top) = (cell_x.floor(), cell_y.floor()); + let (offset_x, offset_y) = (cell_x - left, cell_y - top); + let (left, top) = (left as isize, top as isize); + let corners = [ + (left, top, (1.0 - offset_x) * (1.0 - offset_y)), + (left + 1, top, offset_x * (1.0 - offset_y)), + (left, top + 1, (1.0 - offset_x) * offset_y), + (left + 1, top + 1, offset_x * offset_y), + ]; + let (sum, weight) = corners.iter().fold((0.0, 0.0), |(sum, weight), &(column, row, corner_weight)| match average(column, row) { + Some(value) => (sum + value * corner_weight, weight + corner_weight), + None => (sum, weight), + }); + if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } + }) + .collect() +} + +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset. +fn finish_generator(generator: &Generator, ramp: f32) -> f32 { + let value = generator.global.apply(ramp); + let value = if generator.invert { 1.0 - value } else { value }; + let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; + (value + offset).clamp(0.0, 1.0) } /// Clamp filtered masks to 0..1, and turn filtered content back into straight values. @@ -1216,15 +1367,21 @@ impl<'a, 'b> Texel<'a, 'b> { } } - fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert. + fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let coords = self.coords(); let signal = match (generator.kind, &generator.detail) { - (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes), - (GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - (GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5), - (GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), + (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { + // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let curvature = self.generator_input(generator, BakedMap::Curvature); + self.curvature_detail(detail, sizes, curvature) + } + (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; @@ -1241,12 +1398,29 @@ impl<'a, 'b> Texel<'a, 'b> { signal }; - // A smooth step from black to white over 2 × softness around 1 − level, then the offset - generator.shape(signal) + // A smooth step from black to white over 2 × softness around 1 − level + let threshold = 1.0 - generator.level.clamp(0.0, 1.0); + let softness = generator.softness.max(Generator::MIN_SOFTNESS); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + ramp * ramp * (3.0 - 2.0 * ramp) } - /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let ramp = self.generator_ramp(generator, curvature_sizes); + finish_generator(generator, ramp) + } + + /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). + fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]), + None => self.baked(map), + } + } + + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { let combine = |edges: f32, cavities: f32| match detail.mode { CurvatureMode::Edges => edges, CurvatureMode::Cavities => cavities, @@ -1255,7 +1429,7 @@ impl<'a, 'b> Texel<'a, 'b> { }; // Without curvature to read the texel is flat: no edges or cavities - let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) }; + let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let working_size = (self.res, self.inp.gbuf.height); let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; @@ -2272,7 +2446,7 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti #[cfg(test)] mod tests { use super::*; - use texturecraft_core::{ChannelBlend, Effect, Layer, Procedural, ProceduralKind, TextureSet}; + use texturecraft_core::{ChannelBlend, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; use texturecraft_geom::primitives; struct Fixture { @@ -2564,44 +2738,156 @@ mod tests { assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); } - #[test] - fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + /// A 256² set whose curvature map has a one-texel ridge in column `ridge_x` (flat elsewhere), and a white fill layer to mask. + fn ridge_fixture(ridge_x: usize) -> (Fixture, LayerId) { let mut fixture = fixture(); fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256); fixture.project.texture_sets[0].resolution = 256; - let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect(); + let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == ridge_x { 1.0 } else { 0.5 }).collect(); fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() }; let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); - let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec { + (fixture, layer) + } + + /// `layer`'s mask made of `effects` (bottom first) on black, read along row 128 over `xs`. + fn mask_row(fixture: &mut Fixture, layer: LayerId, effects: Vec, xs: std::ops::Range) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects = effects; + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, layer, &xs.map(|x| (x, 128)).collect::>()).unwrap() + } + + /// A generator effect of `fixture`'s project. + fn generator_effect(fixture: &mut Fixture, generator: Generator) -> Effect { + Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)) + } + + /// An edge wear generator that marks exactly the curvature ridge (the map as baked, a hard step). + fn ridge_generator() -> Generator { + Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::EdgeWear) } + } + + #[test] + fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + let (mut fixture, layer) = ridge_fixture(128); + let mut row_with = |weights: [f32; 7]| { let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights }; let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; - let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); - fixture.project.layer_mut(layer).unwrap().mask = Some(mask); - let images = Default::default(); - let inputs = Inputs { - project: &fixture.project, - ts: 0, - mesh: &fixture.mesh, - gbuf: &fixture.gbuf, - pixels: &fixture.pixels, - baked: &fixture.baked, - block_scales: BlockScales::default(), - preview: None, - images: &images, - bounds: fixture.mesh.bounds(), - }; - mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::>()).unwrap() + let effect = generator_effect(&mut fixture, generator); + mask_row(&mut fixture, layer, vec![effect], 120..137) }; // The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth let (ridge, five_texels_away) = (8, 3); - let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); - let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + let finest = row_with([1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + let largest = row_with([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}"); assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}"); } + #[test] + fn a_replaced_curvature_input_is_read_at_its_own_size_only() { + let (mut fixture, layer) = ridge_fixture(128); + let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] }; + let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + generator.inputs.insert(BakedMap::Curvature, Source::Uniform([0.5; 3])); + let effect = generator_effect(&mut fixture, generator); + let row = mask_row(&mut fixture, layer, vec![effect], 120..137); + + // The largest size alone would mark the ridge and texels around it; the flat input marks nothing + assert!(row.iter().all(|value| *value < 0.01), "the detail sizes of the mesh map are not read: {row:?}"); + } + + #[test] + fn generator_blur_softens_only_the_generator_not_the_stack_below() { + let (mut fixture, layer) = ridge_fixture(100); + let mut row_with = |blur: f32| { + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() }); + let mut generator = ridge_generator(); + generator.global.blur = blur; + let mut lighten = generator_effect(&mut fixture, generator); + lighten.blend = BlendMode::Lighten; + mask_row(&mut fixture, layer, vec![below, lighten], 40..111) + }; + + // The row starts at x 40 and crosses a checker edge at x 64; the ridge at x 100 is texel 60, five texels left of it texel 55, and texels below 30 are out of the blur's reach + let (ridge, five_texels_away, far) = (60, 55, 0..30); + let sharp = row_with(0.0); + let blurred = row_with(1.0); + assert!(sharp[ridge] > 0.99 && sharp[five_texels_away] < 0.01, "unblurred, the ridge is one texel: {sharp:?}"); + assert!(blurred[ridge] < 0.99 && blurred[ridge] > blurred[five_texels_away], "the blur spreads the ridge: {blurred:?}"); + assert!(blurred[five_texels_away] > 0.01, "and reaches texels away from it: {blurred:?}"); + for texel in far { + assert_eq!(blurred[texel], sharp[texel], "the checker below keeps its hard edges at texel {texel}"); + } + } + + #[test] + fn a_lower_generator_resolution_spreads_a_ridge_over_its_cell() { + let (mut fixture, layer) = ridge_fixture(100); + let mut row_with = |factor: i8| { + let mut generator = ridge_generator(); + generator.resolution.factor = factor; + let effect = generator_effect(&mut fixture, generator); + mask_row(&mut fixture, layer, vec![effect], 80..121) + }; + + // The row starts at x 80: the ridge at x 100 is texel 20; at an eighth of the resolution one value covers 8 texels + let (ridge, beside, far) = (20, 18, 0); + let full = row_with(0); + let eighth = row_with(-3); + assert!(full[ridge] > 0.99 && full[beside] < 0.01, "at full resolution the ridge is one texel: {full:?}"); + assert!(eighth[ridge] < 0.5 && eighth[beside] > 0.01, "an eighth of the resolution averages it over its cell: {eighth:?}"); + assert!(eighth[far] < 0.01, "texels a few cells away stay black: {eighth:?}"); + } + + #[test] + fn every_caller_lists_the_same_generator_stages_whatever_resolution_it_passes() { + let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 1024, factor: 0 }; + let effects = [Effect::new(LayerId(1), EffectKind::Generator(Generator { resolution: custom, ..Generator::new(GeneratorKind::Dirt) }))]; + + // A UV tile of 1024 texels in a 2-tile-wide set: callers pass the tile size or the whole set's width + let at_tile: Vec = neighbourhood_filters(&effects, 1024).map(|stage| stage.0).collect(); + let at_set_width: Vec = neighbourhood_filters(&effects, 2048).map(|stage| stage.0).collect(); + assert_eq!(at_tile, at_set_width); + assert_eq!(at_tile, [0], "a custom resolution can be coarser than some UV tile, so it is a stage"); + } + + #[test] + fn a_generator_input_replaced_by_a_value_is_read_instead_of_the_mesh_map() { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; 64 * 64]))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let value_with = |fixture: &mut Fixture, input: Option| -> f32 { + let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, ..Generator::new(GeneratorKind::Dirt) }; + if let Some(value) = input { + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::Uniform([value; 3])); + } + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + run(fixture, None).value(Channel::BaseColor, 20, 20)[0] + }; + + // Dirt is where ambient occlusion is dark: none on the baked white map (the stack below shows), all of it on a black input + let (baked, black) = (value_with(&mut fixture, None), value_with(&mut fixture, Some(0.0))); + assert!(black > 0.99 && baked < black - 0.2, "baked {baked}, black input {black}"); + } + #[test] fn curvature_detail_noise_keeps_flat_areas_neutral() { let mut fixture = fixture(); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 8e7c41e8..acd53874 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,13 +4,19 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use crate::{BlendMode, Channel, ChannelKind, lum}; +use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum}; mod curvature_detail; mod curvature_mode; +mod generator_global; +mod output_resolution; +mod resolution_mode; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; +pub use generator_global::GeneratorGlobal; +pub use output_resolution::OutputResolution; +pub use resolution_mode::ResolutionMode; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -526,6 +532,17 @@ impl GeneratorKind { GeneratorKind::Direction => "Light / direction", } } + + /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. + pub fn inputs(self) -> &'static [BakedMap] { + match self { + GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature], + GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], + GeneratorKind::ThinAreas => &[BakedMap::Thickness], + GeneratorKind::Position | GeneratorKind::Direction => &[], + } + } + pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s)) @@ -552,9 +569,25 @@ pub struct Generator { /// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed). #[serde(default, skip_serializing_if = "Option::is_none")] pub detail: Option, + /// Blur, balance and contrast of the finished value (neutral for generators saved before they existed). + #[serde(default, skip_serializing_if = "GeneratorGlobal::is_neutral")] + pub global: GeneratorGlobal, + /// The resolution the generator is computed at (the texture set's for generators saved before it existed). + #[serde(default, skip_serializing_if = "OutputResolution::is_default")] + pub resolution: OutputResolution, + /// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub inputs: BTreeMap, } impl Generator { + /// The softest a ramp gets, so its threshold never divides by zero. + pub const MIN_SOFTNESS: f32 = 1e-3; + /// The most noise a generator mixes in, and the range of its noise scale. + pub const MAX_NOISE_AMOUNT: f32 = 2.0; + pub const MIN_NOISE_SCALE: f32 = 0.01; + pub const MAX_NOISE_SCALE: f32 = 1000.0; + pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), @@ -568,7 +601,21 @@ impl Generator { GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), _ => None, }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, offset: 0.0, direction: [0.0, 1.0, 0.0], invert: false, detail } + Generator { + kind, + level, + softness, + noise_amount, + noise_scale: 8.0, + seed: 7, + offset: 0.0, + direction: [0.0, 1.0, 0.0], + invert: false, + detail, + global: GeneratorGlobal::default(), + resolution: OutputResolution::default(), + inputs: BTreeMap::new(), + } } /// The mask value for a (noise-broken) signal `s`: the smooth threshold at `level` over @@ -1038,14 +1085,45 @@ impl EffectKind { matches!(self, EffectKind::Paint | EffectKind::Path(_)) } - /// Anchor points read by this effect's sources. + /// Whether a source of this effect (a fill, a material or a generator input) reads an anchor point. fn reads_anchor(&self) -> bool { match self { EffectKind::Fill { source, .. } => source.anchor().is_some(), - EffectKind::Material(f) => f.sources.values().any(|s| s.anchor().is_some()), + EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()), + EffectKind::Generator(generator) => generator.inputs.values().any(|source| source.anchor().is_some()), _ => false, } } + + /// The anchor points this effect's sources read, with the channel each reads. + pub fn anchors_read(&self) -> Vec<(LayerId, Channel)> { + let sources: Vec<&Source> = match self { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Material(fill) => fill.sources.values().collect(), + EffectKind::Generator(generator) => generator.inputs.values().collect(), + _ => Vec::new(), + }; + sources + .into_iter() + .filter_map(|source| match source { + Source::Anchor { anchor, channel } => Some((*anchor, *channel)), + _ => None, + }) + .collect() + } + + /// The image resources this effect's sources read (a fill or a generator input). + pub fn images_read(&self) -> impl Iterator { + let sources: Vec<&Source> = match self { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Generator(generator) => generator.inputs.values().collect(), + _ => Vec::new(), + }; + sources.into_iter().filter_map(|source| match source { + Source::Image { name, .. } => Some(name.as_str()), + _ => None, + }) + } } impl Layer { @@ -1115,6 +1193,22 @@ mod tests { assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes"); } + #[test] + fn generators_saved_before_the_new_settings_load_and_save_unchanged() { + let saved = serde_json::to_value(Generator::new(GeneratorKind::Dirt)).unwrap(); + for field in ["global", "resolution", "inputs"] { + assert!(saved.get(field).is_none(), "a default `{field}` is not written, so saved files stay as they were"); + } + + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert!(loaded.global.is_neutral()); + + let mut blurred = Generator::new(GeneratorKind::Dirt); + blurred.global.blur = 0.5; + let round_trip: Generator = serde_json::from_value(serde_json::to_value(&blurred).unwrap()).unwrap(); + assert_eq!(round_trip, blurred); + } + #[test] fn levels_map_range_and_gamma() { let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; diff --git a/crates/core/src/layer/generator_global.rs b/crates/core/src/layer/generator_global.rs new file mode 100644 index 00000000..15349e0d --- /dev/null +++ b/crates/core/src/layer/generator_global.rs @@ -0,0 +1,96 @@ +use serde::{Deserialize, Serialize}; + +/// Adjustments every generator applies to its finished value: a blur, then balance and contrast. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct GeneratorGlobal { + /// Blur of the generated value (0..1 of [`GeneratorGlobal::MAX_BLUR`]). + pub blur: f32, + /// Shifts the value darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged. + pub balance: f32, + /// Narrows the ramp around its middle (0 unchanged, 1 a hard step). + pub contrast: f32, +} + +impl GeneratorGlobal { + /// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. + pub const MAX_BLUR: f32 = 64.0; + /// Narrower than this, the balanced range is a hard step. + pub const MIN_RANGE: f32 = 1e-6; + /// The texels per side the blur radius is measured at (2K). + pub const BLUR_RESOLUTION: f32 = 2048.0; + + pub fn is_neutral(&self) -> bool { + *self == GeneratorGlobal::default() + } + + /// The blur as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. + pub fn blur_radius(&self) -> f32 { + self.blur.clamp(0.0, 1.0) * GeneratorGlobal::MAX_BLUR + } + + /// The blur as a radius in texels at `resolution` texels per side. + pub fn blur_radius_at(&self, resolution: u32) -> f32 { + self.blur_radius() * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION + } + + /// `value` after balance and contrast: balance picks the input range stretched to 0..1, contrast narrows it around its middle. + pub fn apply(&self, value: f32) -> f32 { + if self.balance == 0.5 && self.contrast == 0.0 { + return value; + } + let balance = self.balance.clamp(0.0, 1.0); + let (low, high) = ((1.0 - 2.0 * balance).max(0.0), (2.0 - 2.0 * balance).min(1.0)); + let middle = (low + high) * 0.5; + let keep = 1.0 - self.contrast.clamp(0.0, 1.0); + let (low, high) = (middle - (middle - low) * keep, middle + (high - middle) * keep); + if high - low < GeneratorGlobal::MIN_RANGE { + return if value >= middle { 1.0 } else { 0.0 }; + } + ((value - low) / (high - low)).clamp(0.0, 1.0) + } +} + +impl Default for GeneratorGlobal { + fn default() -> Self { + GeneratorGlobal { blur: 0.0, balance: 0.5, contrast: 0.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn neutral_settings_leave_the_value_unchanged() { + let global = GeneratorGlobal::default(); + for value in [0.0, 0.1, 0.5, 0.93, 1.0] { + assert_eq!(global.apply(value), value); + } + } + + #[test] + fn balance_darkens_below_the_middle_and_brightens_above() { + let darker = GeneratorGlobal { balance: 0.25, ..GeneratorGlobal::default() }; + assert_eq!(darker.apply(0.4), 0.0, "the lower half goes black"); + assert!((darker.apply(0.75) - 0.5).abs() < 1e-6, "the upper half stretches over the whole range"); + + let brighter = GeneratorGlobal { balance: 0.75, ..GeneratorGlobal::default() }; + assert!((brighter.apply(0.25) - 0.5).abs() < 1e-6); + assert_eq!(brighter.apply(0.6), 1.0, "the upper half goes white"); + + assert_eq!(GeneratorGlobal { balance: 0.0, ..GeneratorGlobal::default() }.apply(0.99), 0.0); + assert_eq!(GeneratorGlobal { balance: 1.0, ..GeneratorGlobal::default() }.apply(0.01), 1.0); + } + + #[test] + fn full_contrast_is_a_step_at_the_middle_of_the_balanced_range() { + let step = GeneratorGlobal { contrast: 1.0, ..GeneratorGlobal::default() }; + assert_eq!(step.apply(0.49), 0.0); + assert_eq!(step.apply(0.51), 1.0); + + let half = GeneratorGlobal { contrast: 0.5, ..GeneratorGlobal::default() }; + assert_eq!(half.apply(0.25), 0.0); + assert!((half.apply(0.5) - 0.5).abs() < 1e-6); + assert_eq!(half.apply(0.75), 1.0); + } +} diff --git a/crates/core/src/layer/output_resolution.rs b/crates/core/src/layer/output_resolution.rs new file mode 100644 index 00000000..6c1e8778 --- /dev/null +++ b/crates/core/src/layer/output_resolution.rs @@ -0,0 +1,110 @@ +use serde::{Deserialize, Serialize}; + +use super::resolution_mode::ResolutionMode; + +/// The resolution a generator computes its output at, before it is sampled onto the texture set. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutputResolution { + pub mode: ResolutionMode, + /// Texels per side for [`ResolutionMode::Custom`]. + pub custom: u32, + /// Power of two applied to the base size (−3 = 1/8 … 3 = ×8; 0 = the same as the context). + pub factor: i8, +} + +impl OutputResolution { + /// The factors the reference app offers: 1/8 to ×8. + pub const FACTORS: std::ops::RangeInclusive = -3..=3; + /// The sizes offered for [`ResolutionMode::Custom`]. + pub const CUSTOM_SIZES: [u32; 6] = [128, 256, 512, 1024, 2048, 4096]; + /// The largest output, the largest texture set resolution. + pub const MAX_SIZE: u32 = 8192; + /// The coarsest output: one value per this many texels of the context per side (a compositing tile). + pub const MAX_CELL: u32 = 64; + + pub fn is_default(&self) -> bool { + *self == OutputResolution::default() + } + + /// Whether some UV tile can get a coarser output than its own resolution (a custom size, the set's size or a factor below 1). + pub fn can_reduce(&self) -> bool { + matches!(self.mode, ResolutionMode::Custom | ResolutionMode::TextureSet) || self.factor < 0 + } + + /// The largest cell a UV tile of up to `uv_tile` texels per side can get, whatever its texture set's resolution. + pub fn largest_cell(&self, uv_tile: u32) -> u32 { + if self.mode == ResolutionMode::TextureSet { OutputResolution::MAX_CELL } else { self.cell(uv_tile, uv_tile) } + } + + /// Texels per side of the output for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`. + pub fn output_size(&self, uv_tile: u32, texture_set: u32) -> u32 { + let base = match self.mode { + ResolutionMode::Auto | ResolutionMode::UvTile => uv_tile, + ResolutionMode::TextureSet => texture_set, + ResolutionMode::Custom => self.custom, + }; + let factor = self.factor.clamp(*OutputResolution::FACTORS.start(), *OutputResolution::FACTORS.end()); + let scaled = if factor >= 0 { base.saturating_mul(1 << factor) } else { base >> -factor }; + scaled.clamp((uv_tile / OutputResolution::MAX_CELL).max(1), OutputResolution::MAX_SIZE) + } + + /// How many texels of the UV tile one output texel covers per side (1 when the output is as fine or finer). + pub fn cell(&self, uv_tile: u32, texture_set: u32) -> u32 { + (uv_tile / self.output_size(uv_tile, texture_set)).max(1) + } +} + +impl Default for OutputResolution { + fn default() -> Self { + OutputResolution { mode: ResolutionMode::Auto, custom: 2048, factor: 0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_follows_the_uv_tile() { + let resolution = OutputResolution::default(); + assert_eq!(resolution.output_size(1024, 2048), 1024); + assert_eq!(resolution.cell(1024, 2048), 1); + assert!(!resolution.can_reduce()); + } + + #[test] + fn the_texture_set_mode_reads_the_set_not_the_uv_tile() { + let resolution = OutputResolution { mode: ResolutionMode::TextureSet, factor: -1, ..OutputResolution::default() }; + assert_eq!(resolution.output_size(512, 2048), 1024, "half the set's 2048"); + assert_eq!(resolution.cell(512, 2048), 1, "finer than the 512 tile: one texel per texel"); + } + + #[test] + fn factors_and_custom_sizes_scale_the_output() { + let eighth = OutputResolution { factor: -3, ..OutputResolution::default() }; + assert_eq!((eighth.output_size(2048, 2048), eighth.cell(2048, 2048)), (256, 8)); + + let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 512, factor: 1 }; + assert_eq!((custom.output_size(2048, 2048), custom.cell(2048, 2048)), (1024, 2)); + + let finer = OutputResolution { factor: 3, ..OutputResolution::default() }; + assert_eq!((finer.output_size(2048, 2048), finer.cell(2048, 2048)), (8192, 1), "a finer output than the tile keeps one texel per texel"); + } + + #[test] + fn the_largest_cell_covers_any_texture_set() { + let set = OutputResolution { mode: ResolutionMode::TextureSet, ..OutputResolution::default() }; + assert!(set.can_reduce(), "a UV tile larger than its set gets the set's coarser size"); + assert_eq!(set.largest_cell(2048), OutputResolution::MAX_CELL); + assert_eq!(OutputResolution { factor: -2, ..OutputResolution::default() }.largest_cell(2048), 4); + } + + #[test] + fn hostile_sizes_stay_within_the_largest_output_and_the_coarsest_cell() { + let huge = OutputResolution { mode: ResolutionMode::Custom, custom: u32::MAX, factor: i8::MAX }; + assert_eq!(huge.output_size(2048, 2048), OutputResolution::MAX_SIZE); + + let tiny = OutputResolution { mode: ResolutionMode::Custom, custom: 1, factor: -3 }; + assert_eq!(tiny.cell(4096, 4096), OutputResolution::MAX_CELL); + } +} diff --git a/crates/core/src/layer/resolution_mode.rs b/crates/core/src/layer/resolution_mode.rs new file mode 100644 index 00000000..ffd6a140 --- /dev/null +++ b/crates/core/src/layer/resolution_mode.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +/// What a generator's output resolution is based on. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ResolutionMode { + /// The context: the resolution of the UV tile it is computed for. + Auto, + /// The texture set's resolution. + TextureSet, + /// The UV tile's resolution. + UvTile, + /// A size of its own. + Custom, +} + +impl ResolutionMode { + pub const ALL: [ResolutionMode; 4] = [ResolutionMode::Auto, ResolutionMode::TextureSet, ResolutionMode::UvTile, ResolutionMode::Custom]; + + pub fn label(self) -> &'static str { + match self { + ResolutionMode::Auto => "Auto", + ResolutionMode::TextureSet => "Texture set", + ResolutionMode::UvTile => "UV tile", + ResolutionMode::Custom => "Custom", + } + } + + pub fn parse(name: &str) -> Option { + let norm = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], ""); + ResolutionMode::ALL.into_iter().find(|mode| norm(&format!("{mode:?}")) == norm(name) || norm(mode.label()) == norm(name)) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 75ea2405..4a17e89e 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,9 +24,9 @@ pub use bake::{ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, - hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask, + Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, OutputResolution, PathShape, Procedural, ProceduralKind, + Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index 36aa5f3a..3f68c147 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -2,7 +2,7 @@ //! clipboard: it holds a layer or an effect. use serde_json::{Value, json}; -use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; +use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground}; use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; use crate::layer_ops::{empty_texel, fit}; @@ -55,26 +55,29 @@ fn cut(s: &mut Session, p: &Value) -> Result { Ok(json!({ "cut": eid })) } -fn paste(s: &mut Session, p: &Value) -> Result { +fn paste(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.paste"; - let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; - let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; - let layer = layer_param(s, CMD, p)?; - // The selected effect's stack, or the content or mask the selection targets. - let selected = match s.target { - StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x), + let (copied, copied_id) = session.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let effect = copied.project.effect(copied_id).map(|(_, effect)| effect.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let layer = layer_param(session, CMD, params)?; + + // The selected effect's stack, or the content or mask the selection targets + let selected = match session.target { + StackTarget::Effect(selected) if session.selected_layer() == Some(layer) => Some(selected), _ => None, }; - let in_content = |s: &Session, x: LayerId| { - s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x)) + let in_content = |session: &Session, effect_id: LayerId| { + let owner = session.doc.project.effect(effect_id).and_then(|(owner, _)| session.doc.project.layers.get(&owner)); + owner.is_some_and(|owner| owner.content_effects.iter().any(|effect| effect.id == effect_id)) }; - let asked = strp(p, "target").is_some(); + let asked = strp(params, "target").is_some(); let content = match selected { - _ if asked => content_target(p, CMD)?, - Some(x) => in_content(s, x), - None => s.target == StackTarget::Content && s.selected_layer() == Some(layer), + _ if asked => content_target(params, CMD)?, + Some(selected) => in_content(session, selected), + None => session.target == StackTarget::Content && session.selected_layer() == Some(layer), }; - // Effects that fit one stack only go there, unless another was asked for. + + // Effects that fit one stack only go there, unless another was asked for let content = match effect.kind.content_only() { Some(only) if only != content && asked => { return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" }))); @@ -82,46 +85,52 @@ fn paste(s: &mut Session, p: &Value) -> Result { Some(only) => only, None => content, }; - // An instance's content and (unless it has its own) mask belong to its source. - let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) }; - let owner_layer = s.doc.project.layer(owner)?; + + // An instance's content and (unless it has its own) mask belong to its source + let owner = if content { session.doc.project.content_layer(layer).map_or(layer, |source| source.id) } else { session.doc.project.mask_owner(layer) }; + let owner_layer = session.doc.project.layer(owner)?; if content && owner_layer.is_group() { return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name))); } - // A fill reading an anchor point needs one below its new layer. - if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind { - anchor_source(s, CMD, owner, *anchor, *channel)?; + + // Each anchor point the effect reads must be below its new layer + for (anchor, channel) in effect.kind.anchors_read() { + anchor_source(session, CMD, owner, anchor, channel)?; } - let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; - let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?; - let new = s.edit("Paste effect", |s| { - let new = s.doc.project.alloc_id(); - let l = s.doc.project.layer_mut(owner)?; - let list = if content { - &mut l.content_effects + let (set, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; + let (size, channels) = session.doc.project.texture_set(set).map(|texture_set| (texture_set.size(), texture_set.channel_list()))?; + + let pasted = session.edit("Paste effect", |session| { + let pasted = session.doc.project.alloc_id(); + let owner_layer = session.doc.project.layer_mut(owner)?; + let stack = if content { + &mut owner_layer.content_effects } else { - let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; - &mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects + let background = + if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; + &mut owner_layer.mask.get_or_insert_with(|| Mask::new(background)).effects }; - let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1); - list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() }); - // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's). - if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) { - s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0])); + let index = selected.and_then(|selected| stack.iter().position(|effect| effect.id == selected)).map_or(stack.len(), |position| position + 1); + stack.insert(index, texturecraft_core::Effect { id: pasted, ..effect.clone() }); + + // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's) + if let Some(image) = copied.pixels.masks.get(&copied_id).filter(|_| !content) { + session.doc.pixels.masks.insert(pasted, fit(image, size, &[0, 0])); } - for c in channels.iter().copied().filter(|_| content) { - if let Some(img) = src.pixels.layer(eid, c) { - s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c))); + for channel in channels.iter().copied().filter(|_| content) { + if let Some(image) = copied.pixels.layer(copied_id, channel) { + session.doc.pixels.layers.insert((pasted, channel), fit(image, size, &empty_texel(channel))); } } - // The target belongs to the active set's selection: a paste into another set leaves it. - if let Some((lts, _, _)) = s.doc.project.locate(layer) { - s.selected.insert(lts, layer); - if lts == s.ts() { - s.target = StackTarget::Effect(new); + + // The target belongs to the active set's selection: a paste into another set leaves it + if let Some((layer_set, _, _)) = session.doc.project.locate(layer) { + session.selected.insert(layer_set, layer); + if layer_set == session.ts() { + session.target = StackTarget::Effect(pasted); } } - Ok(new) + Ok(pasted) })?; - Ok(json!({ "effect": new.0 })) + Ok(json!({ "effect": pasted.0 })) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 233e9f4c..67f70a22 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -69,9 +69,16 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { out } -/// A generator's settings, with its curvature mode and detail size weights when it has them. +/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them. fn generator_json(generator: &Generator) -> Value { - let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert }); + let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast }); + if !generator.resolution.is_default() { + out["resolution"] = + json!({ "mode": format!("{:?}", generator.resolution.mode), "custom": generator.resolution.custom, "factor": generator.resolution.factor }); + } + if !generator.inputs.is_empty() { + out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), json!(source))).collect::>().into(); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 4c286955..a617401c 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, - Procedural, ProceduralKind, Project, Source, + BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, + MaskBackground, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", has_layer, add_generator ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -323,13 +323,13 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R generator.softness = softness.clamp(0.0, 1.0); } if let Some(noise) = f32p(params, "noise") { - generator.noise_amount = noise.clamp(0.0, 2.0); + generator.noise_amount = noise.clamp(0.0, Generator::MAX_NOISE_AMOUNT); } if let Some(offset) = f32p(params, "offset") { generator.offset = offset.clamp(-1.0, 1.0); } if let Some(noise_scale) = f32p(params, "noiseScale") { - generator.noise_scale = noise_scale.clamp(0.01, 1000.0); + generator.noise_scale = noise_scale.clamp(Generator::MIN_NOISE_SCALE, Generator::MAX_NOISE_SCALE); } if let Some(seed) = u64p(params, "seed") { generator.seed = seed as u32; @@ -340,6 +340,26 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R if let Some(direction) = color_param(params, "direction") { generator.direction = direction; } + if let Some(blur) = f32p(params, "blur") { + generator.global.blur = blur.clamp(0.0, 1.0); + } + if let Some(balance) = f32p(params, "balance") { + generator.global.balance = balance.clamp(0.0, 1.0); + } + if let Some(contrast) = f32p(params, "contrast") { + generator.global.contrast = contrast.clamp(0.0, 1.0); + } + if let Some(value) = params.get("resolution") { + let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?; + generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?; + } + if let Some(custom) = u64p(params, "customResolution") { + generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32; + } + if let Some(factor) = params.get("resolutionFactor") { + let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?; + generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8; + } // A mode or sizes also give a curvature generator saved before detail sizes its detail let mode = params @@ -378,6 +398,35 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S Ok(weights) } +/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`. +fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { + const CMD: &str = "effect.set"; + let Some(name) = params.get("input") else { return Ok(None) }; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?; + let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?; + + let image = strp(params, "inputImage"); + let value = f32p(params, "inputValue"); + let anchor = u64p(params, "inputAnchor"); + let baked = boolp(params, "inputBaked") == Some(true); + let source = match (image, value, anchor, baked) { + (Some(image), None, None, false) => { + if !session.doc.resources.contains_key(image) { + return Err(bad(CMD, format!("no image resource `{image}`"))); + } + Some(Source::Image { name: image.to_string(), normal_format: Default::default() }) + } + (None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])), + (None, None, Some(anchor), false) => { + let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height); + Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?) + } + (None, None, None, true) => None, + _ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")), + }; + Ok(Some((map, source))) +} + fn add_generator(session: &mut Session, params: &Value) -> Result { let kind = match strp(params, "generator") { Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?, @@ -475,6 +524,12 @@ fn set(session: &mut Session, params: &Value) -> Result { _ => None, }; + // `input` names a generator input that `inputImage`, `inputValue` or `inputAnchor` replaces, or `inputBaked` puts back + let input = match session.doc.project.effect(effect) { + Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => generator_input_param(session, owner, params)?, + _ => None, + }; + // Naming the filter the effect already is edits its parameters like a plain effect.set let swapped = match strp(params, "filter") { Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None, @@ -508,7 +563,18 @@ fn set(session: &mut Session, params: &Value) -> Result { } match &mut edited.kind { - EffectKind::Generator(generator) => generator_from(CMD, params, generator)?, + EffectKind::Generator(generator) => { + generator_from(CMD, params, generator)?; + if let Some((map, source)) = input { + if !generator.kind.inputs().contains(&map) { + return Err(bad(CMD, format!("this generator has no `{}` input", map.id()))); + } + match source { + Some(source) => generator.inputs.insert(map, source), + None => generator.inputs.remove(&map), + }; + } + } EffectKind::Levels(levels) => levels_from(params, levels), // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index bdd2fbdd..67e30022 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::Value; use texturecraft_compose::PixelStore; -use texturecraft_core::{EffectKind, LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet}; use crate::commands::{CommandSpec, always, has_layer}; use crate::materials::Place; @@ -36,27 +36,26 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and fill effects). -pub(crate) fn images_used(p: &Project, id: LayerId, out: &mut Vec, depth: usize) { +/// Image resources a layer subtree uses (fill sources, mask fills and generator inputs). +pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; } - let Some(l) = p.layers.get(&id) else { return }; - if let LayerKind::Fill(f) = &l.kind { - for s in f.sources.values() { - if let Source::Image { name, .. } = s { + let Some(layer) = project.layers.get(&id) else { return }; + + if let LayerKind::Fill(fill) = &layer.kind { + for source in fill.sources.values() { + if let Source::Image { name, .. } = source { out.push(name.clone()); } } - out.extend(f.link.as_ref().map(|link| link.package.clone())); + out.extend(fill.link.as_ref().map(|link| link.package.clone())); } - for e in l.mask.iter().flat_map(|m| m.effects.iter()) { - if let EffectKind::Fill { source: Source::Image { name, .. }, .. } = &e.kind { - out.push(name.clone()); - } + for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()) { + out.extend(effect.kind.images_read().map(str::to_string)); } - for c in l.children() { - images_used(p, *c, out, depth + 1); + for child in layer.children() { + images_used(project, *child, out, depth + 1); } } diff --git a/crates/engine/tests/it/generator_inputs.rs b/crates/engine/tests/it/generator_inputs.rs new file mode 100644 index 00000000..da36b780 --- /dev/null +++ b/crates/engine/tests/it/generator_inputs.rs @@ -0,0 +1,77 @@ +//! Generator inputs that read an anchor point or an image, through engine commands. + +use serde_json::{Value, json}; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The texture set's texels per side. +const RESOLUTION: u32 = 256; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + session.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// Composited value of `channel` under the viewport center. +fn center(session: &mut Session, channel: Channel) -> [f32; 3] { + session.update(); + let hit = session.pick(session.viewport * 0.5, session.viewport).unwrap(); + let texels = RESOLUTION as f32; + session.caches[0].composite.value(channel, (hit.uv.x * texels) as u32, (hit.uv.y * texels) as u32) +} + +fn id(value: Value, key: &str) -> u64 { + value[key].as_u64().unwrap() +} + +/// A low fill (height 0.8) with an anchor, then a white fill whose black mask holds an AO generator reading it: (anchor, low layer, generator). +fn anchored_generator(session: &mut Session) -> (u64, u64, u64) { + let low = id(execute(session, "layer.add.fill", &json!({"height": 0.8})).unwrap(), "layer"); + let anchor = id(execute(session, "effect.add.anchor", &json!({"name": "Height"})).unwrap(), "effect"); + execute(session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); + execute(session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(session, "effect.add.generator", &json!({"generator": "ambientOcclusion", "level": 0.5, "softness": 0.5})).unwrap(), "effect"); + execute(session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputAnchor": anchor, "anchorChannel": "height"})).unwrap(); + (anchor, low, generator) +} + +#[test] +fn a_generator_input_reads_the_anchor_points_value() { + let mut session = session(); + anchored_generator(&mut session); + + // The low fill's gray, then white through the mask: an occlusion of 0.8 masks most of it, the channel default (0) none + let base = center(&mut session, Channel::BaseColor)[0]; + assert!(base > 0.9, "the generator reads the anchor's height, not the default: {base}"); +} + +#[test] +fn a_generator_reading_an_anchor_cannot_be_pasted_below_it() { + let mut session = session(); + let (_, low, generator) = anchored_generator(&mut session); + execute(&mut session, "effect.copy", &json!({"effect": generator})).unwrap(); + + let pasted = execute(&mut session, "effect.paste", &json!({"layer": low, "target": "mask"})); + assert!(pasted.is_err(), "the anchor point is on that layer, not below it"); +} + +#[test] +fn removing_unused_resources_keeps_an_image_read_by_a_generator_input() { + let mut session = session(); + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("occlusion.png", bytes).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": name})).unwrap(); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the generator input"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index e6157332..52a9ff08 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -10,6 +10,7 @@ mod content_effects; mod export_colour_space; mod filter_swap; mod filters; +mod generator_inputs; mod high_poly_missed; mod instances; mod materialcraft_link; diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 22a17cd5..e85b3767 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -524,3 +524,45 @@ fn curvature_generators_take_a_mode_and_detail_sizes() { assert!(dirt.is_err(), "only curvature generators have a mode"); assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged"); } + +#[test] +fn generators_take_blur_balance_and_contrast() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "blur": 0.25})).unwrap(); + let effect = added["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "balance": 0.75, "contrast": 2.0})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""blur":0.25"#) && inspect.contains(r#""balance":0.75"#), "{inspect}"); + assert!(inspect.contains(r#""contrast":1.0"#), "contrast is clamped to 0..1: {inspect}"); + + execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "custom", "customResolution": 512, "resolutionFactor": -9})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""resolution":{"custom":512,"factor":-3,"mode":"Custom"}"#), "the factor is clamped to 1/8: {inspect}"); + assert!(execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "huge"})).is_err(), "unknown resolutions are rejected"); +} + +#[test] +fn a_generator_input_reads_a_uniform_value_or_its_mesh_map_again() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""inputs":{"ambientOcclusion":{"Uniform":[0.25,0.25,0.25]}}"#), "{inspect}"); + + let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "curvature", "inputValue": 0.5})); + assert!(wrong_input.is_err(), "dirt reads ambient occlusion, not curvature"); + let missing_image = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputImage": "nothing.png"})); + assert!(missing_image.is_err(), "the image must be a resource of the project"); + let two_sources = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.5, "inputBaked": true})); + assert!(two_sources.is_err(), "an input takes one source"); + + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputBaked": true})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(!inspect.contains(r#""inputs""#), "the mesh map is read again: {inspect}"); +} From 03660e5a212c19de1fd81f6dde5791f3208036f4 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:09:31 +0000 Subject: [PATCH 29/42] Generator panel in the reference app's layout; effect blend and opacity on their rows - The generator properties move to generator_panel.rs: Attributes (description, category, tags), Resolution, Parameters with the global adjustments first, a seed with Random and a pencil to type it, Restore defaults, and Image inputs (a picture of what each input reads, a source menu, images dropped from Assets). - Effect rows get a blend mode menu and an opacity field at their right; the effect properties no longer show them. Effect rows alternate two shades just above the panel, so they read as rows under their layer. - Layer and effect rows share the blend mode and opacity controls: the opacity reads as plain text (no field box) and one drag is one undo step. - Translations for every new string in the 9 languages. --- crates/ui-egui/src/dock.rs | 775 +++++++++++---------- crates/ui-egui/src/generator_panel.rs | 385 ++++++++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/tests/it/effect_rows.rs | 79 ++- crates/ui-egui/tests/it/effect_sliders.rs | 232 +++--- crates/ui-egui/tests/it/generator_panel.rs | 128 ++++ crates/ui-egui/tests/it/layers_panel.rs | 6 +- crates/ui-egui/tests/it/main.rs | 1 + 8 files changed, 1115 insertions(+), 492 deletions(-) create mode 100644 crates/ui-egui/src/generator_panel.rs create mode 100644 crates/ui-egui/tests/it/generator_panel.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 1d266ee1..e6ee88ac 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,8 +6,8 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, - LinkParam, MaterialLink, ProceduralKind, Projection, Source, + BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, + Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; @@ -270,6 +270,77 @@ fn row_shade(tk: &Tokens, index: usize) -> Color32 { const RIGHT_COLUMN: f32 = 58.0; /// Indent per folder level, and per level of the effect tree. const INDENT: f32 = 14.0; +/// Edge of the small icon buttons in the properties panel. +const ICON_BUTTON_SIZE: f32 = 22.0; +/// Height of a blend mode menu or opacity field in a stack row, and the rounding of its hover fill. +const ROW_CONTROL_HEIGHT: f32 = 17.0; +const ROW_CONTROL_ROUNDING: f32 = 2.0; +/// Gap between the controls at the right of a stack row, and between them and the row's edge. +const ROW_CONTROL_GAP: f32 = 4.0; +/// Space before an effect row's eye and after its name. +const ROW_LEFT_PADDING: f32 = 7.0; +const ROW_RIGHT_PADDING: f32 = 6.0; +/// Width of the selected row's accent edge. +const SELECTED_EDGE_WIDTH: f32 = 3.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; +const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; +const HIDDEN_STRIKE_WIDTH: f32 = 1.5; +const DROP_LINE_WIDTH: f32 = 2.0; +/// The eye's size and the column it sits in (the eye and a gap before the thumbnail). +const EYE_SIZE: f32 = 16.0; +const EYE_COLUMN_WIDTH: f32 = 22.0; +/// Gap between an effect's thumbnail and its name, and the narrowest name worth showing. +const THUMBNAIL_GAP: f32 = 8.0; +const MIN_NAME_WIDTH: f32 = 20.0; +/// Font sizes in an effect row: the eye, the name, the blend mode and its caret. +const EYE_FONT_SIZE: f32 = 12.0; +const EFFECT_NAME_FONT_SIZE: f32 = 11.5; +const ROW_SMALL_FONT_SIZE: f32 = 11.0; +const CARET_FONT_SIZE: f32 = 8.0; +/// Room for the caret at the right of the blend mode's name. +const CARET_WIDTH: f32 = 10.0; +/// The blend mode menu's width, wide enough for the longest mode name. +const BLEND_MENU_MIN_WIDTH: f32 = 190.0; +/// Padding inside a row's opacity field, and the percent it moves per point dragged. +const ROW_FIELD_PADDING: f32 = 4.0; +const OPACITY_DRAG_SPEED: f64 = 0.5; +/// A layer row's eye: its hit area, its glyph size and the column it sits in. +const LAYER_EYE_SIZE: f32 = 18.0; +const LAYER_EYE_FONT_SIZE: f32 = 13.0; +const LAYER_EYE_COLUMN_WIDTH: f32 = 20.0; +/// A folder's caret: its size (the space it takes before the thumbnail) and its center from where it starts. +const FOLDER_CARET_SIZE: f32 = 14.0; +const FOLDER_CARET_CENTER: f32 = 6.0; +/// A thumbnail's border while it is the layer's target, and how far outside it the mask-view and drop outlines sit. +const TARGET_BORDER_WIDTH: f32 = 1.5; +const HIGHLIGHT_OUTSET: f32 = 2.0; +/// The gap between a layer row's stacked blend mode and opacity, either side of the row's middle. +const ROW_STACK_GAP: f32 = 1.0; +/// Width of a layer's colour tag beside the accent edge. +const TAG_WIDTH: f32 = 3.0; +/// Space between a layer's content and mask thumbnails, and the size of the empty mask slot. +const THUMBNAIL_SPACING: f32 = 4.0; +const MASK_SLOT_SIZE: f32 = 18.0; +/// Grays of a white or black mask before its thumbnail arrives. +const WHITE_MASK_GRAY: u8 = 225; +const BLACK_MASK_GRAY: u8 = 18; +/// A layer's name and subtitle font sizes, and their distance from the row's middle. +const LAYER_NAME_FONT_SIZE: f32 = 12.5; +const LAYER_SUBTITLE_FONT_SIZE: f32 = 10.0; +const NAME_LINE_GAP: f32 = 2.0; +/// Folder lines: their width, how faded they are, how far an indent must reach past one, and where the branch starts. +const FOLDER_LINE_WIDTH: f32 = 1.0; +const FOLDER_LINE_FADE: f32 = 0.6; +const FOLDER_LINE_CLEARANCE: f32 = 8.0; +const FOLDER_BRANCH_OFFSET: f32 = 15.0; +/// The share of a folder row's height, either side of its middle, where a drop goes inside it. +const FOLDER_DROP_ZONE: f32 = 0.25; +/// How far each alternating effect row shade goes from the panel towards the hover colour. +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; /// Height of the "Content effects" / "Mask effects" header rows. const GROUP_HEADER_H: f32 = 20.0; @@ -292,7 +363,7 @@ 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 - 7.0 - 22.0 - preview - 8.0 - 20.0 - 6.0).max(0.0)) + (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) } /// X of the centre of the eye column at indent `level` in a row spanning from `left`. @@ -351,292 +422,280 @@ fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget false } +/// The row of `layer` at folder depth `depth`, the `index`th row of the stack (rows alternate shades). fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); let content_target = selected && targets_content(app); - let size = layer_preview_size(app); - let h = layer_row_height(size); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); - let p = ui.painter().clone(); - let bg = if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover + let preferred_size = layer_preview_size(app); + 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, selected, &layer.name)); + + // Background, folder lines, the selected row's accent edge and the colour tag + let painter = ui.painter().clone(); + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover } else { - row_shade(&tk, index) + row_shade(&tokens, index) }; - p.rect_filled(rect, 0.0, bg); - let (indent, size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), size); + painter.rect_filled(rect, 0.0, background); + let (indent, thumbnail_size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), preferred_size); // Folder contents hang off lines down the left without crossing compact row controls - let line = Stroke::new(1.0, tk.button_border.gamma_multiply(0.6)); + let line = Stroke::new(FOLDER_LINE_WIDTH, tokens.button_border.gamma_multiply(FOLDER_LINE_FADE)); for level in 0..depth { - let x = level_x(rect.left(), level); - if level as f32 * INDENT + 8.0 < indent { - p.vline(x, rect.y_range(), line); + if level as f32 * INDENT + FOLDER_LINE_CLEARANCE < indent { + painter.vline(level_x(rect.left(), level), rect.y_range(), line); } } if depth > 0 && indent >= INDENT { - let x = rect.left() + 15.0 + indent - INDENT; - p.hline(x..=x + INDENT * 0.5, rect.center().y, line); + let x = rect.left() + FOLDER_BRANCH_OFFSET + indent - INDENT; + painter.hline(x..=x + INDENT * 0.5, rect.center().y, line); } if selected { - p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, h)), 0.0, tk.accent); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, row_height)), 0.0, tokens.accent); } - if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(3.0, 0.0), vec2(3.0, h)), 0.0, *tag); + if let Some(tag) = layer.color_tag.and_then(|tag| TAG_COLORS.get(tag as usize)) { + painter.rect_filled(Rect::from_min_size(rect.min + vec2(SELECTED_EDGE_WIDTH, 0.0), vec2(TAG_WIDTH, row_height)), 0.0, *tag); } - let x0 = rect.left() + 7.0 + indent; - // Eye. - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0)); - let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); - p.text( + + // The eye + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(LAYER_EYE_SIZE, LAYER_EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); + painter.text( eye.center(), egui::Align2::CENTER_CENTER, if layer.visible { ic::EYE } else { ic::EYE_SLASH }, - egui::FontId::proportional(13.0), - if layer.visible { tk.text } else { tk.text_dim }, + egui::FontId::proportional(LAYER_EYE_FONT_SIZE), + if layer.visible { tokens.text } else { tokens.text_dim }, ); - if eye_resp.clicked() { + if eye_response.clicked() { app.run("layer.visible", json!({"layer": layer.id.0})); } - // Group caret. - let mut x = x0 + 20.0; + + // A folder's caret + let mut x = content_left + LAYER_EYE_COLUMN_WIDTH; if let LayerKind::Group { collapsed, .. } = layer.kind { - let caret = Rect::from_center_size(pos2(x + 6.0, rect.center().y), vec2(14.0, 14.0)); - let cr = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); - p.text( + let caret = Rect::from_center_size(pos2(x + FOLDER_CARET_CENTER, rect.center().y), vec2(FOLDER_CARET_SIZE, FOLDER_CARET_SIZE)); + let caret_response = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); + painter.text( caret.center(), egui::Align2::CENTER_CENTER, if collapsed { ic::CARET_RIGHT } else { ic::CARET_DOWN }, - egui::FontId::proportional(11.0), - tk.text_dim, + egui::FontId::proportional(ROW_SMALL_FONT_SIZE), + tokens.text_dim, ); - if cr.clicked() - && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|l| &mut l.kind) + if caret_response.clicked() + && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|edited| &mut edited.kind) { *collapsed = !*collapsed; } - x += 14.0; + x += FOLDER_CARET_SIZE; } - // Content thumbnail: the layer's own result in the displayed channel. - let ch = app.ui.layer_channel; - let thumb = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); - let drawn = thumb_box(ui, app, thumb, ThumbTarget::Content { layer: layer.id, channel: ch }, !layer.visible); - if !drawn { - content_glyph(&p, &tk, thumb, layer); + + // Content thumbnail: the layer's own result in the displayed channel + let channel = app.ui.layer_channel; + let thumbnail = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) { + content_glyph(&painter, &tokens, thumbnail, layer); } - p.rect_stroke( - thumb, - 2.0, - Stroke::new(if content_target { 1.5 } else { 1.0 }, if content_target { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - let content_resp = ui.interact(thumb, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); - if content_resp.clicked() { + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); + let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); + if content_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); } - x = thumb.right() + 4.0; - // An instance draws its source's content, blending and (unless it has its own) mask. + x = thumbnail.right() + THUMBNAIL_SPACING; + + // An instance draws its source's content, blending and (unless it has its own) mask let project = &app.session.doc.project; - let source = layer.instance_source().map(|src| { - let set = project.locate(src).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(|t| t.name.as_str()).unwrap_or("?"); - project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name)) + let source = layer.instance_source().map(|source| { + let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); + project.layers.get(&source).map_or_else(|| tr("missing source").to_string(), |source_layer| format!("{} · {set}", source_layer.name)) }); - let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone()); - let blend = project.content_layer(layer.id).and_then(|l| l.blend(ch)); - // Mask thumbnail, selectable on its own; or the slot that adds one. + let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); + let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); + + // Mask thumbnail, selectable on its own; or the slot that adds one let mask_rect; - if let Some(m) = &mask { - let mask_sel = selected && !targets_content(app); - mask_rect = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); - let drawn = thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !m.enabled); - if !drawn { - p.rect_filled( - mask_rect, - 2.0, - if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, - ); - if !m.effects.is_empty() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(13.0), tk.text_dim); + if let Some(mask) = &mask { + let mask_target = selected && !targets_content(app); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask.enabled) { + let white = mask.background == texturecraft_engine::core::MaskBackground::White; + painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); + if !mask.effects.is_empty() { + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(LAYER_EYE_FONT_SIZE), tokens.text_dim); } } - p.rect_stroke( - mask_rect, - 2.0, - Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - if !m.enabled { - p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger)); + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside); + if !mask.enabled { + painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); } - let mr = ui + let mask_response = ui .interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()) .on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)")); - if mr.clicked() { + if mask_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); - if ui.input(|i| i.modifiers.alt) { + if ui.input(|input| input.modifiers.alt) { let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); - let p = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; - app.run("viewport.view", p); + let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; + app.run("viewport.view", view); } } if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); + painter.rect_stroke( + mask_rect.expand(HIGHLIGHT_OUTSET), + THUMBNAIL_ROUNDING, + Stroke::new(TARGET_BORDER_WIDTH, tokens.warning), + egui::StrokeKind::Outside, + ); } - x = mask_rect.right() + 8.0; } else { - // The empty slot adds a mask to this layer. - let slot_size = size.min(18.0); + // The empty slot adds a mask to this layer + let slot_size = thumbnail_size.min(MASK_SLOT_SIZE); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - slot_size * 0.5), vec2(slot_size, slot_size)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); - p.rect_stroke(mask_rect, 2.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + let slot_color = if slot.hovered() { tokens.accent } else { tokens.field_border }; + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, slot_color), egui::StrokeKind::Inside); if slot.hovered() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text); } egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); - x = mask_rect.right() + 8.0; } - // Blend mode and opacity of the displayed channel, stacked at the right. - let blend_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y - 18.0), vec2(RIGHT_COLUMN, 17.0)); - let op_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y + 1.0), vec2(RIGHT_COLUMN, 17.0)); - // Name (or rename editor) with the quieter subtitle under it. + x = mask_rect.right() + THUMBNAIL_GAP; + + // Name (or rename editor) with the quieter subtitle under it let (name_rect, show_blend) = layer_name_layout(rect, x); - let show_name = name_rect.width() >= 20.0; + let show_name = name_rect.width() >= MIN_NAME_WIDTH; if !show_name { - resp.clone().on_hover_text(&layer.name); + row.clone().on_hover_text(&layer.name); if app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0) { app.ui.rename = None; } } - let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0); + let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0); if renaming { - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); - if let Some((_, buf)) = app.ui.rename.as_mut() { - // Escape reaches us instead of just unfocusing the field, so it can cancel. + let mut editor_ui = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + if let Some((_, text)) = app.ui.rename.as_mut() { + // Escape reaches us instead of just unfocusing the field, so it can cancel let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; - let r = child.add(egui::TextEdit::singleline(buf).desired_width(name_rect.width()).event_filter(filter)); - if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + let editor = editor_ui.add(egui::TextEdit::singleline(text).desired_width(name_rect.width()).event_filter(filter)); + if ui.input(|input| input.key_pressed(egui::Key::Escape)) { app.ui.rename = None; - } else if r.lost_focus() { - // Enter or a click elsewhere. - let name = buf.trim().to_string(); + } else if editor.lost_focus() { + // Enter or a click elsewhere + let name = text.trim().to_string(); app.ui.rename = None; if !name.is_empty() && name != layer.name { app.run("layer.rename", json!({"layer": layer.id.0, "name": name})); } - } else if !r.has_focus() { - // Only until the field has focus: requesting it every frame kept it from ever - // losing focus, which trapped the editor open and blocked every shortcut. - r.request_focus(); + } else if !editor.has_focus() { + // Only until the field has focus: asking every frame trapped the editor open and blocked every shortcut + editor.request_focus(); } } } else if show_name { - let galley = elided(&p, layer.name.clone(), 12.5, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y - 2.0 - galley.size().y), galley, tk.text); + let name_color = if layer.visible { tokens.text_strong } else { tokens.text_dim }; + let galley = elided(&painter, layer.name.clone(), LAYER_NAME_FONT_SIZE, name_color, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y - NAME_LINE_GAP - galley.size().y), galley, tokens.text); let kind = tr(match &layer.kind { LayerKind::Paint => "Paint layer", LayerKind::Fill(_) => "Fill layer", LayerKind::Group { .. } => "Folder", LayerKind::Instance { .. } => "Instance", }); - let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |m| m.effects.len()); + let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |mask| mask.effects.len()); let subtitle = match (source, effects) { - (Some(src), _) => format!("{kind} · {} {src}", ic::LINK_SIMPLE), + (Some(source), _) => format!("{kind} · {} {source}", ic::LINK_SIMPLE), (None, 0) => kind.to_string(), (None, 1) => format!("{kind} · {}", tr("1 effect")), - (None, n) => format!("{kind} · {}", trf("{count} effects", &[("count", &n)])), + (None, count) => format!("{kind} · {}", trf("{count} effects", &[("count", &count)])), }; - let sub = elided(&p, subtitle, 10.0, tk.text_dim, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y + 2.0), sub, tk.text_dim); + let subtitle = elided(&painter, subtitle, LAYER_SUBTITLE_FONT_SIZE, tokens.text_dim, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y + NAME_LINE_GAP), subtitle, tokens.text_dim); } - if let Some(b) = blend.filter(|_| show_blend) { - let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel")); - if br.hovered() { - p.rect_filled(blend_rect, 2.0, tk.row_hover); + + // Blend mode and opacity of the displayed channel, stacked at the right + let mode_rect = Rect::from_min_size( + pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y - ROW_CONTROL_HEIGHT - ROW_STACK_GAP), + vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT), + ); + let opacity_rect = + Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y + ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT)); + if let Some(channel_blend) = blend.filter(|_| show_blend) { + let id = ui.scope_id().with(("blend", layer.id.0)); + let (mode, opacity) = + blend_controls(ui, id, (mode_rect, opacity_rect), (channel_blend.mode, channel_blend.opacity), tr("Blending mode of the displayed channel")); + if let Some(mode) = mode { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "mode": format!("{mode:?}")})); } - p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text); - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim); - egui::Popup::menu(&br).show(|ui| { - ui.set_min_width(190.0); - for m in BlendMode::MENU { - match m { - Some(m) => { - if ui.selectable_label(m == b.mode, tr(m.label())).clicked() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "mode": format!("{m:?}")})); - ui.close(); - } - } - None => { - ui.separator(); - } - } - } - }); - let mut op = (b.opacity * 100.0).round(); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); - // As tall as its slot in the row (the style's fields are taller), in the row's small print. - child.spacing_mut().interact_size.y = op_rect.height(); - child.spacing_mut().button_padding = vec2(4.0, 0.0); - child.style_mut().override_text_style = Some(egui::TextStyle::Small); - let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix("%")); - if r.changed() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); + if let Some((opacity, merge)) = opacity { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "opacity": opacity, "merge": merge})); } } else if show_blend { - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(ROW_SMALL_FONT_SIZE), tokens.text_dim); } - // Interaction: select, rename, drag & drop, context menu. - let on_control = eye_resp.clicked() || content_resp.clicked(); - if resp.clicked() && !on_control && !renaming { + + // Interaction: select, rename, drag & drop, context menu + let on_control = eye_response.clicked() || content_response.clicked(); + if row.clicked() && !on_control && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); } - if resp.double_clicked() && !on_control && !renaming && show_name { + if row.double_clicked() && !on_control && !renaming && show_name { app.ui.rename = Some((layer.id.0, layer.name.clone())); } - if resp.drag_started() && !renaming { - resp.dnd_set_drag_payload(layer.id.0); + if row.drag_started() && !renaming { + row.dnd_set_drag_payload(layer.id.0); } - // Drops: a layer or a shelf material lands above this row (inside a folder when dropped on - // its middle); a shelf smart mask replaces this layer's mask. - let inside = layer.is_group() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| (p.y - rect.center().y).abs() < h * 0.25); - let shelf = resp.dnd_hover_payload::().map(|d| d.asset.clone()); - let moving = resp.dnd_hover_payload::().is_some_and(|src| *src != layer.id.0); + + // Drops: a layer or a shelf material lands above this row (inside a folder on its middle); a shelf smart mask replaces the mask + let inside = layer.is_group() + && ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| (pointer.y - rect.center().y).abs() < row_height * FOLDER_DROP_ZONE); + let shelf = row.dnd_hover_payload::().map(|drag| drag.asset.clone()); + let moving = row.dnd_hover_payload::().is_some_and(|dragged| *dragged != layer.id.0); + let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); if moving || shelf.as_ref().is_some_and(Asset::is_material) { if inside { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } else { - p.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); + painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); } } else if matches!(shelf, Some(Asset::SmartMask(_))) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Outside); + painter.rect_stroke(mask_rect.expand(HIGHLIGHT_OUTSET), THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Outside); } else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } - if let Some(src) = dnd_release::(&resp) - && *src != layer.id.0 + if let Some(dragged) = dnd_release::(&row) + && *dragged != layer.id.0 { - app.run("layer.move", json!({"layer": *src, "above": layer.id.0, "inside": inside})); + app.run("layer.move", json!({"layer": *dragged, "above": layer.id.0, "inside": inside})); } - match dnd_release::(&resp).map(|d| d.asset.clone()) { - Some(Asset::Material(m)) => { - app.run("material.apply", json!({"material": m, "above": layer.id.0, "inside": inside})); + match dnd_release::(&row).map(|drag| drag.asset.clone()) { + Some(Asset::Material(material)) => { + app.run("material.apply", json!({"material": material, "above": layer.id.0, "inside": inside})); } Some(Asset::Library(path)) => { app.run("material.load", json!({"path": path, "above": layer.id.0, "inside": inside})); } - Some(Asset::SmartMask(m)) => { - app.run("mask.smart.apply", json!({"name": m, "layer": layer.id.0})); + Some(Asset::SmartMask(smart_mask)) => { + app.run("mask.smart.apply", json!({"name": smart_mask, "layer": layer.id.0})); } - Some(Asset::Filter(f)) => { + Some(Asset::Filter(filter)) => { app.run("layer.select", json!({"layer": layer.id.0})); - app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": f, "target": "content"})); + app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": filter, "target": "content"})); } Some(Asset::Alpha(_) | Asset::Texture(_)) | None => {} } - resp.context_menu(|ui| layer_context_menu(app, ui, layer)); + row.context_menu(|ui| layer_context_menu(app, ui, layer)); +} + +/// The border of a content or mask thumbnail: the accent while it is the layer's target. +fn target_stroke(tokens: &Tokens, target: bool) -> Stroke { + if target { Stroke::new(TARGET_BORDER_WIDTH, tokens.accent) } else { Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border) } } /// What a content thumbnail shows until its picture arrives (or where the layer has none). @@ -721,97 +780,194 @@ fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: & /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// Effect `e` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +/// A stack row's blend mode menu and opacity field (percent): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. +fn blend_controls( + ui: &mut Ui, + id: egui::Id, + (mode_rect, opacity_rect): (Rect, Rect), + (mode, opacity): (BlendMode, f32), + hover: &str, +) -> (Option, Option<(f32, bool)>) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter().clone(); + + let mut picked = None; + let menu = ui.interact(mode_rect, id, Sense::click()).on_hover_text(hover); + if menu.hovered() { + painter.rect_filled(mode_rect, ROW_CONTROL_ROUNDING, tokens.row_hover); + } + let mode_font = egui::FontId::proportional(ROW_SMALL_FONT_SIZE); + painter.text(mode_rect.right_center() - vec2(CARET_WIDTH, 0.0), egui::Align2::RIGHT_CENTER, mode.short(), mode_font, tokens.text); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_FONT_SIZE), tokens.text_dim); + egui::Popup::menu(&menu).show(|ui| { + ui.set_min_width(BLEND_MENU_MIN_WIDTH); + for item in BlendMode::MENU { + match item { + Some(item) => { + if ui.selectable_label(item == mode, tr(item.label())).clicked() { + picked = Some(item); + ui.close(); + } + } + None => { + ui.separator(); + } + } + } + }); + + let mut percent = (opacity * 100.0).round(); + let mut field_ui = ui.new_child(egui::UiBuilder::new().max_rect(opacity_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); + // As tall as its slot in the row (the style's fields are taller), in the row's small print + field_ui.spacing_mut().interact_size.y = opacity_rect.height(); + field_ui.spacing_mut().button_padding = vec2(ROW_FIELD_PADDING, 0.0); + field_ui.style_mut().override_text_style = Some(egui::TextStyle::Small); + + // Plain text like the blend mode beside it: no field box, only the hover fill + let widgets = &mut field_ui.visuals_mut().widgets; + for state in [&mut widgets.inactive, &mut widgets.noninteractive] { + state.weak_bg_fill = Color32::TRANSPARENT; + state.bg_fill = Color32::TRANSPARENT; + state.bg_stroke = Stroke::NONE; + } + for state in [&mut widgets.hovered, &mut widgets.active] { + state.weak_bg_fill = tokens.row_hover; + state.bg_stroke = Stroke::NONE; + } + let field = field_ui.add(egui::DragValue::new(&mut percent).range(0.0..=100.0).speed(OPACITY_DRAG_SPEED).max_decimals(0).suffix("%")); + + // The later changes of one drag continue its first undo step + let merge = field.dragged() && !field.drag_started(); + (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`. #[allow(clippy::too_many_arguments)] -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, level: usize, trunks: &[usize], last: bool, in_mask: bool) { - let tk = Tokens::get(ui.ctx()); - let (eid, visible) = (e.id, e.visible); - let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let size = effect_preview_size(layer_preview_size(app)); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); - let p = ui.painter().clone(); - p.rect_filled( - rect, - 0.0, - if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover - } else { - tk.panel - }, - ); - let indent = effect_row_indent(rect.width(), level, size); - tree_lines(&p, &tk, rect, indent, trunks, !last); +fn effect_row( + app: &mut TextureCraftApp, + ui: &mut Ui, + layer: &Layer, + stack: &[Effect], + effect: &Effect, + level: usize, + trunks: &[usize], + last: bool, + in_mask: bool, +) { + let tokens = Tokens::get(ui.ctx()); + let (effect_id, visible) = (effect.id, effect.visible); + let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(effect_id); + let preview_size = effect_preview_size(layer_preview_size(app)); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &effect.name)); + + // Background, tree lines and the selected row's accent edge + let painter = ui.painter().clone(); + // Effect rows alternate two shades just above the panel, counted from the top of their list + let row_index = stack.iter().rev().position(|other| other.id == effect_id).unwrap_or(0); + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover + } else { + tokens.panel.lerp_to_gamma(tokens.row_hover, EFFECT_ROW_SHADES[row_index % EFFECT_ROW_SHADES.len()]) + }; + painter.rect_filled(rect, 0.0, background); + let indent = effect_row_indent(rect.width(), level, preview_size); + tree_lines(&painter, &tokens, rect, indent, trunks, !last); if selected { - p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, rect.height())), 0.0, tk.accent); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent); } - let x0 = rect.left() + 7.0 + indent; - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0)); - let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); - p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); - // The stack as it is up to and including this effect; a hidden one shows what it bypasses. - let thumb = Rect::from_min_size(pos2(x0 + 22.0, rect.center().y - size * 0.5), vec2(size, size)); - let ch = app.ui.layer_channel; - if !thumb_box(ui, app, thumb, ThumbTarget::Stage { effect: eid, channel: ch }, false) { + + // The eye, then the stack as it is up to and including this effect (a hidden one shows what it bypasses) + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(EYE_SIZE, EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eff_eye", effect_id.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); + let eye_glyph = if visible { ic::EYE } else { ic::EYE_SLASH }; + painter.text(eye.center(), egui::Align2::CENTER_CENTER, eye_glyph, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text_dim); + let thumbnail = Rect::from_min_size(pos2(content_left + EYE_COLUMN_WIDTH, rect.center().y - preview_size * 0.5), vec2(preview_size, preview_size)); + let channel = app.ui.layer_channel; + if !thumb_box(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false) { let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE }; - p.text(thumb.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(size * 0.5), tk.text_dim); + painter.text(thumbnail.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(preview_size * 0.5), tokens.text_dim); } - p.rect_stroke(thumb, 2.0, Stroke::new(1.0, tk.button_border), egui::StrokeKind::Outside); + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border), egui::StrokeKind::Outside); if !visible { - p.line_segment([thumb.left_bottom(), thumb.right_top()], Stroke::new(1.5, tk.text_dim)); + painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim)); } - let name_x = thumb.right() + 8.0; - let galley = elided(&p, e.name.clone(), 11.5, if visible { tk.text } else { tk.text_dim }, (rect.right() - name_x - 6.0).max(20.0)); - p.galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, tk.text); - if er.clicked() { - app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); - } else if resp.clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + + // The name, then the blend mode and opacity side by side at the right 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 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_color = if visible { tokens.text } else { tokens.text_dim }; + let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, (name_right - name_left).max(MIN_NAME_WIDTH)); + painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + if show_blend { + let mode_width = EFFECT_BLEND_WIDTH - ROW_CONTROL_GAP - EFFECT_OPACITY_WIDTH; + let mode_rect = Rect::from_center_size(pos2(controls_left + mode_width * 0.5, rect.center().y), vec2(mode_width, ROW_CONTROL_HEIGHT)); + let opacity_center = pos2(mode_rect.right() + ROW_CONTROL_GAP + EFFECT_OPACITY_WIDTH * 0.5, rect.center().y); + let opacity_rect = Rect::from_center_size(opacity_center, vec2(EFFECT_OPACITY_WIDTH, ROW_CONTROL_HEIGHT)); + let id = ui.scope_id().with(("eff_blend", effect_id.0)); + let (mode, opacity) = blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), tr("Blending mode of the effect")); + if let Some(mode) = mode { + app.run("effect.set", json!({"effect": effect_id.0, "blend": format!("{mode:?}")})); + } + if let Some((opacity, merge)) = opacity { + app.run("effect.set", json!({"effect": effect_id.0, "opacity": opacity, "merge": merge})); + } } - // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half. - if resp.drag_started() { - resp.dnd_set_drag_payload(EffectDrag(eid.0)); + + if eye_response.clicked() { + app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if row.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); } - let pos = |id: u64| stack.iter().position(|x| x.id.0 == id); - let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y); - if resp.dnd_hover_payload::().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) { + + // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half + if row.drag_started() { + row.dnd_set_drag_payload(EffectDrag(effect_id.0)); + } + let position = |id: u64| stack.iter().position(|other| other.id.0 == id); + let below = ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| pointer.y > rect.center().y); + if row.dnd_hover_payload::().is_some_and(|dragged| dragged.0 != effect_id.0 && position(dragged.0).is_some()) { let y = if below { rect.bottom() } else { rect.top() }; - p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent)); + painter.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(DROP_LINE_WIDTH, tokens.accent)); } - if let Some(src) = dnd_release::(&resp) - && let (Some(from), Some(to)) = (pos(src.0), pos(eid.0)) + if let Some(dragged) = dnd_release::(&row) + && let (Some(from), Some(to)) = (position(dragged.0), position(effect_id.0)) && from != to { - // Rows list the stack top first, so above this row is the next index up. + // Rows list the stack top first, so above this row is the next index up let index = match (from < to, below) { (true, false) | (false, true) => to, (true, true) => to - 1, (false, false) => to + 1, }; - app.run("effect.move", json!({"effect": src.0, "index": index})); + app.run("effect.move", json!({"effect": dragged.0, "index": index})); } - resp.context_menu(|ui| { + + row.context_menu(|ui| { let keymap = app.ui.keymap.clone(); - // The row is selected before the paste runs, so a copied effect is all it needs. + // The row is selected before the paste runs, so a copied effect is all it needs let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); - // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. - for (label, id, keys, enabled) in [ + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect + for (label, command, keys, enabled) in [ (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), (tr("Cut effect"), "effect.cut", Some("layer.cut"), true), (tr("Paste effect"), "effect.paste", Some("layer.paste"), paste), (tr("Duplicate effect"), "effect.duplicate", None, true), (tr("Remove effect"), "effect.remove", None, true), ] { - let mut b = egui::Button::new(label); - if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) { - b = b.shortcut_text(sc); + let mut button = egui::Button::new(label); + if let Some(shortcut) = keys.and_then(|key| crate::keymap::shortcut_of(&keymap, key)) { + button = button.shortcut_text(shortcut); } - if ui.add_enabled(enabled, b).clicked() { - // Selected first: a paste lands above it, a duplicate takes the selection. - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); - app.run(id, json!({"effect": eid.0})); + if ui.add_enabled(enabled, button).clicked() { + // Selected first: a paste lands above it, a duplicate takes the selection + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); + app.run(command, json!({"effect": effect_id.0})); ui.close(); } } @@ -1069,7 +1225,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } /// Menu items listing the image resources, then Import...: the image picked, if any. -fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { +pub(crate) fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { ui.label(caption(tr("Images"))); let mut picked = None; // Bounded, so Import... and the items after it stay on screen with many images. @@ -1092,7 +1248,7 @@ fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { /// An image from the Assets panel dropped on `resp`, outlined while one hovers it. Other assets /// are left for the drop targets around it. -fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { +pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { if !resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { return None; } @@ -1103,7 +1259,7 @@ fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { } } -fn mesh_map_color(map: BakedMap) -> Color32 { +pub(crate) fn mesh_map_color(map: BakedMap) -> Color32 { match map { BakedMap::Normal => Color32::from_rgb(128, 128, 255), BakedMap::WorldNormal => Color32::from_rgb(120, 200, 140), @@ -1910,7 +2066,7 @@ fn with(base: &Value, extra: Value) -> Value { } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). -fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { +pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { let p = &app.session.doc.project; let Some((ts, _, _)) = p.locate(reader) else { return Vec::new() }; p.walk(ts) @@ -1922,7 +2078,7 @@ fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String .collect() } -fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { +pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } @@ -2221,30 +2377,16 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu } } -fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) { - let tk = Tokens::get(ui.ctx()); - let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return }; +/// The properties of effect `effect_id` of `layer`: each kind's own settings. +fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { + let tokens = Tokens::get(ui.ctx()); + let Some(effect) = app.session.doc.project.effect(effect_id).map(|(_, effect)| effect.clone()) else { return }; - let id = eid.0; - ui.horizontal(|ui| { - ui.label(tr("Blending")); - egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| { - for mode in BlendMode::all() { - if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() { - app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")})); - } - } - }); - }); - let mut opacity = effect.opacity; - if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge})); - } - ui.separator(); + let id = effect_id.0; match &effect.kind { - EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), - EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, eid, levels), + EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), + EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); let anchors = anchors_below(app, layer.id); @@ -2280,12 +2422,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } }); - ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tokens.text_dim)); } _ => {} } if anchors.is_empty() { - ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); } } EffectKind::Material(fill) => { @@ -2297,27 +2439,27 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(caption(tr("Anchor point"))); ui.label( RichText::new(tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.")) - .color(tk.text_dim), + .color(tokens.text_dim), ); } EffectKind::Paint => { - let hint = if layer.content_effects.iter().any(|content| content.id == eid) { + 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. Use the Material tab's mask value for gray.") }; - ui.label(RichText::new(hint).color(tk.text_dim)); + ui.label(RichText::new(hint).color(tokens.text_dim)); tool_properties(app, ui); } EffectKind::Path(paths) => { 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(tk.text_dim), + .color(tokens.text_dim), ); let editing = app.session.tool.path.editing; for index in 0..paths.len() { ui.horizontal(|ui| { - let selected = editing == Some((eid, index)); + 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})); @@ -2325,7 +2467,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: app.run("path.edit", json!({"effect": id, "index": index})); } } - if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { + if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { app.run("path.remove", json!({"effect": id, "index": index})); } }); @@ -2333,86 +2475,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: tool_properties(app, ui); } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), - EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, eid, colors, *tolerance), + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), other => { - ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); + ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); } } } -/// The settings of generator effect `id`. -fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { - for kind in GeneratorKind::ALL { - if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { - // Replace the generator kind: remove and add keeps ordering simple - app.run("effect.remove", json!({"effect": id})); - app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); - } - } - }); - - let (mut level, mut softness, mut noise, mut noise_scale, mut offset, mut invert) = - (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset, generator.invert); - let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); - let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); - let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); - let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); - if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit).or(invert_edit) { - app.run( - "effect.set", - json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "invert": invert, "merge": merge}), - ); - } - - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); - } -} - -/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). -fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { - let tk = Tokens::get(ui.ctx()); - let shown = detail.cloned().unwrap_or_default(); - combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { - for mode in CurvatureMode::ALL { - if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { - app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); - } - } - }); - - ui.label(caption(tr("Detail sizes"))); - let mut weights = shown.weights; - let mut edit = None; - for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { - edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); - } - if detail.is_none() { - ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim)); - } -} - -/// The translated name of curvature mode `mode`. -fn curvature_mode_label(mode: CurvatureMode) -> &'static str { - match mode { - CurvatureMode::Edges => tr("Edges"), - CurvatureMode::Cavities => tr("Cavities"), - CurvatureMode::Both => tr("Edges and cavities"), - CurvatureMode::Raw => tr("Raw curvature"), - } -} - /// The filter slot and the parameters of filter effect `id` fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs new file mode 100644 index 00000000..99b93905 --- /dev/null +++ b/crates/ui-egui/src/generator_panel.rs @@ -0,0 +1,385 @@ +//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs. + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, OutputResolution, ResolutionMode, Source}; + +use crate::TextureCraftApp; +use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::theme::{Tokens, caption}; +use crate::widgets::{combo, section, slider_edit}; + +/// Random seeds stay below this, short enough to read and type. +const SEED_RANGE: u32 = 10_000; +/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range. +const SEED_MIX: u32 = 2_654_435_761; + +/// Font size of the notes under a control. +const NOTE_FONT_SIZE: f32 = 10.5; + +/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. +const INPUT_TILE_SIZE: f32 = 32.0; +const INPUT_TILE_ROUNDING: f32 = 2.0; +const INPUT_TILE_ICON_SIZE: f32 = 16.0; + +/// Width of the names in the Attributes section, so their values line up. +const ATTRIBUTE_KEY_WIDTH: f32 = 80.0; + +/// The settings of generator effect `id`. +pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(tr("Generator"))); + egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { + for kind in GeneratorKind::ALL { + if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { + // Another kind starts from its own defaults: this effect is removed and one of that kind added + app.run("effect.remove", json!({"effect": id})); + app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); + } + } + }); + + section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); + section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); + section(ui, "generator_parameters", tr("Parameters"), true, |ui| { + global_adjustments(app, ui, id, generator); + ramp_parameters(app, ui, id, generator); + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + app.run("effect.set", defaults_of(id, generator.kind)); + } + }); + }); + }); + if !generator.kind.inputs().is_empty() { + section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { + for map in generator.kind.inputs() { + input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); + } + }); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + ui.label( + RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tokens.warning), + ); + } +} + +/// What a generator kind makes, its category and its tags (read only). +fn attributes(ui: &mut Ui, kind: GeneratorKind) { + let tokens = Tokens::get(ui.ctx()); + let (description, tags) = match kind { + GeneratorKind::EdgeWear => ( + tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::Dirt => ( + tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")], + ), + GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), + GeneratorKind::Curvature => ( + tr("Convex edges, cavities or both from the curvature map, at several detail sizes."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::AmbientOcclusion => { + (tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) + } + GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + }; + + // Wrapped rows: a long line must not widen the panel past its edge + let tags = tags.join(", "); + for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] { + ui.horizontal_top(|ui| { + ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim))); + ui.add(egui::Label::new(value).wrap()); + }); + } +} + +/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to. +fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) { + let tokens = Tokens::get(ui.ctx()); + combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| { + for mode in ResolutionMode::ALL { + if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")})); + } + } + }) + .on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own.")); + if resolution.mode == ResolutionMode::Custom { + combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| { + for size in OutputResolution::CUSTOM_SIZES { + if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() { + app.run("effect.set", json!({"effect": id, "customResolution": size})); + } + } + }); + } + combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| { + for factor in OutputResolution::FACTORS { + if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() { + app.run("effect.set", json!({"effect": id, "resolutionFactor": factor})); + } + } + }) + .on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up.")); + + let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.resolution) else { return }; + + let size = resolution.output_size(texture_set, texture_set); + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Output size")).color(tokens.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(format!("{size} × {size}"))); + }) + .response + .on_hover_text(tr("A finer output than the texture set gives the same result as the texture set's resolution.")); +} + +/// The most powers of two a resolution factor scales by, either way. +const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); + +/// "Same as context", or the fraction or multiple a resolution factor stands for. +fn factor_label(factor: i8) -> String { + match factor { + 0 => tr("Same as context").to_string(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + } +} + +/// Global invert, blur, balance and contrast: what every generator applies to its finished value. +fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut invert, mut global) = (generator.invert, generator.global); + let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false); + let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); + let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); + let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); + if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) { + app.run( + "effect.set", + json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), + ); + } +} + +/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. +fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); + let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); + let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), + ); + } + seed_row(app, ui, id, generator.seed); +} + +/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference. +fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { + let typing_id = ui.make_persistent_id(("generator_seed_typing", id)); + let mut typing = ui.data(|data| data.get_temp::(typing_id)).unwrap_or(false); + ui.horizontal(|ui| { + ui.label(tr("Seed")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() { + typing = !typing; + } + if typing { + let mut typed = seed; + let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); + if field.changed() { + // The later changes of one drag continue its first undo step + let merge = field.dragged() && !field.drag_started(); + app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge})); + } + } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() { + app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)})); + } + }); + }); + ui.data_mut(|data| data.insert_temp(typing_id, typing)); +} + +/// A seed different from `current`, from the clock. +fn random_seed(current: u32) -> u32 { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); + let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; + if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } +} + +/// The `effect.set` params that put generator effect `id` back to the defaults of its kind. +fn defaults_of(id: u64, kind: GeneratorKind) -> Value { + let defaults = Generator::new(kind); + let mut params = json!({ + "effect": id, + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + "seed": defaults.seed, + "direction": defaults.direction, + "invert": defaults.invert, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + if let Some(detail) = defaults.detail { + params["mode"] = json!(format!("{:?}", detail.mode)); + params["sizes"] = json!(detail.weights); + } + params +} + +/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). +fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { + let tokens = Tokens::get(ui.ctx()); + let shown = detail.cloned().unwrap_or_default(); + combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { + for mode in CurvatureMode::ALL { + if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + } + }); + + ui.label(caption(tr("Detail sizes"))); + let mut weights = shown.weights; + let mut edit = None; + for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { + edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + if detail.is_none() { + ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tokens.text_dim)); + } +} + +/// The translated name of curvature mode `mode`. +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Edges and cavities"), + CurvatureMode::Raw => tr("Raw curvature"), + } +} + +/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again. +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) { + let tokens = Tokens::get(ui.ctx()); + let input = map.id(); + let current = match source { + None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), + Some(Source::Uniform(_)) => tr("Uniform value").to_string(), + Some(Source::Anchor { anchor, channel }) => anchor_label(app, *anchor, *channel), + Some(Source::Procedural { .. }) => tr("Procedural").to_string(), + }; + let group = ui.group(|ui| { + ui.horizontal(|ui| { + input_tile(app, ui, map, source); + ui.vertical(|ui| { + ui.label(RichText::new(tr(baked_map_label(map))).strong()); + ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + }); + }); + combo(ui, tr("Source"), current.clone(), |ui| { + let anchors = anchors_below(app, layer); + if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + } + for (anchor, label) in &anchors { + if ui + .selectable_label( + matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), + trf("Anchor: {name}", &[("name", label)]), + ) + .clicked() + { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + }); + if let Some(Source::Uniform(value)) = source { + let mut value = value[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); + } + } + if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) { + ui.label( + RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) + .size(NOTE_FONT_SIZE) + .color(tokens.text_dim), + ); + } + }); + if let Some(name) = image_drop(ui, &group.response) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } +} + +/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list). +fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); + let painter = ui.painter(); + let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + match source { + Some(Source::Image { name, .. }) => match app.session.images.get(name) { + Some(image) => { + let texture = app.thumbs.image(ui.ctx(), name, image); + painter.image(texture.id(), rect, whole, egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + } + }, + Some(Source::Uniform(value)) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8)); + } + Some(Source::Anchor { .. } | Source::Procedural { .. }) => { + let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); + } + None => { + let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); + painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); + } + } + painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..4dd0b5fc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -20,6 +20,7 @@ pub mod export_templates; pub mod file_dialogs; mod filter_slot; pub mod fonts; +mod generator_panel; pub mod gpu; pub mod i18n; pub mod id_color_pick; diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 218eb0cc..156b6616 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. +//! Effect rows in the layer stack: dragging one reorders its stack, and its blend mode and opacity sit at its right. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -12,16 +12,16 @@ fn id(v: Value, key: &str) -> u64 { } /// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. -fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { - let start = h.get_by_label(from).rect().center(); - let r = h.get_by_label(to).rect(); - let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 }); - h.drag_at(start); - h.run_steps(2); - h.hover_at(end); - h.run_steps(2); - h.drop_at(end); - h.run_steps(3); +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { + let start = harness.get_by_label(from).rect().center(); + let row_rect = harness.get_by_label(to).rect(); + let end = egui::pos2(row_rect.center().x, if below { row_rect.bottom() - 4.0 } else { row_rect.top() + 4.0 }); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); } #[test] @@ -32,17 +32,54 @@ fn dragging_an_effect_row_reorders_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 h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); - assert_eq!(order(&h), [a, b, c]); + 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::>(); + assert_eq!(order(&harness), [a, b, c]); // The rows list the top first: C, B, A. A dropped on C's upper half goes to the top. - drag(&mut h, "Effect A", "Effect C", false); - assert_eq!(order(&h), [b, c, a]); + drag(&mut harness, "Effect A", "Effect C", false); + assert_eq!(order(&harness), [b, c, a]); // A dropped on B's lower half goes back to the bottom. - drag(&mut h, "Effect A", "Effect B", true); - assert_eq!(order(&h), [a, b, c]); + drag(&mut harness, "Effect A", "Effect B", true); + assert_eq!(order(&harness), [a, b, c]); // C dropped on A's upper half lands between A and B. - drag(&mut h, "Effect C", "Effect A", false); - assert_eq!(order(&h), [a, c, b]); + drag(&mut harness, "Effect C", "Effect A", false); + assert_eq!(order(&harness), [a, c, b]); +} + +/// An effect row's blend mode menu and opacity field sit at its right, as on layer rows. +#[test] +fn an_effect_row_sets_its_blend_mode_and_opacity() { + 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 effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect, effect_of(&harness).id.0); + + // From the row's right edge: 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_left = pair_right - 82.0; + let mode_at = egui::pos2(pair_left + 20.0, row.center().y); + harness.drag_at(mode_at); + harness.drop_at(mode_at); + harness.run_steps(2); + harness.get_by_label("Multiply").click(); + harness.run_steps(3); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply); + + let history = harness.state().session.history_labels().len(); + let opacity_at = egui::pos2(pair_right - 20.0, row.center().y); + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); } diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index a26ac303..469edeca 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -1,5 +1,4 @@ -//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged -//! or clicked to. +//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all). use egui::accesskit::Role; use egui_kittest::Harness; @@ -9,79 +8,82 @@ use texturecraft_engine::core::{EffectKind, LayerId}; use texturecraft_ui_egui::TextureCraftApp; /// The sample session with its first generator effect selected, and that effect's id. -fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { +fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let (layer, effect) = session .doc .project .layers .values() - .find_map(|l| { - let mask = l.mask.iter().flat_map(|m| m.effects.iter()); - l.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (l.id, e.id)) + .find_map(|label_rect| { + let mask = label_rect.mask.iter().flat_map(|m| m.effects.iter()); + label_rect.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (label_rect.id, e.id)) }) .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - (h, effect) + 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); + (harness, effect) } -fn opacity(h: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { - h.state().session.doc.project.effect(effect).unwrap().1.opacity +fn balance(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.global.balance, + _ => panic!("a generator"), + } } /// The track under the slider labelled `label` (the row below the label). -fn track(h: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { - let l = h.get_by_label(label).rect(); - egui::Rect::from_min_max(egui::pos2(l.left() + 6.0, l.bottom() + 6.0), egui::pos2(l.left() + 200.0, l.bottom() + 14.0)) +fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { + let label_rect = harness.get_by_label(label).rect(); + egui::Rect::from_min_max(egui::pos2(label_rect.left() + 6.0, label_rect.bottom() + 6.0), egui::pos2(label_rect.left() + 200.0, label_rect.bottom() + 14.0)) } #[test] -fn dragging_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - assert_eq!(opacity(&h, effect), 1.0); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect)); +fn dragging_a_slider_applies_it() { + let (mut harness, effect) = selected_generator(); + assert_eq!(balance(&harness, effect), 0.5); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); } /// A generator slider applies while it is dragged (the texture follows the pointer), and the /// whole drag is one undo step. #[test] fn dragging_a_generator_slider_applies_live_as_one_undo_step() { - let (mut h, effect) = harness(); - let level = |h: &Harness<'_, TextureCraftApp>| match &h.state().session.doc.project.effect(effect).unwrap().1.kind { + let (mut harness, effect) = selected_generator(); + let level = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { EffectKind::Generator(g) => g.level, _ => panic!("a generator"), }; - let steps = h.state().session.history_labels().len(); - let t = track(&h, "Level"); - let at = |x: f32| egui::pos2(t.left() + x, t.center().y); - h.drag_at(at(10.0)); - h.run_steps(2); + let steps = harness.state().session.history_labels().len(); + let track_rect = track(&harness, "Level"); + let at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y); + harness.drag_at(at(10.0)); + harness.run_steps(2); let mut last = 0.0; for x in [60.0, 160.0] { - h.hover_at(at(x)); - h.run_steps(2); - assert!(level(&h) > last && level(&h) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&h)); - last = level(&h); + harness.hover_at(at(x)); + harness.run_steps(2); + assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness)); + last = level(&harness); } - h.drop_at(at(160.0)); - h.run_steps(3); - assert_eq!(level(&h), last); - assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); + harness.drop_at(at(160.0)); + harness.run_steps(3); + assert_eq!(level(&harness), last); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } /// The combo box in the row of the levels editor's Reset button. -fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = h.get_by_label("Reset").rect().center().y; - h.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +fn channel_picker<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let row = harness.get_by_label("Reset").rect().center().y; + harness.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } /// A content levels effect offers a channel for its histogram; picking one keeps it selected. @@ -90,102 +92,102 @@ fn content_levels_pick_the_histogram_channel() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel"); - channel_picker(&h).click(); - h.run_steps(2); - h.get_by_label("Roughness").click(); - h.run_steps(3); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays"); + 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); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); + channel_picker(&harness).click(); + harness.run_steps(2); + harness.get_by_label("Roughness").click(); + harness.run_steps(3); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Roughness"), "the picked channel stays"); } #[test] -fn clicking_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - let t = track(&h, "Opacity"); - let at = egui::pos2(t.left() + 20.0, t.center().y); - h.drag_at(at); - h.drop_at(at); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "a click on the track applies: {}", opacity(&h, effect)); +fn clicking_a_slider_track_applies_it() { + let (mut harness, effect) = selected_generator(); + let track_rect = track(&harness, "Global balance"); + let at = egui::pos2(track_rect.left() + 20.0, track_rect.center().y); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect)); } /// The number field in the row of the slider labelled `label`. -fn number_field<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = h.get_by_label(label).rect().center().y; - h.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() } -/// Focus the opacity field and press `keys`, then type `text`, one key per frame like a person. -fn type_opacity(h: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { - number_field(h, "Opacity").focus(); - h.run_steps(2); - for k in keys { - h.key_press(*k); - h.run_steps(1); +/// Focus the balance field and press `keys`, then type `text`, one key per frame like a person. +fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { + number_field(harness, "Global balance").focus(); + harness.run_steps(2); + for key in keys { + harness.key_press(*key); + harness.run_steps(1); } - for c in text.chars() { - number_field(h, "Opacity").type_text(&c.to_string()); - h.run_steps(1); + for character in text.chars() { + number_field(harness, "Global balance").type_text(&character.to_string()); + harness.run_steps(1); } } #[test] fn a_value_typed_in_the_number_field_applies() { - let (mut h, effect) = harness(); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.25); - assert_eq!(h.state().session.history_labels().len(), steps + 1); + let (mut harness, effect) = selected_generator(); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.25); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); } /// Dragging the track while the number field has focus drops what was typed there: leaving the /// field afterwards does not undo the drag. #[test] fn a_track_drag_drops_text_typed_in_the_number_field() { - let (mut h, effect) = harness(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "5"); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - let dragged = opacity(&h, effect); - assert!(dragged < 0.5, "the drag applies: {dragged}"); - // Leave whatever has focus: a click on empty space. - h.drag_at(egui::pos2(5.0, 1390.0)); - h.drop_at(egui::pos2(5.0, 1390.0)); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), dragged, "the text typed before the drag stays dropped"); + let (mut harness, effect) = selected_generator(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "5"); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + let dragged = balance(&harness, effect); + assert!(dragged < 0.25, "the drag applies: {dragged}"); + // Leave whatever has focus: a click on empty space + harness.drag_at(egui::pos2(5.0, 1390.0)); + harness.drop_at(egui::pos2(5.0, 1390.0)); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped"); } /// Leaving the number field without typing, or with Escape, keeps the value (not the rounded /// text the field shows) and makes no undo step. #[test] fn leaving_the_number_field_unchanged_keeps_the_value() { - let (mut h, effect) = harness(); - texturecraft_engine::execute(&mut h.state_mut().session, "effect.set", &json!({"effect": effect.0, "opacity": 0.333})).unwrap(); - h.run_steps(2); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[], ""); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333, "left without typing"); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "9"); - assert_eq!(number_field(&h, "Opacity").value().as_deref(), Some("0.39")); - assert!(number_field(&h, "Opacity").is_focused()); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333); - // Typing the value it already has is no edit either. - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(h.state().session.history_labels().len(), steps); + let (mut harness, effect) = selected_generator(); + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "balance": 0.333})).unwrap(); + harness.run_steps(2); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[], ""); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333, "left without typing"); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9"); + assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39")); + assert!(number_field(&harness, "Global balance").is_focused()); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333); + // Typing the value it already has is no edit either + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(harness.state().session.history_labels().len(), steps); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs new file mode 100644 index 00000000..c8afadc9 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -0,0 +1,128 @@ +//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, Source}; +use texturecraft_engine::{ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::theme::Brightness; + +/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel. +fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + session.camera.pitch = 0.5; + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + (harness, LayerId(effect)) +} + +fn generator(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Generator { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + _ => panic!("expected a generator"), + } +} + +/// Drags the track under slider `label` to the right. +fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + let rect = harness.get_by_label(label).rect(); + let start = egui::pos2(rect.left() + 20.0, rect.bottom() + 10.0); + let end = start + egui::vec2(120.0, 0.0); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); +} + +#[test] +fn global_blur_applies_as_one_undo_step() { + let (mut harness, effect) = harness(false); + let history = harness.state().session.history_labels().len(); + drag_slider(&mut harness, "Global blur"); + assert!(generator(&harness, effect).global.blur > 0.0); + assert_eq!(harness.state().session.history_labels().len(), history + 1); + harness.state_mut().session.undo().unwrap(); + assert_eq!(generator(&harness, effect).global.blur, 0.0); +} + +#[test] +fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { + let (mut harness, effect) = harness(false); + let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.run_steps(3); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); +} + +#[test] +fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { + let (mut harness, effect) = harness(false); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Uniform value").click(); + harness.run_steps(3); + assert!(matches!(generator(&harness, effect).inputs.get(&BakedMap::Curvature), Some(Source::Uniform(_)))); + + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Mesh map").click(); + harness.run_steps(3); + assert!(generator(&harness, effect).inputs.is_empty()); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn generator_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut harness, effect) = harness(true); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-default.png")).unwrap(); + + for section in ["Attributes", "Resolution"] { + harness.get_by_label(section).click(); + harness.run_steps(3); + } + harness.run_steps(6); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-panel-sections-open-{name}.png"))).unwrap(); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + + let edits = json!({"effect": effect.0, "blur": 0.3, "balance": 0.6, "contrast": 0.4, "resolutionFactor": -2}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.state_mut().session.update(); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-adjusted.png")).unwrap(); + + // The effect row with its blend mode and opacity, in the layer stack + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-effect-row.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 7597d587..50e4458e 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -58,9 +58,9 @@ fn mask_and_content_thumbnails_select_their_own_target() { let at = thumb(&h, "Masked fill", false); click(&mut h, at); assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back"); - // Clicking an effect row still selects that effect. - let r = h.get_by_label("Effect A").rect(); - click(&mut h, egui::pos2(r.right() - 40.0, r.center().y)); + // Clicking an effect row's name still selects that effect (its right end holds the blend mode and opacity) + let row = h.get_by_label("Effect A").rect(); + click(&mut h, row.center()); assert!(matches!(h.state().session.target, StackTarget::Effect(_))); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..1b467ac7 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -14,6 +14,7 @@ mod file_dialogs; mod fill_channel_image; mod fill_projection_section; mod filter_picker; +mod generator_panel; mod history_panel; mod layer_clipboard; mod layer_rename; From f734b0b96d22f0fecb8cbf48f080913ccaf66f8a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 12 Nov 2026 04:46:54 +0000 Subject: [PATCH 30/42] Effect rows: an opacity drag's first change starts its undo step; the field is named after its row A drag can start without changing the value, so the first change of a drag, not its first frame, opens the undo step. The opacity field's accessible name is "Opacity of" the layer or effect. --- crates/ui-egui/src/dock.rs | 26 +++++++++++++++------ crates/ui-egui/tests/it/effect_rows.rs | 31 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e6ee88ac..00adf00c 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -628,8 +628,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y + ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT)); if let Some(channel_blend) = blend.filter(|_| show_blend) { let id = ui.scope_id().with(("blend", layer.id.0)); - let (mode, opacity) = - blend_controls(ui, id, (mode_rect, opacity_rect), (channel_blend.mode, channel_blend.opacity), tr("Blending mode of the displayed channel")); + let (mode, opacity) = blend_controls( + ui, + id, + (mode_rect, opacity_rect), + (channel_blend.mode, channel_blend.opacity), + (tr("Blending mode of the displayed channel"), &layer.name), + ); if let Some(mode) = mode { app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "mode": format!("{mode:?}")})); } @@ -780,13 +785,13 @@ fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: & /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// A stack row's blend mode menu and opacity field (percent): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. +/// A stack row's blend mode menu and opacity field (percent, named after row `row_name`): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. fn blend_controls( ui: &mut Ui, id: egui::Id, (mode_rect, opacity_rect): (Rect, Rect), (mode, opacity): (BlendMode, f32), - hover: &str, + (hover, row_name): (&str, &str), ) -> (Option, Option<(f32, bool)>) { let tokens = Tokens::get(ui.ctx()); let painter = ui.painter().clone(); @@ -835,9 +840,15 @@ fn blend_controls( state.bg_stroke = Stroke::NONE; } let field = field_ui.add(egui::DragValue::new(&mut percent).range(0.0..=100.0).speed(OPACITY_DRAG_SPEED).max_decimals(0).suffix("%")); + field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, true, trf("Opacity of {name}", &[("name", &row_name)]))); - // The later changes of one drag continue its first undo step - let merge = field.dragged() && !field.drag_started(); + // A drag's first change starts an undo step and its later changes continue it (a drag can start without a change) + let drag_changed_id = id.with("opacity_drag_changed"); + let drag_changed = !field.drag_started() && ui.data(|data| data.get_temp::(drag_changed_id)).unwrap_or(false); + let merge = field.dragged() && drag_changed; + if field.changed() || field.drag_started() { + ui.data_mut(|data| data.insert_temp(drag_changed_id, field.changed() && field.dragged())); + } (picked, field.changed().then_some((percent / 100.0, merge))) } @@ -910,7 +921,8 @@ fn effect_row( let opacity_center = pos2(mode_rect.right() + ROW_CONTROL_GAP + EFFECT_OPACITY_WIDTH * 0.5, rect.center().y); let opacity_rect = Rect::from_center_size(opacity_center, vec2(EFFECT_OPACITY_WIDTH, ROW_CONTROL_HEIGHT)); let id = ui.scope_id().with(("eff_blend", effect_id.0)); - let (mode, opacity) = blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), tr("Blending mode of the effect")); + let (mode, opacity) = + blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), (tr("Blending mode of the effect"), &effect.name)); if let Some(mode) = mode { app.run("effect.set", json!({"effect": effect_id.0, "blend": format!("{mode:?}")})); } diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 156b6616..9f0a87ff 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -83,3 +83,34 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); } + +/// A drag whose first frame leaves the opacity unchanged still starts its own undo step: undo keeps the blend mode set before it +#[test] +fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { + 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 effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": effect, "blend": "Multiply"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + + let history = harness.state().session.history_labels().len(); + let opacity_at = harness.get_by_label("Opacity of Effect A").rect().center(); + // Equal right and down movement adds nothing to the value: the drag starts without a change + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at + egui::vec2(8.0, 8.0)); + harness.run_steps(2); + assert_eq!(effect_of(&harness).opacity, 1.0, "the drag started without changing the opacity"); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "the drag lowered the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the drag is one new undo step"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(effect_of(&harness).opacity, 1.0); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); +} From f40dc84f72da5e1d23730db3222186b9967133f7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 12:28:11 +0000 Subject: [PATCH 31/42] Use shared streaming project tile payloads --- Cargo.lock | 21 +++ Cargo.toml | 2 + crates/formats/Cargo.toml | 2 + .../formats/src/project_file/load_budget.rs | 14 +- crates/formats/src/project_file/mod.rs | 160 +++++------------- crates/formats/src/project_file/tests.rs | 10 +- 6 files changed, 81 insertions(+), 128 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8368bc88..16ef0634 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -844,6 +844,15 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-tcraft" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5f46c0ab25f067f6fdb863c7e1f9ff567712f394#5f46c0ab25f067f6fdb863c7e1f9ff567712f394" +dependencies = [ + "craft-zip", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -913,6 +922,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5f46c0ab25f067f6fdb863c7e1f9ff567712f394#5f46c0ab25f067f6fdb863c7e1f9ff567712f394" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -4395,6 +4414,8 @@ dependencies = [ "base64 0.22.1", "craft-materialx", "craft-mesh", + "craft-tcraft", + "craft-zip", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index 09fada6a..a7682daa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,6 +69,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "5f46c0ab25f067f6fdb863c7e1f9ff567712f394" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5f46c0ab25f067f6fdb863c7e1f9ff567712f394" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index d78d4d7a..5569b475 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [dependencies] craft-materialx = { workspace = true } craft-mesh = { workspace = true } +craft-tcraft = { workspace = true } +craft-zip = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/project_file/load_budget.rs b/crates/formats/src/project_file/load_budget.rs index 284c4d64..a183336a 100644 --- a/crates/formats/src/project_file/load_budget.rs +++ b/crates/formats/src/project_file/load_budget.rs @@ -13,14 +13,18 @@ impl LoadBudget { self.limit_bytes - self.used_bytes } + pub(super) fn exceeded_message(&self) -> String { + format!( + "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", + self.limit_bytes, + self.limit_bytes as f64 / (1u64 << 30) as f64, + ) + } + /// Reserve bytes before retaining decoded data so entries share one allocation budget. pub(super) fn take(&mut self, bytes: u64) -> Result<(), String> { if bytes > self.remaining() { - return Err(format!( - "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", - self.limit_bytes, - self.limit_bytes as f64 / (1u64 << 30) as f64, - )); + return Err(self.exceeded_message()); } self.used_bytes += bytes; diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index ff7a7b3a..5862e436 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -43,9 +43,11 @@ pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_re pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; const KIND: &str = "project file"; +#[cfg(test)] const MAGIC: &[u8; 4] = b"TCTX"; -/// Version of the `.bin` layout. +#[cfg(test)] const BIN_VERSION: u32 = 1; +#[cfg(test)] const BIN_HEADER_BYTES: usize = 24; const MAX_JSON: u64 = 256 << 20; const MAX_THUMBNAIL: u64 = 64 << 20; @@ -124,6 +126,7 @@ fn zip_err(e: zip::result::ZipError) -> FormatError { } } +#[cfg(test)] fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec { let mut b = MAGIC.to_vec(); for v in [BIN_VERSION, w, h, comps as u32, count as u32] { @@ -132,19 +135,18 @@ fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec { b } -fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> { - w.write_all(&header(img.width(), img.height(), img.comps(), img.allocated_count()))?; - let mut buf = Vec::with_capacity(TILE_AREA * img.comps() * 2 + 8); - for (tx, ty) in img.allocated() { - buf.clear(); - buf.extend_from_slice(&tx.to_le_bytes()); - buf.extend_from_slice(&ty.to_le_bytes()); - for v in img.tile(tx, ty).unwrap_or_default() { - buf.extend_from_slice(&v.to_le_bytes()); - } - w.write_all(&buf)?; +fn codec_write_error(error: craft_tcraft::Error) -> std::io::Error { + match error { + craft_tcraft::Error::Io(error) => error, + other => std::io::Error::other(other), } - Ok(()) +} + +fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> { + let layout = craft_tcraft::Layout { width: img.width(), height: img.height(), components: img.comps() }; + let count = u32::try_from(img.allocated_count()).map_err(std::io::Error::other)?; + let tiles = img.allocated().map(|(x, y)| (x, y, img.tile(x, y).unwrap_or_default())); + craft_tcraft::write_tiles(w, layout, count, tiles).map_err(codec_write_error) } /// Keep `[a-z0-9]`, at most 8 characters (the mesh entry's extension). @@ -169,18 +171,12 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet) -> Strin entry } -/// Floats converted to bytes at a time when a baked map streams into the compressor. +#[cfg(test)] const BAKED_CHUNK: usize = 1 << 16; fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> { - w.write_all(&header(res, h, comps, 0))?; - let mut buf = Vec::with_capacity(BAKED_CHUNK * 4); - for chunk in data.chunks(BAKED_CHUNK) { - buf.clear(); - buf.extend(chunk.iter().flat_map(|v| v.to_le_bytes())); - w.write_all(&buf)?; - } - Ok(()) + let layout = craft_tcraft::Layout { width: res, height: h, components: comps }; + craft_tcraft::write_baked(w, layout, data).map_err(codec_write_error) } /// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. @@ -304,110 +300,34 @@ fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &st Ok(out) } -/// Decode bounded chunks so a false header cannot allocate an entire missing map. -fn read_f32s(reader: &mut impl Read, count: usize, what: &str) -> Result> { - let mut values = Vec::new(); - let mut bytes = vec![0u8; BAKED_CHUNK.min(count) * 4]; - let mut remaining = count; - while remaining > 0 { - let chunk_values = BAKED_CHUNK.min(remaining); - let chunk = bytes.get_mut(..chunk_values * 4).ok_or_else(|| malformed(KIND, format!("{what}: invalid float chunk")))?; - read_exact(reader, chunk, what)?; - values.try_reserve(chunk_values).map_err(|_| FormatError::TooLarge(format!("{what}: not enough memory for {count} values")))?; - values.extend(chunk.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes))); - remaining -= chunk_values; - } - - Ok(values) -} - -fn read_exact(r: &mut impl Read, buf: &mut [u8], what: &str) -> Result<()> { - r.read_exact(buf).map_err(|e| malformed(KIND, format!("{what}: {e}"))) -} - -fn u32_at(b: &[u8], i: usize) -> u32 { - b.get(i * 4..i * 4 + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).unwrap_or(0) -} - -/// Read and check a `.bin` header: returns (width, height, comps, count). -fn read_header(r: &mut impl Read, what: &str) -> Result<(u32, u32, usize, usize)> { - let mut h = [0u8; BIN_HEADER_BYTES]; - read_exact(r, &mut h, what)?; - if h.get(..4) != Some(MAGIC.as_slice()) { - return Err(malformed(KIND, format!("{what}: bad magic"))); - } - let v = u32_at(&h, 1); - if v > BIN_VERSION { - return Err(FormatError::NewerVersion { found: v, supported: BIN_VERSION }); - } - Ok((u32_at(&h, 2), u32_at(&h, 3), u32_at(&h, 4) as usize, u32_at(&h, 5) as usize)) -} - -/// Error unless the entry has no bytes left (also makes the zip reader verify the CRC). -fn expect_end(r: &mut impl Read, what: &str) -> Result<()> { - let mut b = [0u8; 1]; - match r.read(&mut b) { - Ok(0) => Ok(()), - Ok(_) => Err(malformed(KIND, format!("{what}: trailing data"))), - Err(e) => Err(malformed(KIND, format!("{what}: {e}"))), - } +/// Transfer the bytes charged by the shared codec to this project's one load budget. +fn codec_result(result: std::result::Result, shared: &craft_zip::Budget, budget: &mut LoadBudget, what: &str) -> Result { + budget.take(shared.used()).map_err(FormatError::TooLarge)?; + result.map_err(|error| match error { + craft_tcraft::Error::Budget(_) => FormatError::TooLarge(budget.exceeded_message()), + craft_tcraft::Error::Limit(message) => FormatError::TooLarge(format!("{what}: {message}")), + craft_tcraft::Error::NewerVersion(found) => FormatError::NewerVersion { found, supported: craft_tcraft::VERSION }, + other => malformed(KIND, format!("{what}: {other}")), + }) } fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut LoadBudget, what: &str) -> Result { - budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; - let (width, height, stored_components, count) = read_header(reader, what)?; - if (width, height) != size || stored_components != components { - return Err(malformed( - KIND, - format!("{what}: {width}×{height}×{stored_components} does not match the texture set ({}×{}×{components})", size.0, size.1), - )); - } - - let mut image = TileImage::new(width, height, components); - if count > (image.tiles_x() as usize) * (image.tiles_y() as usize) { - return Err(malformed(KIND, format!("{what}: {count} tiles is more than the image holds"))); - } - - let mut bytes = vec![0u8; TILE_AREA * components * 2]; - let mut position_bytes = [0u8; 8]; - for _ in 0..count { - budget.take((position_bytes.len() + bytes.len()) as u64).map_err(FormatError::TooLarge)?; - read_exact(reader, &mut position_bytes, what)?; - let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1)); - if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) { - return Err(malformed(KIND, format!("{what}: bad or repeated tile ({tx}, {ty})"))); - } - - read_exact(reader, &mut bytes, what)?; - let data: Vec = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect(); - image.set_tile(tx, ty, Some(Arc::new(data))); - } - - expect_end(reader, what)?; - - Ok(image) + let layout = craft_tcraft::Layout { width: size.0, height: size.1, components }; + let mut shared = craft_zip::Budget::new("project", budget.remaining()); + let mut image = None; + let result = craft_tcraft::read_tiles(reader, layout, MAX_TEXELS, &mut shared, |x, y, values| { + image.get_or_insert_with(|| TileImage::new(size.0, size.1, components)).set_tile(x, y, Some(Arc::new(values))); + Ok(()) + }); + codec_result(result, &shared, budget, what)?; + Ok(image.unwrap_or_else(|| TileImage::new(size.0, size.1, components))) } -/// A baked map: (width, height, data). fn read_baked(reader: &mut impl Read, declared_bytes: u64, components: usize, budget: &mut LoadBudget, what: &str) -> Result<(u32, u32, Vec)> { - budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; - let (width, height, stored_components, _) = read_header(reader, what)?; - if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components { - return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}"))); - } - - let value_count = u64::from(width) * u64::from(height) * components as u64; - let payload_bytes = value_count * 4; - if declared_bytes != BIN_HEADER_BYTES as u64 + payload_bytes { - return Err(malformed(KIND, format!("{what}: {declared_bytes} bytes for a {width}×{height}×{components} map"))); - } - - budget.take(payload_bytes).map_err(FormatError::TooLarge)?; - let value_count = usize::try_from(value_count).map_err(|_| FormatError::TooLarge(format!("{what}: too many values for this platform")))?; - let data = read_f32s(reader, value_count, what)?; - expect_end(reader, what)?; - - Ok((width, height, data)) + let mut shared = craft_zip::Budget::new("project", budget.remaining()); + let result = craft_tcraft::read_baked(reader, declared_bytes, components, MAX_TEXELS, &mut shared); + let (layout, values) = codec_result(result, &shared, budget, what)?; + Ok((layout.width, layout.height, values)) } /// Texture set holding a paint layer, a content effect or a mask effect id. diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 93a58a9a..b48f2a7c 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -803,13 +803,17 @@ fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() { #[test] fn streamed_float_chunks_preserve_bits_across_the_chunk_boundary() { let values: Vec = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect(); - let bytes: Vec = values.iter().flat_map(|bits| bits.to_le_bytes()).collect(); + let mut bytes = header(values.len() as u32, 1, 1, 0); + bytes.extend(values.iter().flat_map(|bits| bits.to_le_bytes())); + let declared = bytes.len() as u64; let mut reader = Cursor::new(bytes); + let mut budget = LoadBudget::new(declared); - let decoded = read_f32s(&mut reader, values.len(), "baked map").unwrap(); + let (_, _, decoded) = read_baked(&mut reader, declared, 1, &mut budget, "baked map").unwrap(); assert_eq!(decoded.into_iter().map(f32::to_bits).collect::>(), values); - assert_eq!(reader.position(), (values.len() * 4) as u64); + assert_eq!(reader.position(), declared); + assert_eq!(budget.remaining(), 0); } #[test] From 1d0f9665f99466a26008602fd99396d0af570ca6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 12:46:12 +0000 Subject: [PATCH 32/42] Use shared project version parser --- Cargo.lock | 6 ++++-- Cargo.toml | 4 ++-- crates/formats/src/project_file/mod.rs | 10 +++------- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 16ef0634..acf9f9b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -847,9 +847,11 @@ dependencies = [ [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5f46c0ab25f067f6fdb863c7e1f9ff567712f394#5f46c0ab25f067f6fdb863c7e1f9ff567712f394" +source = "git+https://github.com/storytold/craft-libs?rev=b85e4b150#b85e4b150b7e427b1fd3c88b4ed9e6aba055053c" dependencies = [ "craft-zip", + "serde", + "serde_json", "thiserror 2.0.21", ] @@ -925,7 +927,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5f46c0ab25f067f6fdb863c7e1f9ff567712f394#5f46c0ab25f067f6fdb863c7e1f9ff567712f394" +source = "git+https://github.com/storytold/craft-libs?rev=b85e4b150#b85e4b150b7e427b1fd3c88b4ed9e6aba055053c" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a7682daa..0b3672a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,8 +69,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "5f46c0ab25f067f6fdb863c7e1f9ff567712f394" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5f46c0ab25f067f6fdb863c7e1f9ff567712f394" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "b85e4b150" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b85e4b150" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 5862e436..7cbacad0 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -376,13 +376,9 @@ fn load_with_budget(reader: R, mut budget: LoadBudget) -> Result check_archive(&mut zip, budget.remaining())?; let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; - #[derive(serde::Deserialize)] - struct Version { - format_version: u32, - } - let v: Version = serde_json::from_slice(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; - if v.format_version > FORMAT_VERSION { - return Err(FormatError::NewerVersion { found: v.format_version, supported: FORMAT_VERSION }); + let version = craft_tcraft::project_version(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; + if version > FORMAT_VERSION { + return Err(FormatError::NewerVersion { found: version, supported: FORMAT_VERSION }); } let (project, mut recovered) = recovery::read_project(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; From 4864fbbc78b48762a3dc8223f5f824928409fc78 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:01:22 +0000 Subject: [PATCH 33/42] Test shared schema against native project documents --- crates/formats/src/project_file/tests.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index b48f2a7c..95beac51 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -82,6 +82,15 @@ fn round_trip_is_identical_and_deterministic() { assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap()); } +#[test] +fn shared_project_schema_round_trips_the_app_document() { + let project = sample().pf.project; + let original = serde_json::to_value(&project).unwrap(); + let document: craft_tcraft::ProjectDocument = serde_json::from_value(original.clone()).unwrap(); + assert_eq!(document.format_version, project.format_version); + assert_eq!(serde_json::to_value(document).unwrap(), original); +} + #[test] fn legacy_bakes_load_as_is_without_layout_conversion() { let mut sample = sample(); From 6028051a400e3748ac046e20670f47623c0f90c7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:44:48 +0000 Subject: [PATCH 34/42] Update shared project schema pin --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index acf9f9b8..111b6612 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -847,7 +847,7 @@ dependencies = [ [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b85e4b150#b85e4b150b7e427b1fd3c88b4ed9e6aba055053c" +source = "git+https://github.com/storytold/craft-libs?rev=d2c1cac03#d2c1cac0324491bd67f6e3b583a5dffb18bf78eb" dependencies = [ "craft-zip", "serde", @@ -927,7 +927,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b85e4b150#b85e4b150b7e427b1fd3c88b4ed9e6aba055053c" +source = "git+https://github.com/storytold/craft-libs?rev=d2c1cac03#d2c1cac0324491bd67f6e3b583a5dffb18bf78eb" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 0b3672a6..2a45cfb2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,8 +69,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "b85e4b150" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b85e4b150" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "d2c1cac03" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d2c1cac03" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } From 0e218bd23ee0dd76283aeede29c4abf50d404419 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:51:20 +0000 Subject: [PATCH 35/42] Use shared seekable ZIP archive checks --- Cargo.lock | 4 +- Cargo.toml | 4 +- .../src/project_file/metadata_reader.rs | 81 ------------------- crates/formats/src/project_file/mod.rs | 35 +++----- crates/formats/src/project_file/tests.rs | 11 +-- 5 files changed, 17 insertions(+), 118 deletions(-) delete mode 100644 crates/formats/src/project_file/metadata_reader.rs diff --git a/Cargo.lock b/Cargo.lock index 111b6612..4b848b5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -847,7 +847,7 @@ dependencies = [ [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d2c1cac03#d2c1cac0324491bd67f6e3b583a5dffb18bf78eb" +source = "git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833#2cf13ea7c6920f3674e0fd5c362852e77c5cf833" dependencies = [ "craft-zip", "serde", @@ -927,7 +927,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d2c1cac03#d2c1cac0324491bd67f6e3b583a5dffb18bf78eb" +source = "git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833#2cf13ea7c6920f3674e0fd5c362852e77c5cf833" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 2a45cfb2..e1284fde 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,8 +69,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "d2c1cac03" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d2c1cac03" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "2cf13ea7c6920f3674e0fd5c362852e77c5cf833" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "2cf13ea7c6920f3674e0fd5c362852e77c5cf833" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } diff --git a/crates/formats/src/project_file/metadata_reader.rs b/crates/formats/src/project_file/metadata_reader.rs deleted file mode 100644 index 7e82825c..00000000 --- a/crates/formats/src/project_file/metadata_reader.rs +++ /dev/null @@ -1,81 +0,0 @@ -use std::cell::Cell; -use std::io::{self, Read, Seek, SeekFrom}; - -/// Restrict ZIP indexing to a bounded tail and read allowance before enabling payload access. -pub(super) struct MetadataReader<'a, R> { - reader: R, - metadata_only: &'a Cell, - metadata_start: u64, - remaining_bytes: u64, - position: u64, -} - -impl<'a, R: Read + Seek> MetadataReader<'a, R> { - pub(super) fn new(mut reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> io::Result { - let end = reader.seek(SeekFrom::End(0))?; - Ok(Self { reader, metadata_only, metadata_start: end.saturating_sub(metadata_bytes), remaining_bytes: metadata_bytes.saturating_mul(2), position: end }) - } -} - -impl Read for MetadataReader<'_, R> { - fn read(&mut self, bytes: &mut [u8]) -> io::Result { - if bytes.is_empty() { - return Ok(0); - } - - let metadata_only = self.metadata_only.get(); - if metadata_only && (self.position < self.metadata_start || self.remaining_bytes == 0) { - return Err(io::Error::new(io::ErrorKind::InvalidData, "project ZIP metadata exceeds the indexing limit")); - } - - let length = if metadata_only { bytes.len().min(usize::try_from(self.remaining_bytes).unwrap_or(usize::MAX)) } else { bytes.len() }; - let read = self.reader.read(bytes.get_mut(..length).unwrap_or_default())?; - self.position = self.position.saturating_add(read as u64); - if metadata_only { - self.remaining_bytes -= read as u64; - } - - Ok(read) - } -} - -impl Seek for MetadataReader<'_, R> { - fn seek(&mut self, position: SeekFrom) -> io::Result { - self.position = self.reader.seek(position)?; - Ok(self.position) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Cursor; - - #[test] - fn indexing_cannot_read_payloads_outside_the_metadata_window() { - let metadata_only = Cell::new(true); - let mut reader = MetadataReader::new(Cursor::new(vec![7; 100]), &metadata_only, 8).unwrap(); - reader.seek(SeekFrom::Start(91)).unwrap(); - - assert!(reader.read(&mut [0; 1]).is_err()); - reader.seek(SeekFrom::Start(92)).unwrap(); - reader.read_exact(&mut [0; 8]).unwrap(); - - metadata_only.set(false); - reader.seek(SeekFrom::Start(0)).unwrap(); - reader.read_exact(&mut [0; 100]).unwrap(); - } - - #[test] - fn repeated_metadata_scans_share_one_read_allowance() { - let metadata_only = Cell::new(true); - let mut reader = MetadataReader::new(Cursor::new(vec![7; 8]), &metadata_only, 8).unwrap(); - for _ in 0..2 { - reader.seek(SeekFrom::Start(0)).unwrap(); - reader.read_exact(&mut [0; 8]).unwrap(); - } - reader.seek(SeekFrom::Start(0)).unwrap(); - - assert!(reader.read(&mut [0; 1]).is_err()); - } -} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 7cbacad0..e1d98196 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -18,7 +18,6 @@ //! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture //! set cover its whole atlas (`resolution` per tile, see `TileGrid`). -use std::cell::Cell; use std::collections::{BTreeMap, HashSet}; use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; @@ -31,12 +30,10 @@ use zip::{CompressionMethod, ZipArchive, ZipWriter}; use self::entries::Entry; use self::load_budget::LoadBudget; -use self::metadata_reader::MetadataReader; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; mod load_budget; -mod metadata_reader; mod project_open_limit; #[cfg(not(target_arch = "wasm32"))] pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, save_ram_budget, set_save_resources}; @@ -342,37 +339,25 @@ fn load(reader: R) -> Result { } fn check_archive(zip: &mut ZipArchive, limit_bytes: u64) -> Result<()> { - if zip.len() > MAX_ENTRIES { - return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); - } - - // Count every declared payload, including ignored entries, before any decompression - let mut declared_budget = LoadBudget::new(limit_bytes); - for index in 0..zip.len() { - let entry = zip.by_index_raw(index).map_err(zip_err)?; - declared_budget.take(entry.size()).map_err(FormatError::TooLarge)?; - } - - // Shared compressed ranges can amplify one payload into many apparent files - if zip.has_overlapping_entries().map_err(zip_err)? { - return Err(malformed(KIND, "overlapping ZIP entries are not supported")); - } - - Ok(()) + craft_zip::inspect_seekable(zip, MAX_ENTRIES, limit_bytes).map_err(|error| match error { + craft_zip::InspectError::TooManyEntries { .. } => FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries")), + craft_zip::InspectError::DeclaredBytesExceeded { .. } => FormatError::TooLarge(LoadBudget::new(limit_bytes).exceeded_message()), + craft_zip::InspectError::OverlappingEntries => malformed(KIND, "overlapping ZIP entries are not supported"), + craft_zip::InspectError::Zip(error) => zip_err(error), + }) } -fn open_archive<'a, R: Read + Seek>(reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> Result>> { - let reader = MetadataReader::new(reader, metadata_only, metadata_bytes)?; +fn open_archive(reader: R, metadata_bytes: u64) -> Result>> { + let (reader, indexing) = craft_zip::MetadataReader::new(reader, metadata_bytes)?; // Project archives start at byte zero; avoid scanning payloads to guess an embedded ZIP offset let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; let archive = ZipArchive::with_config(config, reader).map_err(zip_err)?; - metadata_only.set(false); + indexing.finish(); Ok(archive) } fn load_with_budget(reader: R, mut budget: LoadBudget) -> Result { - let metadata_only = Cell::new(true); - let mut zip = open_archive(reader, &metadata_only, MAX_ZIP_METADATA_BYTES)?; + let mut zip = open_archive(reader, MAX_ZIP_METADATA_BYTES)?; check_archive(&mut zip, budget.remaining())?; let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 95beac51..4fcc0aed 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -831,23 +831,19 @@ fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() { writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); writer.write_all(&vec![7; 1 << 20]).unwrap(); let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - let mut archive = open_archive(Cursor::new(bytes), &metadata_only, 4096).unwrap(); + let mut archive = open_archive(Cursor::new(bytes), 4096).unwrap(); let mut first_byte = [0; 1]; archive.by_index(0).unwrap().read_exact(&mut first_byte).unwrap(); assert_eq!(first_byte, [7]); - assert!(!metadata_only.get()); let mut writer = ZipWriter::new(Cursor::new(Vec::new())); writer.start_file("a".repeat(5000), SimpleFileOptions::default()).unwrap(); writer.write_all(&[7]).unwrap(); let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - assert!(open_archive(Cursor::new(bytes), &metadata_only, 4096).is_err()); - assert!(metadata_only.get(), "failed indexing must not enable payload access"); + assert!(open_archive(Cursor::new(bytes), 4096).is_err()); } #[test] @@ -858,9 +854,8 @@ fn zip64_entry_counts_remain_supported_and_bounded() { writer.start_file(format!("e{index}"), SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); } let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - let mut archive = open_archive(Cursor::new(bytes), &metadata_only, MAX_ZIP_METADATA_BYTES).unwrap(); + let mut archive = open_archive(Cursor::new(bytes), MAX_ZIP_METADATA_BYTES).unwrap(); let result = check_archive(&mut archive, 0); assert_eq!(archive.len(), count); From e1d4f99da1262d34b324808848602702f1846bdf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:48:44 +0000 Subject: [PATCH 36/42] Pin shared project codecs to merged craft-libs --- Cargo.lock | 22 ++++++---------------- Cargo.toml | 6 +++--- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2f687131..ba685c21 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -818,9 +818,9 @@ dependencies = [ [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627)", + "craft-zip", "serde", "serde_json", "thiserror 2.0.21", @@ -858,9 +858,9 @@ dependencies = [ [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833#2cf13ea7c6920f3674e0fd5c362852e77c5cf833" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833)", + "craft-zip", "serde", "serde_json", "thiserror 2.0.21", @@ -938,17 +938,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833#2cf13ea7c6920f3674e0fd5c362852e77c5cf833" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" dependencies = [ "flate2", "thiserror 2.0.21", @@ -4439,7 +4429,7 @@ dependencies = [ "craft-mcmat", "craft-mesh", "craft-tcraft", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833)", + "craft-zip", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index 9493c02b..3d25ee21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,10 +69,10 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "2cf13ea7c6920f3674e0fd5c362852e77c5cf833" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "2cf13ea7c6920f3674e0fd5c362852e77c5cf833" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } -craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). From ecf313f325a4fb624a35b0c6aabb5ea09ff86440 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:29:05 -0500 Subject: [PATCH 37/42] Use shared ICC v2 profile serialization for texture exports Retain SteamSmith original writer as a test-only wire oracle, including bflatastic is_multiple_of cleanup. Colour adaptation, sampling, names and fixed timestamp remain local policy. Co-authored-by: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Co-authored-by: bflatastic --- Cargo.lock | 20 ++++ crates/formats/Cargo.toml | 2 + crates/formats/src/icc.rs | 141 ++++++-------------------- crates/formats/src/icc_legacy_test.rs | 124 ++++++++++++++++++++++ 4 files changed, 177 insertions(+), 110 deletions(-) create mode 100644 crates/formats/src/icc_legacy_test.rs diff --git a/Cargo.lock b/Cargo.lock index d63a2ff2..c6801d15 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -755,6 +755,15 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6c09292724ec8dbe32950cb5042cfaa2a614fb6c#6c09292724ec8dbe32950cb5042cfaa2a614fb6c" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-dialogs" version = "0.1.0" @@ -2499,6 +2508,16 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.3" @@ -4414,6 +4433,7 @@ name = "texturecraft-formats" version = "0.6.1" dependencies = [ "base64 0.22.1", + "craft-cms", "craft-materialx", "craft-mcmat", "craft-mesh", diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 756b2a78..795e066e 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -9,6 +9,8 @@ license.workspace = true workspace = true [dependencies] +# ICC v2 serialization prerequisite: craft-libs#1735; app colour policy stays local. +craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6c09292724ec8dbe32950cb5042cfaa2a614fb6c" } craft-materialx = { workspace = true } craft-mesh = { workspace = true } craft-mcmat = { workspace = true } diff --git a/crates/formats/src/icc.rs b/crates/formats/src/icc.rs index 9323f561..f0f16a84 100644 --- a/crates/formats/src/icc.rs +++ b/crates/formats/src/icc.rs @@ -1,63 +1,7 @@ -//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small -//! (about 1.2 KiB) and readable by every colour-managed viewer and editor. -//! -//! The colorants come from the space's primaries adapted to the D50 profile connection space -//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear -//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied -//! from a colour-management library or from another profile. - +//! ICC v2.1 export policy; byte serialization is shared with craft-cms. +use craft_cms_icc_v2::write_v2::{MatrixProfile, ToneCurve, matrix_profile}; use texturecraft_texel::{ColorSpace, srgb_to_linear}; - -/// Samples of the sRGB curve table. const CURVE_POINTS: usize = 1024; -/// The D50 white of the profile connection space. -const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249]; - -fn s15f16(v: f64) -> [u8; 4] { - ((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes() -} - -fn xyz_tag(v: [f64; 3]) -> Vec { - let mut b = b"XYZ \0\0\0\0".to_vec(); - for c in v { - b.extend_from_slice(&s15f16(c)); - } - b -} - -fn text_tag(text: &str) -> Vec { - let mut b = b"text\0\0\0\0".to_vec(); - b.extend_from_slice(text.as_bytes()); - b.push(0); - b -} - -/// `textDescriptionType` with the ASCII description only. -fn desc_tag(text: &str) -> Vec { - let mut b = b"desc\0\0\0\0".to_vec(); - b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes()); - b.extend_from_slice(text.as_bytes()); - b.push(0); - // No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler. - b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); - b -} - -fn curve_tag(space: ColorSpace) -> Vec { - let mut b = b"curv\0\0\0\0".to_vec(); - if space == ColorSpace::Srgb { - b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes()); - for i in 0..CURVE_POINTS { - let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); - b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes()); - } - } else { - // One entry is a gamma, u8Fixed8: 1.0 is linear. - b.extend_from_slice(&1u32.to_be_bytes()); - b.extend_from_slice(&0x0100u16.to_be_bytes()); - } - b -} fn description(space: ColorSpace) -> &'static str { match space { @@ -68,64 +12,41 @@ fn description(space: ColorSpace) -> &'static str { } } -/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones). +/// The ICC profile of `space`, or None if its primaries are degenerate. pub fn profile(space: ColorSpace) -> Option> { - let m = space.to_xyz_d50()?; - let column = |c: usize| [m[0][c], m[1][c], m[2][c]]; - let curve = curve_tag(space); - // The green and blue curves are the red one's entry. - let tags: [(&[u8; 4], Vec); 9] = [ - (b"desc", desc_tag(description(space))), - (b"cprt", text_tag("No copyright, generated by TextureCraft")), - (b"wtpt", xyz_tag(D50_XYZ)), - (b"rXYZ", xyz_tag(column(0))), - (b"gXYZ", xyz_tag(column(1))), - (b"bXYZ", xyz_tag(column(2))), - (b"rTRC", curve.clone()), - (b"gTRC", curve.clone()), - (b"bTRC", curve), - ]; - // Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes. - let table_end = 128 + 4 + 12 * tags.len(); - let mut offsets = Vec::new(); - let mut data: Vec = Vec::new(); - for (i, (_, bytes)) in tags.iter().enumerate() { - let shared = i >= 7; - let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() }; - offsets.push(at); - if !shared { - data.extend_from_slice(bytes); - while !data.len().is_multiple_of(4) { - data.push(0); - } - } - } - let total = table_end + data.len(); - let mut out = vec![0u8; 128]; - out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes()); - out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0 - out.get_mut(12..16)?.copy_from_slice(b"mntr"); - out.get_mut(16..20)?.copy_from_slice(b"RGB "); - out.get_mut(20..24)?.copy_from_slice(b"XYZ "); - // A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes. - out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]); - out.get_mut(36..40)?.copy_from_slice(b"acsp"); - for (k, v) in D50_XYZ.iter().enumerate() { - out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v)); - } - out.extend_from_slice(&(tags.len() as u32).to_be_bytes()); - for ((sig, bytes), at) in tags.iter().zip(&offsets) { - out.extend_from_slice(*sig); - out.extend_from_slice(&(*at as u32).to_be_bytes()); - out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); - } - out.extend_from_slice(&data); - Some(out) + let matrix = space.to_xyz_d50()?; + let samples: Vec = if space == ColorSpace::Srgb { + (0..CURVE_POINTS) + .map(|i| { + let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); + (v * 65535.0).round().clamp(0.0, 65535.0) as u16 + }) + .collect() + } else { + Vec::new() + }; + matrix_profile(&MatrixProfile { + matrix, + curve: if samples.is_empty() { ToneCurve::Linear } else { ToneCurve::Samples(&samples) }, + description: description(space), + copyright: "No copyright, generated by TextureCraft", + date: [2026, 1, 1, 0, 0, 0], + }) } +#[cfg(test)] +#[path = "icc_legacy_test.rs"] +mod legacy; + #[cfg(test)] mod tests { use super::*; + #[test] + fn all_spaces_match_legacy_wire_bytes() { + for space in ColorSpace::ALL { + assert_eq!(profile(space), legacy::profile(space), "{space:?}"); + } + } fn u32_at(b: &[u8], i: usize) -> u32 { u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) diff --git a/crates/formats/src/icc_legacy_test.rs b/crates/formats/src/icc_legacy_test.rs new file mode 100644 index 00000000..47b4e600 --- /dev/null +++ b/crates/formats/src/icc_legacy_test.rs @@ -0,0 +1,124 @@ +//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small +//! (about 1.2 KiB) and readable by every colour-managed viewer and editor. +//! +//! The colorants come from the space's primaries adapted to the D50 profile connection space +//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear +//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied +//! from a colour-management library or from another profile. + +use texturecraft_texel::{ColorSpace, srgb_to_linear}; + +/// Samples of the sRGB curve table. +const CURVE_POINTS: usize = 1024; +/// The D50 white of the profile connection space. +const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249]; + +fn s15f16(v: f64) -> [u8; 4] { + ((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes() +} + +fn xyz_tag(v: [f64; 3]) -> Vec { + let mut b = b"XYZ \0\0\0\0".to_vec(); + for c in v { + b.extend_from_slice(&s15f16(c)); + } + b +} + +fn text_tag(text: &str) -> Vec { + let mut b = b"text\0\0\0\0".to_vec(); + b.extend_from_slice(text.as_bytes()); + b.push(0); + b +} + +/// `textDescriptionType` with the ASCII description only. +fn desc_tag(text: &str) -> Vec { + let mut b = b"desc\0\0\0\0".to_vec(); + b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes()); + b.extend_from_slice(text.as_bytes()); + b.push(0); + // No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler. + b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); + b +} + +fn curve_tag(space: ColorSpace) -> Vec { + let mut b = b"curv\0\0\0\0".to_vec(); + if space == ColorSpace::Srgb { + b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes()); + for i in 0..CURVE_POINTS { + let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32)); + b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes()); + } + } else { + // One entry is a gamma, u8Fixed8: 1.0 is linear. + b.extend_from_slice(&1u32.to_be_bytes()); + b.extend_from_slice(&0x0100u16.to_be_bytes()); + } + b +} + +fn description(space: ColorSpace) -> &'static str { + match space { + ColorSpace::Srgb => "sRGB (Rec.709 primaries, sRGB curve)", + ColorSpace::LinearRec709 => "Linear Rec.709 (sRGB primaries, D65)", + ColorSpace::AcesCg => "ACEScg (AP1 primaries, linear)", + ColorSpace::Aces2065 => "ACES2065-1 (AP0 primaries, linear)", + } +} + +/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones). +pub fn profile(space: ColorSpace) -> Option> { + let m = space.to_xyz_d50()?; + let column = |c: usize| [m[0][c], m[1][c], m[2][c]]; + let curve = curve_tag(space); + // The green and blue curves are the red one's entry. + let tags: [(&[u8; 4], Vec); 9] = [ + (b"desc", desc_tag(description(space))), + (b"cprt", text_tag("No copyright, generated by TextureCraft")), + (b"wtpt", xyz_tag(D50_XYZ)), + (b"rXYZ", xyz_tag(column(0))), + (b"gXYZ", xyz_tag(column(1))), + (b"bXYZ", xyz_tag(column(2))), + (b"rTRC", curve.clone()), + (b"gTRC", curve.clone()), + (b"bTRC", curve), + ]; + // Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes. + let table_end = 128 + 4 + 12 * tags.len(); + let mut offsets = Vec::new(); + let mut data: Vec = Vec::new(); + for (i, (_, bytes)) in tags.iter().enumerate() { + let shared = i >= 7; + let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() }; + offsets.push(at); + if !shared { + data.extend_from_slice(bytes); + while !data.len().is_multiple_of(4) { + data.push(0); + } + } + } + let total = table_end + data.len(); + let mut out = vec![0u8; 128]; + out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes()); + out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0 + out.get_mut(12..16)?.copy_from_slice(b"mntr"); + out.get_mut(16..20)?.copy_from_slice(b"RGB "); + out.get_mut(20..24)?.copy_from_slice(b"XYZ "); + // A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes. + out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]); + out.get_mut(36..40)?.copy_from_slice(b"acsp"); + for (k, v) in D50_XYZ.iter().enumerate() { + out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v)); + } + out.extend_from_slice(&(tags.len() as u32).to_be_bytes()); + for ((sig, bytes), at) in tags.iter().zip(&offsets) { + out.extend_from_slice(*sig); + out.extend_from_slice(&(*at as u32).to_be_bytes()); + out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); + } + out.extend_from_slice(&data); + Some(out) +} From df2c0b81db9e9eca4f714a944ff5ec7f72b7a9b1 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 15 Nov 2026 21:09:57 +0000 Subject: [PATCH 38/42] Auto: Reconcile Assets shelf with main and repair presets Keep main's shared translation integration while merging the Assets layout. Guard preset overwrites, restore legacy tab selection, filter unavailable images, and render saved image alphas. Deduplicate folder paths before allocating and render only visible saved-search rows. Validated with release UI tests, clippy, wasm, layers, panic_hunt, and offscreen window snapshots. --- crates/ui-egui/src/brush_preset_save.rs | 126 +++++++++++++++++++--- crates/ui-egui/src/docking.rs | 19 +++- crates/ui-egui/src/preview_image.rs | 71 ++++++++----- crates/ui-egui/src/shelf.rs | 32 ++++-- crates/ui-egui/src/shelf_entry.rs | 7 +- crates/ui-egui/src/shelf_folders.rs | 23 ++-- crates/ui-egui/src/shelf_panes.rs | 34 +++--- crates/ui-egui/src/shelf_preview.rs | 38 +++++-- crates/ui-egui/src/shelf_tabs.rs | 1 + crates/ui-egui/src/state.rs | 2 + crates/ui-egui/src/thumbs.rs | 130 ++++++++++++++++++++++- crates/ui-egui/src/ui_state_store.rs | 69 +++++++++++- crates/ui-egui/tests/it/shelf_panel.rs | 52 +++++++++ crates/ui-egui/tests/it/split_divider.rs | 20 ++++ 14 files changed, 540 insertions(+), 84 deletions(-) diff --git a/crates/ui-egui/src/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs index 1372e0e5..f8d76d78 100644 --- a/crates/ui-egui/src/brush_preset_save.rs +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -2,6 +2,7 @@ use egui::Ui; use serde_json::json; +use std::path::Path; use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; use crate::TextureCraftApp; @@ -13,24 +14,125 @@ const NAME_WIDTH: f32 = 110.0; /// A name field and a button that saves the current brush under that name pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { let dir = crate::user_dir("brushes"); + let name_id = ui.make_persistent_id("brush_preset_name"); + let confirm_id = ui.make_persistent_id("brush_preset_overwrite"); + let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); + let mut pending_path: Option = ui.data_mut(|data| data.get_temp(confirm_id)); + ui.horizontal(|ui| { - let name_id = ui.make_persistent_id("brush_preset_name"); - let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH)); - let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { - let path = dir.join(format!("{file}.{BRUSH_EXT}")); - // A folder that can't be made fails the save, which reports it - let _ = std::fs::create_dir_all(&dir); - if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { - new_name.clear(); - // Saving over a preset keeps its file name, so its tile must redraw - app.brushes = None; - app.thumbs.forget_saved_files(); + let path = dir.join(format!("{}.{BRUSH_EXT}", preset_file_stem(new_name.trim()))); + match std::fs::symlink_metadata(&path) { + Ok(_) => pending_path = Some(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if save_brush(app, &dir, &path) { + new_name.clear(); + } + } + Err(_) => pending_path = Some(path), } } + }); - ui.data_mut(|data| data.insert_temp(name_id, new_name)); + if let Some(path) = pending_path.clone() { + let mut replace = false; + let mut cancel = false; + egui::Window::new(tr("Replace")) + .id(ui.make_persistent_id("brush_preset_replace_dialog")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .show(ui.ctx(), |ui| { + ui.label(path.file_name().and_then(|name| name.to_str()).unwrap_or_default()); + ui.horizontal(|ui| { + replace = ui.button(tr("Replace")).clicked(); + cancel = ui.button(tr("Cancel")).clicked(); + }); + }); + if replace { + if save_brush(app, &dir, &path) { + new_name.clear(); + } + pending_path = None; + } else if cancel { + pending_path = None; + } + } + + ui.data_mut(|data| { + data.insert_temp(name_id, new_name); + data.insert_temp(confirm_id, pending_path); }); } + +/// Preserve Unicode names and encode filename punctuation without collisions +fn preset_file_stem(name: &str) -> String { + let mut stem = String::new(); + + // Six digits cover every Unicode scalar and separate adjacent escapes + for character in name.chars() { + if character.is_alphanumeric() || character == '-' || character == '_' || character == ' ' { + stem.push(character); + } else { + stem.push_str(&format!("~{:06X}", character as u32)); + } + } + let uppercase = stem.to_ascii_uppercase(); + if matches!( + uppercase.as_str(), + "CON" + | "PRN" + | "AUX" + | "NUL" + | "COM1" + | "COM2" + | "COM3" + | "COM4" + | "COM5" + | "COM6" + | "COM7" + | "COM8" + | "COM9" + | "LPT1" + | "LPT2" + | "LPT3" + | "LPT4" + | "LPT5" + | "LPT6" + | "LPT7" + | "LPT8" + | "LPT9" + ) { + stem.insert_str(0, "brush-"); + } + stem +} + +/// Save a preset and invalidate cached tiles only when the write succeeds +fn save_brush(app: &mut TextureCraftApp, dir: &Path, path: &Path) -> bool { + // A folder that cannot be made is reported by the save command + let _ = std::fs::create_dir_all(dir); + if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_none() { + return false; + } + + app.brushes = None; + app.thumbs.forget_saved_files(); + true +} + +#[cfg(test)] +mod tests { + use super::preset_file_stem; + + #[test] + fn distinct_unicode_brush_names_have_distinct_safe_file_stems() { + assert_ne!(preset_file_stem("水彩"), preset_file_stem("油画")); + assert_ne!(preset_file_stem("a/b"), preset_file_stem("a~00002Fb")); + assert_eq!(preset_file_stem("水彩"), "水彩"); + assert!(!preset_file_stem("a/b").contains('/')); + assert_eq!(preset_file_stem("CON"), "brush-CON"); + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 1b6e9b2a..d5061e17 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -136,14 +136,25 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node Workspace { use Panel::*; + + // 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; + const LAYERS_SPLIT_RATIO: f32 = 0.57; + let column = split( SplitAxis::Vertical, - SplitSize::Ratio(0.125), + SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO), tabs(&[TextureSetList]), - split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + ); + let root = split( + SplitAxis::Horizontal, + SplitSize::Ratio(ASSETS_SPLIT_RATIO), + tabs(&[Assets]), + split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column), ); - let root = - split(SplitAxis::Horizontal, SplitSize::Ratio(0.16), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.80), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); for panel in Panel::ALL { diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 16709385..7e6469d6 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -153,46 +153,69 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { preview } -/// Preview the brush along an S curve in an `n`-pixel square -pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { - let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = n as f32 * 0.11; - let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); - let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); - let mut cover = vec![0f32; n * n]; - // Stable jitter keeps the preview reproducible - let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; - let step = (b.spacing * 2.0 * radius).max(0.5); +/// 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 + 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, level: 0 }.at_radius(radius); + + // The horizontal inset and vertical wave keep the S curve inside the swatch + let curve = |t: f32| { + ( + size_px as f32 * (CURVE_HORIZONTAL_INSET + CURVE_HORIZONTAL_SPAN * t), + size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()), + ) + }; + let mut cover = vec![0f32; size_px * size_px]; + + // 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); let mut last = curve(0.0); - while t <= 1.0 && i < 2000 { + + while t <= 1.0 && i < MAX_STAMPS { let p = curve(t); travelled += (p.0 - last.0).hypot(p.1 - last.1); last = p; - t += 0.002; + t += CURVE_SAMPLE_STEP; if travelled < step { continue; } travelled = 0.0; i += 1; - let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); - let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); - let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); - let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); + 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), + ); + let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5)); let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); - let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); + 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)); for y in y0..y1 { for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); - let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; - let c = &mut cover[y * n + x]; - *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); + 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]; + *coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0)); } } } - ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) + ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect()) } /// Environment `name`'s panorama across a `size²` swatch, transparent above and below diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 0209b61c..c32de5f6 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -20,8 +20,12 @@ use crate::widgets::dnd_release; /// The gap between tiles in points (their sizes are [`ShelfView`]'s) const TILE_GAP: f32 = 2.0; -/// The gap after a grid or a list of rows, and the size of a hint under a header, in points +/// The gap after a grid or a list of rows, in points const SECTION_GAP: f32 = 6.0; +/// The gap between the type row and asset grid, in points +const TYPE_GRID_GAP: f32 = 4.0; +/// The saved material hint's font size, in points +#[cfg(not(target_arch = "wasm32"))] const HINT_SIZE: f32 = 10.0; /// The name of a saved material whose file name isn't text const SAVED_MATERIAL_NAME: &str = "material"; @@ -121,7 +125,7 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { && content && let Some(name) = unpainted_paint_layer(app) { - // Otherwise the filter seems to do nothing: it has nothing to change yet. + // Otherwise the filter seems to do nothing: it has nothing to change yet app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false); } return; @@ -259,7 +263,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { crate::shelf_folders::breadcrumb(app, ui, &paths); search_field(app, ui); crate::shelf_tabs::row(app, ui, &counts, crate::shelf_view::menu); - ui.add_space(4.0); + ui.add_space(TYPE_GRID_GAP); let tab = app.ui.shelf_tab; let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); @@ -279,6 +283,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { }); ui.separator(); } + // Saved smart materials are files in the user's library, without folders of their own let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter); @@ -413,6 +418,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { for path in shown { let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string())); + // MaterialCraft materials (sent from MaterialCraft) show a graph let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { @@ -465,7 +471,18 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry let texture = entry.thumbnail(app, ctx); let asset = entry.asset(); let session = &app.session; - let response = tile_in_view(ui, &mut app.thumbs, texture.as_ref(), || entry.preview(session), entry.label(), asset.as_ref(), view); + let response = tile_in_view( + ui, + &mut app.thumbs, + texture.as_ref(), + |thumbs| match entry { + ShelfEntry::SavedBrush(path) => Some(thumbs.saved_brush_preview(path, &session.images)), + _ => entry.preview(session), + }, + entry.label(), + asset.as_ref(), + view, + ); if selected || entry.in_use(app) { let tokens = Tokens::get(ctx); @@ -508,7 +525,7 @@ pub(crate) fn tile( label: &str, drag: Option<&Asset>, ) -> egui::Response { - tile_in_view(ui, thumbs, texture, || Some(preview()), label, drag, ShelfView::Medium) + tile_in_view(ui, thumbs, texture, |_| Some(preview()), label, drag, ShelfView::Medium) } /// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside; `preview` runs on hover @@ -516,7 +533,7 @@ fn tile_in_view( ui: &mut Ui, thumbs: &mut Thumbs, texture: Option<&egui::TextureHandle>, - preview: impl FnOnce() -> Option, + preview: impl FnOnce(&mut Thumbs) -> Option, label: &str, drag: Option<&Asset>, view: ShelfView, @@ -547,7 +564,7 @@ fn tile_in_view( painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tokens.text); } - let big = if response.hovered() { preview().and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; + let big = if response.hovered() { preview(thumbs).and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) } @@ -628,6 +645,7 @@ mod tests { let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { laid_out = Some(ui.painter().layout_job(one_line("Steel Painted Rust Leaks Extra", width, Color32::WHITE))); }); + // The font atlas upload is not under test output.textures_delta.clear(); let galley = laid_out.unwrap(); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index cad9e30a..2ea615a6 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -62,7 +62,8 @@ impl ShelfEntry { .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush); - built_in.chain(saved).chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() + let images = app.session.doc.resources.keys().filter(|name| app.session.images.contains_key(*name)).cloned().map(ShelfEntry::Image); + built_in.chain(saved).chain(images).collect() } /// The tab that lists the asset @@ -156,7 +157,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), - ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path), + ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path, &app.session.images), ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), @@ -174,7 +175,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), - ShelfEntry::SavedBrush(path) => ShelfPreview::SavedBrush(path.clone()), + ShelfEntry::SavedBrush(path) => ShelfPreview::saved_brush(path, &session.images), ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), ShelfEntry::Environment(name) => ShelfPreview::Environment(name), diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs index 317d109b..e581f480 100644 --- a/crates/ui-egui/src/shelf_folders.rs +++ b/crates/ui-egui/src/shelf_folders.rs @@ -1,5 +1,7 @@ //! The shelf's library folders ([`ShelfEntry::path`]) for the breadcrumb above the search and the Filter by path tree +use std::collections::BTreeSet; + use egui::{RichText, Ui}; use crate::TextureCraftApp; @@ -13,10 +15,9 @@ const ARROW_SCALE: f32 = 0.8; /// The folder paths of `entries`, each a library id then folder names pub(crate) fn paths<'a>(entries: impl IntoIterator) -> Vec> { - let mut paths: Vec> = entries.into_iter().map(|entry| entry.path().into_iter().map(str::to_string).collect()).collect(); - paths.sort(); - paths.dedup(); - paths + let unique_paths: BTreeSet> = entries.into_iter().map(ShelfEntry::path).collect(); + + unique_paths.into_iter().map(|segments| segments.into_iter().map(str::to_string).collect()).collect() } /// `paths` and every library, even one with nothing in it (the picker always lists them all) @@ -29,18 +30,19 @@ pub(crate) fn with_every_library(mut paths: Vec>) -> Vec /// The folders right below `prefix` (libraries in their usual order, folders by name) pub(crate) fn children(paths: &[Vec], prefix: &[String]) -> Vec { - let mut out: Vec = Vec::new(); + let mut children = Vec::new(); for path in paths.iter().filter(|path| path.len() > prefix.len() && path.starts_with(prefix)) { - if let Some(next) = path.get(prefix.len()) - && !out.contains(next) + if let Some(child) = path.get(prefix.len()) + && !children.contains(child) { - out.push(next.clone()); + children.push(child.clone()); } } + if prefix.is_empty() { - out.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library)); + children.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library)); } - out + children } /// A folder's shown name: libraries by their name, folders (type and category names) translated @@ -86,6 +88,7 @@ pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec, image: Option> }, /// An image resource by name Image(String, Arc), /// A built-in lighting environment's panorama @@ -43,6 +45,13 @@ pub enum ShelfPreview { } impl ShelfPreview { + /// Resolve a saved brush's image alpha while the project images are available + pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self { + let settings = read_saved_brush(path); + let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)).cloned(); + ShelfPreview::SavedBrush { path: path.to_path_buf(), settings, image } + } + /// Smart materials preview on the orb, plain materials on a sphere pub fn material(id: &'static str) -> ShelfPreview { match materials::find(id) { @@ -61,7 +70,7 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), - ShelfPreview::SavedBrush(path) => format!("saved-brush:{}", path.display()), + ShelfPreview::SavedBrush { path, .. } => format!("saved-brush:{}", path.display()), ShelfPreview::Image(name, _) => format!("image:{name}"), ShelfPreview::Environment(name) => format!("environment:{name}"), } @@ -76,8 +85,14 @@ impl ShelfPreview { ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), - ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), - ShelfPreview::SavedBrush(path) => Some(stroke_preview(&saved_brush(path)?, size)), + ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size, None)), + ShelfPreview::SavedBrush { settings, image, .. } => { + let settings = settings.as_ref()?; + if settings.alpha_image.is_some() && image.is_none() { + return None; + } + Some(stroke_preview(settings, size, image.as_deref())) + } ShelfPreview::Image(_, image) => Some(image_preview(image, size)), ShelfPreview::Environment(name) => Some(environment_image(name, size)), } @@ -86,7 +101,7 @@ impl ShelfPreview { /// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files) #[cfg(not(target_arch = "wasm32"))] -fn saved_brush(path: &std::path::Path) -> Option { +pub(crate) fn read_saved_brush(path: &std::path::Path) -> Option { use std::io::Read as _; let mut bytes = Vec::new(); @@ -99,7 +114,7 @@ fn saved_brush(path: &std::path::Path) -> Option { } #[cfg(target_arch = "wasm32")] -fn saved_brush(_: &std::path::Path) -> Option { +pub(crate) fn read_saved_brush(_: &std::path::Path) -> Option { None } @@ -150,4 +165,15 @@ mod tests { assert_eq!(on_the_orb, material.smart, "{}", material.id); } } + + #[test] + fn saved_brush_preview_uses_its_project_image_alpha() { + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + let transparent = Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[1.0, 1.0, 1.0, 0.0]; 4], srgb: false }); + let preview = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings.clone()), image: Some(transparent) }; + + assert!(preview.image(64).is_some_and(|image| image.pixels.iter().all(|pixel| pixel.r() == 0))); + let missing = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings), image: None }; + assert!(missing.image(64).is_none()); + } } diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs index cb620500..5898a943 100644 --- a/crates/ui-egui/src/shelf_tabs.rs +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -18,6 +18,7 @@ pub(crate) const NO_TYPE: usize = TABS.len(); /// The row, then `trailing` at its right end; `counts[i]` is how many assets of `TABS[i]` match the search pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) { let size = ui.spacing().interact_size.y; + // The type icons and one icon after them let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP); let mut picked = app.ui.shelf_tab.min(NO_TYPE); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index a8b43813..70748428 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -442,7 +442,9 @@ mod tests { ui.keymap.insert("file.save".into(), "F5".into()); let mut layout = UiState::default(); layout.dock.close(crate::docking::Panel::Assets); + ui.adopt_layout(layout); + assert!(!ui.dock.is_open(crate::docking::Panel::Assets)); assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); assert_eq!(ui.export.preset, "Mine"); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 4c7bab4b..75693775 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -3,11 +3,14 @@ //! Smart masks, smart materials and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; +use texturecraft_engine::compose::{ImageRes, ImageStore}; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::paint::presets::BrushPreset; -use texturecraft_engine::paint::{BrushAlpha, alphas}; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::texel::linear_to_srgb; use crate::preview_image::{aces, image_preview, shade}; @@ -36,6 +39,8 @@ const BIG_PREVIEWS_KEPT: usize = 32; pub struct Thumbs { /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, + /// Parsed saved brushes and weak project-image identities, reused by tile and hover previews + saved_brush_previews: HashMap, Option>)>, images: HashMap, /// (frame, thumbnails rendered in it) budget: (u64, usize), @@ -200,6 +205,7 @@ impl Thumbs { self.shelf.retain(|key, _| current(key)); self.rendered.retain(|key, _| current(key)); self.big_shown.retain(current); + self.saved_brush_previews.clear(); } /// Smart mask thumbnail; None until the worker returns it @@ -228,8 +234,43 @@ impl Thumbs { } /// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable - pub fn saved_brush(&mut self, ctx: &egui::Context, path: &std::path::Path) -> Option { - self.shelf(ctx, ShelfPreview::SavedBrush(path.to_path_buf()), SWATCH_PX) + pub fn saved_brush(&mut self, ctx: &egui::Context, path: &Path, images: &ImageStore) -> Option { + let key = format!("saved-brush:{}", path.display()); + let cached_preview = self.saved_brush_previews.contains_key(path).then(|| self.saved_brush_preview(path, images)); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); + } + if !self.spend_budget(ctx, 1) { + return None; + } + + let preview = cached_preview.unwrap_or_else(|| self.saved_brush_preview(path, images)); + let image = preview.image(SWATCH_PX).unwrap_or_else(|| ColorImage::filled([SWATCH_PX, SWATCH_PX], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) + } + + /// Reuse parsed settings until refresh; rebuild previews when their project image changes + pub fn saved_brush_preview(&mut self, path: &Path, images: &ImageStore) -> ShelfPreview { + let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None)); + let (settings, previous_image) = cached; + let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)); + let image_changed = match (previous_image.as_ref(), image) { + (Some(previous), Some(current)) => previous.upgrade().is_none_or(|previous| !Arc::ptr_eq(&previous, current)), + (None, None) => false, + _ => true, + }; + *previous_image = image.map(Arc::downgrade); + if image_changed { + let key = format!("saved-brush:{}", path.display()); + let rendered_prefix = format!("{key}@"); + self.shelf.remove(&key); + self.rendered.retain(|rendered, _| !rendered.starts_with(&rendered_prefix)); + self.big_shown.retain(|rendered| !rendered.starts_with(&rendered_prefix)); + } + + ShelfPreview::SavedBrush { path: path.to_path_buf(), settings: settings.clone(), image: image.cloned() } } /// A brush preset's stroke along an S curve @@ -296,3 +337,86 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) { } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + + #[test] + fn saved_brush_file_read_waits_for_the_thumbnail_budget() { + let path = std::env::temp_dir().join(format!("texturecraft-brush-budget-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap(); + let context = egui::Context::default(); + let mut thumbs = Thumbs::default(); + thumbs.budget = (context.cumulative_pass_nr(), PER_FRAME); + + assert!(thumbs.saved_brush(&context, &path, &ImageStore::new()).is_none()); + assert!(thumbs.saved_brush_previews.is_empty(), "a deferred thumbnail has not read its file"); + + std::fs::remove_file(&path).unwrap(); + } + + #[test] + fn saved_brush_settings_are_read_once_until_refresh() { + let path = + std::env::temp_dir().join(format!("texturecraft-brush-preview-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap(); + let mut thumbs = Thumbs::default(); + let images = ImageStore::new(); + + assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. })); + std::fs::remove_file(&path).unwrap(); + assert!( + matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. }), + "cached settings avoid a second file read" + ); + + thumbs.forget_saved_files(); + assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: None, .. }), "refresh reads the file again"); + } + + #[test] + fn saved_brush_cache_releases_old_images_on_change_and_refresh() { + const IMAGE_SIDE: u32 = 512; + const IMAGE_TEXELS: usize = IMAGE_SIDE as usize * IMAGE_SIDE as usize; + const IMAGE_BYTES: usize = IMAGE_TEXELS * std::mem::size_of::<[f32; 4]>(); + + let mut thumbs = Thumbs::default(); + let first_path = PathBuf::from("first.tcbrush"); + let second_path = PathBuf::from("second.tcbrush"); + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + let old_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[1.0; 4]; IMAGE_TEXELS], srgb: false }); + let other_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.5; 4]; IMAGE_TEXELS], srgb: false }); + let old_weak = Arc::downgrade(&old_image); + let other_weak = Arc::downgrade(&other_image); + assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); + assert!(other_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); + + thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None)); + thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None)); + let mut images: ImageStore = [("alpha.png".into(), old_image.clone())].into(); + drop(thumbs.saved_brush_preview(&first_path, &images)); + images.insert("alpha.png".into(), other_image.clone()); + drop(thumbs.saved_brush_preview(&second_path, &images)); + drop(old_image); + drop(other_image); + assert!(old_weak.upgrade().is_none(), "cached settings do not retain a replaced image"); + assert!(other_weak.upgrade().is_some(), "the project still owns its current image"); + eprintln!( + "saved brush cache after first replacement: 0 of {IMAGE_BYTES} old image bytes retained, {} current image strong owners", + Arc::strong_count(&images["alpha.png"]) + ); + + let replacement = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.0; 4]; IMAGE_TEXELS], srgb: false }); + images.insert("alpha.png".into(), replacement); + drop(thumbs.saved_brush_preview(&first_path, &images)); + assert!(other_weak.upgrade().is_none(), "another saved brush does not retain the old project image"); + eprintln!("saved brush cache after second replacement: 0 of {IMAGE_BYTES} previous image bytes retained"); + + thumbs.forget_saved_files(); + assert!(thumbs.saved_brush_previews.is_empty(), "refresh releases parsed brush settings"); + } +} diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index dcce58df..7bd1a539 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -13,6 +13,9 @@ const STORAGE_STEM: &str = "ui"; /// eframe storage key under which earlier builds kept the UI state, as RON const RON_STORAGE_KEY: &str = "ui"; +/// Textures moved from index 8 to index 6 when procedurals joined that type +const LEGACY_TEXTURES_TAB: usize = 8; +const TEXTURES_TAB: usize = 6; /// Maximum encoded UI state size for both reads and writes; typical states are a few kilobytes const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; @@ -65,7 +68,7 @@ impl UiStateStore { return None; } - let ui = serde_json::from_slice::(&bytes).ok(); + let ui = decode_json_ui(&bytes); if !ui.as_ref().is_some_and(fully_read) { self.unreadable = Some((bytes, "json")); } @@ -75,7 +78,10 @@ impl UiStateStore { /// Preserve the original RON when decoding loses either dock, even if other settings load fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option { let text = storage.get_string(RON_STORAGE_KEY)?; - let ui = eframe::get_value::(storage, RON_STORAGE_KEY); + let mut ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if let Some(ui) = &mut ui { + migrate_shelf_tab(ui, ron_has_shelf_path(&text)); + } if !ui.as_ref().is_some_and(fully_read) { self.unreadable = Some((text.into_bytes(), "ron")); } @@ -158,9 +164,52 @@ impl UiStateStore { } } +/// Old saved states have no shelf path, so their former Textures index needs remapping +fn migrate_shelf_tab(ui: &mut UiState, has_shelf_path: bool) { + if ui.shelf_tab == LEGACY_TEXTURES_TAB && !has_shelf_path { + ui.shelf_tab = TEXTURES_TAB; + } +} + +/// Decode JSON settings and map the old Textures index only when its new fields are absent +fn decode_json_ui(bytes: &[u8]) -> Option { + let mut ui = serde_json::from_slice::(bytes).ok()?; + if ui.shelf_tab == LEGACY_TEXTURES_TAB { + let has_shelf_path = serde_json::from_slice::(bytes) + .ok() + .and_then(|state| state.as_object().map(|fields| fields.contains_key("shelf_path"))) + .unwrap_or(true); + migrate_shelf_tab(&mut ui, has_shelf_path); + } + Some(ui) +} + +/// Ignore user text while looking for the field in legacy RON settings +fn ron_has_shelf_path(text: &str) -> bool { + let bytes = text.as_bytes(); + let mut quoted = false; + let mut escaped = false; + for (index, byte) in bytes.iter().enumerate() { + if quoted { + if escaped { + escaped = false; + } else if *byte == b'\\' { + escaped = true; + } else if *byte == b'"' { + quoted = false; + } + } else if *byte == b'"' { + quoted = true; + } else if bytes[index..].starts_with(b"shelf_path:") && (index == 0 || matches!(bytes[index - 1], b',' | b'(' | b' ' | b'\n')) { + return true; + } + } + false +} + /// The UI state saved in `file`, if it reads pub fn read(file: &Path) -> Option { - serde_json::from_slice(&read_bytes(file).ok()?).ok() + decode_json_ui(&read_bytes(file).ok()?) } /// eframe's browser storage reports write failures only through logging, so verify before discarding old settings @@ -311,6 +360,20 @@ pub(crate) mod tests { assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); } + #[test] + fn legacy_ron_textures_index_migrates_to_the_combined_type() { + let mut storage = MemoryStorage::default(); + let legacy = include_str!("../tests/fixture/ui_state_before_json.ron") + .replace("shelf_tab:0", "shelf_tab:8") + .replace("shelf_filter:\"\"", "shelf_filter:\"shelf_path:\""); + assert!(legacy.contains("shelf_tab:8") && !ron_has_shelf_path(&legacy)); + storage.values.insert(RON_STORAGE_KEY.into(), legacy); + + let loaded = UiStateStore::default().load(Some(&storage)).expect("the legacy state loads"); + + assert_eq!(loaded.shelf_tab, TEXTURES_TAB); + } + #[test] fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { let folder = test_folder("unreadable"); diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index e241293f..a33068b7 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -7,6 +7,7 @@ use texturecraft_engine::core::project::ENVIRONMENTS; use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::saved_search::SavedSearch; use texturecraft_ui_egui::shelf_view::ShelfView; /// The reference's capture window: its Assets panel shows four columns there @@ -86,6 +87,17 @@ fn the_search_narrows_the_picked_type_and_greys_types_without_matches() { assert!(harness.query_by_label(material.label).is_some()); } +#[test] +fn unavailable_project_images_do_not_make_textures_match() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().session.doc.resources.insert("unavailable-preview.png".into(), vec![0].into()); + harness.state_mut().ui.shelf_filter = "unavailable-preview.png".into(); + harness.run_steps(3); + + assert!(button(&harness, "Textures").accesskit_node().is_disabled()); + assert!(harness.query_by_label("unavailable-preview.png").is_none()); +} + #[test] fn the_breadcrumb_arrow_picks_a_library() { let mut harness = shelf(REFERENCE_WINDOW); @@ -184,6 +196,46 @@ fn filter_by_path_picks_a_folder() { assert_eq!(harness.state().ui.shelf_path, ["starter"]); } +#[test] +fn many_saved_searches_keep_the_path_filter_reachable() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.state_mut().ui.shelf_saved_searches = (0..100) + .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .collect(); + harness.run_steps(3); + + let heading = harness.get_by_label("FILTER BY PATH").rect(); + assert!(heading.bottom() < NARROW_WINDOW.y, "the path pane heading stays on screen: {heading:?}"); + assert!(harness.query_by_label("Starter assets").is_some(), "the folder tree remains reachable"); +} + +#[test] +fn a_long_saved_search_list_can_select_the_last_query() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_saved_searches = (0..1000) + .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .collect(); + harness.run_steps(3); + assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); + + harness.get_by_label("search 0").hover(); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -50_000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(3); + harness.get_by_label("search 999").click(); + harness.run_steps(2); + + assert_eq!(harness.state().ui.shelf_filter, "filter 999"); +} + #[test] fn a_narrow_panel_keeps_the_toolbar_and_folds_the_type_row() { let mut harness = shelf(NARROW_WINDOW); diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index e0a487fc..4e8c0364 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -157,6 +157,26 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { assert_eq!(restored.split_ratio, 0.5); } +#[test] +fn old_textures_tab_index_migrates_without_changing_new_all_types() { + let mut storage = MemoryStorage::default(); + let mut state = UiState::default(); + state.shelf_tab = 8; + UiStateStore::default().save(&state, &mut storage); + + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(8)); + + let mut legacy: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + legacy.as_object_mut().unwrap().remove("shelf_path"); + legacy.as_object_mut().unwrap().insert("shelf_filter".into(), "shelf_path".into()); + storage.0.insert("ui.json".into(), legacy.to_string()); + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(6)); + + state.shelf_tab = 0; + UiStateStore::default().save(&state, &mut storage); + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(0)); +} + #[test] fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { // Zoomed in, a 2D sliver needs a zoom far past the one the view starts with From 7ad3f7070124e8367341d0d6fde0e12d56e027e2 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 15 Nov 2026 21:21:52 +0000 Subject: [PATCH 39/42] Auto: Preserve path history and clean up unavailable tools Reject pending path undo/redo during quick-mask editing without consuming history. Finish active strokes and polygon-fill boxes when tools become unavailable in either viewport. Hide unavailable tool properties for Paint and Path effects. Add regression tests for history preservation, gesture cleanup, and effect tool controls. --- crates/engine/src/path_tool.rs | 28 ++++++++++++++ crates/ui-egui/src/dock.rs | 8 +++- crates/ui-egui/src/viewport.rs | 40 ++++++++++++++++++++ crates/ui-egui/tests/it/tool_availability.rs | 31 +++++++++++++++ 4 files changed, 105 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 596c8749..745e3197 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -669,6 +669,11 @@ impl Session { let from = if back { &self.path_steps.0 } else { &self.path_steps.1 }; let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) }; + // Returning false here would let undo/redo consume document history instead. + if self.quick_mask.editing { + return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); + } + let path = &mut self.tool.path; let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() }); if let Err(error) = self.path_live() { @@ -1086,6 +1091,29 @@ mod tests { assert_eq!(changed_tiles(&before, &after, LayerId(8)), BTreeSet::new()); } + #[test] + fn quick_mask_preserves_pending_path_undo_and_redo() { + let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + session.path_checkpoint(); + session.tool.path.points[0].y = 0.3; + session.path_live().unwrap(); + for back in [true, false] { + let curve = session.tool.path.clone(); + let steps = (session.path_steps.0.len(), session.path_steps.1.len()); + let history = (session.history_labels(), session.redo_labels()); + let pixels = session.doc.pixels.clone(); + session.quick_mask.editing = true; + assert!(if back { session.undo() } else { session.redo() }.is_err()); + assert!(curve.same_curve(&session.tool.path)); + assert_eq!(steps, (session.path_steps.0.len(), session.path_steps.1.len())); + assert_eq!(history, (session.history_labels(), session.redo_labels())); + assert_eq!(format!("{:?}", pixels), format!("{:?}", session.doc.pixels)); + session.quick_mask.editing = false; + if back { session.undo() } else { session.redo() }.unwrap(); + } + } + #[test] fn point_checkpoints_skip_noops_and_bound_retained_points() { let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ad67d1fb..848ed309 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2510,7 +2510,9 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") }; ui.label(RichText::new(hint).color(tokens.text_dim)); - tool_properties(app, ui); + if app.session.tool_usable(app.session.tool.tool) { + tool_properties(app, ui); + } } EffectKind::Path(paths) => { ui.label( @@ -2533,7 +2535,9 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe } }); } - tool_properties(app, ui); + if app.session.tool_usable(app.session.tool.tool) { + tool_properties(app, ui); + } } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index b76a1454..65c82fb0 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -54,6 +54,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { crate::toolbar::paint_bar(app, ui); } + finish_unavailable_tool_gestures(app); crate::id_color_pick::IdColorPick::end_when_stale(app); let tokens = Tokens::get(ui.ctx()); let aux_view = match app.session.view { @@ -1545,6 +1546,18 @@ fn tool_acts(app: &TextureCraftApp) -> bool { app.ui.mode == crate::state::Mode::Painting && app.session.tool_usable(app.session.tool.tool) } +/// Both views must close gestures even when the selection disables their input handlers. +fn finish_unavailable_tool_gestures(app: &mut TextureCraftApp) { + if !tool_acts(app) { + if app.session.stroke_active() + && let Err(error) = app.session.end_stroke() + { + app.toast(error.to_string(), true); + } + app.session.end_polygon_fill_box(); + } +} + /// Tools that paint with the brush (and show its cursor). fn brush_tool(t: Tool) -> bool { matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) @@ -1996,6 +2009,33 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t mod tests { use super::*; + #[test] + fn unavailable_tools_finish_strokes_and_box_fills() { + use texturecraft_engine::{StackTarget, core::LayerId, geom::primitives}; + + for tool in [Tool::Paint, Tool::PolygonFill] { + let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap(); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.session.tool.tool = tool; + let history = app.session.history_labels().len(); + if tool == Tool::Paint { + app.session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + assert!(app.session.stroke_active()); + } else { + assert!(app.session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0); + } + app.session.target = StackTarget::Effect(LayerId(u64::MAX)); + assert!(!tool_acts(app)); + finish_unavailable_tool_gestures(app); + assert!(!app.session.stroke_active()); + assert_eq!(app.session.history_labels().len(), history + 1); + assert_eq!(app.session.end_polygon_fill_box(), 0, "the interrupted box is already closed"); + finish_unavailable_tool_gestures(app); + assert_eq!(app.session.history_labels().len(), history + 1, "cleanup records the gesture only once"); + } + } + #[test] fn stored_surfaces_release_after_a_frame_without_paths() { use texturecraft_engine::{core::EffectKind, execute, geom::primitives}; diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index 094e858a..77fd888f 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -237,3 +237,34 @@ fn tool_availability_snapshots() { harness.state_mut().ui.mode = Mode::Rendering; save(&mut harness, "rendering"); } + +#[test] +fn unavailable_effect_tools_hide_their_properties() { + for path in [false, true] { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let layer = add_layer(session, "layer.add.paint"); + select(session, layer, json!("content")); + let (effect, usable, blocked) = if path { + let result = execute(session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + (result["committed"]["effect"].as_u64().unwrap(), Tool::Path, Tool::Paint) + } else { + execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); + let result = execute(session, "effect.add.paint", &json!({"layer": layer, "target": "mask"})).unwrap(); + (result["effect"].as_u64().unwrap(), Tool::Paint, Tool::Smudge) + }; + select(session, layer, json!(effect)); + session.tool.tool = usable; + harness.run_steps(4); + assert!(shows_text(&harness, "Size")); + harness.state_mut().session.tool.tool = blocked; + harness.run_steps(4); + assert!(!shows_text(&harness, "Size"), "unavailable effect tools hide brush controls"); + if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") { + let directory = std::path::PathBuf::from(directory); + std::fs::create_dir_all(&directory).unwrap(); + let name = if path { "unavailable-path-effect.png" } else { "unavailable-mask-paint-effect.png" }; + harness.render().unwrap().save(directory.join(name)).unwrap(); + } + } +} From 1683a2c63c8c6f473dd7baf99ed626cc7e0db17b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:03:57 -0500 Subject: [PATCH 40/42] Pin shared ICC writer to merged prerequisite --- Cargo.lock | 2 +- crates/formats/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c6801d15..5435da3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,7 +758,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6c09292724ec8dbe32950cb5042cfaa2a614fb6c#6c09292724ec8dbe32950cb5042cfaa2a614fb6c" +source = "git+https://github.com/storytold/craft-libs?rev=272a095b61257917693da3d09f2f8ecccd7f0295#272a095b61257917693da3d09f2f8ecccd7f0295" dependencies = [ "md-5", "rayon", diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 795e066e..662032fc 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # ICC v2 serialization prerequisite: craft-libs#1735; app colour policy stays local. -craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6c09292724ec8dbe32950cb5042cfaa2a614fb6c" } +craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "272a095b61257917693da3d09f2f8ecccd7f0295" } craft-materialx = { workspace = true } craft-mesh = { workspace = true } craft-mcmat = { workspace = true } From b34130c6d84bd47d3dc75bcbe652da10b8b79f6a Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 15 Nov 2026 22:27:16 +0000 Subject: [PATCH 41/42] Auto: Preserve 2D stroke endpoints after forced completion Update the Shift-click line origin when an unavailable tool forces a 2D stroke to finish successfully. Clear pending endpoints after completion or cancellation to prevent reuse by later gestures. Add a regression test for Shift-click following forced stroke completion. --- crates/ui-egui/src/viewport.rs | 40 ++++++++++++++++++----- crates/ui-egui/tests/it/shift_lines_2d.rs | 37 +++++++++++++++++++++ 2 files changed, 68 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 65c82fb0..a610d07f 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -54,7 +54,18 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { crate::toolbar::paint_bar(app, ui); } - finish_unavailable_tool_gestures(app); + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); + // A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture. + let pending_2d_endpoint = if !app.session.stroke_active() || !tool_acts(app) { + ui.data_mut(|data| { + let endpoint = data.get_temp(stroke_end); + data.remove::(stroke_end); + endpoint + }) + } else { + None + }; + finish_unavailable_tool_gestures(app, pending_2d_endpoint); crate::id_color_pick::IdColorPick::end_when_stale(app); let tokens = Tokens::get(ui.ctx()); let aux_view = match app.session.view { @@ -1547,12 +1558,17 @@ fn tool_acts(app: &TextureCraftApp) -> bool { } /// Both views must close gestures even when the selection disables their input handlers. -fn finish_unavailable_tool_gestures(app: &mut TextureCraftApp) { +fn finish_unavailable_tool_gestures(app: &mut TextureCraftApp, pending_2d_endpoint: Option) { if !tool_acts(app) { - if app.session.stroke_active() - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); + if app.session.stroke_active() { + match app.session.end_stroke() { + Ok(()) => { + if let Some(endpoint) = pending_2d_endpoint { + app.last_paint_uv = Some(endpoint); + } + } + Err(error) => app.toast(error.to_string(), true), + } } app.session.end_polygon_fill_box(); } @@ -1946,7 +1962,13 @@ fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, if response.clicked_by(PointerButton::Primary) || response.drag_stopped_by(PointerButton::Primary) { let finishing = app.session.stroke_active(); match app.session.end_stroke() { - Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)), + Ok(()) if finishing => { + app.last_paint_uv = ui.data_mut(|data| { + let endpoint = data.get_temp(stroke_end); + data.remove::(stroke_end); + endpoint + }); + } Ok(()) => {} Err(error) => app.toast(error.to_string(), true), } @@ -2027,11 +2049,11 @@ mod tests { } app.session.target = StackTarget::Effect(LayerId(u64::MAX)); assert!(!tool_acts(app)); - finish_unavailable_tool_gestures(app); + finish_unavailable_tool_gestures(app, None); assert!(!app.session.stroke_active()); assert_eq!(app.session.history_labels().len(), history + 1); assert_eq!(app.session.end_polygon_fill_box(), 0, "the interrupted box is already closed"); - finish_unavailable_tool_gestures(app); + finish_unavailable_tool_gestures(app, None); assert_eq!(app.session.history_labels().len(), history + 1, "cleanup records the gesture only once"); } } diff --git a/crates/ui-egui/tests/it/shift_lines_2d.rs b/crates/ui-egui/tests/it/shift_lines_2d.rs index a6e6175d..08537f4f 100644 --- a/crates/ui-egui/tests/it/shift_lines_2d.rs +++ b/crates/ui-egui/tests/it/shift_lines_2d.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use serde_json::json; use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::{StackTarget, core::LayerId}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::ViewLayout; @@ -179,6 +180,42 @@ fn a_stroke_cancelled_with_escape_leaves_the_line_start_where_it_was() { assert_shift_click_draws_a_line(|harness| cancelled_drag(harness, CANCELLED_DRAG_FROM, CANCELLED_DRAG_TO)); } +#[test] +fn a_forced_2d_completion_moves_the_next_line_start() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + + harness.hover_at(CANCELLED_DRAG_FROM); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: CANCELLED_DRAG_FROM, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(CANCELLED_DRAG_TO); + harness.run_steps(2); + assert!(harness.state().session.stroke_active(), "the 2D drag is still active"); + + harness.state_mut().session.target = StackTarget::Effect(LayerId(u64::MAX)); + harness.run_steps(1); + assert!(!harness.state().session.stroke_active(), "the unavailable tool finishes the drag"); + harness.state_mut().session.target = StackTarget::Content; + harness.event(Event::PointerButton { pos: CANCELLED_DRAG_TO, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + let (before_line, width) = alpha(&harness); + click(&mut harness, SECOND_CLICK, true); + let (after_line, _) = alpha(&harness); + let line = added(&before_line, &after_line); + + let dab_centre = |point| { + let mut reference = uv_view_app(); + let (blank, width) = alpha(&reference); + click(&mut reference, point, false); + let (painted, _) = alpha(&reference); + centre(&added(&blank, &painted), width) + }; + let expected_middle = (dab_centre(CANCELLED_DRAG_TO) + dab_centre(SECOND_CLICK)) * 0.5; + assert!(painted_at(&line, width, expected_middle), "Shift+click starts at the forced completion endpoint"); +} + #[test] fn a_new_project_does_not_reuse_the_previous_projects_line_start() { let mut harness = uv_view_app(); From 000361d4e150e5354459e90b8f846a05c2a62b21 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 15 Nov 2026 23:27:06 +0000 Subject: [PATCH 42/42] Auto: Reject stale saved-brush preview results --- crates/ui-egui/src/thumbs.rs | 89 ++++++++++++++++++++++++++++++------ 1 file changed, 75 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index d7f91c5b..9a7bda37 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -36,13 +36,18 @@ const STENCIL_MAX_SIZE_PX: f32 = 1024.0; /// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; +/// Parsed settings, weak image identity and preview revision for a saved brush +type SavedBrushCacheEntry = (Option, Option>, u64); + /// The shelf's and the brush panel's preview textures #[derive(Default)] pub struct Thumbs { /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, - /// Parsed saved brushes and weak project-image identities, reused by tile and hover previews - saved_brush_previews: HashMap, Option>)>, + /// Parsed settings, weak image identity and preview revision for each saved brush + saved_brush_previews: HashMap, + /// Refresh generation; queued results from earlier generations must not match new requests + saved_files_epoch: u64, images: HashMap, TextureHandle)>, images_revision: Option, /// (frame, thumbnails rendered in it) @@ -150,7 +155,7 @@ impl Thumbs { fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { self.receive(ctx); - let key = worker_key(&preview, size_px); + let key = self.worker_key(&preview, size_px); if !self.rendered.contains_key(&key) && self.may_request(ctx) { let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); @@ -199,7 +204,7 @@ impl Thumbs { /// Request a hover preview and evict the least recently shown beyond the cache limit pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { - let key = worker_key(&preview, size_px); + let key = self.worker_key(&preview, size_px); self.big_shown.retain(|k| *k != key); self.big_shown.push_back(key); while self.big_shown.len() > BIG_PREVIEWS_KEPT { @@ -214,7 +219,7 @@ impl Thumbs { /// The big preview of `preview` if the worker already rendered it (requests nothing) pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { self.receive(ctx); - self.ready(&worker_key(preview, size_px)) + self.ready(&self.worker_key(preview, size_px)) } /// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres @@ -227,6 +232,7 @@ impl Thumbs { /// Drop the thumbnails and hover previews of the user's saved files, which may have changed on disk pub fn forget_saved_files(&mut self) { + self.saved_files_epoch = self.saved_files_epoch.wrapping_add(1); let current = |key: &String| !key.starts_with(SAVED_FILE_KEY_PREFIX); self.shelf.retain(|key, _| current(key)); self.rendered.retain(|key, _| current(key)); @@ -279,8 +285,8 @@ impl Thumbs { /// Reuse parsed settings until refresh; rebuild previews when their project image changes pub fn saved_brush_preview(&mut self, path: &Path, images: &ImageStore) -> ShelfPreview { - let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None)); - let (settings, previous_image) = cached; + let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None, 0)); + let (settings, previous_image, revision) = cached; let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)); let image_changed = match (previous_image.as_ref(), image) { (Some(previous), Some(current)) => previous.upgrade().is_none_or(|previous| !Arc::ptr_eq(&previous, current)), @@ -289,6 +295,7 @@ impl Thumbs { }; *previous_image = image.map(Arc::downgrade); if image_changed { + *revision = revision.wrapping_add(1); let key = format!("saved-brush:{}", path.display()); let rendered_prefix = format!("{key}@"); self.shelf.remove(&key); @@ -299,17 +306,23 @@ impl Thumbs { ShelfPreview::SavedBrush { path: path.to_path_buf(), settings: settings.clone(), image: image.cloned() } } + /// A saved-brush key also identifies the refresh and image version of its request + fn worker_key(&self, preview: &ShelfPreview, size_px: usize) -> String { + let key = format!("{}@{size_px}", preview.key()); + if let ShelfPreview::SavedBrush { path, .. } = preview { + let revision = self.saved_brush_previews.get(path).map_or(0, |(_, _, revision)| *revision); + format!("{key}#{}:{revision}", self.saved_files_epoch) + } else { + key + } + } + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// The key of a worker-rendered preview: one per asset and size -fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { - format!("{}@{size_px}", preview.key()) -} - /// 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(); @@ -369,8 +382,56 @@ mod tests { use super::*; use std::sync::atomic::{AtomicUsize, Ordering}; + use crate::orb_shape::OrbShape; + static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + #[test] + fn saved_brush_refresh_discards_old_worker_result() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let preview = ShelfPreview::SavedBrush { path: PathBuf::from("refreshed.tcbrush"), settings: None, image: None }; + + assert!(thumbs.big(&ctx, preview.clone(), 8).is_none()); + thumbs.forget_saved_files(); + assert!(thumbs.big(&ctx, preview.clone(), 8).is_none()); + + let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") }; + let old_key = results[0].0.clone(); + let current_key = results[1].0.clone(); + *results = vec![(current_key, None), (old_key, Some(ColorImage::filled([8, 8], Color32::RED)))]; + + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, &preview, 8).is_none(), "an old completion must not replace the current failed result"); + } + + #[test] + fn saved_brush_image_replacement_preserves_current_worker_result() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let path = PathBuf::from("changed-alpha.tcbrush"); + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + thumbs.saved_brush_previews.insert(path.clone(), (Some(settings), None, 0)); + let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + let mut images: ImageStore = [("alpha.png".into(), image(0.2))].into(); + + let old_preview = thumbs.saved_brush_preview(&path, &images); + assert!(thumbs.big(&ctx, old_preview, 8).is_none()); + images.insert("alpha.png".into(), image(0.8)); + let current_preview = thumbs.saved_brush_preview(&path, &images); + assert!(thumbs.big(&ctx, current_preview.clone(), 8).is_none()); + + let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") }; + let old_key = results[0].0.clone(); + let current_key = results[1].0.clone(); + *results = vec![(current_key, Some(ColorImage::filled([8, 8], Color32::RED))), (old_key, None)]; + + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, ¤t_preview, 8).is_some(), "the current completion must survive an old failure"); + } + #[test] fn saved_brush_file_read_waits_for_the_thumbnail_budget() { let path = std::env::temp_dir().join(format!("texturecraft-brush-budget-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); @@ -421,8 +482,8 @@ mod tests { assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); assert!(other_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); - thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None)); - thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None)); + thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None, 0)); + thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None, 0)); let mut images: ImageStore = [("alpha.png".into(), old_image.clone())].into(); drop(thumbs.saved_brush_preview(&first_path, &images)); images.insert("alpha.png".into(), other_image.clone());