From e0404360e4cf7f7cd1cd7a59ffcc364a27b20ae2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:42:10 +0100 Subject: [PATCH 001/115] 2D view: draw the brush outline under the pointer while painting Fixes #179 Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/viewport.rs | 30 ++++++++++++++++++ crates/ui-egui/tests/brush_cursor_2d.rs | 41 +++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 crates/ui-egui/tests/brush_cursor_2d.rs diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a809c341..a0ab8bb9 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1056,6 +1056,20 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin painter.circle_stroke(hover, r, Stroke::new(1.0, Color32::from_white_alpha(200))); } } + // Brush cursor: the stamp's size and hardness at the pointer, as in the 3D view. + let cursor_mode = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held; + if cursor_mode + && !path_tool + && brush_tool(app.session.tool.tool) + && !resp.dragged_by(PointerButton::Middle) + // While a Ctrl+drag changes the brush, its cursor stays where the drag began. + && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos().or_else(|| resp.interact_pointer_pos()) } + { + // A UV brush stamp has a radius of twice the brush size, as in `continue_stroke_uv`. + let r = (to(app.session.tool.brush.size * 2.0, 0.0).x - to(0.0, 0.0).x).abs().max(1.5); + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + brush_cursor_2d(&painter, hp, r, app.session.tool.brush.hardness); + } brush_readout(app, ui, &resp, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); @@ -1064,6 +1078,22 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let _ = (RichText::new(""), Channel::BaseColor); } +/// The brush outline (and its hardness ring) as screen circles around `c`, radius `r` in points. +fn brush_cursor_2d(p: &egui::Painter, c: egui::Pos2, r: f32, hardness: f32) { + p.circle_stroke(c, r, Stroke::new(2.5, Color32::from_black_alpha(140))); + p.circle_stroke(c, r, Stroke::new(1.2, Color32::from_white_alpha(230))); + if hardness > 0.05 { + let inner: Vec = (0..=48) + .map(|k| { + let a = k as f32 / 48.0 * std::f32::consts::TAU; + c + vec2(a.cos(), a.sin()) * r * hardness + }) + .collect(); + p.add(egui::Shape::dashed_line(&inner, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); + } + p.circle_filled(c, 1.5, Color32::WHITE); +} + /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). fn skew_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { let last = ui.scope_id().with("skew_last"); diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs new file mode 100644 index 00000000..58cb4a8e --- /dev/null +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -0,0 +1,41 @@ +//! The 2D view hides the system pointer and draws the brush outline under it while painting. + +use egui::CursorIcon; +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.layout = ViewLayout::Only2D; + h.run_steps(4); + h +} + +fn cursor(h: &Harness<'_, TextureCraftApp>) -> CursorIcon { + h.output().platform_output.cursor_icon +} + +#[test] +fn painting_in_the_2d_view_replaces_the_pointer_with_the_brush_outline() { + let mut h = harness(); + let c = egui::pos2(800.0, 480.0); + h.hover_at(c); + h.run_steps(3); + assert_eq!(cursor(&h), CursorIcon::None, "the brush outline replaces the pointer"); + h.hover_at(egui::pos2(2.0, 2.0)); + h.run_steps(3); + assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is back"); +} + +#[test] +fn outside_painting_the_2d_view_keeps_the_normal_pointer() { + let mut h = harness(); + h.state_mut().ui.mode = Mode::Baking; + h.run_steps(3); + let c = egui::pos2(800.0, 480.0); + h.hover_at(c); + h.run_steps(3); + assert_ne!(cursor(&h), CursorIcon::None); +} From 9c570137f7b5557559c3d64c612ac068e2a98b47 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 15:37:56 +0100 Subject: [PATCH 002/115] Keep the pointer over the 2D view header and size the brush outline by pen pressure The brush cursor in the 2D view hid the system pointer and drew the outline over the view header pickers. Its radius also ignored pen pressure, while painting shrinks the stamp towards min_size. Both now follow the painted footprint (BrushSettings::uv_stamp_radius, shared with continue_stroke_uv), with regression tests for header hover and partial pressure. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/painting.rs | 3 +- crates/paint/src/brush.rs | 16 +++++++ crates/ui-egui/src/viewport.rs | 20 +++++---- crates/ui-egui/tests/brush_cursor_2d.rs | 59 ++++++++++++++++++++++++- 4 files changed, 87 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6f2a74ff..388758b9 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -318,8 +318,7 @@ impl Session { let Some((last, carry)) = st.uv.as_mut() else { return }; let Some(cache) = self.caches.get_mut(st.ts) else { return }; let b = &st.stroke.settings; - let p = pressure.clamp(0.0, 1.0); - let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 }; + let radius = b.uv_stamp_radius(pressure); let step = (b.spacing * 2.0 * radius).max(1e-5); let mut points = Vec::new(); match *last { diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 61313d57..45c9ed30 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -291,6 +291,13 @@ impl Default for BrushSettings { } impl BrushSettings { + /// Radius of a 2D (UV) stamp as a fraction of the UV square, for pen `pressure` 0..1: twice the + /// brush size, shrunk towards `min_size` by a light pen. Painting and the 2D cursor share it. + pub fn uv_stamp_radius(&self, pressure: f32) -> f32 { + let p = pressure.clamp(0.0, 1.0); + self.size * 2.0 * if p < 1.0 { self.min_size + (1.0 - self.min_size) * p } else { 1.0 } + } + /// Clamp every value into its valid range (input from UI, CLI or agents). pub fn sanitized(&self) -> BrushSettings { let f = |v: f32, lo: f32, hi: f32, d: f32| if v.is_finite() { v.clamp(lo, hi) } else { d }; @@ -323,6 +330,15 @@ impl BrushSettings { #[cfg(test)] mod tests { + #[test] + fn uv_stamp_radius_follows_pen_pressure() { + let b = BrushSettings { size: 0.1, min_size: 0.5, ..BrushSettings::default() }; + assert!((b.uv_stamp_radius(1.0) - 0.2).abs() < 1e-6); + assert!((b.uv_stamp_radius(0.5) - 0.15).abs() < 1e-6); + assert!((b.uv_stamp_radius(0.0) - 0.1).abs() < 1e-6); + assert!((b.uv_stamp_radius(7.0) - 0.2).abs() < 1e-6, "pressure clamps to 1"); + } + use super::*; #[test] diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 24ed251c..213dc8f0 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -332,14 +332,16 @@ const VIEW_HEADER_TOP_GAP: f32 = 8.0; /// Width of each of the two pickers const VIEW_PICKER_WIDTH: f32 = 130.0; +/// Where `view_header` draws its pickers in a view of `rect`; `None` when the view is too narrow. +fn view_header_rect(rect: Rect) -> Option { + (rect.width() >= VIEW_HEADER_WIDTH).then(|| { + Rect::from_min_size(rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP), vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)) + }) +} + /// The camera and view pickers at the top of a view, left out when the view is too narrow to hold them fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { - if rect.width() < VIEW_HEADER_WIDTH { - return; - } - - let header_min = rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP); - let header = Rect::from_min_size(header_min, vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)); + let Some(header) = view_header_rect(rect) else { return }; let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center))); let current = texturecraft_engine::camera_cmds::current(&app.session); @@ -1300,9 +1302,11 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !response.dragged_by(PointerButton::Middle) // While a Ctrl+drag changes the brush, its cursor stays where the drag began. && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } + // The view header's pickers keep the normal pointer. + && !view_header_rect(rect).is_some_and(|header| header.expand(2.0).contains(hp)) { - // A UV brush stamp has a radius of twice the brush size, as in `continue_stroke_uv`. - let r = (to_screen(app.session.tool.brush.size * 2.0, 0.0).x - to_screen(0.0, 0.0).x).abs().max(1.5); + // The stamp's radius as `continue_stroke_uv` paints it, including a light pen's smaller footprint. + let r = (to_screen(app.session.tool.brush.uv_stamp_radius(pen_pressure(ui)), 0.0).x - to_screen(0.0, 0.0).x).abs().max(1.5); ui.ctx().set_cursor_icon(egui::CursorIcon::None); brush_cursor_2d(&painter, hp, r, app.session.tool.brush.hardness); } diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 58cb4a8e..d205c541 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -1,6 +1,6 @@ //! The 2D view hides the system pointer and draws the brush outline under it while painting. -use egui::CursorIcon; +use egui::{CursorIcon, Event, Pos2, Shape, TouchDeviceId, TouchId, TouchPhase}; use egui_kittest::Harness; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; @@ -39,3 +39,60 @@ fn outside_painting_the_2d_view_keeps_the_normal_pointer() { h.run_steps(3); assert_ne!(cursor(&h), CursorIcon::None); } + +/// Radii of the white brush-outline rings (stroke 1.2) around `c` in the last frame. +fn rings_at(h: &Harness<'_, TextureCraftApp>, c: Pos2) -> Vec { + fn walk(shape: &Shape, c: Pos2, out: &mut Vec) { + match shape { + Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, c, out)), + Shape::Circle(circle) if (circle.stroke.width - 1.2).abs() < 1e-3 && circle.center.distance(c) < 0.5 => out.push(circle.radius), + _ => {} + } + } + let mut out = Vec::new(); + h.output().shapes.iter().for_each(|clipped| walk(&clipped.shape, c, &mut out)); + out +} + +#[test] +fn the_view_header_keeps_the_normal_pointer_and_gets_no_brush_outline() { + let mut h = harness(); + // The view's top edge is where the brush outline first replaces the pointer; the header is + // centred 8 points below it and 22 high. + let view_top = (0..200).map(|y| y as f32).find(|&y| { + h.hover_at(egui::pos2(300.0, y)); + h.run_steps(2); + cursor(&h) == CursorIcon::None + }); + let top = view_top.expect("the view has a top edge"); + let header = egui::pos2(800.0, top + 8.0 + 11.0); + h.hover_at(header); + h.run_steps(3); + assert_ne!(cursor(&h), CursorIcon::None, "over the pickers the pointer stays"); + assert!(rings_at(&h, header).is_empty(), "no brush outline over the pickers"); + let below = egui::pos2(800.0, top + 120.0); + h.hover_at(below); + h.run_steps(3); + assert_eq!(cursor(&h), CursorIcon::None, "below the header the brush outline is back"); + assert!(!rings_at(&h, below).is_empty()); +} + +#[test] +fn a_light_pen_shows_the_smaller_footprint_it_paints() { + let mut h = harness(); + h.state_mut().session.tool.brush.size = 0.05; + h.state_mut().session.tool.brush.min_size = 0.5; + let c = egui::pos2(800.0, 600.0); + h.hover_at(c); + h.run_steps(3); + let full = rings_at(&h, c); + assert_eq!(full.len(), 1, "one outline at full pressure"); + // A pen sample at half pressure: stamp radius is min + (1 - min) * p = 0.75 of full. + let events = &mut h.input_mut().events; + events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: c, force: Some(0.5) }); + events.push(Event::PointerMoved(c)); + h.step(); + let light = rings_at(&h, c); + assert_eq!(light.len(), 1); + assert!((light[0] / full[0] - 0.75).abs() < 1e-3, "half pressure shows 0.75 of the radius: {} vs {}", light[0], full[0]); +} From 8d902bea6fe28a607be989064373aba6ff0de146 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:54:02 +0100 Subject: [PATCH 003/115] Hide the system pointer only while it is over the 2D view Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/viewport.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 213dc8f0..2443e182 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1300,6 +1300,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !path_tool && brush_tool(app.session.tool.tool) && !response.dragged_by(PointerButton::Middle) + // During a drag egui keeps reporting a hover position after the pointer left the view: + // the system pointer is hidden only while the pointer is really over it. + && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)) // While a Ctrl+drag changes the brush, its cursor stays where the drag began. && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } // The view header's pickers keep the normal pointer. From d0967df09eacb8fe6737e5b538c0de3f5a9bcebe Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 00:54:33 +0100 Subject: [PATCH 004/115] Test that the system pointer returns when a drag leaves the 2D view Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/tests/brush_cursor_2d.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index d205c541..3b7cca9c 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -96,3 +96,23 @@ fn a_light_pen_shows_the_smaller_footprint_it_paints() { assert_eq!(light.len(), 1); assert!((light[0] / full[0] - 0.75).abs() < 1e-3, "half pressure shows 0.75 of the radius: {} vs {}", light[0], full[0]); } + +#[test] +fn dragging_out_of_the_2d_view_brings_the_system_pointer_back() { + let mut h = harness(); + let c = egui::pos2(800.0, 480.0); + h.hover_at(c); + h.run_steps(3); + assert_eq!(cursor(&h), CursorIcon::None, "inside the view the brush outline replaces the pointer"); + // Press inside the view, then carry the pointer out of the view (top-left corner) with the button held. + h.event(Event::PointerButton { pos: c, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(2); + assert_eq!(cursor(&h), CursorIcon::None, "still inside while dragging"); + let outside = egui::pos2(2.0, 2.0); + h.hover_at(outside); + h.run_steps(3); + assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is visible even during a drag"); + assert!(rings_at(&h, outside).is_empty(), "no brush outline outside the view"); + h.event(Event::PointerButton { pos: outside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); +} From c3a59ed421996439db27424de589989a6d91c784 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 01:40:50 +0100 Subject: [PATCH 005/115] Keep the anchored brush outline when a Ctrl+right drag leaves the 2D view The outline is drawn at the press origin for the whole adjustment drag; only the system-pointer hiding depends on the pointer being in the view. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/viewport.rs | 14 ++++++++++---- crates/ui-egui/tests/brush_cursor_2d.rs | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 2443e182..9c7c8808 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1054,7 +1054,9 @@ fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjustin let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return }; let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return }; // The pointer would cover the values; the brush cursor stays where the drag began. - ui.ctx().set_cursor_icon(egui::CursorIcon::None); + if ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| resp.rect.contains(p)) { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + } let b = &app.session.tool.brush; let text = if right { format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0) @@ -1296,13 +1298,15 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Brush cursor: the stamp's size and hardness at the pointer, as in the 3D view. let cursor_mode = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held; + let pointer_in_view = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)); if cursor_mode && !path_tool && brush_tool(app.session.tool.tool) && !response.dragged_by(PointerButton::Middle) // During a drag egui keeps reporting a hover position after the pointer left the view: - // the system pointer is hidden only while the pointer is really over it. - && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)) + // the system pointer is hidden only while the pointer is really over it. A Ctrl+drag that + // changes the brush keeps its outline at the press origin wherever the pointer goes. + && (adjusting || pointer_in_view) // While a Ctrl+drag changes the brush, its cursor stays where the drag began. && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } // The view header's pickers keep the normal pointer. @@ -1310,7 +1314,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin { // The stamp's radius as `continue_stroke_uv` paints it, including a light pen's smaller footprint. let r = (to_screen(app.session.tool.brush.uv_stamp_radius(pen_pressure(ui)), 0.0).x - to_screen(0.0, 0.0).x).abs().max(1.5); - ui.ctx().set_cursor_icon(egui::CursorIcon::None); + if pointer_in_view { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + } brush_cursor_2d(&painter, hp, r, app.session.tool.brush.hardness); } brush_readout(app, ui, &response, adjusting); diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 3b7cca9c..8f790099 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -116,3 +116,28 @@ fn dragging_out_of_the_2d_view_brings_the_system_pointer_back() { h.event(Event::PointerButton { pos: outside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); h.run_steps(2); } + +#[test] +fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() { + let mut h = harness(); + let c = egui::pos2(800.0, 480.0); + let ctrl = egui::Modifiers::COMMAND; + h.hover_at(c); + h.run_steps(2); + h.event(Event::ModifiersChanged(ctrl)); + h.event(Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: ctrl }); + h.run_steps(2); + // Drag a little inside the view: the outline is anchored and the pointer hidden. + h.hover_at(c + egui::vec2(10.0, 0.0)); + h.run_steps(3); + assert_eq!(rings_at(&h, c).len(), 1, "anchored outline while the pointer is in the view"); + assert_eq!(cursor(&h), CursorIcon::None); + // Carry the pointer out of the view: the outline stays at the anchor, the system pointer is back. + h.hover_at(egui::pos2(2.0, 2.0)); + h.run_steps(3); + assert_eq!(rings_at(&h, c).len(), 1, "the outline stays at the press origin outside the view"); + assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is visible"); + h.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl }); + h.event(Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(2); +} From 77d5edbce6aef32b021fe6bb3b9ace044ae4cd31 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 03:53:58 +0000 Subject: [PATCH 006/115] 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 007/115] 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 008/115] 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 009/115] 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 010/115] 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 011/115] 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 012/115] 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 013/115] 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 014/115] 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 015/115] 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 016/115] 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 017/115] 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 018/115] 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 019/115] =?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 020/115] 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 021/115] 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 022/115] 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 023/115] 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 024/115] 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 025/115] 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 026/115] 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 027/115] 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 028/115] 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 029/115] 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 030/115] 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 031/115] 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 032/115] 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 dafbdf3ec731514e5fba5fde5c482b8b2d1e80b8 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 07:30:11 +0000 Subject: [PATCH 033/115] Bake mode: the Baking Visualization panel and neutral material, as in the reference Every overlay gets the reference's colour swatch and eyedropper: the high poly, its matching error, the cage's surface and wireframe (separate, each with an opacity), the missing seams and the project mesh. The panel opens as the reference's does at first launch; its eye hides the baking meshes and greys their rows. Show for selected texture set only filters the cage and the high poly; a hidden high poly leaves the GPU. The UV seam overlay now marks the hard edges the UV layout does not split, on the low poly and the cage, in the 3D and 2D views. The project mesh can show the neutral material, picked in the 3D view's view menu: colour, roughness, metallic, baked AO, an optional baked bent normal, and Quality as importance-sampled reflections per pixel. --- Cargo.lock | 1 + crates/bake/src/cage/cage_shell.rs | 22 ++- crates/bake/src/test/cage_shell.rs | 51 +++++ crates/engine/src/bake/high_poly_missed.rs | 17 +- crates/engine/src/bake/mod.rs | 2 +- crates/engine/tests/it/high_poly_missed.rs | 11 +- crates/geom/src/mesh.rs | 102 ++++++---- crates/render/Cargo.toml | 1 + crates/render/src/bake_overlay.rs | 24 +++ crates/render/src/bake_visualization.rs | 60 +++++- crates/render/src/cage_geometry.rs | 13 ++ crates/render/src/cage_gpu.rs | 3 + crates/render/src/lib.rs | 8 +- .../{uv_seam_gpu.rs => missing_seam_gpu.rs} | 4 +- crates/render/src/neutral_material.rs | 75 +++++++ crates/render/src/renderer.rs | 168 +++++++++++----- crates/render/src/shaders/bake_view.wgsl | 154 +++++++++++++-- crates/render/src/shaders/mesh.wgsl | 12 ++ crates/render/tests/headless.rs | 172 +++++++++++++--- .../src/bake_mode/bake_visualization_panel.rs | 183 +++++++++++++++--- .../bake_mode/bake_visualization_toggles.rs | 140 ++++++++++++-- crates/ui-egui/src/bake_mode/mod.rs | 1 + .../ui-egui/src/bake_mode/section_opening.rs | 6 + .../ui-egui/src/bake_scene/bake_scene_link.rs | 83 +++++--- crates/ui-egui/src/gpu.rs | 20 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/screen_color_pick.rs | 94 +++++++++ crates/ui-egui/src/state.rs | 4 +- crates/ui-egui/src/viewport.rs | 41 +++- crates/ui-egui/tests/it/bake_mode.rs | 60 ++++++ 30 files changed, 1300 insertions(+), 233 deletions(-) create mode 100644 crates/render/src/bake_overlay.rs create mode 100644 crates/render/src/cage_geometry.rs rename crates/render/src/{uv_seam_gpu.rs => missing_seam_gpu.rs} (63%) create mode 100644 crates/render/src/neutral_material.rs create mode 100644 crates/ui-egui/src/bake_mode/section_opening.rs create mode 100644 crates/ui-egui/src/screen_color_pick.rs diff --git a/Cargo.lock b/Cargo.lock index bcd091ae..c3832334 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4425,6 +4425,7 @@ dependencies = [ "log", "pollster 0.4.0", "rayon", + "serde", "texturecraft-bake", "texturecraft-compose", "texturecraft-core", diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs index e1664219..3d07a14a 100644 --- a/crates/bake/src/cage/cage_shell.rs +++ b/crates/bake/src/cage/cage_shell.rs @@ -16,6 +16,8 @@ pub struct CageShell { pub starts: Vec, /// Corner pairs along the low poly's polygon edges, for the wireframe pub edges: Vec<[u32; 2]>, + /// Corner pairs along the low poly's hard edges without a UV seam + pub missing_seams: Vec<[u32; 2]>, /// World units per unit of the max frontal distance setting pub cage_units: f32, } @@ -37,7 +39,8 @@ impl CageShell { .unzip(); let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); - let mut edge_corners = HashMap::new(); + let missing_seam_edges: HashSet<(u32, u32)> = mesh.missing_seam_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + let (mut edge_corners, mut seam_corners) = (HashMap::new(), HashMap::new()); for (triangle_index, &triangle) in triangles.iter().enumerate() { let Some(vertices) = mesh.tri(triangle) else { continue }; @@ -45,16 +48,23 @@ impl CageShell { let next = (corner + 1) % 3; let (from, to) = (vertices[corner] as u32, vertices[next] as u32); let key = (from.min(to), from.max(to)); + let first_corner = (triangle_index * 3) as u32; + let corners = [first_corner + corner as u32, first_corner + next as u32]; if wire_edges.contains(&key) { - let first_corner = (triangle_index * 3) as u32; - edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]); + edge_corners.entry(key).or_insert(corners); + } + if missing_seam_edges.contains(&key) { + seam_corners.entry(key).or_insert(corners); } } } - let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect(); - edges.sort_unstable(); + let sorted = |corners: HashMap<(u32, u32), [u32; 2]>| { + let mut pairs: Vec<[u32; 2]> = corners.into_values().collect(); + pairs.sort_unstable(); + pairs + }; - Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units }) + Ok(CageShell { positions, starts, edges: sorted(edge_corners), missing_seams: sorted(seam_corners), cage_units: ray_frame.cage_units }) } /// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs index 2d114b06..3bfe5a5d 100644 --- a/crates/bake/src/test/cage_shell.rs +++ b/crates/bake/src/test/cage_shell.rs @@ -101,3 +101,54 @@ fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() { assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is"); assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO)); } + +#[test] +fn the_cage_lists_its_hard_edges_without_a_uv_seam() { + // A quad whose diagonal is split into two vertices with the same UV, smooth or hard by the copy's normal + let quad_with_diagonal_normal = |normal: Vec3| { + let mut mesh = Mesh::from_parts( + vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y], + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)], + vec![0, 1, 2, 0, 2, 3], + "Default", + ) + .unwrap(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(normal); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(mesh.uvs[0]); + mesh.indices[3] = 4; + mesh + }; + let shell_of = |low: &Mesh| { + let bvh = Bvh::new(low); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: low, bvh: &bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + CageShell::new(&request).unwrap() + }; + + let smooth = quad_with_diagonal_normal(Vec3::Z); + assert!(shell_of(&smooth).missing_seams.is_empty(), "the same normal on both sides is a smooth edge"); + + let hard = quad_with_diagonal_normal(Vec3::new(1.0, 0.0, 1.0).normalize()); + let shell = shell_of(&hard); + let diagonal = [Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)]; + assert_eq!(shell.missing_seams.len(), 2, "the diagonal, once per triangle"); + for [from, to] in &shell.missing_seams { + let mut ends = [shell.positions[*from as usize], shell.positions[*to as usize]]; + ends.sort_by(|a, b| a.x.total_cmp(&b.x)); + assert_eq!(ends, diagonal, "the line runs along the hard diagonal"); + } +} diff --git a/crates/engine/src/bake/high_poly_missed.rs b/crates/engine/src/bake/high_poly_missed.rs index 21de6c05..c9663ac1 100644 --- a/crates/engine/src/bake/high_poly_missed.rs +++ b/crates/engine/src/bake/high_poly_missed.rs @@ -1,9 +1,10 @@ use rayon::prelude::*; use texturecraft_bake::HighPolyReach; -/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0 -/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked -/// `vertex_count` is the validated high-poly mesh's vertex count +/// The value [`high_poly_missed`] gives a vertex that `only_set` doesn't own, which the 3D view leaves out +pub const HIDDEN_HIGH_POLY_VERTEX: f32 = -1.0; + +/// Per vertex of the validated high poly: 1.0 if its owning set's bake misses it at that set's (max frontal, max rear), 0.0 if reached or unknown, [`HIDDEN_HIGH_POLY_VERTEX`] if `only_set` doesn't own it pub fn high_poly_missed(reach: &[Option], distances: &[(f32, f32)], only_set: Option, vertex_count: usize) -> Vec { // Ownership is already assigned by HighPolyReach; other sets must not color the vertex let sets: Vec<(&HighPolyReach, f32, f32)> = reach @@ -13,11 +14,21 @@ pub fn high_poly_missed(reach: &[Option], distances: &[(f32, f32) .filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set)) .filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear))) .collect(); + (0..vertex_count) .into_par_iter() .map(|vertex| { + if only_set.is_some_and(|only| !owns(reach, only, vertex)) { + return HIDDEN_HIGH_POLY_VERTEX; + } + let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear)); f32::from(u8::from(missed.unwrap_or(false))) }) .collect() } + +/// Whether texture set `texture_set`'s reach claims high-poly vertex `vertex` +fn owns(reach: &[Option], texture_set: usize, vertex: usize) -> bool { + reach.get(texture_set).and_then(Option::as_ref).and_then(|set| set.vertices.get(vertex)).is_some_and(Option::is_some) +} diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index f06ab265..15377142 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -19,7 +19,7 @@ pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; -pub use high_poly_missed::high_poly_missed; +pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed}; pub use merged_high::MergedHigh; pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params}; pub use model_patch::settings_patch; diff --git a/crates/engine/tests/it/high_poly_missed.rs b/crates/engine/tests/it/high_poly_missed.rs index c5b132fa..2af1e085 100644 --- a/crates/engine/tests/it/high_poly_missed.rs +++ b/crates/engine/tests/it/high_poly_missed.rs @@ -1,4 +1,4 @@ -use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed}; +use texturecraft_engine::bake::{HIDDEN_HIGH_POLY_VERTEX, HighPolyReach, RayStart, VertexReach, high_poly_missed}; use texturecraft_engine::geom::glam::Vec3; fn vertex(height: f32) -> Option { @@ -30,12 +30,13 @@ fn each_owning_set_uses_its_own_frontal_and_rear_distances() { } #[test] -fn selected_set_filter_leaves_other_sets_unmarked() { +fn selected_set_filter_hides_other_sets_vertices() { + const H: f32 = HIDDEN_HIGH_POLY_VERTEX; let reaches = sets(); - assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); - assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, H, H, H, H]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![H, H, 0.0, 1.0, H, H]); for only_set in [0, reaches.len(), usize::MAX] { - assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![H; 6], "a set without a reach shows none of the high poly"); } } diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 5680a499..d6bea209 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -7,6 +7,9 @@ use crate::{GeomError, Result}; /// An edge by the bits of its two end positions, the lower one first type EdgePositions = ([u32; 3], [u32; 3]); +/// Normals closer than about one degree are the same normal: the edge between them is smooth +const SAME_NORMAL_MIN_COSINE: f32 = 0.9998; + /// A contiguous index range drawn with one material. #[derive(Clone, Debug, PartialEq)] pub struct SubMesh { @@ -110,8 +113,8 @@ impl Mesh { .collect() } - /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` - pub fn uv_seam_edges(&self) -> Vec> { + /// Hard edges the UV layout does not split, which bake visible lines into the normal map: two triangles meet there with different normals but the same UVs, per material in `0..materials.len().max(1)` + pub fn missing_seam_edges(&self) -> Vec> { // Signed zero denotes the same position on either side of an imported seam let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() }); let mut seams = vec![Vec::new(); self.materials.len().max(1)]; @@ -132,10 +135,18 @@ impl Mesh { } let uv = |index: u32| self.uvs.get(index as usize).copied(); + // Directions only: imported normals need not be unit length, and two missing normals agree + let direction = |index: u32| self.normals.get(index as usize).map_or(Vec3::ZERO, |normal| normal.normalize_or_zero()); + let same_normal = |a: u32, b: u32| { + let (a, b) = (direction(a), direction(b)); + a == b || a.dot(b) >= SAME_NORMAL_MIN_COSINE + }; for pairs in sides.into_values() { let Some(&(first_from, first_to, _)) = pairs.first() else { continue }; - if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) { + let uv_split = pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))); + let hard = pairs.iter().any(|&(from, to, _)| !same_normal(from, first_from) || !same_normal(to, first_to)); + if hard && !uv_split { for (from, to, material) in pairs { if let Some(edges) = seams.get_mut(material) { edges.push((from.min(to), from.max(to))); @@ -485,53 +496,60 @@ mod tests { assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } - #[test] - fn uv_seams_are_where_the_uv_layout_splits() { - let mesh = quad(); - assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); - - // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut - let mut seam = mesh.clone(); - seam.positions.push(seam.positions[0]); - seam.normals.push(seam.normals[0]); - seam.tangents.push(seam.tangents[0]); - seam.uvs.push(Vec2::new(0.9, 0.9)); - seam.indices[3] = 4; - assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); - - // The same split with the same UV is a hard edge, not a seam - let mut hard = seam.clone(); - hard.uvs[4] = hard.uvs[0]; - assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); - } - - #[test] - fn uv_seams_join_positions_with_opposite_signed_zero() { - let mut mesh = quad(); - mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0)); - mesh.normals.push(mesh.normals[0]); - mesh.tangents.push(mesh.tangents[0]); - mesh.uvs.push(Vec2::new(0.9, 0.9)); - mesh.indices[3] = 4; - assert_eq!(mesh.positions[0], mesh.positions[4]); - assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); - } - - #[test] - fn uv_seams_between_materials_belong_to_both_materials() { + /// `quad` with vertex 4 a copy of vertex 0 at `uv` with `normal`, used by the second triangle: the diagonal (0, 2) / (4, 2) has two sides + fn split_quad(uv: Vec2, normal: Vec3) -> Mesh { let mut mesh = quad(); mesh.positions.push(mesh.positions[0]); - mesh.normals.push(mesh.normals[0]); + mesh.normals.push(normal); mesh.tangents.push(mesh.tangents[0]); - mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.uvs.push(uv); mesh.indices[3] = 4; + mesh + } + + #[test] + fn missing_seams_are_hard_edges_the_uv_layout_does_not_split() { + let none = vec![Vec::<(u32, u32)>::new()]; + assert_eq!(quad().missing_seam_edges(), none, "a smooth quad has no hard edge"); + + let shared_uv = quad().uvs[0]; + let smooth_split = split_quad(shared_uv, Vec3::Z); + assert_eq!(smooth_split.missing_seam_edges(), none, "the same normal on both sides is a smooth edge"); + + let hard = split_quad(shared_uv, Vec3::new(1.0, 0.0, 1.0).normalize()); + assert_eq!(hard.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]], "a hard edge inside one UV island"); + + let seamed = split_quad(Vec2::new(0.9, 0.9), hard.normals[4]); + assert_eq!(seamed.missing_seam_edges(), none, "a hard edge on a UV seam is fine"); + + let mut short_normals = quad(); + short_normals.normals.iter_mut().for_each(|normal| *normal *= 0.5); + assert_eq!(short_normals.missing_seam_edges(), none, "normals shorter than unit length point the same way"); + assert_eq!(split_quad(shared_uv, Vec3::Z * 0.5).missing_seam_edges(), none, "normals of different lengths point the same way"); + + let mut no_normals = quad(); + no_normals.normals.fill(Vec3::ZERO); + assert_eq!(no_normals.missing_seam_edges(), none, "two missing normals agree"); + } + + #[test] + fn missing_seams_join_positions_with_opposite_signed_zero() { + let mut mesh = split_quad(quad().uvs[0], Vec3::X); + mesh.positions[4] = Vec3::new(-0.0, 0.0, 0.0); + assert_eq!(mesh.positions[0], mesh.positions[4]); + assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + } + + #[test] + fn missing_seams_between_materials_belong_to_both_materials() { + let mut mesh = split_quad(quad().uvs[0], Vec3::X); mesh.materials.push("second".into()); mesh.submeshes[0].count = 3; mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 }); - assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); - mesh.uvs[4] = mesh.uvs[0]; - assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); + assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); + mesh.normals[4] = mesh.normals[0]; + assert_eq!(mesh.missing_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a hard edge"); } #[test] diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 080f12ba..ee15b556 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,6 +19,7 @@ bytemuck = { workspace = true } half = { workspace = true } log = { workspace = true } rayon = { workspace = true } +serde = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = "0.4" diff --git a/crates/render/src/bake_overlay.rs b/crates/render/src/bake_overlay.rs new file mode 100644 index 00000000..31d8135d --- /dev/null +++ b/crates/render/src/bake_overlay.rs @@ -0,0 +1,24 @@ +//! One overlay of bake mode's 3D view: whether it shows, its color and its opacity + +/// Whether a part of the bake setup shows in the 3D view, and in which color and opacity +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct BakeOverlay { + pub shown: bool, + /// Linear RGB + pub color: [f32; 3], + /// 0 transparent, 1 opaque; the matching error mixes into the high poly by it + pub opacity: f32, +} + +impl BakeOverlay { + /// A hidden overlay in `color`, fully opaque + pub const fn hidden(color: [f32; 3]) -> Self { + Self { shown: false, color, opacity: 1.0 } + } + + /// The overlay's shader globals: rgb its color, a its opacity (0 while hidden) + pub(crate) fn globals(&self) -> [f32; 4] { + let [red, green, blue] = self.color; + [red, green, blue, if self.shown { self.opacity.clamp(0.0, 1.0) } else { 0.0 }] + } +} diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs index 8dbc4927..a03fbfd1 100644 --- a/crates/render/src/bake_visualization.rs +++ b/crates/render/src/bake_visualization.rs @@ -1,12 +1,58 @@ -//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly +//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the missing seams and the low poly -/// Which parts of the bake setup the 3D view draws +use crate::bake_overlay::BakeOverlay; +use crate::neutral_material::NeutralMaterial; + +/// Default overlay colors, linear RGB +const HIGH_POLY_COLOR: [f32; 3] = [0.0, 0.216, 0.521]; +const MATCHING_ERROR_COLOR: [f32; 3] = [1.0, 0.0, 0.0]; +const CAGE_SURFACE_COLOR: [f32; 3] = [0.604, 0.451, 0.216]; +const CAGE_WIRE_COLOR: [f32; 3] = [0.604, 0.604, 0.604]; +const MISSING_SEAM_COLOR: [f32; 3] = [0.451, 0.0, 0.451]; +const LOW_POLY_COLOR: [f32; 3] = [0.216, 0.216, 0.216]; + +/// Which parts of the bake setup the 3D view draws, and how #[derive(Clone, Copy, Debug, PartialEq)] pub struct BakeVisualization { - pub high_poly: bool, - pub cage: bool, - pub uv_seams: bool, - pub low_poly: bool, - /// Draw the cage, seams and low poly of only this texture set + pub high_poly: BakeOverlay, + /// Tints the high poly where the bake's rays miss it + pub matching_error: BakeOverlay, + pub cage_surface: BakeOverlay, + pub cage_wire: BakeOverlay, + /// The low poly's hard edges that are not UV seams + pub missing_seams: BakeOverlay, + /// The low poly; its color is the neutral material's color + pub low_poly: BakeOverlay, + /// Shade the low poly with this plain material instead of its painted one + pub neutral: Option, + /// Draw the cage and high poly of only this texture set (the high poly's vertices of other sets come marked hidden) pub only_set: Option, } + +impl Default for BakeVisualization { + /// Every part hidden, in its default color, the low poly with its painted material + fn default() -> Self { + Self { + high_poly: BakeOverlay::hidden(HIGH_POLY_COLOR), + matching_error: BakeOverlay::hidden(MATCHING_ERROR_COLOR), + cage_surface: BakeOverlay::hidden(CAGE_SURFACE_COLOR), + cage_wire: BakeOverlay::hidden(CAGE_WIRE_COLOR), + missing_seams: BakeOverlay::hidden(MISSING_SEAM_COLOR), + low_poly: BakeOverlay::hidden(LOW_POLY_COLOR), + neutral: None, + only_set: None, + } + } +} + +impl BakeVisualization { + /// Whether any part of the cage shows + pub fn cage_shown(&self) -> bool { + self.cage_surface.shown || self.cage_wire.shown + } + + /// The neutral material while the low poly shows with it + pub fn shown_neutral(&self) -> Option { + self.neutral.filter(|_| self.low_poly.shown) + } +} diff --git a/crates/render/src/cage_geometry.rs b/crates/render/src/cage_geometry.rs new file mode 100644 index 00000000..95b0ec6f --- /dev/null +++ b/crates/render/src/cage_geometry.rs @@ -0,0 +1,13 @@ +//! A texture set's cage as the renderer takes it + +use texturecraft_geom::glam::Vec3; + +/// A cage for [`crate::Renderer::set_bake_cage`]: three corners per low-poly triangle, and lines as corner pairs +#[derive(Clone, Copy, Debug)] +pub struct CageGeometry<'a> { + pub corners: &'a [Vec3], + /// The low poly's polygon edges, for the wireframe + pub edges: &'a [[u32; 2]], + /// The low poly's hard edges without a UV seam + pub missing_seams: &'a [[u32; 2]], +} diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs index 3ed4f13f..98b7b15e 100644 --- a/crates/render/src/cage_gpu.rs +++ b/crates/render/src/cage_gpu.rs @@ -6,4 +6,7 @@ pub(crate) struct CageGpu { pub(crate) corner_count: u32, pub(crate) edges: wgpu::Buffer, pub(crate) edge_index_count: u32, + /// Corner pairs along the low poly's hard edges without a UV seam + pub(crate) missing_seams: wgpu::Buffer, + pub(crate) missing_seam_index_count: u32, } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 649d9988..fc777e80 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,7 +13,9 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_overlay; pub mod bake_visualization; +pub mod cage_geometry; mod cage_gpu; pub mod displace; #[cfg(not(target_arch = "wasm32"))] @@ -24,15 +26,19 @@ pub mod headless; mod high_poly_gpu; pub mod ibl; pub mod mesh_maps; +mod missing_seam_gpu; +pub mod neutral_material; pub mod overlay_quad; pub mod readback; pub mod renderer; pub mod set_highlight; mod subdivide; pub mod trace; -mod uv_seam_gpu; +pub use bake_overlay::BakeOverlay; pub use bake_visualization::BakeVisualization; +pub use cage_geometry::CageGeometry; +pub use neutral_material::NeutralMaterial; pub use overlay_quad::OverlayQuad; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; pub use set_highlight::SetHighlight; diff --git a/crates/render/src/uv_seam_gpu.rs b/crates/render/src/missing_seam_gpu.rs similarity index 63% rename from crates/render/src/uv_seam_gpu.rs rename to crates/render/src/missing_seam_gpu.rs index 0ac80dc9..07a69168 100644 --- a/crates/render/src/uv_seam_gpu.rs +++ b/crates/render/src/missing_seam_gpu.rs @@ -1,5 +1,5 @@ -/// The low poly's UV seams as a line list over its vertex buffer -pub(crate) struct UvSeamGpu { +/// The low poly's hard edges without a UV seam, as a line list over its vertex buffer +pub(crate) struct MissingSeamGpu { /// The low-poly mesh the lines belong to pub(crate) mesh_id: u64, pub(crate) lines: wgpu::Buffer, diff --git a/crates/render/src/neutral_material.rs b/crates/render/src/neutral_material.rs new file mode 100644 index 00000000..d3331185 --- /dev/null +++ b/crates/render/src/neutral_material.rs @@ -0,0 +1,75 @@ +//! The plain material bake mode can show the low poly with, so the bake reads without the painted colours + +/// The highest Quality: reflection samples per pixel +pub const MAX_SAMPLES_PER_PIXEL: u32 = 256; + +/// A plain material for the low poly in bake mode: its color comes from the low poly's overlay; its normal and occlusion are the texture set's as shown (the bake under any painted normal, height or AO) +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct NeutralMaterial { + pub roughness: f32, + pub metallic: f32, + /// How much the texture set's ambient occlusion (baked × painted) darkens the material (0 none, 1 fully) + pub ao_intensity: f32, + /// Environment reflection samples per pixel, taken by every frame so a moving view looks like a still one + pub samples_per_pixel: u32, + /// Light the material along the baked bent normal: the open direction above each point + pub bent_normal: bool, + /// How far the diffuse light turns to the bent normal, and how much reflections facing away from it dim (0..1) + pub bent_normal_diffuse: f32, + pub bent_normal_specular: f32, +} + +impl Default for NeutralMaterial { + /// Low quality (16 samples per pixel), a slightly rough half metal, most of the baked occlusion, no bent normal + fn default() -> Self { + Self { + roughness: 0.3, + metallic: 0.6, + ao_intensity: 0.75, + samples_per_pixel: 16, + bent_normal: false, + bent_normal_diffuse: 1.0, + bent_normal_specular: 1.0, + } + } +} + +impl NeutralMaterial { + /// The material's shader globals: x roughness, y metallic, z AO intensity, w 1 (on) + pub(crate) fn globals(&self) -> [f32; 4] { + [self.roughness, self.metallic, self.ao_intensity, 1.0] + } + + /// Reflection samples each frame takes: the whole quality, from 1 to [`MAX_SAMPLES_PER_PIXEL`] (a damaged settings file can't stall the GPU) + pub(crate) fn samples_per_frame(&self) -> u32 { + self.samples_per_pixel.clamp(1, MAX_SAMPLES_PER_PIXEL) + } + + /// The bent normal's shader globals: x diffuse amount, y specular amount (both 0 while off), zw - + pub(crate) fn bent_normal_globals(&self) -> [f32; 4] { + if self.bent_normal { [self.bent_normal_diffuse, self.bent_normal_specular, 0.0, 0.0] } else { [0.0; 4] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_frame_takes_the_whole_quality() { + let quality = |samples_per_pixel| NeutralMaterial { samples_per_pixel, ..NeutralMaterial::default() }; + assert_eq!(quality(16).samples_per_frame(), 16); + assert_eq!(quality(256).samples_per_frame(), 256); + assert_eq!(quality(u32::MAX).samples_per_frame(), MAX_SAMPLES_PER_PIXEL, "a damaged file is held to the highest quality"); + assert_eq!(quality(0).samples_per_frame(), 1); + } + + #[test] + fn the_bent_normal_reaches_the_shader_only_when_on() { + let off = NeutralMaterial::default(); + assert_eq!(off.bent_normal_globals(), [0.0; 4]); + let on = NeutralMaterial { bent_normal: true, bent_normal_diffuse: 0.5, bent_normal_specular: 0.25, ..off }; + assert_eq!(on.bent_normal_globals(), [0.5, 0.25, 0.0, 0.0]); + } +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1636f1ad..4e5295df 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -31,14 +31,15 @@ use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; use crate::bake_visualization::BakeVisualization; +use crate::cage_geometry::CageGeometry; use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; +use crate::missing_seam_gpu::MissingSeamGpu; use crate::overlay_quad::OverlayQuad; use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; -use crate::uv_seam_gpu::UvSeamGpu; pub const MSAA: u32 = 4; pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; @@ -84,6 +85,14 @@ struct GlobalsRaw { refr: [f32; 4], highlight: [f32; 4], highlight_shift: [f32; 4], + bake_high: [f32; 4], + bake_matching_error: [f32; 4], + bake_cage: [f32; 4], + bake_cage_wire: [f32; 4], + bake_missing_seam: [f32; 4], + bake_neutral_color: [f32; 4], + bake_neutral: [f32; 4], + bake_bent_normal: [f32; 4], } /// The post pass uniform (see `Post` in post.wgsl). @@ -548,7 +557,10 @@ pub struct Renderer { bake_high_pipeline: wgpu::RenderPipeline, cage_pipeline: wgpu::RenderPipeline, cage_wire_pipeline: wgpu::RenderPipeline, - uv_seam_pipeline: wgpu::RenderPipeline, + missing_seam_pipeline: wgpu::RenderPipeline, + /// The missing seams along the cage, and in the 2D view + cage_missing_seam_pipeline: wgpu::RenderPipeline, + uv_missing_seam_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -585,7 +597,7 @@ pub struct Renderer { bake_high: Option, /// Each texture set's cage, by set index cages: Vec>, - uv_seams: Option, + missing_seams: Option, sets: Vec, /// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least /// as reduced as the device's texture limit needs). @@ -1001,8 +1013,30 @@ impl Renderer { MSAA, wire3d_depth.clone(), ); - let uv_seam_pipeline = - pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone()); + let cage_missing_seam_pipeline = pipeline( + device, + "tc_cage_missing_seam", + &background_layout, + &module, + "vs_bake_cage_wire", + &corner_layout, + hdr_target("fs_wire_cage_missing_seam", blend), + MSAA, + wire3d_depth.clone(), + ); + let uv_missing_seam_pipeline = + pipeline(device, "tc_uv_missing_seam", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire_missing_seam", blend), MSAA, always()); + let missing_seam_pipeline = pipeline( + device, + "tc_missing_seam", + &layout, + &module, + "vs_wire3d", + &vertex_layout, + hdr_target("fs_wire_missing_seam", blend), + MSAA, + wire3d_depth.clone(), + ); let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always()); let overlay_pipeline = pipeline(device, "tc_overlay", &background_layout, &module, "vs_overlay", &vertex_layout, hdr_target("fs_overlay", blend), MSAA, wire3d_depth); @@ -1135,7 +1169,9 @@ impl Renderer { bake_high_pipeline, cage_pipeline, cage_wire_pipeline, - uv_seam_pipeline, + missing_seam_pipeline, + cage_missing_seam_pipeline, + uv_missing_seam_pipeline, bg_pipeline, blit_pipeline, post_pipeline, @@ -1162,7 +1198,7 @@ impl Renderer { mesh: None, bake_high: None, cages: Vec::new(), - uv_seams: None, + missing_seams: None, sets: Vec::new(), display_shift: 0, material_sets: Vec::new(), @@ -1289,8 +1325,8 @@ impl Renderer { self.content_rev += 1; } - /// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners - pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) { + /// Texture set `texture_set`'s cage; `None` removes it. The same `topology` as before only rewrites the corners + pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option>, topology: u64) { if self.cages.len() <= texture_set { self.cages.resize_with(texture_set + 1, || None); } @@ -1298,16 +1334,18 @@ impl Renderer { match (cage, slot.as_mut()) { (None, _) => *slot = None, - (Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => { - queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners)); + (Some(cage), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == cage.corners.len() => { + queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(cage.corners)); } - (Some((corners, edges)), _) => { + (Some(cage), _) => { *slot = Some(CageGpu { topology, - corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX), - corner_count: corners.len() as u32, - edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX), - edge_index_count: (edges.len() * 2) as u32, + corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(cage.corners), wgpu::BufferUsages::VERTEX), + corner_count: cage.corners.len() as u32, + edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(cage.edges), wgpu::BufferUsages::INDEX), + edge_index_count: (cage.edges.len() * 2) as u32, + missing_seams: upload_buffer(device, queue, "tc_cage_seam_ib", bytemuck::cast_slice(cage.missing_seams), wgpu::BufferUsages::INDEX), + missing_seam_index_count: (cage.missing_seams.len() * 2) as u32, }); } } @@ -1322,8 +1360,8 @@ impl Renderer { } } - /// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id` - pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { + /// The low poly's hard edges without a UV seam as vertex pairs per material ([`Mesh::missing_seam_edges`]) for mesh `mesh_id` + pub fn set_missing_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { let mut line_indices: Vec = Vec::new(); let mut line_draws = Vec::new(); for (material, edges) in seams.iter().enumerate() { @@ -1332,8 +1370,8 @@ impl Renderer { line_draws.push((start, line_indices.len() as u32 - start, material)); } - let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); - self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws }); + let lines = upload_buffer(device, queue, "tc_missing_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); + self.missing_seams = Some(MissingSeamGpu { mesh_id, lines, line_draws }); self.content_rev += 1; } @@ -1938,6 +1976,7 @@ impl Renderer { refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], highlight: highlight_globals(s, data), highlight_shift: highlight_shift(frame.size), + ..bake_globals(s.bake) }; let flag = |b: bool| if b { 1.0 } else { 0.0 }; let post = PostRaw { @@ -2148,14 +2187,13 @@ impl Renderer { pass.set_bind_group(2, refraction_source, &[]); let geometry = self.geometry(mesh, frame); let bake = frame.shade.bake.filter(|_| uv_set.is_none()); - let low_poly_shown = bake.is_none_or(|bake| bake.low_poly); - let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set); - let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && low_poly_set.is_none_or(|only| only == *set)).unzip(); + let low_poly_shown = bake.is_none_or(|bake| bake.low_poly.shown); + let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && uv_set.is_none_or(|only| only == *set)).unzip(); // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) let passes = [ - (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1), - (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, low_poly_set, 1), + (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1), + (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1), (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), ]; for (pipeline, vertices, indices, ranges, only_set, instances) in passes { @@ -2173,6 +2211,18 @@ impl Renderer { if let Some(bake) = bake { self.draw_bake(&mut pass, mesh, frame, bake); } + if let Some(texture_set) = uv_set + && frame.shade.bake.is_some_and(|bake| bake.missing_seams.shown) + && let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == mesh.id) + { + pass.set_pipeline(&self.uv_missing_seam_pipeline); + pass.set_vertex_buffer(0, mesh.geo.vb.slice(..)); + pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) { + pass.set_bind_group(1, &set.bind_group, &[]); + pass.draw_indexed(range, 0, 0..1); + } + } // Overlay quads last, so the mesh's depth hides what is behind it if uv_set.is_none() @@ -2184,9 +2234,9 @@ impl Renderer { } } - /// Bake mode's high poly, UV seams and cages over the low poly `low_poly` + /// Bake mode's high poly, missing seams and cages over the low poly `low_poly` fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) { - if bake.high_poly + if bake.high_poly.shown && let Some(high) = &self.bake_high { pass.set_pipeline(&self.bake_high_pipeline); @@ -2196,35 +2246,45 @@ impl Renderer { pass.draw_indexed(0..high.index_count, 0, 0..1); } - if bake.uv_seams - && let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) + if bake.missing_seams.shown + && let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) { - pass.set_pipeline(&self.uv_seam_pipeline); + pass.set_pipeline(&self.missing_seam_pipeline); pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) { + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, None) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } } - if !bake.cage { - return; - } - let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true); let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref()); // The translucent faces first, then the wireframe over them - pass.set_pipeline(&self.cage_pipeline); - for cage in cages() { - pass.set_vertex_buffer(0, cage.corners.slice(..)); - pass.draw(0..cage.corner_count, 0..1); + if bake.cage_surface.shown { + pass.set_pipeline(&self.cage_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.draw(0..cage.corner_count, 0..1); + } } - pass.set_pipeline(&self.cage_wire_pipeline); - for cage in cages() { - pass.set_vertex_buffer(0, cage.corners.slice(..)); - pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); - pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + + if bake.cage_wire.shown { + pass.set_pipeline(&self.cage_wire_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + } + } + + if bake.missing_seams.shown && bake.cage_shown() { + pass.set_pipeline(&self.cage_missing_seam_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.missing_seams.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.missing_seam_index_count, 0, 0..1); + } } } @@ -2336,6 +2396,26 @@ fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { [r, g, b, HIGHLIGHT_OPACITY] } +/// The globals of bake mode's overlays and neutral material for `bake` (all zero without it) +fn bake_globals(bake: Option) -> GlobalsRaw { + let Some(bake) = bake else { return GlobalsRaw::zeroed() }; + + let [red, green, blue] = bake.low_poly.color; + let neutral = bake.shown_neutral(); + let samples_per_frame = neutral.map_or(0, |neutral| neutral.samples_per_frame()); + GlobalsRaw { + bake_high: bake.high_poly.globals(), + bake_matching_error: bake.matching_error.globals(), + bake_cage: bake.cage_surface.globals(), + bake_cage_wire: bake.cage_wire.globals(), + bake_missing_seam: bake.missing_seams.globals(), + bake_neutral_color: [red, green, blue, samples_per_frame as f32], + bake_neutral: neutral.map_or([0.0; 4], |neutral| neutral.globals()), + bake_bent_normal: neutral.map_or([0.0; 4], |neutral| neutral.bent_normal_globals()), + ..GlobalsRaw::zeroed() + } +} + /// Globals `highlight_shift`: how far each of the highlight's line copies moves sideways, in clip units of a `size` pixel target fn highlight_shift(size: [u32; 2]) -> [f32; 4] { let half_extra_width = (HIGHLIGHT_WIDTH_PX - 1.0) * 0.5; diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl index 1985f980..f611bbc3 100644 --- a/crates/render/src/shaders/bake_view.wgsl +++ b/crates/render/src/shaders/bake_view.wgsl @@ -1,19 +1,46 @@ -// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams +// Bake mode's 3D view: the high poly, the cage around the low poly, the missing seams and the neutral material struct BakeViewOut { @builtin(position) clip: vec4, @location(0) world_position: vec3, @location(1) normal: vec3, - // 1 where the bake's rays miss the high poly, 0 where they reach it + // 1 where the bake's rays miss the high poly, 0 where they reach it, negative where another texture set owns it (hidden) @location(2) missed: f32, }; -const HIGH_POLY_COLOR: vec3 = vec3(0.10, 0.36, 0.56); -const MISSED_COLOR: vec3 = vec3(0.80, 0.01, 0.01); -const CAGE_COLOR: vec3 = vec3(0.55, 0.42, 0.26); -const CAGE_OPACITY: f32 = 0.16; -const CAGE_WIRE_COLOR: vec4 = vec4(0.75, 0.62, 0.42, 0.7); -const UV_SEAM_COLOR: vec4 = vec4(0.20, 0.85, 0.30, 1.0); +// Reflectance of the neutral material's dielectric part facing the camera +const NEUTRAL_F0: f32 = 0.04; + +// Lowest roughness the neutral material shades with: below it the GGX lobe is too narrow for its samples +const MIN_NEUTRAL_ROUGHNESS: f32 = 0.045; + +// How fast reflections fade as they dip below the mesh surface (larger = sooner) +const HORIZON_FADE: f32 = 1.3; + +// Floor of the cosines that divide the reflection terms, so grazing angles stay finite +const MIN_COSINE: f32 = 1e-4; + +// A normal closer than this to +-Z builds its tangent frame from X, where the cross product with Z would vanish +const TANGENT_HELPER_MAX_Z: f32 = 0.999; + +// One mip coarser than each sample's share of the lobe: hides the gaps between few samples (filtered importance sampling) +const FILTERED_SAMPLING_LOD_BIAS: f32 = 1.0; + +// A packed bent normal shorter than this is the unbaked gray, not a direction +const BENT_NORMAL_MIN_LENGTH: f32 = 0.5; + +// Cosines between a reflection and the bent normal over which the reflection goes from occluded to open +const BENT_OCCLUSION_START: f32 = -0.25; +const BENT_OCCLUSION_END: f32 = 0.75; + +// Floor of the GGX distribution's denominator, which reaches 0 at the peak of a mirror-like lobe +const MIN_GGX_DENOMINATOR: f32 = 1e-6; + +// Fractional part of the golden ratio: shifts each accumulated frame's samples around the lobe +const GOLDEN_RATIO_FRACTION: f32 = 0.618034; + +// High-poly surface where the interpolated `missed` falls below this belongs to a hidden texture set +const HIDDEN_BELOW: f32 = -0.5; // Brightness of surfaces seen edge-on; facing the camera adds the rest const HEADLIGHT_AMBIENT: f32 = 0.3; @@ -45,7 +72,11 @@ fn vs_bake_high(@location(0) position: vec3, @location(1) normal: vec3 @fragment fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4 { - let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed); + if (surface.missed < HIDDEN_BELOW) { + discard; + } + + let color = mix(g.bake_high.rgb, g.bake_matching_error.rgb, max(surface.missed, 0.0) * g.bake_matching_error.a); return vec4(headlight(color, normalize(surface.normal), surface.world_position), 1.0); } @@ -63,7 +94,7 @@ fn vs_bake_cage(@location(0) position: vec3) -> BakeViewOut { @fragment fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position))); - return vec4(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY); + return vec4(headlight(g.bake_cage.rgb, face_normal, surface.world_position), g.bake_cage.a); } // Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces @@ -79,10 +110,107 @@ fn vs_bake_cage_wire(@location(0) position: vec3) -> BakeViewOut { @fragment fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { - return CAGE_WIRE_COLOR; + return g.bake_cage_wire; } @fragment -fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4 { - return UV_SEAM_COLOR; +fn fs_wire_missing_seam(surface: VOut) -> @location(0) vec4 { + return g.bake_missing_seam; +} + +// The missing seams along the cage, whose vertices carry the bake view's outputs +@fragment +fn fs_wire_cage_missing_seam(surface: BakeViewOut) -> @location(0) vec4 { + return g.bake_missing_seam; +} + +// The neutral material at the texture set's normal `n` (over the mesh normal `n_geo`) seen from direction `v`, darkened by its occlusion `ao_channel`, lit along the packed bent normal `packed_bent` when it is on +fn neutral_color(n: vec3, n_geo: vec3, v: vec3, world_position: vec3, ao_channel: f32, packed_bent: vec3) -> vec4 { + let albedo = g.bake_neutral_color.rgb; + let rough = clamp(g.bake_neutral.x, MIN_NEUTRAL_ROUGHNESS, 1.0); + let metal = g.bake_neutral.y; + let ao = mix(1.0, ao_channel, g.bake_neutral.z); + let f0 = mix(vec3(NEUTRAL_F0), albedo, metal); + let diffuse_col = albedo * (1.0 - metal); + let nov = clamp(abs(dot(n, v)), MIN_COSINE, 1.0); + + // An unbaked bent normal reads as the neutral gray (length 0): the surface normal stands in + var bent = packed_bent * 2.0 - 1.0; + bent = select(n, normalize(bent), dot(bent, bent) > BENT_NORMAL_MIN_LENGTH * BENT_NORMAL_MIN_LENGTH); + let diffuse = sh_irradiance(normalize(mix(n, bent, g.bake_bent_normal.x)), vec3(0.0)) * diffuse_col * ao; + let r = reflect(-v, n); + let horizon = clamp(1.0 + HORIZON_FADE * dot(r, n_geo), 0.0, 1.0); + // Reflections pointing away from the open direction are occluded + let bent_occlusion = mix(1.0, smoothstep(BENT_OCCLUSION_START, BENT_OCCLUSION_END, dot(bent, r)), g.bake_bent_normal.y); + let spec = sampled_reflection(n, v, rough, f0, nov) * ao * bent_occlusion * horizon * horizon; + + var direct = vec3(0.0); + if (g.light.w > 0.0) { + let l = normalize(g.light.xyz); + let h = normalize(l + v); + let nol = clamp(dot(n, l), 0.0, 1.0); + let f = f0 + (vec3(1.0) - f0) * pow(1.0 - clamp(dot(v, h), 0.0, 1.0), 5.0); + direct = ((vec3(1.0) - f) * diffuse_col / PI + ggx_dv(rough * rough, nov, nol, clamp(dot(n, h), 0.0, 1.0)) * f) * nol * g.light.w; + if (g.shadow.x > 0.5 && nol > 0.0) { + direct *= shadow_factor(world_position, n_geo); + } + } + let color = diffuse + spec + direct; + return vec4(select(color, vec3(0.0), any(color != color)), 1.0); +} + +// The environment's GGX reflection at normal `n`, importance sampled with this frame's share of the neutral material's quality; each accumulated frame takes other samples +fn sampled_reflection(n: vec3, v: vec3, rough: f32, f0: vec3, nov: f32) -> vec3 { + let count = max(u32(g.bake_neutral_color.w), 1u); + let a = rough * rough; + let a2 = a * a; + let env_size = vec2(textureDimensions(env_tex)); + let texel_solid_angle = 4.0 * PI / (env_size.x * env_size.y); + let side = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), abs(n.z) < TANGENT_HELPER_MAX_Z); + let tangent = normalize(cross(side, n)); + let bitangent = cross(n, tangent); + let frame_offset = u32(g.material.z) * count; + // Schlick-GGX geometry term at k = a / 2 + let k = a * 0.5; + let view_visibility = nov / (nov * (1.0 - k) + k); + + var sum = vec3(0.0); + for (var index = 0u; index < count; index++) { + let xi = vec2(fract((f32(index) + 0.5) / f32(count) + f32(g.material.z) * GOLDEN_RATIO_FRACTION), radical_inverse(index + frame_offset)); + let phi = 2.0 * PI * xi.x; + // Clamped: near roughness 0 the ratio rounds a hair past 1, and the sine's square root would be NaN (a black pixel once frames accumulate) + let cos_theta = clamp(sqrt((1.0 - xi.y) / (1.0 + (a2 - 1.0) * xi.y)), 0.0, 1.0); + let sin_theta = sqrt(1.0 - cos_theta * cos_theta); + let h = normalize(tangent * (cos(phi) * sin_theta) + bitangent * (sin(phi) * sin_theta) + n * cos_theta); + let l = reflect(-v, h); + let nol = min(dot(n, l), 1.0); + if (nol <= 0.0) { + continue; + } + + // Capped at 1: a dot product rounding past it makes pow(1 - voh, 5) NaN on GPUs that compute pow through log2 + let noh = clamp(dot(n, h), MIN_COSINE, 1.0); + let voh = clamp(dot(v, h), MIN_COSINE, 1.0); + let denominator = max(noh * noh * (a2 - 1.0) + 1.0, MIN_GGX_DENOMINATOR); + let pdf = a2 / (PI * denominator * denominator) * noh / (4.0 * voh); + // Filtered importance sampling: each sample reads the mip that covers its share of the lobe + let lod = clamp(0.5 * log2(1.0 / (f32(count) * pdf * texel_solid_angle)) + FILTERED_SAMPLING_LOD_BIAS, 0.0, g.env.y); + let light = textureSampleLevel(env_tex, env_samp, env_uv(l), lod).rgb; + let fresnel = f0 + (vec3(1.0) - f0) * pow(1.0 - voh, 5.0); + let visibility = view_visibility * nol / (nol * (1.0 - k) + k); + let contribution = light * fresnel * (visibility * voh / (noh * nov)); + // A sample that still came out NaN (x != x) is dropped: the frame average would carry it, and post effects spread it over the image + sum += select(contribution, vec3(0.0), any(contribution != contribution)); + } + return sum / f32(count); +} + +// Van der Corput: the bits of `index` mirrored behind the binary point (swapped by hand: WebGL2 lacks a bit reverse) +fn radical_inverse(index: u32) -> f32 { + var bits = (index << 16u) | (index >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return f32(bits) / 4294967296.0; } diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 23c4bd64..961304f3 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -26,6 +26,14 @@ struct Globals { refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - + bake_high: vec4, // bake mode: rgb high poly color, a - + bake_matching_error: vec4, // rgb color where the bake's rays miss the high poly, a its strength (0 hidden) + bake_cage: vec4, // rgb cage surface color, a opacity + bake_cage_wire: vec4, // rgb cage wireframe color, a opacity + bake_missing_seam: vec4, // rgb color of hard edges without a UV seam, a opacity + bake_neutral_color: vec4, // rgb the neutral material's color, a its reflection samples this frame + bake_neutral: vec4, // x roughness, y metallic, z AO intensity of the neutral material, w on (1) + bake_bent_normal: vec4, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw - }; @group(0) @binding(0) var g: Globals; @@ -446,6 +454,10 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { return unlit(data_out((col + tint) * diff)); } + if (g.bake_neutral.w > 0.5) { + return Shaded(neutral_color(n, n_geo, v, i.wpos, orm.r, aux.rgb), vec3(0.0)); + } + // Opacity: dithered alpha test (a new pattern per accumulated frame, so it averages out). if (base_s.a < hash12(i.clip.xy + g.material.z * vec2(17.0, 59.0))) { discard; diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 3b5b3938..23a96b08 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -3,7 +3,7 @@ use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; use texturecraft_render::renderer::TAA_SAMPLES; -use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind}; +use texturecraft_render::{BakeOverlay, BakeVisualization, CageGeometry, Frame, NeutralMaterial, Shade, ViewKind}; /// The UI's key light (`viewport::shade`). const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5]; @@ -226,6 +226,91 @@ fn wireframe_3d_overlays_the_mesh() { assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean"); } +/// `overlay` shown +fn shown(overlay: BakeOverlay) -> BakeOverlay { + BakeOverlay { shown: true, ..overlay } +} + +#[test] +fn bake_neutral_material_shades_the_low_poly_in_its_settings() { + const COLOR_LEAD: i32 = 30; + let Some((mut h, frame)) = setup() else { return }; + + let neutral = NeutralMaterial { roughness: 0.5, metallic: 0.0, ao_intensity: 1.0, samples_per_pixel: 16, ..NeutralMaterial::default() }; + let low_poly = BakeOverlay { color: [0.0, 0.0, 0.8], ..shown(BakeVisualization::default().low_poly) }; + let painted_parts = BakeVisualization { low_poly, ..BakeVisualization::default() }; + let neutral_parts = BakeVisualization { neutral: Some(neutral), ..painted_parts }; + let painted = render(&mut h, &shaded(&frame, |s| s.bake = Some(painted_parts)), "bake_neutral_off"); + let blue = render(&mut h, &shaded(&frame, |s| s.bake = Some(neutral_parts)), "bake_neutral_blue"); + let center = (frame.size[0] / 2, frame.size[1] / 2); + let [red, green, blue_channel] = blue.at(center.0, center.1).map(i32::from); + assert!( + blue_channel > red + COLOR_LEAD && blue_channel > green + COLOR_LEAD, + "the neutral material takes the project mesh's color: {:?}", + [red, green, blue_channel] + ); + assert_ne!(blue.px, painted.px, "the painted material is replaced"); + + let metal = BakeVisualization { neutral: Some(NeutralMaterial { metallic: 1.0, roughness: 0.1, ..neutral }), ..neutral_parts }; + assert_ne!(render(&mut h, &shaded(&frame, |s| s.bake = Some(metal)), "bake_neutral_metal").px, blue.px, "roughness and metallic reach the shader"); + + let hidden_low_poly = BakeVisualization { low_poly: BakeOverlay { shown: false, ..low_poly }, ..neutral_parts }; + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_neutral_background"); + assert_same( + &render(&mut h, &shaded(&frame, |s| s.bake = Some(hidden_low_poly)), "bake_neutral_hidden"), + &background, + "a hidden project mesh draws nothing", + ); +} + +#[test] +fn bake_neutral_material_looks_the_same_moving_as_still() { + // A moving view only ever shows its first frame; with the whole quality in it, it stays close to the settled image (one sample a frame was 6.6 levels off) + const MAX_MEAN_LEVELS: f32 = 4.0; + let Some((mut h, frame)) = setup() else { return }; + + let neutral = NeutralMaterial { roughness: 0.5, metallic: 1.0, ..NeutralMaterial::default() }; + let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() }; + let still = shaded(&frame, |s| { + s.taa = true; + s.bake = Some(parts); + }); + let first = render(&mut h, &still, "bake_neutral_first_frame"); + for _ in 1..TAA_SAMPLES { + render(&mut h, &still, "bake_neutral_settling"); + } + let settled = render(&mut h, &still, "bake_neutral_settled"); + // Compared on the ball in the middle of the view, where the reflections are + let (width, height) = (frame.size[0], frame.size[1]); + let ball = (width * 3 / 8..width * 5 / 8).flat_map(|x| (height / 4..height / 2).map(move |y| (x, y))); + let differences: Vec = ball.map(|(x, y)| (first.luma(x, y) - settled.luma(x, y)).abs()).collect(); + let mean_difference = differences.iter().sum::() / differences.len() as f32; + assert!(mean_difference < MAX_MEAN_LEVELS, "the first frame is {mean_difference} levels off the settled one on average"); +} + +#[test] +fn bake_neutral_material_stays_lit_at_any_roughness_once_settled() { + // Near roughness 0 a bad sample gave NaN, and the settled average of all frames went black + const MIN_BALL_LUMA: f32 = 20.0; + let Some((mut h, frame)) = setup() else { return }; + + for roughness in [0.0, 0.05, 0.1] { + let neutral = NeutralMaterial { roughness, ..NeutralMaterial::default() }; + let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() }; + let still = shaded(&frame, |s| { + s.taa = true; + s.bake = Some(parts); + }); + for _ in 0..TAA_SAMPLES { + render(&mut h, &still, "bake_neutral_mirror_settling"); + } + let settled = render(&mut h, &still, "bake_neutral_mirror_settled"); + let (width, height) = (frame.size[0], frame.size[1]); + let ball = settled.mean(width * 3 / 8, height / 4, width * 5 / 8, height / 2); + assert!(ball > MIN_BALL_LUMA, "roughness {roughness}: the settled ball is black ({ball})"); + } +} + #[test] fn bake_visualization_draws_the_high_poly_and_the_cage() { // A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color @@ -246,15 +331,17 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() { } h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap(); let corners: Vec = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect(); - h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY); - let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None }; + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some(CageGeometry { corners: &corners, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY); + let bake = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), ..BakeVisualization::default() }; let center = (frame.size[0] / 2, frame.size[1] / 2); let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name); let low_only = only(&mut h, bake, "bake_low_only"); - let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden"); - let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly"); - let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage"); + let high_only = BakeVisualization { high_poly: shown(bake.high_poly), matching_error: shown(bake.matching_error), ..BakeVisualization::default() }; + let caged_parts = BakeVisualization { cage_surface: shown(bake.cage_surface), cage_wire: shown(bake.cage_wire), ..bake }; + let hidden = only(&mut h, BakeVisualization::default(), "bake_low_hidden"); + let high_poly = only(&mut h, high_only, "bake_high_poly"); + let caged = only(&mut h, caged_parts, "bake_cage"); assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly"); let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background"); assert_same(&hidden, &background, "without the low poly only the background is left"); @@ -270,26 +357,63 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() { // Vertices the bake's rays miss turn red h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]); - let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed"); + let missed = only(&mut h, high_only, "bake_high_missed"); let [red, green, blue] = missed.at(center.0, center.1).map(i32::from); assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]); + let no_error = only(&mut h, BakeVisualization { matching_error: bake.matching_error, ..high_only }, "bake_high_missed_hidden"); + assert_same(&no_error, &high_poly, "with the matching error hidden the missed vertices keep the high poly's color"); + let green_error = BakeOverlay { color: [0.0, 1.0, 0.0], ..high_only.matching_error }; + let [red, green, blue] = + only(&mut h, BakeVisualization { matching_error: green_error, ..high_only }, "bake_high_missed_green").at(center.0, center.1).map(i32::from); + assert!(green > red + COLOR_LEAD && green > blue + COLOR_LEAD, "the matching error's color reaches the shader: {:?}", [red, green, blue]); - // Show for selected texture set only: the other set's low poly and the cage of set 0 drop out - let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set"); - let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set"); - assert_ne!(first_set.px, caged.px, "the second set's low poly is left out"); - assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out"); - assert_ne!(first_set.px, second_set.px); + // Show for selected texture set only filters the cage (only set 0 has one here), never the low poly + let first_set = only(&mut h, BakeVisualization { only_set: Some(0), ..caged_parts }, "bake_only_first_set"); + let second_set = only(&mut h, BakeVisualization { only_set: Some(1), ..caged_parts }, "bake_only_second_set"); + assert_same(&first_set, &caged, "set 0's cage stays and both sets' low poly draws"); + assert_same(&second_set, &low_only, "set 0's cage drops out, the low poly stays"); - // UV seams draw over the low poly - h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges()); - let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams"); + // The cage's surface and wireframe show apart, in their own color and opacity + let surface_only = only(&mut h, BakeVisualization { cage_surface: shown(bake.cage_surface), ..bake }, "bake_cage_surface"); + let wire_only = only(&mut h, BakeVisualization { cage_wire: shown(bake.cage_wire), ..bake }, "bake_cage_wire"); + assert!(surface_only.px != low_only.px && wire_only.px != low_only.px && surface_only.px != wire_only.px, "each part of the cage draws on its own"); + let opaque_blue = BakeOverlay { color: [0.0, 0.0, 1.0], opacity: 1.0, ..caged_parts.cage_surface }; + let [red, green, blue] = + only(&mut h, BakeVisualization { cage_surface: opaque_blue, ..bake }, "bake_cage_surface_blue").at(center.0, center.1).map(i32::from); + assert!(blue > red + COLOR_LEAD && blue > green + COLOR_LEAD, "an opaque blue cage hides the ball: {:?}", [red, green, blue]); + let clear = only(&mut h, BakeVisualization { cage_surface: BakeOverlay { opacity: 0.0, ..opaque_blue }, ..bake }, "bake_cage_surface_clear"); + assert_same(&clear, &low_only, "a fully transparent cage leaves the ball as it is"); + + // High-poly vertices another set owns are left out + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![-1.0; high.positions.len()]); + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_high_hidden_background"); + assert_same(&only(&mut h, high_only, "bake_high_other_set"), &background, "a high poly owned by other sets draws nothing"); + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![0.0; high.positions.len()]); + + // The missing seams draw over the low poly in their color + h.renderer.set_missing_seams(&h.device, &h.queue, MESH_ID, &ball.wire_edges()); + let seams = only(&mut h, BakeVisualization { missing_seams: shown(bake.missing_seams), ..bake }, "bake_missing_seams"); assert_ne!(seams.px, low_only.px, "the seams show"); + let green_seams = BakeOverlay { color: [0.0, 1.0, 0.0], ..shown(bake.missing_seams) }; + assert_ne!( + only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_green").px, + seams.px, + "the seams' color reaches the shader" + ); + let uv = Frame { view_id: 2, kind: ViewKind::Uv { ts: 0, zoom: 1.0, pan: [0.0, 0.0] }, ..frame.clone() }; + let uv_plain = render(&mut h, &shaded(&uv, |s| s.bake = Some(bake)), "bake_missing_seams_uv_off"); + let uv_seams = render(&mut h, &shaded(&uv, |s| s.bake = Some(BakeVisualization { missing_seams: green_seams, ..bake })), "bake_missing_seams_uv"); + assert_ne!(uv_seams.px, uv_plain.px, "the seams show in the 2D view too"); + let caged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..caged_parts }, "bake_missing_seams_cage"); + let uncaged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_no_cage"); + let caged_plain = only(&mut h, caged_parts, "bake_cage_no_seams"); + assert_ne!(caged_seams.px, caged_plain.px, "the seams show with the cage"); + assert_ne!(caged_seams.px, uncaged_seams.px); // A new distance with the same topology only moves the corners let grown: Vec = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect(); - h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY); - let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown"); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some(CageGeometry { corners: &grown, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY); + let bigger = only(&mut h, caged_parts, "bake_cage_grown"); assert_ne!(caged.px, bigger.px, "the cage grew"); } @@ -307,7 +431,7 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() { assert!(error.contains("GPU buffer limit"), "{error}"); headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]); - let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None }; + let bake = BakeVisualization { high_poly: shown(BakeVisualization::default().high_poly), ..BakeVisualization::default() }; let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared"); let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background"); assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible"); @@ -317,10 +441,10 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() { } #[test] -fn bake_low_poly_visibility_also_filters_its_wireframe() { +fn bake_low_poly_visibility_also_filters_its_wireframe_but_not_by_selected_set() { let Some((mut headless, frame)) = setup() else { return }; - let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None }; + let bake = BakeVisualization::default(); let hidden = shaded(&frame, |shade| { shade.bake = Some(bake); shade.wireframe_3d = true; @@ -332,13 +456,13 @@ fn bake_low_poly_visibility_also_filters_its_wireframe() { for texture_set in [0, 1] { let selected = shaded(&hidden, |shade| { - shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake }); + shade.bake = Some(BakeVisualization { low_poly: shown(bake.low_poly), only_set: Some(texture_set), ..bake }); shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] }); }); - let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() }; + let expected = shaded(&selected, |shade| shade.bake = Some(BakeVisualization { only_set: None, ..shade.bake.unwrap_or(bake) })); let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}")); let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}")); - assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set"); + assert_same(&actual, &expected, "the selected-set filter leaves the low poly, its wireframe and highlight alone"); } } diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs index 42da4393..e8d1c665 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -1,58 +1,189 @@ use egui::collapsing_header::CollapsingState; use egui::{Rect, Ui, vec2}; use egui_phosphor::regular as icon; +use texturecraft_render::BakeOverlay; +use super::BakeVisualizationToggles; +use super::section_opening::SectionOpening; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{n_, tr, trf}; +use crate::screen_color_pick::eyedropper; use crate::theme::Tokens; -use crate::widgets::{icon_button_without_tooltip, section_chevron}; +use crate::widgets::{color_swatch, combo, icon_button, section_chevron, slider}; /// The panel's width and its gap from the 3D view's top-left corner const PANEL_WIDTH: f32 = 280.0; const PANEL_MARGIN: f32 = 12.0; -/// Size of the panel's eye buttons +/// Opacity of the panel's backing +const PANEL_OPACITY: f32 = 0.92; + +/// Size of the panel's eye button, and of the smaller buttons on its rows const EYE_BUTTON_SIZE: f32 = 22.0; +const ROW_BUTTON_SIZE: f32 = 18.0; + +/// Width of an overlay's color swatch +const SWATCH_WIDTH: f32 = 44.0; + +/// The neutral material's quality steps: samples per pixel and their names +const QUALITIES: [(u32, &str); 6] = [ + (4, n_("Very Low (4 spp)")), + (16, n_("Low (16 spp)")), + (32, n_("Medium (32 spp)")), + (64, n_("High (64 spp)")), + (128, n_("Very High (128 spp)")), + (256, n_("Ultra (256 spp)")), +]; /// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { let toggles = &mut app.ui.bake_visualization; + let tokens = Tokens::get(ui.ctx()); egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( ui.ctx(), |ui| { - ui.set_width(PANEL_WIDTH); - let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true); - let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open())); - if header.clicked() { - collapsing_state.toggle(ui); - } + // Its own backing, so the panel reads in every theme over whatever the 3D view shows + egui::Frame::popup(ui.style()).fill(tokens.panel.gamma_multiply(PANEL_OPACITY)).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + // Ids renamed with the reference defaults, so open/closed states saved by earlier builds don't carry over + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("baking_visualization_open"), true); + if header(ui, toggles, collapsing_state.is_open()).clicked() { + collapsing_state.toggle(ui); + } - collapsing_state.show_body_unindented(ui, |ui| { - ui.add_enabled_ui(toggles.on, |ui| { - ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); - eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None); - eye_row(ui, &mut toggles.cage, tr("Cage"), None); - eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None); - eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None); - }); + collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles)); }); }, ); } -/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response -fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option) -> egui::Response { +/// The panel's sections below its header +fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { + ui.horizontal(|ui| { + ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(egui::RichText::new(icon::INFO).color(Tokens::get(ui.ctx()).text_dim)) + .on_hover_text(tr("Only the cage and the high poly meshes of the selected texture set show.")); + }); + }); + + // The eye greys what it hides, and holds the project mesh shown + let meshes_editable = !toggles.hide_baking_meshes; + if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| { + overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh); + overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error); + }) { + toggles.reset_high_poly(); + } + + if collapsible(ui, "cage", tr("Cage"), SectionOpening::Open, true, meshes_editable, |ui| { + overlay_row(ui, "bake_cage_surface_color", tr("Cage Surface"), &mut toggles.cage_surface); + ui.add_enabled_ui(toggles.cage_surface.shown, |ui| slider(ui, tr("Cage Surface Opacity"), &mut toggles.cage_surface.opacity, 0.0..=1.0, 2)); + overlay_row(ui, "bake_cage_wire_color", tr("Cage Wireframe"), &mut toggles.cage_wire); + ui.add_enabled_ui(toggles.cage_wire.shown, |ui| slider(ui, tr("Cage Wireframe Opacity"), &mut toggles.cage_wire.opacity, 0.0..=1.0, 2)); + }) { + toggles.reset_cage(); + } + + if collapsible(ui, "seams", tr("UV Seams"), SectionOpening::Closed, true, true, |ui| { + overlay_row(ui, "bake_missing_seam_color", tr("Missing Seams on Hard Edges"), &mut toggles.missing_seams); + }) { + toggles.reset_seams(); + } + + if collapsible(ui, "project_mesh", tr("Project Mesh (LP)"), SectionOpening::Closed, true, true, |ui| { + ui.add_enabled_ui(meshes_editable, |ui| overlay_row(ui, "bake_project_mesh_color", tr("Project Mesh"), &mut toggles.project_mesh)); + ui.add_enabled_ui(toggles.project_mesh.shown, |ui| { + collapsible(ui, "neutral_material", tr("Neutral Material"), SectionOpening::Open, false, true, |ui| neutral_material(ui, toggles)) + }); + }) { + toggles.reset_project_mesh(); + } +} + +/// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal +fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { + ui.add_enabled_ui(toggles.neutral_shown, |ui| { + let neutral = &mut toggles.neutral; + let selected = QUALITIES.iter().find(|(samples, _)| *samples == neutral.samples_per_pixel).map_or("", |(_, name)| tr(name)); + combo(ui, tr("Quality"), selected, |ui| { + for (samples, name) in QUALITIES { + ui.selectable_value(&mut neutral.samples_per_pixel, samples, tr(name)); + } + }); + slider(ui, tr("Roughness"), &mut neutral.roughness, 0.0..=1.0, 2); + slider(ui, tr("Metallic"), &mut neutral.metallic, 0.0..=1.0, 2); + slider(ui, tr("AO intensity"), &mut neutral.ao_intensity, 0.0..=1.0, 2); + ui.checkbox(&mut neutral.bent_normal, tr("Bent Normal")); + ui.add_enabled_ui(neutral.bent_normal, |ui| { + slider(ui, tr("Bent Normal Diffuse Amount"), &mut neutral.bent_normal_diffuse, 0.0..=1.0, 2); + slider(ui, tr("Bent Normal Specular Amount"), &mut neutral.bent_normal_specular, 0.0..=1.0, 2); + }); + }); +} + +/// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked +fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool { + let tokens = Tokens::get(ui.ctx()); + let mut collapsing_state = + CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open); + let (header, reset) = ui + .horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = egui::RichText::new(format!("{} {title}", section_chevron(ui, collapsing_state.is_open()).text())).strong().color(tokens.text_strong); + let header = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); + // Dimmed while the section is closed, as the reference draws it + let reset = resettable.then(|| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(collapsing_state.is_open() && editable, |ui| { + icon_button(ui, icon::CLOCK_COUNTER_CLOCKWISE, &trf("Reset {section}", &[("section", &title)]), false, ROW_BUTTON_SIZE) + }) + .inner + }) + .inner + }); + (header, reset) + }) + .inner; + if header.clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_indented(&header, ui, |ui| { + ui.add_enabled_ui(editable, body); + }); + reset.is_some_and(|reset| reset.clicked()) +} + +/// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right +fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) { + ui.horizontal(|ui| { + ui.checkbox(&mut overlay.shown, label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(overlay.shown, |ui| { + eyedropper( + ui, + ui.make_persistent_id(id), + &mut overlay.color, + &trf("Pick the {overlay} Color from the Screen", &[("overlay", &label)]), + ROW_BUTTON_SIZE, + ); + color_swatch(ui, id, &mut overlay.color, SWATCH_WIDTH); + }); + }); + }); +} + +/// The panel's title with a chevron showing whether the panel is `open`, and the eye that hides the baking meshes; returns the title's response +fn header(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, open: bool) -> egui::Response { let tokens = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.set_min_height(EYE_BUTTON_SIZE); - let text = match open { - Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())), - None => egui::RichText::new(label), - }; - let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click())); + let text = egui::RichText::new(format!("{} {}", section_chevron(ui, open).text(), tr("Baking Visualization"))).color(tokens.text_strong); + let response = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() { - *shown = !*shown; + if icon_button(ui, icon::EYE_SLASH, tr("Hide Baking Meshes"), toggles.hide_baking_meshes, EYE_BUTTON_SIZE).clicked() { + toggles.toggle_hiding(); } }); response diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs index 0603c523..bb99e09b 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -1,34 +1,140 @@ use serde::{Deserialize, Serialize}; -use texturecraft_render::BakeVisualization; +use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial}; -/// The Baking Visualization panel's switches in bake mode's 3D view +/// Opacity of the cage's surface and wireframe until changed +const CAGE_OPACITY: f32 = 0.4; + +/// The Baking Visualization panel's settings for bake mode's 3D view (view state, not saved in the project) #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct BakeVisualizationToggles { - /// The panel's eye: the whole visualization on or off - pub on: bool, + /// The panel's eye: hides the high poly and the cage, whatever their own switches say + pub hide_baking_meshes: bool, pub selected_set_only: bool, - pub high_poly: bool, - pub cage: bool, - pub uv_seams: bool, - pub low_poly: bool, + pub high_poly_mesh: BakeOverlay, + pub matching_error: BakeOverlay, + pub cage_surface: BakeOverlay, + pub cage_wire: BakeOverlay, + pub missing_seams: BakeOverlay, + pub project_mesh: BakeOverlay, + /// Show the project mesh with [`Self::neutral`] instead of its painted material + pub neutral_shown: bool, + pub neutral: NeutralMaterial, } impl Default for BakeVisualizationToggles { fn default() -> Self { - Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true } + let parts = BakeVisualization::default(); + let shown = |overlay: BakeOverlay| BakeOverlay { shown: true, ..overlay }; + Self { + hide_baking_meshes: false, + selected_set_only: false, + high_poly_mesh: shown(parts.high_poly), + matching_error: shown(parts.matching_error), + cage_surface: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_surface) }, + cage_wire: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_wire) }, + missing_seams: shown(parts.missing_seams), + project_mesh: shown(parts.low_poly), + neutral_shown: true, + neutral: NeutralMaterial::default(), + } } } impl BakeVisualizationToggles { - /// What the renderer draws with these switches while texture set `selected_set` is selected - pub fn visualization(&self, selected_set: usize) -> Option { - self.on.then_some(BakeVisualization { - high_poly: self.high_poly, - cage: self.cage, - uv_seams: self.uv_seams, - low_poly: self.low_poly, + /// What the renderer draws with these settings while texture set `selected_set` is selected + pub fn visualization(&self, selected_set: usize) -> BakeVisualization { + let unless_hidden = |overlay: BakeOverlay| BakeOverlay { shown: overlay.shown && !self.hide_baking_meshes, ..overlay }; + BakeVisualization { + high_poly: unless_hidden(self.high_poly_mesh), + matching_error: self.matching_error, + cage_surface: unless_hidden(self.cage_surface), + cage_wire: unless_hidden(self.cage_wire), + missing_seams: self.missing_seams, + low_poly: self.project_mesh, + neutral: self.neutral_shown.then_some(self.neutral), only_set: self.selected_set_only.then_some(selected_set), - }) + } + } + + /// Whether the project mesh shows the neutral material lit along the bent normal, which the 3D view then reads in place of a mesh map + pub fn bent_normal_shown(&self) -> bool { + self.project_mesh.shown && self.neutral_shown && self.neutral.bent_normal + } + + /// Switch the panel's eye; hiding the baking meshes shows the project mesh, so the view never goes empty + pub fn toggle_hiding(&mut self) { + self.hide_baking_meshes = !self.hide_baking_meshes; + self.project_mesh.shown |= self.hide_baking_meshes; + } + + /// Put the High Definition Mesh section back to its defaults + pub fn reset_high_poly(&mut self) { + let defaults = Self::default(); + (self.high_poly_mesh, self.matching_error) = (defaults.high_poly_mesh, defaults.matching_error); + } + + /// Put the Cage section back to its defaults + pub fn reset_cage(&mut self) { + let defaults = Self::default(); + (self.cage_surface, self.cage_wire) = (defaults.cage_surface, defaults.cage_wire); + } + + /// Put the UV Seams section back to its defaults + pub fn reset_seams(&mut self) { + self.missing_seams = Self::default().missing_seams; + } + + /// Put the Project Mesh section back to its defaults + pub fn reset_project_mesh(&mut self) { + let defaults = Self::default(); + (self.project_mesh, self.neutral_shown, self.neutral) = (defaults.project_mesh, defaults.neutral_shown, defaults.neutral); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn panel_settings_saved_by_earlier_builds_start_over_from_the_defaults() { + let mut saved = serde_json::to_value(crate::state::UiState::default()).unwrap(); + let fields = saved.as_object_mut().unwrap(); + fields.remove("baking_visualization"); + fields.insert( + "bake_visualization".into(), + serde_json::json!({"hide_baking_meshes": false, "missing_seams": {"shown": false, "color": [1, 0, 0], "opacity": 1}}), + ); + let state: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(state.bake_visualization, BakeVisualizationToggles::default()); + } + + #[test] + fn the_settings_reach_the_renderer() { + let mut toggles = BakeVisualizationToggles::default(); + toggles.cage_wire.color = [0.1, 0.2, 0.3]; + toggles.neutral_shown = false; + let visualization = toggles.visualization(2); + assert_eq!(visualization.cage_wire, toggles.cage_wire); + assert_eq!(visualization.neutral, None); + assert_eq!(visualization.only_set, None); + toggles.selected_set_only = true; + assert_eq!(toggles.visualization(2).only_set, Some(2)); + } + + #[test] + fn the_eye_hides_the_baking_meshes_and_keeps_the_project_mesh() { + let mut toggles = BakeVisualizationToggles::default(); + let shown = toggles.visualization(0); + assert!(shown.high_poly.shown && shown.cage_surface.shown && shown.cage_wire.shown, "the eye starts off, as in the reference"); + + toggles.project_mesh.shown = false; + toggles.toggle_hiding(); + let hidden = toggles.visualization(0); + assert!(!hidden.high_poly.shown && !hidden.cage_surface.shown && !hidden.cage_wire.shown); + assert!(hidden.low_poly.shown, "hiding the baking meshes brings the project mesh back"); + + toggles.toggle_hiding(); + assert!(toggles.visualization(0).high_poly.shown, "the eye switches back"); } } diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 9013be73..490fa2a5 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -5,6 +5,7 @@ mod bake_visualization_panel; mod bake_visualization_toggles; mod breadcrumb; mod common_settings; +mod section_opening; pub use bake_paint_brush::BakePaintBrush; pub(crate) use bake_visualization_panel::bake_visualization_panel; pub use bake_visualization_toggles::BakeVisualizationToggles; diff --git a/crates/ui-egui/src/bake_mode/section_opening.rs b/crates/ui-egui/src/bake_mode/section_opening.rs new file mode 100644 index 00000000..8428a7f7 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/section_opening.rs @@ -0,0 +1,6 @@ +/// Whether a Baking Visualization section starts open, as the reference shows the panel at first launch (HP and Cage open, UV seams and Project mesh closed) +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum SectionOpening { + Open, + Closed, +} diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs index b9cecaa9..c53d6e20 100644 --- a/crates/ui-egui/src/bake_scene/bake_scene_link.rs +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -11,7 +11,7 @@ use super::reach_link::ReachLink; use super::shared_handle::SharedHandle; use crate::gpu::SceneSync; -/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams +/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the missing seams #[derive(Default)] pub struct BakeSceneLink { /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one) @@ -51,7 +51,7 @@ impl BakeSceneLink { let Some(visualization) = visualization else { return }; - if visualization.high_poly { + if visualization.high_poly.shown { let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); let handle = SharedHandle::of(high.as_ref()); if handle != self.high { @@ -64,14 +64,19 @@ impl BakeSceneLink { self.high_sent = true; } self.reach.sync(session, self.high_id, visualization.only_set, out); + } else if self.high_sent { + // A hidden high poly leaves the GPU; showing it again sends it and its colours under the same id, so its reach is not worked out again + out.bake_high = Some((None, self.high_id)); + self.high_sent = false; + self.reach.resend(); } - if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) { + if visualization.missing_seams.shown && self.seams_mesh_id != Some(session.mesh_id) { self.seams_mesh_id = Some(session.mesh_id); - out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges())); + out.missing_seams = Some((session.mesh_id, session.mesh.missing_seam_edges())); } - if visualization.cage { + if visualization.cage_shown() { self.sync_cages(session, out); } } @@ -117,7 +122,20 @@ mod tests { use super::*; use serde_json::json; - const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + /// Every part of the visualization shown + fn everything() -> BakeVisualization { + let parts = BakeVisualization::default(); + let shown = |overlay: texturecraft_render::BakeOverlay| texturecraft_render::BakeOverlay { shown: true, ..overlay }; + BakeVisualization { + high_poly: shown(parts.high_poly), + matching_error: shown(parts.matching_error), + cage_surface: shown(parts.cage_surface), + cage_wire: shown(parts.cage_wire), + missing_seams: shown(parts.missing_seams), + low_poly: shown(parts.low_poly), + ..parts + } + } /// How long a test waits for the reach worker: frames, and the pause between them const WAIT_FRAMES: usize = 2000; @@ -165,41 +183,61 @@ mod tests { #[test] fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() { let (mut session, mut link) = (session(), BakeSceneLink::default()); - let first = sync(&mut link, &session, EVERYTHING); - assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); + let first = sync(&mut link, &session, everything()); + assert!(first.bake_high.is_some() && first.missing_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; - let unchanged = sync(&mut link, &session, EVERYTHING); - assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent"); + let unchanged = sync(&mut link, &session, everything()); + assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.missing_seams.is_none(), "nothing changed, nothing is sent"); set_distances(&mut session, 0.03); - let moved = sync(&mut link, &session, EVERYTHING); + let moved = sync(&mut link, &session, everything()); let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; assert_eq!(moved_topology, topology, "a distance only moves the corners"); assert_ne!(moved_cage.corners, cage.corners); texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); - let rebuilt = sync(&mut link, &session, EVERYTHING); + let rebuilt = sync(&mut link, &session, everything()); assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); // The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts - red_share(&mut link, &session, EVERYTHING); + red_share(&mut link, &session, everything()); link.resend(); - let resent = sync(&mut link, &session, EVERYTHING); - assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); + let resent = sync(&mut link, &session, everything()); + assert!(resent.bake_high.is_some() && resent.missing_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len()); assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame"); assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id"); assert!(!link.busy(), "a lost frame doesn't work out the reach again"); } + #[test] + fn a_hidden_high_poly_leaves_the_gpu_and_comes_back_without_a_new_reach() { + let (session, mut link) = (session(), BakeSceneLink::default()); + let sent = |out: SceneSync| out.bake_high.map(|(high, id)| (high.is_some(), id)); + let hidden = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() }; + let first = sent(sync(&mut link, &session, everything())); + red_share(&mut link, &session, everything()); + let dropped = sent(sync(&mut link, &session, hidden)); + assert!(sync(&mut link, &session, hidden).bake_high.is_none(), "dropped once"); + let back = sync(&mut link, &session, everything()); + assert!(!link.busy(), "showing it again starts no new reach"); + assert!(back.bake_high_missed.is_some(), "its colours are sent again with it"); + + let (Some((true, first_id)), Some((false, dropped_id)), Some((true, back_id))) = (first, dropped, sent(back)) else { + panic!("the high poly is sent, dropped, then sent again") + }; + + assert_eq!((dropped_id, back_id), (first_id, first_id)); + } + #[test] fn a_reach_finishes_while_nothing_is_drawn() { let session = session(); - let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING }; + let no_high_poly = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() }; for hidden in [None, Some(no_high_poly)] { let mut link = BakeSceneLink::default(); - sync(&mut link, &session, EVERYTHING); + sync(&mut link, &session, everything()); assert!(link.busy(), "the first frame starts working out the reach"); let finished = (0..WAIT_FRAMES).any(|_| { @@ -215,11 +253,11 @@ mod tests { fn the_red_follows_the_distances_and_the_selected_set() { let (mut session, mut link) = (session(), BakeSceneLink::default()); set_distances(&mut session, 0.0); - let at_zero = red_share(&mut link, &session, EVERYTHING); + let at_zero = red_share(&mut link, &session, everything()); assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}"); set_distances(&mut session, 0.05); - let covered = red_share(&mut link, &session, EVERYTHING); + let covered = red_share(&mut link, &session, everything()); assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}"); set_distances(&mut session, 0.0); @@ -230,10 +268,11 @@ mod tests { } }; by_name(&mut session, "_no_such_suffix"); - let by_name_red = red_share(&mut link, &session, EVERYTHING); + let by_name_red = red_share(&mut link, &session, everything()); assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}"); - let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING }; - assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing"); + let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..everything() }; + let hidden = texturecraft_engine::bake::HIDDEN_HIGH_POLY_VERTEX; + assert_eq!(red_share(&mut link, &session, no_set), hidden, "a filter that keeps no set hides the whole high poly"); } } diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 944a8ecd..520c5616 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -11,7 +11,7 @@ use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::Mesh; -use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu}; +use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu}; use crate::bake_scene::{BakeSceneLink, CageUpload}; @@ -27,8 +27,8 @@ pub enum AuxView { /// A texture set's texels across and down, and its mesh material. pub type SetLayout = ((u32, u32), usize); -/// The low poly's UV seam edges (vertex pairs) per material -pub type UvSeamEdges = Vec>; +/// The low poly's hard edges without a UV seam (vertex pairs) per material +pub type MissingSeamEdges = Vec>; /// What the renderer must catch up with before drawing. #[derive(Default)] @@ -49,8 +49,8 @@ pub struct SceneSync { pub bake_cages: Vec<(usize, Option, u64)>, /// Texture sets left after some were removed: their cages go too pub bake_cage_count: Option, - /// The low poly's UV seams per material, for mesh id - pub uv_seams: Option<(u64, UvSeamEdges)>, + /// The low poly's hard edges without a UV seam per material, for mesh id + pub missing_seams: Option<(u64, MissingSeamEdges)>, } /// Lives in egui's callback resources. @@ -366,11 +366,15 @@ impl CallbackTrait for ViewCallback { gpu.renderer.truncate_bake_cages(count); } for (texture_set, cage, topology) in &sync.bake_cages { - let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice())); + let cage = cage.as_ref().map(|upload| CageGeometry { + corners: &upload.corners, + edges: &upload.shell.edges, + missing_seams: &upload.shell.missing_seams, + }); gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology); } - if let Some((mesh_id, seams)) = &sync.uv_seams { - gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams); + if let Some((mesh_id, seams)) = &sync.missing_seams { + gpu.renderer.set_missing_seams(device, queue, *mesh_id, seams); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..78047b99 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -46,6 +46,7 @@ pub mod render_mode; mod resource_picker; mod resource_picker_item; mod running_bake; +mod screen_color_pick; pub mod shelf; pub mod shelf_preview; mod soft_box; diff --git a/crates/ui-egui/src/screen_color_pick.rs b/crates/ui-egui/src/screen_color_pick.rs new file mode 100644 index 00000000..3cd752d5 --- /dev/null +++ b/crates/ui-egui/src/screen_color_pick.rs @@ -0,0 +1,94 @@ +//! An eyedropper button: after it is pressed, the next click anywhere in the window picks the color shown there + +use std::sync::{Arc, Mutex}; + +use egui::{Id, Pos2, Ui}; +use egui_phosphor::regular as icon; + +use crate::widgets::icon_button; + +/// Where the pick in progress is kept between frames +const PICK_ID: &str = "screen_color_pick"; + +/// Where a screenshot callback leaves the sampled sRGB color for the button that asked for it +type SampledSlot = Arc>>; + +/// The pick in progress: which button started it, and the color its screenshot sampled once that arrives +#[derive(Clone, Default)] +struct ScreenColorPick { + target: Option, + /// Filled by the screenshot callback with the target and the sRGB color under the click + sampled: SampledSlot, +} + +/// An eyedropper button for the linear RGB color `linear`, `size` points square; a picked color lands in `linear` a frame or two after the click +pub fn eyedropper(ui: &mut Ui, id: Id, linear: &mut [f32; 3], tooltip: &str, size: f32) { + let key = Id::unique(PICK_ID); + let mut pick: ScreenColorPick = ui.data(|data| data.get_temp(key)).unwrap_or_default(); + let picking = pick.target == Some(id); + + let button = icon_button(ui, icon::EYEDROPPER, tooltip, picking, size); + if button.clicked() { + pick.target = if picking { None } else { Some(id) }; + } else if picking { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + let (clicked, escaped, pointer) = + ui.input(|input| (input.pointer.primary_clicked(), input.key_pressed(egui::Key::Escape), input.pointer.interact_pos())); + if escaped { + pick.target = None; + } else if clicked && let Some(point) = pointer { + request_sample(ui.ctx(), id, point, pick.sampled.clone()); + pick.target = None; + } + } + + let landed = pick.sampled.lock().ok().and_then(|mut sampled| sampled.take_if(|(target, _)| *target == id)); + if let Some((_, srgb)) = landed { + *linear = srgb.map(|channel| texturecraft_engine::texel::srgb_to_linear(f32::from(channel) / 255.0)); + } + + ui.data_mut(|data| data.insert_temp(key, pick)); +} + +/// Screenshot the next frame and put the color at `point` (in points) into `sampled` for `target` +fn request_sample(ctx: &egui::Context, target: Id, point: Pos2, sampled: SampledSlot) { + let pixels_per_point = ctx.pixels_per_point(); + let repaint = ctx.clone(); + let callback = egui::ScreenshotCallback::new(move |image| { + if let (Some(color), Ok(mut slot)) = (pixel_at(&image, point, pixels_per_point), sampled.lock()) { + *slot = Some((target, color)); + } + repaint.request_repaint(); + }); + ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback)); + ctx.request_repaint(); +} + +/// The sRGB color of `image` under `point` (in points at `pixels_per_point`); `None` outside it +fn pixel_at(image: &egui::ColorImage, point: Pos2, pixels_per_point: f32) -> Option<[u8; 3]> { + let (x, y) = ((point.x * pixels_per_point).floor(), (point.y * pixels_per_point).floor()); + let [width, height] = image.size; + if !(x >= 0.0 && y >= 0.0 && (x as usize) < width && (y as usize) < height) { + return None; + } + + let color = image.pixels.get(y as usize * width + x as usize)?; + Some([color.r(), color.g(), color.b()]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pixel_under_the_point_is_sampled_at_the_display_scale() { + let mut image = egui::ColorImage::filled([4, 2], egui::Color32::BLACK); + image.pixels[4 + 3] = egui::Color32::from_rgb(10, 20, 30); + + assert_eq!(pixel_at(&image, egui::pos2(1.6, 0.6), 2.0), Some([10, 20, 30])); + assert_eq!(pixel_at(&image, egui::pos2(0.2, 0.2), 2.0), Some([0, 0, 0])); + for outside in [egui::pos2(-0.1, 0.0), egui::pos2(2.0, 0.0), egui::pos2(0.0, 1.0), egui::pos2(f32::NAN, 0.0)] { + assert_eq!(pixel_at(&image, outside, 2.0), None, "{outside:?}"); + } + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e52a2907..1dd45d4f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -329,8 +329,8 @@ pub struct UiState { /// How the 3D view shows symmetry #[serde(default)] pub symmetry: crate::symmetry::SymmetryDisplay, - /// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel) - #[serde(default)] + /// The Baking Visualization panel's settings, under a key of their own since the reference defaults: older saved ones start over + #[serde(default, rename = "baking_visualization")] pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4ac469eb..a1facb47 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -60,6 +60,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => Some(crate::gpu::AuxView::QuickMask), ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), + _ if mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)), _ => None, }; let mut sync = PendingSync(Some(aux_view)); @@ -316,7 +317,7 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame, sync: &mut PendingSync) { let tokens = Tokens::get(ui.ctx()); let bake = bake_visualization(app); - frame.shade.bake = bake.filter(|_| frame.kind == ViewKind::Scene); + frame.shade.bake = bake; let scene = match (sync.0.take(), app.gpu.as_mut()) { (Some(aux), Some(gpu_link)) => { let sync_start_ms = crate::now_ms(); @@ -392,28 +393,38 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { } }); + // Bake mode lights the project mesh with the neutral material unless the painted one is asked for + let baking = app.ui.mode == crate::state::Mode::Baking; + let neutral = baking && app.session.view == ViewMode::Material && app.ui.bake_visualization.neutral_shown; let label = match app.session.view { + _ if neutral => "Neutral Material".to_owned(), ViewMode::MeshMap(map) => crate::i18n::baked_map_label(map).to_owned(), _ => app.session.view.label(), }; let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(&mut child, |ui| { - if ui.selectable_label(app.session.view == ViewMode::Material, tr("Material")).clicked() { + if baking && ui.selectable_label(neutral, tr("Neutral Material")).clicked() { + app.ui.bake_visualization.neutral_shown = true; + app.run("viewport.view", json!({"mode": "material"})); + } + if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() { + // Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone + app.ui.bake_visualization.neutral_shown &= !baking; app.run("viewport.view", json!({"mode": "material"})); } ui.separator(); + if baking { + mesh_map_entries(app, ui); + return; + } + for channel in channels { if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { app.run("viewport.view", json!({"mode": channel.id()})); } } ui.separator(); - for map in BakedMap::ALL { - let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); - if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() { - app.run("viewport.view", json!({"mode": format!("map:{}", map.id())})); - } - } + mesh_map_entries(app, ui); ui.separator(); if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() { app.run("viewport.view", json!({"mode": "uvChecker"})); @@ -421,6 +432,16 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { }); } +/// The view picker's entries that show one baked mesh map +fn mesh_map_entries(app: &mut TextureCraftApp, ui: &mut Ui) { + for map in BakedMap::ALL { + let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); + if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() { + app.run("viewport.view", json!({"mode": format!("map:{}", map.id())})); + } + } +} + fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) { let tk = Tokens::get(ui.ctx()); let o = pos2(rect.left() + 28.0, rect.bottom() - 28.0); @@ -781,7 +802,7 @@ fn bake_visualization(app: &TextureCraftApp) -> Option Date: Wed, 11 Nov 2026 07:30:11 +0000 Subject: [PATCH 034/115] Bake settings: high poly list, and Cage and Skew Correction greyed with the reason High Poly Scene is a list with + and -, as in the reference. Without a high poly the high-poly, Cage and Skew Correction controls show greyed instead of hidden, and a line says why. Skew Correction applies only to a distance-based cage with Average Normals and a separate high poly, in the panel and in the bake (a painted skew map no longer changes other bakes). --- crates/core/src/bake/bake_settings.rs | 9 +- crates/engine/src/bake/mesh_map_command.rs | 3 +- crates/engine/tests/it/bake.rs | 15 ++ .../ui-egui/src/bake_mode/common_settings.rs | 201 +++++++++++------- crates/ui-egui/src/viewport.rs | 8 +- crates/ui-egui/tests/it/bake_mode.rs | 65 +++++- crates/ui-egui/tests/it/skew_paint.rs | 12 ++ 7 files changed, 233 insertions(+), 80 deletions(-) diff --git a/crates/core/src/bake/bake_settings.rs b/crates/core/src/bake/bake_settings.rs index 4528270d..8d121419 100644 --- a/crates/core/src/bake/bake_settings.rs +++ b/crates/core/src/bake/bake_settings.rs @@ -1,4 +1,4 @@ -use super::{CageSettings, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; +use super::{CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; use serde::{Deserialize, Serialize}; /// Persisted clean-room bake settings, grouped by the controls they belong to @@ -11,3 +11,10 @@ pub struct BakeSettings { pub skew: SkewSettings, pub maps: MeshMapSettings, } + +impl BakeSettings { + /// Whether a painted skew map steers the rays: it needs a separate high poly and a distance-based cage with averaged normals + pub fn skew_applies(&self) -> bool { + !self.high_poly.use_low_as_high && self.cage.kind == CageType::DistanceBased && self.cage.average_normals + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 14248cc3..0c14027f 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -182,7 +182,8 @@ impl Session { /// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result>> { let set = self.doc.project.texture_set(texture_set)?; - let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high); + let steers = has_high && (target != BakePaintTarget::Skew || set.bake.skew_applies()); + let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| steers); paint.map(|map| super::layout::paint_for_bake(map, set)).transpose() } diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 85b0142c..20c3d5ab 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -504,6 +504,21 @@ fn the_skew_map_is_saved_with_the_project() { ); } +#[test] +fn the_skew_map_steers_only_a_distance_cage_with_averaged_normals() { + let mut s = leaning_session(false); + execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap(); + assert!(s.bake_task(0).unwrap().skew.is_some()); + + s.doc.project.texture_sets[0].bake.cage.average_normals = false; + assert!(s.bake_task(0).unwrap().skew.is_none(), "without averaged normals the skew map is left out"); + s.doc.project.texture_sets[0].bake.cage.average_normals = true; + let cage = obj(&s.mesh.clone(), 0.05, f32::MAX, [1.0; 3]); + s.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap(); + s.doc.project.texture_sets[0].bake.cage.kind = texturecraft_core::CageType::CustomFile; + assert!(s.bake_task(0).unwrap().skew.is_none(), "a cage file sets the rays itself"); +} + #[test] fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() { let mut s = leaning_session(true); diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index 02d712a0..1953d2d3 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -1,6 +1,7 @@ use super::controls::{choice, hint, integer, number, section, text_input}; use crate::TextureCraftApp; use crate::i18n::tr; +use crate::theme::Tokens; use crate::widgets::icon_button; use egui::Ui; use egui_phosphor::regular as icon; @@ -9,7 +10,16 @@ use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; -/// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage) +/// How many rows the high poly list box is tall +const HIGH_POLY_LIST_ROWS: f32 = 5.0; + +/// Space between the panel's sections, in points +const SECTION_GAP: f32 = 8.0; + +/// Widest dilation the slider offers, in texels (the bake settings command accepts the same) +const MAX_DILATION_WIDTH: u32 = 128; + +/// The output and high-poly sections, then cage and skew, greyed with the reason when they can't apply pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option { let mut reset = Map::new(); ui.push_id("common", |ui| { @@ -28,7 +38,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe (BakeAntialiasing::Subsampling8x8, tr("Subsampling 8x8")), ], ); - integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=128); + integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH); ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion")); }) { settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; @@ -40,12 +50,14 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } }); - ui.add_space(8.0); + // Without a high poly the reference shows everything that needs one greyed, not hidden + let has_high = !app.session.bake_meshes.high.is_empty(); + ui.add_space(SECTION_GAP); ui.push_id("high_poly", |ui| { if section(ui, tr("High-Poly Parameters"), |ui| { ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh")); - high_poly_files(app, ui); - if !app.session.bake_meshes.high.is_empty() { + high_poly_scene(app, ui); + ui.add_enabled_ui(has_high, |ui| { ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface")); choice( ui, @@ -56,67 +68,89 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe text_input(ui, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); text_input(ui, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); text_input(ui, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); - } + }); }) { settings.high_poly = Default::default(); reset.insert("high_poly".into(), json!(settings.high_poly)); } }); - if !app.session.bake_meshes.high.is_empty() { - ui.add_space(8.0); - ui.push_id("cage", |ui| { - if section(ui, tr("Cage"), |ui| { + ui.add_space(SECTION_GAP); + ui.push_id("cage", |ui| { + if section(ui, tr("Cage"), |ui| { + // The cage steers rays toward a separate high poly, so it has nothing to do without one + let cage_applies = has_high && !settings.high_poly.use_low_as_high; + if !has_high { + hint(ui, tr("The cage applies once a high poly mesh is loaded.")); + } else if !cage_applies { + hint(ui, tr("The cage is not used while the low poly mesh is used as the high poly mesh.")); + } + ui.add_enabled_ui(cage_applies, |ui| { choice( ui, tr("Cage Type"), &mut settings.cage.kind, &[(CageType::DistanceBased, tr("Distance-Based")), (CageType::CustomFile, tr("Custom File"))], ); - match settings.cage.kind { - CageType::DistanceBased => { - paint_brush(app, ui, BakePaintTarget::Cage); - number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); - number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); - ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); - ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); - } - CageType::CustomFile => cage_file(app, ui), - } - }) { - settings.cage = Default::default(); - reset.insert("cage".into(), json!(settings.cage)); - } - }); - - if settings.cage.kind == CageType::DistanceBased { - ui.add_space(8.0); - ui.push_id("skew", |ui| { - if section(ui, tr("Skew Correction"), |ui| { - choice( - ui, - tr("Skew Correction Method"), - &mut settings.skew.method, - &[ - (SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), - (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based")), - ], - ); - paint_brush(app, ui, BakePaintTarget::Skew); - ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); - number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); - number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); - }) { - settings.skew = Default::default(); - reset.insert("skew".into(), json!(settings.skew)); + if settings.cage.kind == CageType::DistanceBased { + paint_brush(app, ui, BakePaintTarget::Cage); + number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); + number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); + ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); + ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); } }); + if settings.cage.kind == CageType::CustomFile { + cage_file(app, ui, cage_applies); + } + }) { + settings.cage = Default::default(); + reset.insert("cage".into(), json!(settings.cage)); } - } + }); + + // Shown greyed when it can't apply, as the reference does, with the reason on top + let skew_applies = has_high && settings.skew_applies(); + ui.add_space(SECTION_GAP); + ui.push_id("skew", |ui| { + if section(ui, tr("Skew Correction"), |ui| { + if !skew_applies { + hint(ui, skew_unavailable_reason(settings, has_high)); + } + ui.add_enabled_ui(skew_applies, |ui| { + choice( + ui, + tr("Skew Correction Method"), + &mut settings.skew.method, + &[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))], + ); + paint_brush(app, ui, BakePaintTarget::Skew); + ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); + number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); + number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); + }); + }) { + settings.skew = Default::default(); + reset.insert("skew".into(), json!(settings.skew)); + } + }); (!reset.is_empty()).then_some(Value::Object(reset)) } +/// Why Skew Correction can't apply: no high poly (`has_high` false), or `settings` rule it out (see [`BakeSettings::skew_applies`]) +fn skew_unavailable_reason(settings: &BakeSettings, has_high: bool) -> &'static str { + if !has_high { + tr("Skew Correction applies once a high poly mesh is loaded.") + } else if settings.high_poly.use_low_as_high { + tr("Skew Correction is not available while the low poly mesh is used as the high poly mesh.") + } else if settings.cage.kind == CageType::CustomFile { + tr("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself.") + } else { + tr("Skew Correction needs Average Normals turned on in the cage settings.") + } +} + fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { ui.label(tr("Output Size")); ui.horizontal(|ui| { @@ -144,42 +178,65 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { }); } -fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(tr("High Poly Scene")); - let meshes: Vec<_> = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); - let mut remove = None; - for (index, name) in meshes.iter().enumerate() { - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - let label_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); - ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(name).truncate()).on_hover_text(name); - if icon_button(ui, icon::TRASH, tr("Remove"), false, button_size).clicked() { - remove = Some(index); - } - }); - } +/// The high poly meshes as a list box, with + to add some and − to remove the selected one +fn high_poly_scene(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let names: Vec = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); + let selected_id = ui.make_persistent_id("high_poly_selected"); + let mut selected = ui.data(|data| data.get_temp::(selected_id)).filter(|index| *index < names.len()); - if meshes.is_empty() { - hint(ui, tr("No High-Poly Meshes")); - } - if let Some(index) = remove { + ui.label(tr("High Poly Scene")); + let (mut add, mut remove) = (false, false); + ui.horizontal_top(|ui| { + let button_size = ui.spacing().interact_size.y; + let list_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); + let list_height = HIGH_POLY_LIST_ROWS * ui.spacing().interact_size.y; + egui::Frame::NONE.fill(tokens.field).stroke(egui::Stroke::new(1.0, tokens.field_border)).corner_radius(tokens.cr()).show(ui, |ui| { + ui.set_min_size(egui::vec2(list_width, list_height)); + ui.set_max_width(list_width); + egui::ScrollArea::both().id_salt("high_poly_list").max_height(list_height).auto_shrink([false; 2]).show(ui, |ui| { + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(selected == Some(index), name).on_hover_text(name).clicked() { + selected = Some(index); + } + } + }); + }); + ui.vertical(|ui| { + add = icon_button(ui, icon::PLUS, tr("Add High-Poly Meshes"), false, button_size).clicked(); + remove = ui.add_enabled_ui(selected.is_some(), |ui| icon_button(ui, icon::MINUS, tr("Remove"), false, button_size)).inner.clicked(); + }); + }); + + if let (true, Some(index)) = (remove, selected) { app.run("bake.highPoly.remove", json!({ "index": index })); + selected = None; } - if ui.button(tr("Add High-Poly Meshes")).clicked() { + ui.data_mut(|data| { + if let Some(index) = selected { + data.insert_temp(selected_id, index); + } else { + data.remove_temp::(selected_id); + } + }); + if add { crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), false); } } -fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(tr("Cage Scene")); +/// The cage file row; while the cage can't `apply` only removing a loaded one stays available, so a saved cage can still be dropped +fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui, apply: bool) { + ui.add_enabled(apply, egui::Label::new(tr("Cage Scene"))); let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); ui.horizontal(|ui| { let button_size = ui.spacing().interact_size.y; let label_width = (ui.available_width() - 2.0 * (button_size + ui.spacing().item_spacing.x)).max(0.0); - ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { - crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); - } + ui.add_enabled_ui(apply, |ui| { + ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); + if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { + crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); + } + }); if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, button_size).clicked() { app.run("bake.cage.clear", json!({})); } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a1facb47..1a341d84 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -46,7 +46,13 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { && app.ui.bake_paint_brush.on && !app.session.bake_meshes.high.is_empty() && app.session.doc.project.texture_sets.get(app.session.ts()).is_some_and(|texture_set| { - !texture_set.bake.high_poly.use_low_as_high && texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased + let settings = &texture_set.bake; + match app.ui.bake_paint_brush.target { + texturecraft_engine::core::BakePaintTarget::Skew => settings.skew_applies(), + texturecraft_engine::core::BakePaintTarget::Cage => { + !settings.high_poly.use_low_as_high && settings.cage.kind == texturecraft_engine::core::CageType::DistanceBased + } + } }); app.ui.bake_paint_brush.on = bake_painting; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 437016a3..6da22b0d 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -479,24 +479,44 @@ fn curvature_controls_follow_the_method_and_notes_visibility_rules() { } #[test] -fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { +fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { let mut harness = harness(None); harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); - assert!(harness.query_by_label("Cage Type").is_none()); - assert!(harness.query_by_label("Skew Correction").is_none()); + // Without a high poly everything that needs one shows greyed, as in the reference + for needs_high in ["Match", "Max Frontal Distance", "Edge Protection"] { + assert!(harness.get_by_label(needs_high).accesskit_node().is_disabled(), "{needs_high} is greyed"); + } + harness.get_by_label("The cage applies once a high poly mesh is loaded."); + harness.get_by_label("Skew Correction applies once a high poly mesh is loaded."); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "nothing selected to remove"); harness.state_mut().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(); harness.run_steps(3); - harness.get_by_label("Max Frontal Distance"); + assert!(!harness.get_by_label("Max Frontal Distance").accesskit_node().is_disabled()); + assert!(harness.query_by_label("The cage applies once a high poly mesh is loaded.").is_none()); harness.get_by_label("Skew Correction"); + harness.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; + harness.run_steps(3); + assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); + harness.get_by_label("Skew Correction needs Average Normals turned on in the cage settings."); + harness.state_mut().session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; + harness.run_steps(3); + harness.get_by_label("Skew Correction is not available while the low poly mesh is used as the high poly mesh."); + harness.get_by_label("The cage is not used while the low poly mesh is used as the high poly mesh."); + assert!(harness.get_by_label("Paint Cage").accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); + let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; + (settings.cage.average_normals, settings.high_poly.use_low_as_high) = (true, false); + harness.run_steps(3); + assert!(!harness.get_by_label("Edge Protection").accesskit_node().is_disabled()); click(&mut harness, "Cage Type"); click(&mut harness, "Custom File"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::CustomFile); harness.get_by_label("Cage Scene"); assert!(harness.query_by_label("Max Frontal Distance").is_none()); - assert!(harness.query_by_label("Skew Correction").is_none()); + assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); + harness.get_by_label("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself."); for button_size in [20.0, 28.0] { harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); @@ -507,6 +527,24 @@ fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { } } +#[test] +fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + let session = &mut harness.state_mut().session; + session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let mesh = session.mesh.clone(); + session.bake_meshes.cage = Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), bytes: Default::default(), mesh, base_color: Vec::new() }); + let settings = &mut session.doc.project.texture_sets[0].bake; + (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); + harness.run_steps(3); + + assert!(harness.get_by_label("Load Cage").accesskit_node().is_disabled(), "the cage does not apply"); + assert!(!harness.get_by_label("Remove Cage").accesskit_node().is_disabled()); + click(&mut harness, "Remove Cage"); + assert!(harness.state().session.bake_meshes.cage.is_none()); +} + #[test] fn the_view_menu_picks_the_neutral_or_the_painted_material_in_bake_mode() { let mut harness = harness(None); @@ -532,6 +570,23 @@ fn the_baking_visualization_panel_opens_like_the_reference_at_first_launch() { assert!(harness.state().ui.bake_visualization.missing_seams.shown, "missing seams are ticked in every reference capture"); } +#[test] +fn the_high_poly_scene_is_a_list_with_add_and_remove() { + let mut harness = harness(None); + harness.state_mut().session.add_high_poly_bytes("Gunhigh.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_label("Add High-Poly Meshes"); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "− waits for a selection"); + + harness.get_by_label("Gunhigh.obj").click(); + harness.run_steps(3); + harness.get_by_label("Remove").click(); + harness.run_steps(3); + assert!(harness.state().session.bake_meshes.high.is_empty()); + assert!(harness.get_by_label("Remove").accesskit_node().is_disabled()); +} + #[test] fn the_eye_greys_the_baking_meshes_and_holds_the_project_mesh() { let mut harness = harness(None); diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index bfcc3e3e..f62af998 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -55,3 +55,15 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { h.run_steps(3); assert!(h.state().session.doc.bake_paint.is_empty()); } + +#[test] +fn turning_average_normals_off_stops_the_skew_brush() { + let mut h = harness(); + h.state_mut().ui.bake_paint_brush.on = true; + h.run_steps(2); + assert!(h.state().ui.bake_paint_brush.on, "skew correction applies with the default cage"); + + h.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; + h.run_steps(2); + assert!(!h.state().ui.bake_paint_brush.on, "the bake would leave the skew map out"); +} From 5214f3dbbaaaae3d23b79531d1653c416cb5b8a7 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 07:30:12 +0000 Subject: [PATCH 035/115] Bake mode: list overlapping UVs and unpaired parts before baking Above the bake bar, bake mode lists what would spoil the next bake of the included texture sets: a UV layout overlapping by more than 1%, and under "By Mesh Name" the low-poly parts no high-poly part matches and the high-poly parts that match no low-poly part. The pairing comes from the bake's own name keys, now one helper the bake and the list share. --- crates/bake/src/lib.rs | 2 + crates/bake/src/map.rs | 2 + crates/bake/src/map/part_key.rs | 18 ++ crates/bake/src/map/source.rs | 22 +- crates/bake/src/name_pair.rs | 103 +++++++++ crates/engine/src/bake/bake_checks.rs | 108 ++++++++++ crates/engine/src/bake/mesh_map_command.rs | 2 +- crates/engine/src/bake/mod.rs | 1 + crates/engine/tests/it/bake_checks.rs | 111 ++++++++++ crates/engine/tests/it/main.rs | 1 + crates/geom/src/gbuffer.rs | 146 ++++++++----- crates/ui-egui/src/bake_mode/bake_checks.rs | 222 ++++++++++++++++++++ crates/ui-egui/src/bake_mode/mod.rs | 16 +- crates/ui-egui/src/viewport.rs | 1 + 14 files changed, 684 insertions(+), 71 deletions(-) create mode 100644 crates/bake/src/map/part_key.rs create mode 100644 crates/bake/src/name_pair.rs create mode 100644 crates/engine/src/bake/bake_checks.rs create mode 100644 crates/engine/tests/it/bake_checks.rs create mode 100644 crates/ui-egui/src/bake_mode/bake_checks.rs diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index eb8a61de..1d99ab36 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -9,6 +9,7 @@ mod bake_request; mod cage; mod high_poly; mod mesh_extent; +mod name_pair; mod progress; pub use bake_error::BakeError; @@ -17,6 +18,7 @@ pub use bake_request::BakeRequest; pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; +pub use name_pair::NamePair; pub use progress::Progress; mod map; diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index c9c30fd6..08a98224 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -4,8 +4,10 @@ mod curvature_tuning; mod diffusion; mod normal_curvature; mod normalization; +mod part_key; pub(crate) use diffusion::diffuse; pub(crate) use normalization::normalize; +pub(crate) use part_key::part_key; mod sample; mod seam; pub(crate) use seam::fix_seams; diff --git a/crates/bake/src/map/part_key.rs b/crates/bake/src/map/part_key.rs new file mode 100644 index 00000000..bda45809 --- /dev/null +++ b/crates/bake/src/map/part_key.rs @@ -0,0 +1,18 @@ +use std::collections::HashMap; + +/// A mesh part's key in `keys` (shared by names that agree once `suffix` is dropped), whether it ignores backfaces, and its lowercase name without that suffix +pub(crate) fn part_key(name: &str, suffix: &str, backface_suffix: &str, keys: &mut HashMap) -> (u32, bool, String) { + let name = name.trim().to_lowercase(); + let ignore_backface = !backface_suffix.is_empty() && name.ends_with(backface_suffix); + let name = if ignore_backface { name.strip_suffix(backface_suffix).unwrap_or(&name).to_owned() } else { name }; + + (match_key(&name, suffix, keys), ignore_backface, name) +} + +/// The key in `keys` of the lowercase part name `name` without `suffix` +fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { + let suffix = suffix.trim().to_lowercase(); + let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(name).to_string(); + let next = keys.len() as u32; + *keys.entry(base).or_insert(next) +} diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index ad057b11..c5cd5f3f 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -1,3 +1,4 @@ +use super::part_key::part_key; use super::sampling::{generated_hue, interpolate, splitmix64}; use crate::BakeRequest; use crate::tracing::{ANY, TraceMesh}; @@ -50,21 +51,24 @@ impl<'a> Source<'a> { let mut mesh_ids = Vec::with_capacity(mesh.submeshes.len()); let mut part_keys = Vec::with_capacity(mesh.submeshes.len()); let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase(); + for (part_index, submesh) in mesh.submeshes.iter().enumerate() { let first_triangle = (submesh.start / 3) as usize; let last_triangle = (submesh.start.saturating_add(submesh.count) / 3) as usize; let range = first_triangle.min(last_triangle)..last_triangle.min(triangle_count); part.get_mut(range.clone()).unwrap_or_default().fill(part_index as u32); - let name = submesh.name.trim().to_lowercase(); - let ignore_backface = !backface_suffix.is_empty() && name.ends_with(&backface_suffix); + + let (key, ignore_backface, name) = part_key(&submesh.name, suffix, &backface_suffix, keys); backface_culling.get_mut(range).unwrap_or_default().fill(ignore_backface); - let name = if ignore_backface { name.strip_suffix(&backface_suffix).unwrap_or(&name) } else { &name }; - part_keys.push(match_key(name, suffix, keys)); + part_keys.push(key); + let next = mesh_keys.len() as u32; let file_id = file_ids.get(part_index).copied().unwrap_or(0); - mesh_ids.push(*mesh_keys.entry((file_id, name.to_owned())).or_insert(next)); + mesh_ids.push(*mesh_keys.entry((file_id, name)).or_insert(next)); } + let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect(); + Source { mesh, bvh, @@ -138,11 +142,3 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { let color = sampled_color * material.factor; Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w) } - -fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { - let name = name.trim().to_lowercase(); - let suffix = suffix.trim().to_lowercase(); - let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string(); - let next = keys.len() as u32; - *keys.entry(base).or_insert(next) -} diff --git a/crates/bake/src/name_pair.rs b/crates/bake/src/name_pair.rs new file mode 100644 index 00000000..8863cc58 --- /dev/null +++ b/crates/bake/src/name_pair.rs @@ -0,0 +1,103 @@ +//! How "By Mesh Name" pairs low-poly parts with high-poly parts, listed before a bake runs + +use std::collections::{HashMap, HashSet}; + +use texturecraft_core::HighPolySettings; +use texturecraft_geom::Mesh; + +use crate::map::part_key; + +/// A low-poly part and the high-poly part its rays may hit under "By Mesh Name"; one side is missing when that part pairs with nothing +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NamePair { + /// The low-poly part's name as in its mesh + pub low: Option, + /// The high-poly part's name as in its mesh + pub high: Option, +} + +impl NamePair { + /// Each part of `low` in `material` with every `high` part it pairs with (a row per pair), then the `high` parts pairing with none; keyed like the bake, low poly first + pub fn list(low: &Mesh, material: usize, high: &Mesh, settings: &HighPolySettings) -> Vec { + let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase(); + let mut keys = HashMap::new(); + let mut keyed = |mesh: &Mesh, suffix: &str, only_material: Option| { + let mut seen = HashSet::new(); + let mut parts = Vec::new(); + for part in mesh.submeshes.iter().filter(|part| only_material.is_none_or(|material| part.material == material)) { + let (key, ..) = part_key(&part.name, suffix, &backface_suffix, &mut keys); + if seen.insert(part.name.as_str()) { + parts.push((key, part.name.clone())); + } + } + parts + }; + let low_parts = keyed(low, &settings.low_suffix, Some(material)); + let high_parts = keyed(high, &settings.high_suffix, None); + + let mut pairs = Vec::new(); + for (key, low_name) in &low_parts { + let matches: Vec<&String> = high_parts.iter().filter(|(high_key, _)| high_key == key).map(|(_, name)| name).collect(); + if matches.is_empty() { + pairs.push(NamePair { low: Some(low_name.clone()), high: None }); + } + pairs.extend(matches.into_iter().map(|high_name| NamePair { low: Some(low_name.clone()), high: Some(high_name.clone()) })); + } + + let low_keys: HashSet = low_parts.iter().map(|(key, _)| *key).collect(); + pairs.extend(high_parts.into_iter().filter(|(key, _)| !low_keys.contains(key)).map(|(_, name)| NamePair { low: None, high: Some(name) })); + pairs + } + + /// Whether one side is missing: a part the bake will leave unpaired + pub fn unpaired(&self) -> bool { + self.low.is_none() || self.high.is_none() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_geom::SubMesh; + + /// A mesh with one empty part per (name, material) + fn parts(names: &[(&str, usize)]) -> Mesh { + Mesh { + submeshes: names.iter().map(|(name, material)| SubMesh { name: (*name).into(), material: *material, start: 0, count: 0 }).collect(), + materials: vec!["first".into(), "second".into()], + ..Default::default() + } + } + + fn pair(low: Option<&str>, high: Option<&str>) -> NamePair { + NamePair { low: low.map(Into::into), high: high.map(Into::into) } + } + + #[test] + fn parts_pair_by_name_without_their_suffixes() { + let low = parts(&[("Barrel_low", 0), ("Base_low", 0), ("Slide_low", 1)]); + let high = parts(&[("Barrel_high", 0), ("Slide_high", 0), ("Grip_high", 0), ("BARREL_high_ignorebf", 0)]); + let settings = HighPolySettings::default(); + + assert_eq!( + NamePair::list(&low, 0, &high, &settings), + vec![ + pair(Some("Barrel_low"), Some("Barrel_high")), + pair(Some("Barrel_low"), Some("BARREL_high_ignorebf")), + pair(Some("Base_low"), None), + pair(None, Some("Slide_high")), + pair(None, Some("Grip_high")), + ], + "another material's parts are left out, so its high-poly part counts as unpaired here" + ); + assert_eq!(NamePair::list(&low, 1, &high, &settings).iter().filter(|pair| !pair.unpaired()).count(), 1); + } + + #[test] + fn a_part_split_over_triangle_ranges_is_listed_once() { + let low = parts(&[("Body_low", 0), ("Body_low", 0)]); + let high = parts(&[("Body_high", 0), ("Body_high", 0)]); + + assert_eq!(NamePair::list(&low, 0, &high, &HighPolySettings::default()), vec![pair(Some("Body_low"), Some("Body_high"))]); + } +} diff --git a/crates/engine/src/bake/bake_checks.rs b/crates/engine/src/bake/bake_checks.rs new file mode 100644 index 00000000..03cfb4c2 --- /dev/null +++ b/crates/engine/src/bake/bake_checks.rs @@ -0,0 +1,108 @@ +//! What can spoil a texture set's bake, checked before it runs: overlapping UVs and parts "By Mesh Name" leaves unpaired + +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_bake::NamePair; +use texturecraft_core::MeshMatchMode; +use texturecraft_geom::{Mesh, SubMesh, UvGBuffer, glam::Vec2}; + +use crate::{Result, Session}; + +/// Side of the UV raster the overlap check counts texels on, per UV tile (as mesh import does) +const OVERLAP_CHECK_RESOLUTION: u32 = 512; + +/// The only material of the UV-only mesh the overlap check builds per UV tile +const BLOCK_MATERIAL: usize = 0; + +impl Session { + /// About the share (0..1) of texture set `texture_set`'s UV layout the bake sees covered more than once, over the UV tiles it bakes: a texel under three triangles counts twice + pub fn bake_uv_overlap(&self, texture_set: usize) -> Result { + let set = self.doc.project.texture_set(texture_set)?; + let mesh = self.bake_mesh(texture_set)?; + let (overlaps, covered) = match set.tile_grid() { + Some(grid) => { + let baked_blocks: BTreeSet<(u32, u32)> = + set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid.block(*tile)).collect(); + let blocks = triangles_by_block(&mesh, set.material, (grid.cols, grid.rows), &baked_blocks); + blocks + .values() + .map(|block| overlap_counts(block, BLOCK_MATERIAL)) + .fold((0, 0), |(overlaps, covered), (block_overlaps, block_covered)| (overlaps + block_overlaps, covered + block_covered)) + } + None => overlap_counts(&mesh, set.material), + }; + + Ok(if covered == 0 { 0.0 } else { (overlaps as f32 / covered as f32).min(1.0) }) + } + + /// How texture set `texture_set`'s low-poly parts pair with the high-poly parts ([`NamePair::list`]); `None` unless it bakes from a high poly "By Mesh Name" + pub fn bake_name_pairs(&self, texture_set: usize) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + let settings = &set.bake.high_poly; + let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); + + Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings))) + } + + /// The high-poly parts none of `texture_sets` bakes from, by name: a set matching "Always" bakes from every part, one matching "By Mesh Name" only from the parts its names pair with + pub fn bake_unpaired_high_parts(&self, texture_sets: &[usize]) -> Result> { + let (mut paired, mut unpaired) = (BTreeSet::new(), BTreeSet::new()); + for &texture_set in texture_sets { + let settings = &self.doc.project.texture_set(texture_set)?.bake.high_poly; + if !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always { + return Ok(Vec::new()); + } + + for pair in self.bake_name_pairs(texture_set)?.unwrap_or_default() { + match pair { + NamePair { low: Some(_), high: Some(high) } => paired.insert(high), + NamePair { low: None, high: Some(high) } => unpaired.insert(high), + _ => false, + }; + } + } + + Ok(unpaired.difference(&paired).cloned().collect()) + } +} + +/// Texels covered more than once and texels covered, rasterizing material `material`'s UVs over 0..1 +fn overlap_counts(mesh: &Mesh, material: usize) -> (usize, usize) { + let gbuffer = UvGBuffer::new(mesh, material, OVERLAP_CHECK_RESOLUTION, OVERLAP_CHECK_RESOLUTION); + (gbuffer.overlaps as usize, gbuffer.covered_count()) +} + +/// Material `material`'s triangles sorted into the `baked_blocks` of a `grid` (columns, rows) atlas their UVs reach, one UV-only mesh per block with the block's UVs over 0..1: a single pass, however many blocks +fn triangles_by_block(mesh: &Mesh, material: usize, grid: (u32, u32), baked_blocks: &BTreeSet<(u32, u32)>) -> BTreeMap<(u32, u32), Mesh> { + let scale = Vec2::new(grid.0 as f32, grid.1 as f32); + let mut blocks: BTreeMap<(u32, u32), Mesh> = BTreeMap::new(); + for triangle in mesh.triangles_of(material) { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(first_uv), Some(second_uv), Some(third_uv)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { continue }; + let uvs = [*first_uv * scale, *second_uv * scale, *third_uv * scale]; + + // Every block the triangle's UV bounds touch, so a triangle across a border counts in both + let (uv_min, uv_max) = uvs.iter().fold((Vec2::INFINITY, Vec2::NEG_INFINITY), |(uv_min, uv_max), uv| (uv_min.min(*uv), uv_max.max(*uv))); + // Capped at the grid: a stray huge UV must not walk billions of blocks + let columns = uv_min.x.floor().max(0.0) as u32..=((uv_max.x.ceil() as u32).saturating_sub(1)).min(grid.0 - 1); + let rows = uv_min.y.floor().max(0.0) as u32..=((uv_max.y.ceil() as u32).saturating_sub(1)).min(grid.1 - 1); + for column in columns { + for row in rows.clone() { + if !baked_blocks.contains(&(column, row)) { + continue; + } + + let block = blocks.entry((column, row)).or_insert_with(|| Mesh { materials: vec![String::new()], ..Mesh::default() }); + let offset = Vec2::new(column as f32, row as f32); + block.indices.extend(block.uvs.len() as u32..block.uvs.len() as u32 + 3); + block.uvs.extend(uvs.iter().map(|uv| *uv - offset)); + } + } + } + + for block in blocks.values_mut() { + block.submeshes = vec![SubMesh { name: String::new(), material: BLOCK_MATERIAL, start: 0, count: block.indices.len() as u32 }]; + } + + blocks +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 0c14027f..f8826b44 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -188,7 +188,7 @@ impl Session { } /// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas - fn bake_mesh(&self, texture_set: usize) -> Result> { + pub(super) fn bake_mesh(&self, texture_set: usize) -> Result> { let set = self.doc.project.texture_set(texture_set)?; Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) { Some(grid) => { diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 15377142..bfe9b22c 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,6 +1,7 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API mod bake_cage_inputs; +mod bake_checks; mod bake_mesh; mod bake_meshes; mod bake_task; diff --git a/crates/engine/tests/it/bake_checks.rs b/crates/engine/tests/it/bake_checks.rs new file mode 100644 index 00000000..cc885aaa --- /dev/null +++ b/crates/engine/tests/it/bake_checks.rs @@ -0,0 +1,111 @@ +//! What bake mode lists before a bake: overlapping UVs and parts "By Mesh Name" leaves unpaired + +use texturecraft_engine::Session; +use texturecraft_engine::bake::NamePair; +use texturecraft_engine::core::MeshMatchMode; + +/// Two quads side by side; `shared_uvs` lays both on the same UV square instead of side by side in UV space +fn two_quads(shared_uvs: bool) -> Session { + let second_u = if shared_uvs { 0.0 } else { 0.5 }; + let obj = format!( + "o Box_low\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\ + o Lone_low\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt {second_u} 0\nvt {} 0\nvt {} 1\nvt {second_u} 1\nf 5/5 6/6 7/7 8/8\n", + second_u + 0.5, + second_u + 0.5 + ); + Session::from_mesh_bytes("quads.obj", obj.as_bytes(), 128, "quads").unwrap() +} + +const HIGH_POLY: &[u8] = b"o Box_high\nv 0 0 0.01\nv 1 0 0.01\nv 0 1 0.01\nf 1 2 3\no Extra_high\nv 2 0 0.01\nv 3 0 0.01\nv 2 1 0.01\nf 4 5 6\n"; + +#[test] +fn overlapping_uvs_are_measured_before_the_bake() { + assert!(two_quads(true).bake_uv_overlap(0).unwrap() > 0.4, "the second quad covers the first one's UVs"); + assert_eq!(two_quads(false).bake_uv_overlap(0).unwrap(), 0.0, "side by side in UV space nothing overlaps"); + const MISSING_TEXTURE_SET: usize = 9; + assert!(two_quads(false).bake_uv_overlap(MISSING_TEXTURE_SET).is_err()); +} + +#[test] +fn overlap_in_a_uv_tile_left_out_of_the_bake_is_not_counted() { + // One quad in tile 1001, two on the same UVs in tile 1002 + let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\ + o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 5/5 6/6 7/7 8/8\n\ + o Third\nv 4 0 0\nv 5 0 0\nv 5 1 0\nv 4 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 9/9 10/10 11/11 12/12\n"; + let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "the last two quads share tile 1002's UVs"); + + session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002); + assert_eq!(session.bake_uv_overlap(0).unwrap(), 0.0, "tile 1001 alone has no overlap"); +} + +#[test] +fn overlap_is_measured_at_the_same_detail_in_every_uv_tile() { + // Tiles 1001 and 1010 make a grid ten tiles wide; 512 texels across all ten would give each tile about 51 + const TEXELS_PER_TILE: f32 = 512.0; + const SLIVER_TEXELS: f32 = 4.0; + // Inside tile 1010 (column 9), clear of the wide raster's texel centres + const SLIVER_LEFT_U: f32 = 9.1; + let (left, right) = (SLIVER_LEFT_U, SLIVER_LEFT_U + SLIVER_TEXELS / TEXELS_PER_TILE); + let sliver = |name: &str, first: u32, x: f32| { + let (second, third, fourth) = (first + 1, first + 2, first + 3); + let corners = format!("v {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\n", x + 1.0, x + 1.0); + format!( + "o {name}\n{corners}vt {left} 0\nvt {right} 0\nvt {right} 1\nvt {left} 1\nf {first}/{first} {second}/{second} {third}/{third} {fourth}/{fourth}\n" + ) + }; + let corner = "o Corner\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; + let obj = [corner.to_owned(), sliver("First", 5, 2.0), sliver("Second", 9, 4.0)].concat(); + let session = Session::from_mesh_bytes("wide.obj", obj.as_bytes(), 128, "wide").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1010]); + + assert!(session.bake_uv_overlap(0).unwrap() > 0.0, "two slivers a few texels wide overlap in tile 1010"); +} + +#[test] +fn a_triangle_across_a_uv_tile_border_counts_in_both_tiles() { + // Two quads on the same UVs, from u 0.9 in tile 1001 to u 1.1 in tile 1002 + let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 1/1 2/2 3/3 4/4\n\ + o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 5/5 6/6 7/7 8/8\n"; + let mut session = Session::from_mesh_bytes("border.obj", obj.as_bytes(), 128, "border").unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + + for (excluded, kept) in [(1002, 1001), (1001, 1002)] { + let excluded_tiles = &mut session.doc.project.texture_sets[0].bake_excluded_tiles; + excluded_tiles.clear(); + excluded_tiles.insert(excluded); + assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "tile {kept} holds part of the overlap"); + } +} + +#[test] +fn unpaired_parts_are_listed_only_when_matching_by_name() { + let mut session = two_quads(false); + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "no high poly"); + session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap(); + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "\"Always\" pairs every part"); + + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let pairs = session.bake_name_pairs(0).unwrap().unwrap(); + let unpaired: Vec<&NamePair> = pairs.iter().filter(|pair| pair.unpaired()).collect(); + assert_eq!(unpaired, [&NamePair { low: Some("Lone_low".into()), high: None }, &NamePair { low: None, high: Some("Extra_high".into()) }], "{pairs:?}"); + assert!(pairs.contains(&NamePair { low: Some("Box_low".into()), high: Some("Box_high".into()) })); + + session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; + assert_eq!(session.bake_name_pairs(0).unwrap(), None, "the low poly as its own high poly pairs every part"); +} + +#[test] +fn a_set_matching_always_bakes_from_every_high_poly_part() { + let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap(); + let both = [0, 1]; + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), Vec::::new(), "the other set matches \"Always\""); + + session.doc.project.texture_sets[1].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), ["Extra_high"]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index e6157332..dba7b02d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone session.rs target remains available. mod bake; +mod bake_checks; mod bake_resolution; mod bake_settings; mod bake_tiles; diff --git a/crates/geom/src/gbuffer.rs b/crates/geom/src/gbuffer.rs index e26b923f..05f8221e 100644 --- a/crates/geom/src/gbuffer.rs +++ b/crates/geom/src/gbuffer.rs @@ -20,7 +20,7 @@ pub struct UvGBuffer { pub tri: Vec, /// Barycentric weights of the triangle's second and third vertices. pub bary: Vec<[f32; 2]>, - /// Texels written by more than one triangle (overlapping UVs). + /// Covers past the first on texels where any cover has the texel center strictly inside (overlapping UVs; an edge two neighbours share is no overlap) pub overlaps: u32, } @@ -41,74 +41,95 @@ fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 { (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) } +/// Twice-areas (in texels²) below this are degenerate triangles, which cover nothing +const MIN_DOUBLE_AREA: f32 = 1e-12; + +/// How far outside a triangle (as a share of its double area) a texel center may sit and still count as covered, so shared edges leave no gaps +const EDGE_TOLERANCE: f32 = 1e-6; + impl UvGBuffer { - /// Rasterize the triangles of material `material` at `width × height`. + /// Rasterize the triangles of material `material` at `width × height` pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer { - let (w, h) = (width.max(1), height.max(1)); - let size = Vec2::new(w as f32, h as f32); - let bands = h.div_ceil(BAND) as usize; - let mut bins: Vec> = vec![Vec::new(); bands]; - for t in mesh.triangles_of(material) { - let Some([a, b, c]) = mesh.tri(t) else { continue }; - let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; - let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64; - let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64; - if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() { + let (width, height) = (width.max(1), height.max(1)); + let size = Vec2::new(width as f32, height as f32); + let corner_uvs = |triangle: usize| { + let [first, second, third] = mesh.tri(triangle)?; + Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) + }; + + // Sort triangles into bands of rows so each band rasterizes on its own thread + let mut bands: Vec> = vec![Vec::new(); height.div_ceil(BAND) as usize]; + for triangle in mesh.triangles_of(material) { + let Some(uvs) = corner_uvs(triangle) else { continue }; + let top = (uvs.iter().map(|uv| uv.y).fold(f32::INFINITY, f32::min) * size.y).floor().max(0.0) as i64; + let bottom = (uvs.iter().map(|uv| uv.y).fold(f32::NEG_INFINITY, f32::max) * size.y).ceil().min(size.y) as i64; + if bottom <= top || !uvs.iter().all(|uv| uv.is_finite()) { continue; } - let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize); - for bin in bins.iter_mut().take(b1 + 1).skip(b0) { - bin.push(t as u32); + + let (first_band, last_band) = ((top / BAND as i64) as usize, ((bottom - 1).max(0) / BAND as i64) as usize); + for band in bands.iter_mut().take(last_band + 1).skip(first_band) { + band.push(triangle as u32); } } - let n = w as usize * h as usize; - let mut tri = vec![NO_TRI; n]; - let mut bary = vec![[0.0f32; 2]; n]; - let band_len = (BAND * w) as usize; + + let texel_count = width as usize * height as usize; + let mut tri = vec![NO_TRI; texel_count]; + let mut bary = vec![[0.0f32; 2]; texel_count]; + let band_texels = (BAND * width) as usize; let overlaps: u32 = tri - .par_chunks_mut(band_len) - .zip(bary.par_chunks_mut(band_len)) + .par_chunks_mut(band_texels) + .zip(bary.par_chunks_mut(band_texels)) .enumerate() - .map(|(bi, (tri, bary))| { - let mut overlaps = 0u32; - let row0 = bi as u32 * BAND; - let rows = (tri.len() as u32) / w; - for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { - let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; - let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; - let (pa, pb, pc) = (ua * size, ub * size, uc * size); - let area = edge(pa, pb, pc); - if area.abs() < 1e-12 { + .map(|(band_index, (band_tri, band_bary))| { + // Per texel: how many triangles cover it, and whether any has its center strictly inside, so the count doesn't depend on triangle order + let mut covers = vec![0u32; band_tri.len()]; + let mut strict_cover = vec![false; band_tri.len()]; + let first_row = band_index as u32 * BAND; + let band_rows = (band_tri.len() as u32) / width; + for &triangle in bands.get(band_index).map(Vec::as_slice).unwrap_or(&[]) { + let Some(uvs) = corner_uvs(triangle as usize) else { continue }; + let [a, b, c] = uvs.map(|uv| uv * size); + let double_area = edge(a, b, c); + if double_area.abs() < MIN_DOUBLE_AREA { continue; } - let eps = -1e-6 * area.abs(); - let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32; - let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w); - let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0); - let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows); - for y in y0..y1 { - for x in x0..x1 { - let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); - let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum()); - if w0 < eps || w1 < eps || w2 < eps { + + let tolerance = EDGE_TOLERANCE * double_area.abs(); + let (sign, inverse_area) = (double_area.signum(), 1.0 / double_area.abs()); + let left = a.x.min(b.x).min(c.x).floor().max(0.0) as u32; + let right = (a.x.max(b.x).max(c.x).ceil().min(width as f32) as u32).min(width); + let top = (a.y.min(b.y).min(c.y).floor().max(first_row as f32) as u32).max(first_row); + let bottom = (a.y.max(b.y).max(c.y).ceil() as u32).min(first_row + band_rows); + for y in top..bottom { + for x in left..right { + let center = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let weights = [edge(b, c, center) * sign, edge(c, a, center) * sign, edge(a, b, center) * sign]; + if weights.iter().any(|weight| *weight < -tolerance) { continue; } - let i = ((y - row0) * w + x) as usize; - if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { - if *slot != NO_TRI { - overlaps += 1; - } - *slot = t; - let inv = 1.0 / area.abs(); - *bw = [w1 * inv, w2 * inv]; - } + + let index = ((y - first_row) * width + x) as usize; + let (Some(slot), Some(slot_bary), Some(cover_count), Some(strict)) = + (band_tri.get_mut(index), band_bary.get_mut(index), covers.get_mut(index), strict_cover.get_mut(index)) + else { + continue; + }; + + *cover_count += 1; + *strict |= weights.iter().all(|weight| *weight > tolerance); + *slot = triangle; + *slot_bary = [weights[1] * inverse_area, weights[2] * inverse_area]; } } } - overlaps + + // Every cover past the first overlaps, unless all of them only touch the texel center with an edge (neighbours sharing it) + covers.iter().zip(&strict_cover).filter(|(_, strict)| **strict).map(|(count, _)| count.saturating_sub(1)).sum::() }) .sum(); - UvGBuffer { width: w, height: h, tri, bary, overlaps } + + UvGBuffer { width, height, tri, bary, overlaps } } pub fn covered(&self, i: usize) -> bool { @@ -171,6 +192,27 @@ mod tests { assert_eq!(g.overlaps, 0); } + #[test] + fn neighbours_sharing_an_edge_through_texel_centers_do_not_overlap() { + // An 8×8 grid of quads at 512 texels: each quad's diagonal runs through 64 texel centers + let grid = primitives::plane(1.0, 8); + let gbuffer = UvGBuffer::new(&grid, 0, 512, 512); + assert_eq!(gbuffer.covered_count(), 512 * 512); + assert_eq!(gbuffer.overlaps, 0); + } + + #[test] + fn an_edge_through_a_covered_texel_center_counts_both_edge_covers() { + // The texel center (0.5, 0.5) lies inside the first triangle and on the diagonal the other two share + let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.2), Vec2::new(0.2, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)]; + let positions = vec![Vec3::ZERO; uv.len()]; + // In either order: the inside cover first, or the two edge covers first + for indices in [vec![0, 1, 2, 0, 3, 4, 0, 5, 3], vec![0, 3, 4, 0, 5, 3, 0, 1, 2]] { + let m = Mesh::from_parts(positions.clone(), None, uv.clone(), indices.clone(), "m").unwrap(); + assert_eq!(UvGBuffer::new(&m, 0, 1, 1).overlaps, 2, "{indices:?}"); + } + } + #[test] fn overlapping_and_degenerate_triangles() { let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)]; diff --git a/crates/ui-egui/src/bake_mode/bake_checks.rs b/crates/ui-egui/src/bake_mode/bake_checks.rs new file mode 100644 index 00000000..c3806617 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_checks.rs @@ -0,0 +1,222 @@ +//! Problems the next bake would have, listed above the bake bar before Bake is pressed + +use std::sync::{Arc, Weak}; + +use egui_phosphor::regular as icon; +use texturecraft_engine::Session; +use texturecraft_engine::geom::Mesh; + +use crate::TextureCraftApp; +use crate::i18n::trf; +use crate::theme::Tokens; + +/// Share of a texture set's UV layout that may overlap before it is listed (as mesh import warns) +const UV_OVERLAP_WARNING: f32 = 0.01; + +/// How many part names a warning spells out before "and N more" +const NAMES_SHOWN: usize = 3; + +/// The warnings' gap above the bake bar +const WARNINGS_GAP: f32 = 8.0; + +/// The warnings above bake mode's bake bar in the 3D view `viewport`, until a bake starts +pub(crate) fn bake_warnings(app: &TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { + if app.bake_progress().is_some() { + return; + } + + let warnings = cached_warnings(ctx, &app.session); + if warnings.is_empty() { + return; + } + + let tokens = Tokens::get(ctx); + let above_bar = super::BAKE_BAR_MARGIN + ctx.global_style().spacing.interact_size.y + WARNINGS_GAP; + egui::Area::new(egui::Id::unique("bake_warnings")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -above_bar)).show( + ctx, + |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| { + for warning in warnings.iter() { + ui.label(egui::RichText::new(format!("{} {warning}", icon::WARNING)).color(tokens.warning)); + } + }); + }, + ); +} + +/// The warnings for the texture sets the next bake includes, worked out again only when what they read changes +pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc> { + let id = egui::Id::unique("bake_check_warnings"); + let key = inputs_key(session); + // A handle, not an address: a rebuilt high poly could reuse a dropped one's address + let high = session.bake_meshes.merged_high().map_or_else(Weak::new, |high| Arc::downgrade(&high.mesh)); + if let Some((cached_key, cached_high, cached)) = ctx.data(|data| data.get_temp::<(String, Weak, Arc>)>(id)) + && cached_key == key + && cached_high.ptr_eq(&high) + { + return cached; + } + + let fresh = Arc::new(warnings(session)); + ctx.data_mut(|data| data.insert_temp(id, (key, high, fresh.clone()))); + fresh +} + +/// Everything the warnings read or show apart from the high poly (cached as a handle): the low poly, the UI language, and per included set its name, material, high-poly settings, UV tile resolutions and the tiles left out of the bake +fn inputs_key(session: &Session) -> String { + let sets: Vec<_> = baked_sets(session) + .filter_map(|index| { + let set = session.doc.project.texture_sets.get(index)?; + Some((index, &set.name, set.material, &set.bake.high_poly, &set.tile_resolutions, &set.bake_excluded_tiles)) + }) + .collect(); + + format!("{}|{}|{sets:?}", session.mesh_id, crate::i18n::current().code) +} + +/// The texture sets the next bake includes +fn baked_sets(session: &Session) -> impl Iterator + '_ { + session.doc.project.texture_sets.iter().enumerate().filter(|(_, set)| set.bake.common.is_enabled && set.has_enabled_bake_tiles()).map(|(index, _)| index) +} + +/// Overlapping UVs per included set, its low-poly parts "By Mesh Name" pairs with nothing, then the high-poly parts no included set bakes from +pub(crate) fn warnings(session: &Session) -> Vec { + let mut lines = Vec::new(); + let included: Vec = baked_sets(session).collect(); + for &index in &included { + let Some(set) = session.doc.project.texture_sets.get(index) else { continue }; + + let overlap = session.bake_uv_overlap(index).unwrap_or(0.0); + if overlap > UV_OVERLAP_WARNING { + let percent = format!("{:.1}", overlap * 100.0); + lines.push(trf( + "{set}: {percent}% of the UV layout overlaps, so those texels bake one place for several", + &[("set", &set.name), ("percent", &percent)], + )); + } + + let Ok(Some(pairs)) = session.bake_name_pairs(index) else { continue }; + + let unpaired_low: Vec<&str> = pairs.iter().filter(|pair| pair.high.is_none()).filter_map(|pair| pair.low.as_deref()).collect(); + if !unpaired_low.is_empty() { + lines.push(trf("{set}: no high poly part matches {names}", &[("set", &set.name), ("names", &listed(&unpaired_low))])); + } + } + + let unpaired_high = session.bake_unpaired_high_parts(&included).unwrap_or_default(); + if !unpaired_high.is_empty() { + let names: Vec<&str> = unpaired_high.iter().map(String::as_str).collect(); + lines.push(trf("No low poly part matches {names}", &[("names", &listed(&names))])); + } + + lines +} + +/// `names` joined, the first few spelled out and the rest counted +fn listed(names: &[&str]) -> String { + let shown = names.iter().take(NAMES_SHOWN).copied().collect::>().join(", "); + match names.len().checked_sub(NAMES_SHOWN).filter(|more| *more > 0) { + Some(more) => trf("{names} and {count} more", &[("names", &shown), ("count", &more)]), + None => shown, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::MeshMatchMode; + + /// Part `index` named `name` (an OBJ object): a quad at x offset `x` whose UVs span `u` to `u` + 0.2 + fn quad(name: &str, index: usize, x: f32, u: f32) -> String { + let first = index * 4 + 1; + format!( + "o {name}\nv {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\nvt {u} 0\nvt {} 0\nvt {} 1\nvt {u} 1\nf {first}/{first} {}/{} {}/{} {}/{}\n", + x + 1.0, + x + 1.0, + u + 0.2, + u + 0.2, + first + 1, + first + 1, + first + 2, + first + 2, + first + 3, + first + 3 + ) + } + + fn session(overlapping: bool) -> Session { + let names = ["Box_low", "Lid_low", "Bolt_low", "Nut_low", "Pin_low"]; + let obj: String = + names.iter().enumerate().map(|(index, name)| quad(name, index, index as f32 * 2.0, if overlapping { 0.0 } else { index as f32 * 0.2 })).collect(); + Session::from_mesh_bytes("parts.obj", obj.as_bytes(), 128, "parts").unwrap() + } + + #[test] + fn a_clean_setup_lists_nothing() { + let mut session = session(false); + assert_eq!(warnings(&session), Vec::::new()); + session.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + assert_eq!(warnings(&session), Vec::::new(), "\"Always\" pairs every part"); + } + + #[test] + fn renaming_a_set_refreshes_the_cached_warnings() { + let mut session = session(true); + let ctx = egui::Context::default(); + let before = cached_warnings(&ctx, &session); + assert!(before.iter().any(|line| line.starts_with(&session.doc.project.texture_sets[0].name)), "{before:?}"); + + session.doc.project.texture_sets[0].name = "Renamed".into(); + let after = cached_warnings(&ctx, &session); + assert!(after.iter().any(|line| line.starts_with("Renamed:")), "{after:?}"); + } + + #[test] + fn swapping_the_high_poly_refreshes_the_cached_warnings() { + let mut session = session(false); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + session.add_high_poly_bytes("spare.obj", b"o Spare_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let ctx = egui::Context::default(); + assert!(cached_warnings(&ctx, &session).contains(&"No low poly part matches Spare_high".to_owned())); + + // The new high poly's mesh may take the dropped one's address + drop(session.remove_high_poly(0).unwrap()); + session.add_high_poly_bytes("box.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let after = cached_warnings(&ctx, &session); + assert!(!after.iter().any(|line| line.contains("Spare_high")), "{after:?}"); + } + + #[test] + fn leaving_the_overlapping_tile_out_refreshes_the_cached_warnings() { + // One quad in tile 1001, two on the same UVs in tile 1002 + let obj = [quad("First_low", 0, 0.0, 0.0), quad("Second_low", 1, 2.0, 1.0), quad("Third_low", 2, 4.0, 1.0)].concat(); + let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap(); + let ctx = egui::Context::default(); + assert_eq!(cached_warnings(&ctx, &session).len(), 1, "tile 1002 overlaps"); + + session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002); + assert_eq!(*cached_warnings(&ctx, &session), Vec::::new(), "tile 1001 alone has no overlap"); + } + + #[test] + fn overlapping_uvs_and_unpaired_parts_are_listed() { + let mut session = session(true); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Spare_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let set = session.doc.project.texture_sets[0].name.clone(); + + assert_eq!( + warnings(&session), + [ + format!("{set}: 100.0% of the UV layout overlaps, so those texels bake one place for several"), + format!("{set}: no high poly part matches Lid_low, Bolt_low, Nut_low and 1 more"), + "No low poly part matches Spare_high".to_owned(), + ] + ); + + session.doc.project.texture_sets[0].bake.common.is_enabled = false; + assert_eq!(warnings(&session), Vec::::new(), "a set the bake leaves out is not checked"); + } +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 490fa2a5..020daa02 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -1,11 +1,13 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands +mod bake_checks; mod bake_paint_brush; mod bake_visualization_panel; mod bake_visualization_toggles; mod breadcrumb; mod common_settings; mod section_opening; +pub(crate) use bake_checks::bake_warnings; pub use bake_paint_brush::BakePaintBrush; pub(crate) use bake_visualization_panel::bake_visualization_panel; pub use bake_visualization_toggles::BakeVisualizationToggles; @@ -229,10 +231,15 @@ fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// The bake bar's gap from the bottom of the 3D view, in points (the pre-bake warnings sit above it) +pub(super) const BAKE_BAR_MARGIN: f32 = 16.0; + pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { - egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( - ctx, - |ui| { + egui::Area::new(egui::Id::unique("bake_bar")) + .constrain_to(viewport) + .anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -BAKE_BAR_MARGIN)) + .default_width(0.0) + .show(ctx, |ui| { if let Some(status) = app.bake_status() { ui.vertical_centered(|ui| ui.label(egui::RichText::new(status).strong())); } @@ -264,6 +271,5 @@ pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: app.ui.mode = Mode::Painting; } }); - }, - ); + }); } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1a341d84..465456cc 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -107,6 +107,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } if mode == crate::state::Mode::Baking { crate::bake_mode::bake_bar(app, ui.ctx(), full); + crate::bake_mode::bake_warnings(app, ui.ctx(), full); } // Keep drawing until the 3D view finishes accumulating anti-aliasing samples From bafcbef303a6cea3ce020d19a25192001295f586 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 07:30:13 +0000 Subject: [PATCH 036/115] Bake mode: texture set names in full and a Bake (N) button, as in the reference The texture set list shows each name in full beside its NxN size, and the bake button reads Bake (N), counting checked maps x included UV tiles x texture sets. --- crates/ui-egui/src/bake_mode/mod.rs | 58 ++++++++++++++++++--------- crates/ui-egui/src/docking.rs | 4 +- crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/tests/it/bake_mode.rs | 44 +++++++++++++------- crates/ui-egui/tests/it/skew_paint.rs | 22 +++++----- crates/ui-egui/tests/ui_snapshots.rs | 6 +-- 6 files changed, 88 insertions(+), 48 deletions(-) diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 020daa02..f6070091 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -50,18 +50,22 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), format!("{resolution} × {resolution}"), resolution, None) - && selected != resolution - { - app.start_resize(set_index, selected); - } - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - if ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()).on_hover_text(&name).clicked() { - app.run("textureSet.select", json!({ "ts": set_index })); - } - }); + // The name takes the room the resolution leaves, so it only shortens when the row is too narrow + let resolution_text = format!("{resolution}x{resolution}"); + let name_width = (ui.available_width() - resolution_menu_width(ui, &resolution_text) - ui.spacing().item_spacing.x).max(0.0); + let name_size = egui::vec2(name_width, ui.spacing().interact_size.y); + let name_button = ui.allocate_ui_with_layout(name_size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(name_width); + ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()) }); + if name_button.inner.on_hover_text(&name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + } + if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), resolution_text, resolution, None) + && selected != resolution + { + app.start_resize(set_index, selected); + } }); if !tiles.is_empty() { @@ -74,7 +78,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { app.run("bake.tile.set", json!({"ts": set_index, "tile": tile, "enabled": enabled})); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let text = override_resolution.map(|value| format!("{value} × {value}*")).unwrap_or_default(); + let text = override_resolution.map(|value| format!("{value}x{value}*")).unwrap_or_default(); let label = trf("UV tile {tile} resolution", &[("tile", &tile.to_string())]); if let Some(selected) = resolution_menu( ui, @@ -96,12 +100,17 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { }); } +/// How wide [`resolution_menu`] draws `text`, with a button's padding on both sides +fn resolution_menu_width(ui: &Ui, text: &str) -> f32 { + let font = egui::TextStyle::Button.resolve(ui.style()); + ui.painter().layout_no_wrap(text.to_owned(), font, ui.visuals().text_color()).size().x + ui.spacing().button_padding.x * 2.0 +} + fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inherited_resolution: Option) -> Option { - let effective_size = format!("{resolution} × {resolution}"); + let effective_size = format!("{resolution}x{resolution}"); let measured = if text.is_empty() { &effective_size } else { &text }; let font = egui::TextStyle::Button.resolve(ui.style()); - let text_width = ui.painter().layout_no_wrap(measured.clone(), font.clone(), ui.visuals().text_color()).size().x; - let width = text_width + ui.spacing().button_padding.x * 2.0; + let width = resolution_menu_width(ui, measured); let response = ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new("").frame(false)); let popup_id = response.id.with("resolution_menu"); let open = egui::Popup::is_id_open(ui.ctx(), popup_id) || response.clicked(); @@ -118,7 +127,7 @@ fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inhe ui.separator(); } for candidate in [128, 256, 512, 1024, 2048, 4096, 8192] { - if ui.selectable_label(candidate == resolution, format!("{candidate} × {candidate}")).clicked() { + if ui.selectable_label(candidate == resolution, format!("{candidate}x{candidate}")).clicked() { selected = Some(candidate); } } @@ -231,6 +240,18 @@ fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// How many maps baking `texture_sets` makes, counted as the reference's Bake button counts them: checked maps × included UV tiles, per set +fn maps_to_bake(app: &TextureCraftApp, texture_sets: &[usize]) -> usize { + texture_sets + .iter() + .filter_map(|index| app.session.doc.project.texture_sets.get(*index)) + .map(|set| { + let tiles = if set.uv_tiles.is_empty() { 1 } else { set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).count() }; + set.bake.maps.enabled().count() * tiles + }) + .sum() +} + /// The bake bar's gap from the bottom of the 3D view, in points (the pre-bake warnings sit above it) pub(super) const BAKE_BAR_MARGIN: f32 = 16.0; @@ -261,8 +282,9 @@ pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: .filter(|(_, texture_set)| texture_set.bake.common.is_enabled && texture_set.has_enabled_bake_tiles()) .map(|(index, _)| index) .collect(); - let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); - if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { + let maps = maps_to_bake(app, &texture_sets); + let label = trf("Bake ({n})", &[("n", &maps)]); + if ui.add_enabled(maps > 0, primary_button(ui, &label)).clicked() { app.start_bake(texture_sets); } } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 5bebfd98..afdae8a8 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -215,8 +215,8 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> { // --------------------------------------------------------------------------------------------- // The live dock -/// 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 texture set and mesh map bakers column in points: the reference's scaled to our larger font +const BAKERS_COLUMN_WIDTH: f32 = 232.0; /// Width of the bake layout's common and mesh map settings column, in points const SETTINGS_COLUMN_WIDTH: f32 = 330.0; /// Height of the log under the bake layout's columns, in points diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 1dd45d4f..104d8124 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -264,7 +264,7 @@ fn default_split_ratio() -> f32 { 0.5 } /// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` -const BAKE_LAYOUT_VERSION: u32 = 1; +const BAKE_LAYOUT_VERSION: u32 = 2; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 6da22b0d..65aa73ba 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -187,9 +187,9 @@ fn texture_set_resolution_controls_are_independent_from_bake_output() { let mut harness = harness(Some(BakedMap::AmbientOcclusion)); let before = harness.state().session.doc.project.clone(); let active_set = harness.state().session.ts(); - harness.get_all_by_value("256 × 256").nth(1).unwrap().click(); + harness.get_all_by_value("256x256").nth(1).unwrap().click(); harness.run_steps(3); - click(&mut harness, "128 × 128"); + click(&mut harness, "128x128"); wait_for_resolution(&mut harness, 1, 128); let session = &harness.state().session; @@ -226,33 +226,33 @@ fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() { harness.run_steps(4); let before = harness.state().session.doc.project.clone(); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + assert_eq!(harness.get_all_by_value("256x256").count(), 1); let resolution_position = harness.get_by_label("UV tile 1002 resolution").rect().center(); harness.hover_at(resolution_position); harness.run_steps(3); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + assert_eq!(harness.get_all_by_value("256x256").count(), 2); harness.hover_at(egui::pos2(900.0, 500.0)); harness.run_steps(3); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + assert_eq!(harness.get_all_by_value("256x256").count(), 1); harness.get_by_label("UV tile 1002 resolution").click(); harness.run_steps(3); - click(&mut harness, "128 × 128"); - harness.get_by_value("128 × 128*"); + click(&mut harness, "128x128"); + harness.get_by_value("128x128*"); let texture_set = &harness.state().session.doc.project.texture_sets[0]; assert_eq!(texture_set.resolution, 256); assert_eq!(texture_set.tile_resolution(1001), 256); assert_eq!(texture_set.tile_resolution(1002), 128); assert_eq!(texture_set.bake, before.texture_sets[0].bake); - harness.get_by_value("128 × 128*").click(); + harness.get_by_value("128x128*").click(); harness.run_steps(3); click(&mut harness, "Remove resolution override"); assert_eq!(harness.state().session.doc.project, before); - assert!(harness.query_by_value("128 × 128*").is_none()); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + assert!(harness.query_by_value("128x128*").is_none()); + assert_eq!(harness.get_all_by_value("256x256").count(), 1); harness.state_mut().session.undo().unwrap(); harness.run_steps(3); - harness.get_by_value("128 × 128*"); + harness.get_by_value("128x128*"); harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); @@ -277,14 +277,14 @@ fn bake_texture_sets_list_uv_tiles_and_their_resolutions() { harness.run_steps(4); harness.get_by_label("1001"); - harness.get_by_value("256 × 256"); + harness.get_by_value("256x256"); harness.get_by_label("1002"); - harness.get_by_value("128 × 128*"); + harness.get_by_value("128x128*"); click_checkbox(&mut harness, "1002"); assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002)); - assert!(!harness.get_by_label("Bake Selected Textures (1)").accesskit_node().is_disabled()); + assert!(!harness.get_by_label("Bake (7)").accesskit_node().is_disabled(), "7 checked maps on the one tile left"); click_checkbox(&mut harness, "1001"); - assert!(harness.get_by_label("Bake Selected Textures (0)").accesskit_node().is_disabled()); + assert!(harness.get_by_label("Bake (0)").accesskit_node().is_disabled()); harness.state_mut().session.undo().unwrap(); harness.state_mut().session.undo().unwrap(); harness.run_steps(3); @@ -570,6 +570,20 @@ fn the_baking_visualization_panel_opens_like_the_reference_at_first_launch() { assert!(harness.state().ui.bake_visualization.missing_seams.shown, "missing seams are ticked in every reference capture"); } +#[test] +fn texture_set_names_show_in_full_beside_their_resolution() { + let mut harness = harness(None); + harness.state_mut().session.doc.project.texture_sets[0].name = "LowerTorso".into(); + harness.state_mut().ui.dock.focus(Panel::TextureSetList); + harness.run_steps(3); + // "LowerTorso" is about 75 points wide; cut short it collapses to an ellipsis of about 20 + const FULL_NAME_MIN_WIDTH: f32 = 60.0; + // The breadcrumb names the set too; the list row is the top-most + let row = harness.get_all_by_label("LowerTorso").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap(); + let width = row.rect().width(); + assert!(width >= FULL_NAME_MIN_WIDTH, "the name is not cut short: {width}"); +} + #[test] fn the_high_poly_scene_is_a_list_with_add_and_remove() { let mut harness = harness(None); diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index f62af998..97964db4 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -6,6 +6,10 @@ use egui_kittest::kittest::Queryable; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; +/// A stroke inside the 2D view, right of bake mode's two settings columns +const STROKE_START: egui::Pos2 = egui::pos2(700.0, 500.0); +const STROKE_END: egui::Pos2 = egui::pos2(900.0, 500.0); + /// A bake-mode app with a high poly, the 2D view, and Common Settings in front fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -24,31 +28,31 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { let mut h = harness(); h.get_by_label("Skew Correction"); assert!(h.state().session.doc.bake_paint.is_empty() && !h.state().ui.bake_paint_brush.on); - // Off: a drag in the view paints nothing. - h.drag_at(egui::pos2(600.0, 500.0)); - h.hover_at(egui::pos2(800.0, 500.0)); - h.drop_at(egui::pos2(800.0, 500.0)); + // Off: a drag in the view paints nothing + h.drag_at(STROKE_START); + h.hover_at(STROKE_END); + h.drop_at(STROKE_END); h.run_steps(3); assert!(h.state().session.doc.bake_paint.is_empty(), "the brush is off"); - // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke. + // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke h.get_by_label("Paint Skew Correction").scroll_to_me(); h.run_steps(3); h.get_by_label("Paint Skew Correction").click(); h.run_steps(3); assert!(h.state().ui.bake_paint_brush.on); h.get_by_label("Radius"); - h.drag_at(egui::pos2(600.0, 500.0)); + h.drag_at(STROKE_START); h.run_steps(2); - h.hover_at(egui::pos2(800.0, 500.0)); + h.hover_at(STROKE_END); h.run_steps(2); - h.drop_at(egui::pos2(800.0, 500.0)); + h.drop_at(STROKE_END); h.run_steps(3); let map = h.state().session.doc.bake_paint.get(&(0, texturecraft_engine::core::BakePaintTarget::Skew)).cloned().expect("the stroke made a skew map"); let painted = map.values.iter().filter(|v| **v > 0.5).count(); assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len()); - // Removing it from the panel clears the map. + // Removing it from the panel clears the map h.get_by_label("Remove Skew Correction").scroll_to_me(); h.run_steps(3); h.get_by_label("Remove Skew Correction").click(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index fbcecb49..d4374926 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -282,16 +282,16 @@ fn bake_uv_tiles_snapshot() { harness.state_mut().ui.mode = Mode::Baking; save(&mut harness, &output_dir, "bake-uv-tiles"); - harness.get_by_value("128 × 128*").click(); + harness.get_by_value("128x128*").click(); save(&mut harness, &output_dir, "bake-tile-resolution-menu"); harness.get_by_label("Remove resolution override").click(); save(&mut harness, &output_dir, "bake-tile-resolution-inherited"); - assert!(harness.query_by_value("128 × 128*").is_none()); + assert!(harness.query_by_value("128x128*").is_none()); assert!(harness.state().session.doc.project.texture_sets[0].tile_resolutions.is_empty()); let inherited_resolution = harness.get_by_label("UV tile 1002 resolution").rect().center(); harness.hover_at(inherited_resolution); save(&mut harness, &output_dir, "bake-tile-resolution-hover"); - assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + assert_eq!(harness.get_all_by_value("256x256").count(), 2); harness.hover_at(egui::pos2(900.0, 500.0)); harness.state_mut().session.undo().unwrap(); harness.run_steps(3); From 7bd6c0ef2bdd327f58e027677c4dad3965c4a96d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:09:31 +0000 Subject: [PATCH 037/115] 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 038/115] 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 039/115] 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 e03e6fae6a677a505caf6ac9c971a61e62f177d9 Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Thu, 12 Nov 2026 17:56:19 +0100 Subject: [PATCH 040/115] fix(engine): reject unparseable colour parameters with an error (#369) (#390) * fix(engine): reject unparseable colour parameters with an error (#369) When a colour parameter cannot be parsed, fail with an error describing the expected color format instead of silently falling back to defaults. Update color_param to return an explicit error and propagate across commands that accept color values. * fix(engine): validate f32 overflow, pre-parse state mutations, and keep UV pairs strict (#369) --- crates/engine/src/commands.rs | 66 +++++++++++++++++++++++++++++++-- crates/engine/src/filter_lib.rs | 7 ++-- crates/engine/src/layer_cmds.rs | 16 +++++--- crates/engine/src/mask_cmds.rs | 6 +-- crates/engine/src/text_cmds.rs | 2 +- crates/engine/src/tool_cmds.rs | 20 +++++----- crates/engine/src/view_cmds.rs | 3 +- crates/engine/tests/session.rs | 49 ++++++++++++++++++++++++ 8 files changed, 141 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index d754fc70..a03a58a9 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -195,16 +195,26 @@ pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result Option<[f32; 3]> { - color_of(p.get(key)?) +pub(crate) fn color_param(cmd: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => color_of(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")"))), + } } /// A color value (see [`color_param`]). pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { match v { Value::Array(a) if a.len() >= 3 => { - let v: Vec = a.iter().take(3).map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); - if v.iter().all(|x| x.is_finite()) { Some([v[0], v[1], v[2]]) } else { None } + let mut out = [0.0f32; 3]; + for (i, x) in a.iter().take(3).enumerate() { + let f = x.as_f64()? as f32; + if !f.is_finite() { + return None; + } + out[i] = f; + } + Some(out) } Value::Number(n) => n.as_f64().map(|v| [v as f32; 3]).filter(|v| v[0].is_finite()), Value::String(s) => { @@ -218,3 +228,51 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { _ => None, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn color_param_accepts_valid_forms() { + let p = json!({ + "hex": "#336699", + "hex_plain": "336699", + "rgb": [0.2, 0.4, 0.6], + "grey": 0.5, + }); + assert!(color_param("cmd", &p, "hex").unwrap().is_some()); + assert!(color_param("cmd", &p, "hex_plain").unwrap().is_some()); + assert_eq!(color_param("cmd", &p, "rgb").unwrap(), Some([0.2, 0.4, 0.6])); + assert_eq!(color_param("cmd", &p, "grey").unwrap(), Some([0.5, 0.5, 0.5])); + assert_eq!(color_param("cmd", &p, "missing").unwrap(), None); + assert_eq!(color_param("cmd", &json!({"c": null}), "c").unwrap(), None); + } + + #[test] + fn color_param_rejects_invalid_forms() { + let bad_cases = [ + ("#fff", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("red", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("#12345", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("#gggggg", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ]; + for (input, expected_err) in bad_cases { + let p = json!({ "color": input }); + let err = color_param("test.cmd", &p, "color").unwrap_err(); + assert_eq!(err.to_string(), format!("`test.cmd`: {expected_err}")); + } + + let bad_array = json!({ "color": ["a", "b", "c"] }); + assert!(color_param("test.cmd", &bad_array, "color").is_err()); + + let short_array = json!({ "color": [0.5, 0.5] }); + assert!(color_param("test.cmd", &short_array, "color").is_err()); + + let overflow_array = json!({ "color": [1e40, 0.0, 0.0] }); + assert!(color_param("test.cmd", &overflow_array, "color").is_err()); + + let overflow_scalar = json!({ "color": 1e40 }); + assert!(color_param("test.cmd", &overflow_scalar, "color").is_err()); + } +} diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 7856f565..1e7c2b69 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -253,8 +253,8 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { } Filter::ColorBalance { shadows, midtones, highlights } => { for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] { - if p.get(key).is_some() { - let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; + if let Some(val) = p.get(key).filter(|v| !v.is_null()) { + let v = color_of(val).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; *slot = v.map(|x| x.clamp(-1.0, 1.0)); } } @@ -305,8 +305,7 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { } Filter::ReplaceColor { from, to, tolerance, softness } => { for (key, slot) in [("from", from), ("to", to)] { - if p.get(key).is_some() { - let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")")))?; + if let Some(v) = color_param(cmd, p, key)? { *slot = v.map(|x| x.clamp(0.0, 1.0)); } } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 36cd090c..5d5fc104 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -71,9 +71,9 @@ fn add_paint(s: &mut Session, p: &Value) -> Result { } /// A uniform fill from the `color`, `roughness`, `metallic`, `height` and `opacity` params. -pub(crate) fn fill_from(p: &Value) -> Fill { +pub(crate) fn fill_from(cmd: &str, p: &Value) -> Result { let mut fill = Fill::default(); - if let Some(c) = color_param(p, "color") { + if let Some(c) = color_param(cmd, p, "color")? { fill.sources.insert(Channel::BaseColor, Source::Uniform(c)); } for (key, ch) in [("roughness", Channel::Roughness), ("metallic", Channel::Metallic), ("height", Channel::Height), ("opacity", Channel::Opacity)] { @@ -81,13 +81,13 @@ pub(crate) fn fill_from(p: &Value) -> Fill { fill.sources.insert(ch, Source::Uniform([v; 3])); } } - fill + Ok(fill) } fn add_fill(s: &mut Session, p: &Value) -> Result { let ts = s.ts(); let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Fill layer")); - let fill = fill_from(p); + let fill = fill_from("layer.add.fill", p)?; let id = s.edit("Add fill layer", |s| { let id = s.doc.project.alloc_id(); insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &channels_of(s))) @@ -316,6 +316,10 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { let solo = boolp(p, "solo") == Some(true); let enabled = if solo { Some(true) } else { boolp(p, "enabled") }; let normal_format = normal_format_param("layer.fill.set", p)?; + let low = color_param("layer.fill.set", p, "low")?.unwrap_or([0.0; 3]); + let high = color_param("layer.fill.set", p, "high")?.unwrap_or([1.0; 3]); + let color = color_param("layer.fill.set", p, "color")?; + let value = color_param("layer.fill.set", p, "value")?; let source = if let Some(kind) = strp(p, "procedural") { let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?; let mut pr = Procedural::new(kind); @@ -332,8 +336,8 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { pr.balance = v.clamp(-1.0, 1.0); } pr.invert = boolp(p, "invert").unwrap_or(false); - Some(Source::Procedural { pattern: pr, low: color_param(p, "low").unwrap_or([0.0; 3]), high: color_param(p, "high").unwrap_or([1.0; 3]) }) - } else if let Some(c) = color_param(p, "color").or_else(|| color_param(p, "value")) { + Some(Source::Procedural { pattern: pr, low, high }) + } else if let Some(c) = color.or(value) { Some(Source::Uniform(c)) } else if let Some(name) = strp(p, "image") { Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() }) diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 4c286955..b61e745d 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -141,7 +141,7 @@ fn add_mask(s: &mut Session, p: &Value, bg: MaskBackground) -> Result { } fn add_color_mask(s: &mut Session, p: &Value) -> Result { - let color = color_param(p, "color").unwrap_or([1.0, 0.0, 0.0]); + let color = color_param("mask.add.colorSelection", p, "color")?.unwrap_or([1.0, 0.0, 0.0]); let tolerance = f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0); with_mask(s, p, "mask.add.colorSelection", "Add mask with color selection", |s, id| { let eid = s.doc.project.alloc_id(); @@ -285,7 +285,7 @@ fn add_fill(s: &mut Session, p: &Value) -> Result { let blend = blend_param("effect.add.fill", p, "blend")?.unwrap_or(BlendMode::Normal); let id = layer_param(s, "effect.add.fill", p)?; if content_target(p, "effect.add.fill")? { - let mut fill = crate::layer_cmds::fill_from(p); + let mut fill = crate::layer_cmds::fill_from("effect.add.fill", p)?; if fill.sources.is_empty() { fill.sources = s.doc.project.layer(id)?.channels.keys().map(|c| (*c, Source::uniform_of(*c))).collect(); } @@ -337,7 +337,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R if let Some(invert) = boolp(params, "invert") { generator.invert = invert; } - if let Some(direction) = color_param(params, "direction") { + if let Some(direction) = color_param(command, params, "direction")? { generator.direction = direction; } diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs index 7f39bd2a..5964813f 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -100,7 +100,7 @@ fn add_text(s: &mut Session, p: &Value) -> Result { let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?; let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0); let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?; - let rgb = color_param(p, "color").unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); + let rgb = color_param(cmd, p, "color")?.unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?; // The resource is named after the text (its first line, shortened) unless a name is given. let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect(); diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 6a390866..4c6c4e29 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -6,7 +6,7 @@ use texturecraft_core::Channel; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{Alignment, BrushAlpha, MAX_RADIAL_COPIES, alphas}; -use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp, vec3}; +use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_of, color_param, f32p, strp, vec3}; use crate::fill_hit_test::FillHitTest; use crate::fill_mode::FillMode; use crate::session::{CloneFrom, CloneSource, StackTarget, Tool}; @@ -285,11 +285,14 @@ pub(crate) fn brush_json(session: &Session) -> Value { } fn material(s: &mut Session, p: &Value) -> Result { + let channel = channel_param("tool.material", p, "channel")?; + let color = color_param("tool.material", p, "color")?; + let value = color_param("tool.material", p, "value")?; if let Some(v) = f32p(p, "maskValue") { s.tool.mask_value = v.clamp(0.0, 1.0); } - if let Some(c) = channel_param("tool.material", p, "channel")? { - if let Some(v) = color_param(p, "color").or_else(|| color_param(p, "value")) { + if let Some(c) = channel { + if let Some(v) = color.or(value) { let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) }; s.tool.values.insert(c, v); s.tool.enabled.insert(c); @@ -356,7 +359,7 @@ fn stencil(s: &mut Session, p: &Value) -> Result { s.tool.stencil = Some(st); } let st = s.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?; - if let Some(c) = color_param(p, "center").map(|c| [c[0], c[1]]).or_else(|| pair(p, "center")) { + if let Some(c) = pair(p, "center").or_else(|| p.get("center").and_then(color_of).map(|c| [c[0], c[1]])) { st.center = c.map(|v| v.clamp(-4.0, 4.0)); } if let Some(v) = f32p(p, "scale") { @@ -378,11 +381,10 @@ fn stencil(s: &mut Session, p: &Value) -> Result { /// A `[a, b]` param of two finite numbers. fn pair(p: &Value, key: &str) -> Option<[f32; 2]> { let a = p.get(key)?.as_array()?; - let v: Vec = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - match v.as_slice() { - [x, y] => Some([*x, *y]), - _ => None, - } + let [x, y] = a.as_slice() else { return None }; + let x = x.as_f64()? as f32; + let y = y.as_f64()? as f32; + (x.is_finite() && y.is_finite()).then_some([x, y]) } fn clone_source(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 9fb03ecf..db03435c 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -211,6 +211,7 @@ fn display(s: &mut Session, p: &Value) -> Result { if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) { return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); } + let scatter_color = color_param("display.set", p, "scatterColor")?; let d = &mut s.doc.project.display; if let Some(e) = env { d.environment = e; @@ -236,7 +237,7 @@ fn display(s: &mut Session, p: &Value) -> Result { if let Some(t) = tm { d.tone_mapping = t; } - if let Some(c) = color_param(p, "scatterColor") { + if let Some(c) = scatter_color { d.scatter_color = c.map(|v| v.clamp(0.0, 1.0)); } if let Some(b) = boolp(p, "shadows") { diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 22a17cd5..ddc25049 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -524,3 +524,52 @@ 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 unparseable_color_param_returns_error() { + let mut s = session(); + let err = execute(&mut s, "layer.add.fill", &json!({"color": "#fff"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "color": "#123"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "mask.add.colorSelection", &json!({"color": "#xyz"})).unwrap_err(); + assert_eq!(err.to_string(), "`mask.add.colorSelection`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let err = execute(&mut s, "display.set", &json!({"scatterColor": "#12345"})).unwrap_err(); + assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")"); + + let rev_before = s.revision; + let exposure_before = s.doc.project.display.env_exposure; + let err = execute(&mut s, "display.set", &json!({"exposure": 2.0, "scatterColor": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.doc.project.display.env_exposure, exposure_before); + assert_eq!(s.revision, rev_before); + + let mask_before = s.tool.mask_value; + let err = execute(&mut s, "tool.material", &json!({"maskValue": 0.25, "channel": "baseColor", "color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.tool.mask_value, mask_before); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "tool.material", &json!({"color": "invalid"})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "layer.add.fill", &json!({"color": [1e40, 0.0, 0.0]})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "noise", "color": "red"})).unwrap_err(); + assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(s.revision, rev_before); + + assert!(execute(&mut s, "tool.cloneSource", &json!({"uv": [0.2, 0.8, 0.4]})).is_err()); + execute(&mut s, "tool.polygonFill", &Value::Null).unwrap(); + let err = execute(&mut s, "tool.click", &json!({"uv": [0.2, 0.8, 0.4]})).unwrap_err(); + assert_eq!(err.to_string(), "`tool.click`: a 2D view point needs `uv` as [u, v]"); +} From a969983a5259cf2a032e7c5e2614da048b1445db Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Thu, 12 Nov 2026 17:56:34 +0100 Subject: [PATCH 041/115] fix(engine): resolve resource stem and list available names in layer.add.image (#337) (#391) * fix(engine): resolve resource stem and list available names in layer.add.image (#337) Accept an unambiguous file stem in layer.add.image alongside the full resource name with extension. When the requested resource is not found, list the available resources or guide the user to resource.import. * fix(engine): filter image lookup stems and hints to decoded images (#337) --- crates/engine/src/resource_cmds.rs | 34 ++++++++++++++--- crates/engine/tests/session.rs | 61 ++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 86e7c9b8..54876d19 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Add fill layer from image", [], None, - "{name, channel?: baseColor, projection?: uv|triplanar|planar, scale?}", + "{name (exact resource name with extension or unique stem), channel?: baseColor, projection?: uv|triplanar|planar, scale?}", always, add_image_fill ), @@ -179,11 +179,35 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { Ok(json!({ "removed": unused })) } -fn add_image_fill(s: &mut Session, p: &Value) -> Result { - let name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?.to_string(); - if !s.doc.resources.contains_key(&name) { - return Err(bad("layer.add.image", format!("no resource `{name}`"))); +#[cfg(not(target_arch = "wasm32"))] +const IMPORT_HINT: &str = "resource.import"; +#[cfg(target_arch = "wasm32")] +const IMPORT_HINT: &str = "File > Import resources"; + +/// Resolve an image resource by exact name or unique file stem. +fn resolve_resource_name(s: &Session, name: &str) -> Result { + if s.images.contains_key(name) { + return Ok(name.to_string()); } + let matches: Vec<&String> = s.images.keys().filter(|k| std::path::Path::new(k).file_stem().and_then(|stem| stem.to_str()) == Some(name)).collect(); + match matches.as_slice() { + [single] => Ok((*single).clone()), + [] => { + let available: Vec<&str> = s.images.keys().map(String::as_str).collect(); + let hint = + if available.is_empty() { format!(" (no resources imported: use {IMPORT_HINT})") } else { format!(" (available: {})", available.join(", ")) }; + Err(bad("layer.add.image", format!("no resource `{name}`{hint}"))) + } + multiple => { + let matches_str = multiple.iter().map(|m| format!("`{m}`")).collect::>().join(", "); + Err(bad("layer.add.image", format!("ambiguous resource `{name}` matches {matches_str}: give the full name with extension"))) + } + } +} + +fn add_image_fill(s: &mut Session, p: &Value) -> Result { + let raw_name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?; + let name = resolve_resource_name(s, raw_name)?; let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor); let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None)?; let ts = s.ts(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index ddc25049..34f5c4c2 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -308,6 +308,67 @@ fn image_resources_fill_layers_and_round_trip() { assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err()); } +#[test] +fn image_resource_lookup_accepts_extension_and_stem() { + let mut s = session(); + + // No resources imported yet + let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err(); + assert!(err.to_string().contains("no resource `missing` (no resources imported: use resource.import)")); + + let mut png = Vec::new(); + let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.import_resource_bytes("tile.png", png.clone()).unwrap(); + + // Lookup by stem + let r = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap(); + assert!(r["layer"].as_u64().is_some()); + + // Lookup by full name + let r2 = execute(&mut s, "layer.add.image", &json!({"name": "tile.png"})).unwrap(); + assert!(r2["layer"].as_u64().is_some()); + + // Missing resource lists available + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err(); + assert!(err.to_string().contains("no resource `wood` (available: tile.png)")); + + // Ambiguous stem resolution + s.import_resource_bytes("tile.jpg", png).unwrap(); + let err = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap_err(); + assert!(err.to_string().contains("ambiguous resource `tile`")); +} + +#[test] +fn image_resource_lookup_ignores_linked_packages() { + use std::sync::Arc; + use texturecraft_engine::core::{LayerId, LayerKind, Source}; + + let mut s = session(); + s.doc.resources.insert("wood.mcraft".into(), Arc::new(b"package bytes".to_vec())); + s.sync_images(); + assert!(!s.images.contains_key("wood.mcraft")); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err(); + assert!(err.to_string().contains("no resources imported"), "{err}"); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "wood.mcraft"})).unwrap_err(); + assert!(err.to_string().contains("no resource `wood.mcraft` (no resources imported"), "{err}"); + + let mut png = Vec::new(); + let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.import_resource_bytes("wood.png", png).unwrap(); + + let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err(); + assert!(err.to_string().contains("no resource `missing` (available: wood.png)"), "{err}"); + + let res = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap(); + let id = LayerId(res["layer"].as_u64().unwrap()); + let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("expected fill layer") }; + assert_eq!(fill.sources.get(&Channel::BaseColor), Some(&Source::image("wood.png"))); +} + #[test] fn brush_presets_apply_save_and_load() { let mut s = session(); From 6270aeca05d92527c6e09461efc9b0a35d415137 Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Thu, 12 Nov 2026 17:56:41 +0100 Subject: [PATCH 042/115] fix(engine): reset paint target to content when undoing mask (#307) (#398) * fix(engine): reset paint target to content when undoing mask (#307) * fix(engine): resolve mask_owner in after_history and clear below cache in test (#307) --- crates/engine/src/session.rs | 4 +++ crates/engine/tests/it/tools.rs | 51 +++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 41bfacbb..9d58670b 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -740,6 +740,10 @@ impl Session { let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e)); self.target = if content { StackTarget::Content } else { StackTarget::Mask }; } + let has_mask = self.selected_layer().and_then(|lid| self.doc.project.layer(self.doc.project.mask_owner(lid)).ok()).is_some_and(|l| l.mask.is_some()); + if self.target == StackTarget::Mask && !has_mask { + self.target = StackTarget::Content; + } } // ----------------------------------------------------------------------------------------- diff --git a/crates/engine/tests/it/tools.rs b/crates/engine/tests/it/tools.rs index afadf0b3..def69c97 100644 --- a/crates/engine/tests/it/tools.rs +++ b/crates/engine/tests/it/tools.rs @@ -244,3 +244,54 @@ fn swap_mask_value_inverts_only_while_a_mask_is_the_target() { assert_eq!(session.tool.mask_value, 0.0, "a mask effect paints the mask too"); } + +#[test] +fn stroke_after_undoing_mask_is_paint_stroke() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:random", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 50, "opacity": 0.8})).unwrap(); + execute(&mut s, "tool.paint", &Value::Null).unwrap(); + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.9, 0.3, 0.9]})).unwrap(); + + execute(&mut s, "tool.stroke", &json!({"points": [[130, 130], [170, 150]]})).unwrap(); + s.update(); + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + execute(&mut s, "tool.stroke", &json!({"points": [[167, 183], [207, 203]]})).unwrap(); + s.update(); + + let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(undone["undone"], "Paint stroke", "the stroke after undoing the mask was recorded as {}", undone["undone"]); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + s.update(); + + let settled = s.caches[0].composite.clone(); + s.caches[0].below.clear(); + s.caches[0].invalidate_all(); + s.update(); + assert_eq!(settled, s.caches[0].composite, "the composite after the stroke matches a full recomposite"); +} + +#[test] +fn undoing_after_painting_on_instance_source_mask_keeps_mask_target() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:random", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + execute(&mut s, "layer.instance", &Value::Null).unwrap(); + s.update(); + s.target = StackTarget::Mask; + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 50, "opacity": 0.8})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[170, 180], [210, 200]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.target, StackTarget::Mask); + + execute(&mut s, "tool.stroke", &json!({"points": [[180, 180], [210, 200]]})).unwrap(); + let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(undone["undone"], "Mask stroke"); +} From feb2a83b851e1095038ae530b1b706966ad2d5b6 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:59:43 +0100 Subject: [PATCH 043/115] test(cli): resolve binary paths after nextest archive relocation (#454) --- apps/texturecraft-cli/tests/cli.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 686bee97..4cb6a5aa 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -1,12 +1,34 @@ //! Drives the `texturecraft-cli` binary. +use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use serde_json::Value; +// Nextest 0.9.130+ remaps this variable when an archive is extracted on another +// runner. Cargo's compile-time path still supports ordinary `cargo test`. +fn cli_binary() -> OsString { + cli_binary_path(std::env::var_os("CARGO_BIN_EXE_texturecraft-cli")) +} + +fn cli_binary_path(runner_path: Option) -> OsString { + runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into()) +} + +#[test] +fn cli_binary_prefers_relocated_runner_path() { + let relocated = OsString::from("relocated archive/texturecraft-cli"); + assert_eq!(cli_binary_path(Some(relocated.clone())), relocated); +} + +#[test] +fn cli_binary_defaults_to_cargo_path() { + assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli"))); +} + fn cli(args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")).args(args).output().unwrap() + Command::new(cli_binary()).args(args).output().unwrap() } fn ok(args: &[&str]) -> String { @@ -101,7 +123,7 @@ fn info_on_a_mesh_reports_uvs() { fn serve_takes_the_automation_root_spelling_too() { use std::io::Write as _; let d = tmp("automation-root"); - let mut child = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) + let mut child = Command::new(cli_binary()) .args(["serve", "--automation-write-root", p(&d)]) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) From a03f14ea88c7538e884d226ce3ca195712837e8b Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Thu, 12 Nov 2026 16:21:42 -0500 Subject: [PATCH 044/115] Updating CI with local profile for faster runs (#453) * Run CI on stable Rust and check layering earlier * Add a faster profile for optimized verification --- .github/workflows/ci.yml | 1 - Cargo.toml | 7 +++++++ docs/testing-ci.md | 25 +++++++++++++++++++++++++ xtask/src/main.rs | 5 +++-- 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7bef15d1..1145b532 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,6 @@ jobs: # Same craft-fonts commit as release.yml. craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc os: '["ubuntu-24.04","windows-latest"]' - toolchain: "1.96.0" # xtask ci runs cargo test (including doctests), not cargo nextest. tools: "" packages: >- diff --git a/Cargo.toml b/Cargo.toml index 692bd9f4..cb9745b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -117,6 +117,13 @@ opt-level = 1 lto = "thin" codegen-units = 1 +# Fast optimized verification: each test executable otherwise repeats cross-crate LTO. +# `false` keeps thin LTO within each crate; release packaging keeps the profile above. +[profile.verify] +inherits = "release" +lto = false +codegen-units = 16 + [profile.wasm-release] inherits = "release" opt-level = "s" diff --git a/docs/testing-ci.md b/docs/testing-ci.md index 7db9ae07..4fb8d5fd 100644 --- a/docs/testing-ci.md +++ b/docs/testing-ci.md @@ -12,6 +12,31 @@ Run a feature module with a test-name filter, for example: cargo test -p texturecraft-engine --test it bake:: ``` +For faster optimized local verification, run the same workspace tests and doctests +with the `verify` profile: + +```sh +cargo test --workspace --profile verify +``` + +`verify` inherits the release profile's optimization level and runtime checks, but +uses 16 codegen units and `lto = false`. Cargo retains thin LTO within each crate +without repeating cross-crate LTO for every test executable. The existing test +selection and ignore attributes still apply. Keep the target directory between +runs so Cargo can reuse unchanged build artifacts. + +To compile the normal application binaries alongside the test binaries before +running them: + +```sh +cargo build --workspace --bins --tests --profile verify +cargo test --workspace --profile verify +``` + +This profile is for local verification. Use `--release` for release validation and +performance measurements; its compiler settings remain unchanged. The regular +debug test profile and CI gates also remain unchanged. + The standalone engine `session` target and UI `ui_snapshots` target remain available for the commands in `AGENTS.md`. Existing ignore attributes are unchanged. Tests in the shared executable can run concurrently across modules; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ccbdc2c7..2ff6178a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -15,7 +15,7 @@ usage: cargo xtask commands: layers enforce the crate dependency layering (xtask/src/layers.rs) wasm cargo check --target wasm32-unknown-unknown for the wasm crates and the web app - ci fmt --check, clippy -D warnings, test, layers, wasm (stops at the first failure) + ci fmt --check, layers, clippy -D warnings, test, wasm (stops at the first failure) version [set X.Y.Z[-pre]] print the workspace version, or set it (Cargo.toml + Cargo.lock) ico ... @@ -154,11 +154,12 @@ fn cmd_ci() -> Result<(), String> { } }; type Step = (&'static str, Box Result<(), String>>); + // Reject invalid dependency layering before spending time compiling and running the workspace. let steps: Vec = vec![ ("fmt", Box::new(cargo_step(&["fmt", "--all", "--", "--check"]))), + ("layers", Box::new(cmd_layers)), ("clippy", Box::new(cargo_step(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]))), ("test", Box::new(cargo_step(&["test", "--workspace"]))), - ("layers", Box::new(cmd_layers)), ("wasm", Box::new(cmd_wasm)), ]; for (i, (name, step)) in steps.iter().enumerate() { From aa99a798a7e64c9b00cb2e13b434c75ee38ddea1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:15:49 +0100 Subject: [PATCH 045/115] test(formats): split malformed scene fixtures for parallel CI (#455) --- crates/formats/src/mesh_import/scene_tests.rs | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 5c5f4b5a..09515423 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -589,19 +589,55 @@ fn fbx_old_versions_and_garbage_are_errors() { assert!(import_mesh_bytes("h.fbx", &huge).is_err()); } +// Keep these fixtures independently schedulable: one serial test took 24 minutes in +// instrumented coverage. Splitting cases keeps every mutation and assertion intact. #[test] -fn malformed_fbx_and_dae_never_panic() { +fn malformed_fbx_and_dae_never_panic_binary_7400() { hammer("x.fbx", &binary_fbx(&scene(false), 7400, false)); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_binary_7500() { hammer("x.fbx", &binary_fbx(&scene(true), 7500, true)); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_ascii() { hammer("x.fbx", ascii_fbx(&scene(false)).as_bytes()); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_collada() { hammer("x.dae", DAE.as_bytes()); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_binary() { + random_scene_corruptions(0); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_ascii() { + random_scene_corruptions(1); +} + +#[test] +fn malformed_fbx_and_dae_never_panic_random_collada() { + random_scene_corruptions(2); +} + +fn random_scene_corruptions(selected_fixture: usize) { // Random multi-byte corruptions (a fixed LCG keeps failures reproducible). let mut seed = 0x2545_f491_4f6c_dd1du64; let mut next = move || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) as usize }; - for good in [binary_fbx(&scene(false), 7500, true), ascii_fbx(&scene(true)).into_bytes(), DAE.as_bytes().to_vec()] { + // Replay earlier mutations without parsing them so each fixture receives exactly + // its original LCG stream, not a fresh seed. Fixture sizes and all 1,500 cases + // per fixture stay unchanged; generating these bytes is cheap next to parsing. + let fixtures = [binary_fbx(&scene(false), 7500, true), ascii_fbx(&scene(true)).into_bytes(), DAE.as_bytes().to_vec()]; + for (fixture, good) in fixtures.into_iter().enumerate().take(selected_fixture + 1) { let name = if good.starts_with(b" Date: Fri, 13 Nov 2026 05:53:14 +0000 Subject: [PATCH 046/115] Use shared MaterialX parser and writer --- Cargo.lock | 37 ++- Cargo.toml | 17 +- crates/formats/Cargo.toml | 1 + crates/formats/src/materialx.rs | 143 ++------- crates/formats/src/materialx_read.rs | 427 +++++---------------------- 5 files changed, 135 insertions(+), 490 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bcd091ae..66ad4529 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,7 +758,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -771,12 +771,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "fixed_decimal", "icu_decimal", @@ -799,17 +799,26 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "egui", "serde", "serde_json", ] +[[package]] +name = "craft-materialx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +dependencies = [ + "craft-xml", + "thiserror 2.0.21", +] + [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "craft-keymap", "craft-quit", @@ -822,7 +831,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "dispatch2", "egui", @@ -833,7 +842,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -854,7 +863,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "chrono", "dunce", @@ -881,7 +890,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "egui", "objc2 0.6.5", @@ -889,6 +898,15 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -4369,6 +4387,7 @@ name = "texturecraft-formats" version = "0.6.1" dependencies = [ "base64 0.22.1", + "craft-materialx", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index cb9745b5..5fa07cf3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,20 +66,21 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["serde"] } +craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } # 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 = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } # Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 7b458a53..50654ab8 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +craft-materialx = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs index e7440328..9481ed13 100644 --- a/crates/formats/src/materialx.rs +++ b/crates/formats/src/materialx.rs @@ -1,20 +1,7 @@ -//! MaterialX documents for exported texture sets, written from the ASWF MaterialX specification -//! (version 1.39) and the OpenPBR Surface specification. Pure Rust: no MaterialX library is -//! linked, and nothing is read from any other application. +//! TextureCraft's MaterialX export adapter. //! -//! [`write`] takes a material's name and the texture files an export produced, each tagged with -//! the OpenPBR input it feeds, and gives the text of a `.mtlx` file: an `open_pbr_surface` shader -//! whose inputs read `tiledimage` nodes, wrapped in a `surfacematerial`. The inputs are the ones -//! the built-in "OpenPBR (separate maps)" export preset writes ([`INPUTS`]); `height` becomes a -//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node -//! (OpenGL, +Y up, which is what that node expects). -//! -//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were -//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `` filename token MaterialX defines. -//! Texture file names are relative to the document. - -use std::collections::HashSet; -use std::fmt::Write as _; +//! The shared `craft-materialx` crate owns the MaterialX document writer. This module maps the +//! built-in preset's map names and TextureCraft color spaces to that format-level API. use texturecraft_texel::ColorSpace; @@ -51,7 +38,6 @@ pub const INPUTS: &[(&str, Kind)] = &[ ("height", Kind::Height), ]; -/// The file-name prefix of the built-in OpenPBR preset's maps. const PREFIX: &str = "$mesh_$textureSet_"; /// One exported texture: the OpenPBR input it feeds and the file (relative to the `.mtlx`). @@ -59,14 +45,11 @@ const PREFIX: &str = "$mesh_$textureSet_"; pub struct Texture { pub input: String, pub file: String, - /// The MaterialX colour space of the file's values (`srgb_texture`, `lin_rec709`, ...); - /// used for colour inputs only, data maps are always linear. + /// The MaterialX colour space of the file's values; used for color inputs only. pub colorspace: &'static str, } -/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no -/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the -/// specification, which 1.39 readers may not know. +/// The MaterialX colour space of colour maps written in `space`. pub fn colorspace_name(space: ColorSpace) -> &'static str { match space { ColorSpace::Srgb => "srgb_texture", @@ -76,116 +59,28 @@ pub fn colorspace_name(space: ColorSpace) -> &'static str { } } -/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → -/// `base_color`), or None for templates this module has no place for. +/// The OpenPBR input a preset map's file template feeds, or None for unsupported templates. pub fn input_of_template(template: &str) -> Option<&'static str> { let suffix = template.strip_prefix(PREFIX)?; - INPUTS.iter().find(|(n, _)| *n == suffix).map(|(n, _)| *n) -} - -fn kind_of(input: &str) -> Option { - INPUTS.iter().find(|(n, _)| *n == input).map(|(_, k)| *k) + INPUTS.iter().find(|(name, _)| *name == suffix).map(|(name, _)| *name) } /// A MaterialX name: letters, digits and underscores, not starting with a digit. -pub fn node_name(s: &str) -> String { - let mut out: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); +pub fn node_name(name: &str) -> String { + let mut out: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { out.insert(0, '_'); } out } -fn esc(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - c if c.is_control() => out.push(' '), - c => out.push(c), - } - } - out -} - -fn image_name(input: &str) -> String { - format!("image_{}", node_name(input)) -} - -/// The text of a MaterialX document for `name` with the given textures. `physical_size_cm` goes -/// into the material's `doc` attribute. Inputs this module has no place for are skipped, and so -/// are repeats of one input (the first wins). +/// The text of a MaterialX OpenPBR document for `name` and the given texture files. pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2]>) -> String { - let base = node_name(name); - let mut seen = HashSet::new(); - let tex: Vec<(&Texture, Kind)> = textures.iter().filter_map(|t| kind_of(&t.input).map(|k| (t, k))).filter(|(t, _)| seen.insert(t.input.as_str())).collect(); - let has = |i: &str| tex.iter().any(|(t, _)| t.input == i); - let mut x = String::new(); - let _ = writeln!(x, ""); - let _ = writeln!(x, ""); - - let shader = format!("OPBR_{base}"); - let _ = writeln!(x, " ", esc(&shader)); - for (t, kind) in &tex { - let (ty, node) = match kind { - Kind::Color => ("color3", image_name(&t.input)), - Kind::Float => ("float", image_name(&t.input)), - Kind::Normal => ("vector3", "normalmap".to_owned()), - Kind::Height => continue, - }; - let _ = writeln!(x, " ", t.input); - } - if has("emission_color") { - let _ = writeln!(x, " "); - } - let _ = writeln!(x, " "); - - for (t, kind) in &tex { - let (ty, space) = match kind { - Kind::Color => ("color3", Some(t.colorspace)), - Kind::Normal => ("vector3", None), - Kind::Float | Kind::Height => ("float", None), - }; - let node = image_name(&t.input); - let _ = writeln!(x, " "); - match space { - Some(space) => { - let _ = writeln!(x, " ", esc(&t.file)); - } - None => { - let _ = writeln!(x, " ", esc(&t.file)); - } - } - let _ = writeln!(x, " "); - } - if has("geometry_normal") { - let _ = writeln!(x, " "); - let _ = writeln!(x, " ", image_name("geometry_normal")); - let _ = writeln!(x, " "); - } - if has("height") { - let _ = writeln!(x, " "); - let _ = writeln!(x, " ", image_name("height")); - let _ = writeln!(x, " "); - let _ = writeln!(x, " "); - } - - let doc = match physical_size_cm { - Some([w, h]) if w.is_finite() && h.is_finite() => format!(" doc=\"Tiles every {w} x {h} cm\""), - _ => String::new(), - }; - let _ = writeln!(x, " ", esc(&base)); - let _ = writeln!(x, " ", esc(&shader)); - if has("height") { - let _ = writeln!(x, " "); - } - let _ = writeln!(x, " "); - let _ = writeln!(x, ""); - x + let textures: Vec = textures + .iter() + .map(|texture| craft_materialx::Texture { input: texture.input.clone(), file: texture.file.clone(), colorspace: texture.colorspace.to_owned() }) + .collect(); + craft_materialx::write_open_pbr(name, &textures, physical_size_cm) } #[cfg(test)] @@ -247,7 +142,7 @@ mod tests { assert!(x.contains(want), "missing {want}\n{x}"); } // Data textures carry no colour space, and height is not an OpenPBR input. - assert!(x.contains("value=\"stone_specular_roughness.png\" />")); + assert!(x.contains("value=\"stone_specular_roughness.png\"/>")); assert!(!x.contains("name=\"height\"")); } @@ -265,7 +160,7 @@ mod tests { fn colour_inputs_carry_their_files_space_and_data_inputs_none() { let lin = |input: &str, file: &str| Texture { colorspace: "lin_rec709", ..tex(input, file) }; let x = write("m", &[lin("base_color", "c.exr"), lin("specular_roughness", "r.exr")], None); - assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\" />"), "{x}"); + assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\"/>"), "{x}"); } #[test] @@ -292,7 +187,9 @@ mod tests { assert_eq!(node_name(""), "_"); let x = write("a&\"c", &[tex("base_color", "x\"&<'>..png")], Some([f32::NAN, 1.0])); assert!(balanced(&x.replace("<UDIM>", "UDIM")), "{x}"); - assert!(x.contains("value=\"x"&<'>.<UDIM>.png\"")); + let doc = craft_materialx::Document::parse(x.as_bytes()).unwrap(); + let material = doc.read_material(None).unwrap(); + assert!(material.inputs.iter().any(|(input, value)| input == "base_color" && value == &craft_materialx::Value::Image("x\"&<'>..png".into()))); assert!(!x.contains("doc="), "a non-finite size is left out"); assert!(x.contains("OPBR_a_b___c")); } diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs index c8cd8b39..1b3da9ea 100644 --- a/crates/formats/src/materialx_read.rs +++ b/crates/formats/src/materialx_read.rs @@ -1,41 +1,16 @@ -//! Reading a MaterialX (`.mtlx`) material into TextureCraft's channels, written from the ASWF -//! MaterialX specification (1.39) and the OpenPBR Surface and glTF PBR node definitions. Pure -//! Rust: no MaterialX library is linked. +//! MaterialX material import adapted to TextureCraft's channel model. //! -//! [`read_materialx`] finds a `surfacematerial`, follows its `surfaceshader` to an -//! `open_pbr_surface`, `standard_surface` or `gltf_pbr` node, and turns each input TextureCraft -//! has a channel for into a literal value or an image file: -//! -//! - a literal `value` becomes a constant (`color3` values tagged `srgb_texture` are converted -//! to linear; a colour given for a scalar channel is averaged); -//! - an input wired to a `tiledimage` or `image` node (directly or through a `nodegraph` -//! output) becomes that node's `file` (with `fileprefix` applied); `normalmap`, `convert` and -//! `constant` nodes in between are passed through; -//! - the material's `displacementshader` becomes the height channel; -//! - `uvtiling` of the first tiled image is returned as the UV tiling. -//! -//! Anything else (maths nodes, procedural patterns, other shaders) is skipped with a warning -//! rather than guessed at. Emission follows the specifications' defaults: OpenPBR emits nothing -//! unless `emission_luminance` is above 0, and `standard_surface` unless `emission` is. -//! -//! The reader takes untrusted bytes: the document size, nesting and element count are capped, a -//! wiring loop stops at a depth limit, and every failure is an error, never a panic. +//! XML parsing, nodegraph traversal and shader input resolution live in `craft-materialx`. +//! This module maps those format-level values to TextureCraft's channels and color handling. -use std::collections::HashMap; - -use quick_xml::events::{BytesStart, Event}; -use texturecraft_core::Channel; +use texturecraft_core::{Channel, ChannelKind}; use texturecraft_texel::srgb_to_linear; use crate::{FormatError, Result, malformed}; const KIND: &str = "MaterialX document"; /// Largest document read, in bytes. -pub const MAX_BYTES: usize = 16 << 20; -const MAX_DEPTH: usize = 64; -const MAX_ELEMENTS: usize = 200_000; -/// Longest chain of nodes followed from one shader input. -const MAX_HOPS: usize = 16; +pub const MAX_BYTES: usize = craft_materialx::MAX_BYTES; /// What one channel is set from. #[derive(Clone, Debug, PartialEq)] @@ -58,259 +33,40 @@ pub struct Material { pub warnings: Vec, } -// --------------------------------------------------------------------------------------------- -// XML. - -#[derive(Default)] -struct El { - name: String, - attrs: Vec<(String, String)>, - children: Vec, +fn channel(shader: craft_materialx::Shader, input: &str) -> Option { + use craft_materialx::Shader::{GltfPbr, OpenPbr, StandardSurface}; + Some(match (shader, input) { + (OpenPbr, "base_color") | (StandardSurface, "base_color") | (GltfPbr, "base_color") => Channel::BaseColor, + (OpenPbr, "base_metalness") | (StandardSurface, "metalness") | (GltfPbr, "metallic") => Channel::Metallic, + (OpenPbr, "specular_roughness") | (StandardSurface, "specular_roughness") | (GltfPbr, "roughness") => Channel::Roughness, + (OpenPbr, "geometry_normal") | (StandardSurface, "normal") | (GltfPbr, "normal") => Channel::Normal, + (OpenPbr, "geometry_opacity") | (StandardSurface, "opacity") | (GltfPbr, "alpha") => Channel::Opacity, + (OpenPbr, "emission_color") | (StandardSurface, "emission_color") | (GltfPbr, "emission") => Channel::Emissive, + (OpenPbr, "coat_weight") | (StandardSurface, "coat") | (GltfPbr, "clearcoat") => Channel::CoatWeight, + (OpenPbr, "coat_roughness") | (StandardSurface, "coat_roughness") | (GltfPbr, "clearcoat_roughness") => Channel::CoatRoughness, + (OpenPbr, "geometry_coat_normal") | (StandardSurface, "coat_normal") | (GltfPbr, "clearcoat_normal") => Channel::CoatNormal, + (OpenPbr, "fuzz_weight") | (StandardSurface, "sheen") => Channel::SheenWeight, + (OpenPbr, "fuzz_color") | (StandardSurface, "sheen_color") | (GltfPbr, "sheen_color") => Channel::SheenColor, + (OpenPbr, "fuzz_roughness") | (StandardSurface, "sheen_roughness") | (GltfPbr, "sheen_roughness") => Channel::SheenRoughness, + (OpenPbr, "specular_roughness_anisotropy") | (StandardSurface, "specular_anisotropy") => Channel::AnisotropyLevel, + (OpenPbr, "transmission_weight") | (StandardSurface, "transmission") | (GltfPbr, "transmission") => Channel::Transmission, + (OpenPbr, "subsurface_weight") | (StandardSurface, "subsurface") => Channel::ScatterWeight, + (GltfPbr, "occlusion") => Channel::AmbientOcclusion, + _ => return None, + }) } -impl El { - fn attr(&self, k: &str) -> Option<&str> { - self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) +fn constant(channel: Channel, values: &[f32], colorspace: Option<&str>) -> [f32; 3] { + let mut values = values.to_vec(); + if let Some(space) = colorspace + && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) + && values.len() >= 3 + { + values.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); } - - /// The child element named `name` (the `name` attribute: inputs and nodes are looked up by it). - fn input(&self, name: &str) -> Option<&El> { - self.children.iter().find(|c| c.attr("name") == Some(name)) - } -} - -fn element(e: &BytesStart) -> El { - let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); - let attrs = e - .attributes() - .with_checks(false) - .flatten() - .map(|a| { - (text(a.key.local_name().as_ref()), a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned())) - }) - .collect(); - El { name: text(e.local_name().as_ref()), attrs, children: Vec::new() } -} - -fn parse_xml(bytes: &[u8]) -> Result { - let mut reader = quick_xml::Reader::from_reader(bytes); - let mut stack = vec![El::default()]; - let mut count = 0usize; - loop { - let event = reader.read_event().map_err(|e| malformed(KIND, e))?; - if matches!(event, Event::Start(_) | Event::Empty(_)) { - count += 1; - if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH { - return Err(FormatError::TooLarge(format!( - "the MaterialX document has more than {MAX_ELEMENTS} elements or is nested deeper than {MAX_DEPTH}" - ))); - } - } - match event { - Event::Start(e) => stack.push(element(&e)), - Event::Empty(e) => { - if let Some(parent) = stack.last_mut() { - parent.children.push(element(&e)); - } - } - Event::End(_) => { - let el = stack.pop().filter(|_| !stack.is_empty()).ok_or_else(|| malformed(KIND, "unbalanced end tag"))?; - if let Some(parent) = stack.last_mut() { - parent.children.push(el); - } - } - Event::Eof => break, - _ => {} - } - } - match (stack.pop(), stack.is_empty()) { - (Some(root), true) => Ok(root), - _ => Err(malformed(KIND, "unclosed elements at the end of the document")), - } -} - -// --------------------------------------------------------------------------------------------- -// Shader input tables: (shader input, channel). `kind` says how to read the value. - -#[derive(Clone, Copy, PartialEq)] -enum Shader { - OpenPbr, - Standard, - Gltf, -} - -const OPEN_PBR: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("base_metalness", Channel::Metallic), - ("specular_roughness", Channel::Roughness), - ("geometry_normal", Channel::Normal), - ("geometry_opacity", Channel::Opacity), - ("emission_color", Channel::Emissive), - ("coat_weight", Channel::CoatWeight), - ("coat_roughness", Channel::CoatRoughness), - ("geometry_coat_normal", Channel::CoatNormal), - ("fuzz_weight", Channel::SheenWeight), - ("fuzz_color", Channel::SheenColor), - ("fuzz_roughness", Channel::SheenRoughness), - ("specular_roughness_anisotropy", Channel::AnisotropyLevel), - ("transmission_weight", Channel::Transmission), - ("subsurface_weight", Channel::ScatterWeight), -]; - -const STANDARD: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("metalness", Channel::Metallic), - ("specular_roughness", Channel::Roughness), - ("normal", Channel::Normal), - ("opacity", Channel::Opacity), - ("emission_color", Channel::Emissive), - ("coat", Channel::CoatWeight), - ("coat_roughness", Channel::CoatRoughness), - ("coat_normal", Channel::CoatNormal), - ("sheen", Channel::SheenWeight), - ("sheen_color", Channel::SheenColor), - ("sheen_roughness", Channel::SheenRoughness), - ("specular_anisotropy", Channel::AnisotropyLevel), - ("transmission", Channel::Transmission), - ("subsurface", Channel::ScatterWeight), -]; - -const GLTF: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("metallic", Channel::Metallic), - ("roughness", Channel::Roughness), - ("normal", Channel::Normal), - ("alpha", Channel::Opacity), - ("emission", Channel::Emissive), - ("occlusion", Channel::AmbientOcclusion), - ("clearcoat", Channel::CoatWeight), - ("clearcoat_roughness", Channel::CoatRoughness), - ("clearcoat_normal", Channel::CoatNormal), - ("sheen_color", Channel::SheenColor), - ("sheen_roughness", Channel::SheenRoughness), - ("transmission", Channel::Transmission), -]; - -// --------------------------------------------------------------------------------------------- -// Resolving what feeds an input. - -struct Doc<'a> { - root: &'a El, - /// Every node by name: the document's own, and each nodegraph's (qualified `graph/node`). - nodes: HashMap, - /// Each nodegraph's outputs: `graph/output` to the node name inside (qualified). - outputs: HashMap, - tiling: Option<[f32; 2]>, - warnings: Vec, -} - -enum Found { - Constant(Vec), - Image(String), - None, -} - -fn numbers(text: &str) -> Option> { - let v: Option> = text.split(',').map(|p| p.trim().parse::().ok().filter(|f| f.is_finite())).collect(); - v.filter(|v| !v.is_empty() && v.len() <= 4) -} - -impl<'a> Doc<'a> { - fn new(root: &'a El) -> Doc<'a> { - let mut nodes = HashMap::new(); - let mut outputs = HashMap::new(); - for c in &root.children { - match (c.name.as_str(), c.attr("name")) { - ("nodegraph", Some(g)) => { - for n in &c.children { - let Some(name) = n.attr("name") else { continue }; - if n.name == "output" { - if let Some(from) = n.attr("nodename") { - outputs.insert(format!("{g}/{name}"), format!("{g}/{from}")); - } - } else { - nodes.insert(format!("{g}/{name}"), n); - } - } - } - (_, Some(name)) => { - nodes.insert(name.to_owned(), c); - } - _ => {} - } - } - Doc { root, nodes, outputs, tiling: None, warnings: Vec::new() } - } - - /// What `input` (an `` element of a node) resolves to; `scope` is the nodegraph the - /// node lives in, if any. - fn resolve(&mut self, input: &El, scope: Option<&str>, hops: usize) -> Found { - if hops > MAX_HOPS { - self.warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); - return Found::None; - } - if let Some(v) = input.attr("value") { - return numbers(v).map_or(Found::None, |n| Found::Constant(self.tag(input, n))); - } - let target = match (input.attr("nodegraph"), input.attr("output"), input.attr("nodename")) { - (Some(g), out, _) => { - let out = out.map(str::to_owned).or_else(|| self.outputs.keys().find_map(|k| k.strip_prefix(&format!("{g}/")).map(str::to_owned))); - out.and_then(|o| self.outputs.get(&format!("{g}/{o}")).cloned()) - } - (None, _, Some(n)) => { - Some(scope.map_or_else(|| n.to_owned(), |g| format!("{g}/{n}"))).filter(|q| self.nodes.contains_key(q)).or_else(|| Some(n.to_owned())) - } - _ => None, - }; - let Some(node) = target.as_deref().and_then(|t| self.nodes.get(t).copied()) else { return Found::None }; - let scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g.to_owned()); - let scope = scope.as_deref(); - match node.name.as_str() { - "tiledimage" | "image" => { - let Some(file) = node.input("file").and_then(|f| f.attr("value")) else { - self.warnings.push(format!("image node {:?} has no file", node.attr("name").unwrap_or(""))); - return Found::None; - }; - let prefix = - [node.input("file").and_then(|f| f.attr("fileprefix")), node.attr("fileprefix"), self.root.attr("fileprefix")].into_iter().flatten().next(); - if self.tiling.is_none() - && let Some(t) = - node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0)) - { - // The range a fill's UV scale accepts (`layer.fill.projection`). - self.tiling = Some([t[0].clamp(0.001, 1000.0), t[1].clamp(0.001, 1000.0)]); - } - Found::Image(format!("{}{file}", prefix.unwrap_or(""))) - } - "normalmap" | "convert" => match node.input("in") { - Some(i) => self.resolve(i, scope, hops + 1), - None => Found::None, - }, - "constant" => match node.input("value") { - Some(v) => self.resolve(v, scope, hops + 1), - None => Found::None, - }, - other => { - self.warnings.push(format!("a {other} node ({:?}) is not supported; its input was skipped", node.attr("name").unwrap_or(""))); - Found::None - } - } - } - - /// Literal values tagged with an sRGB colour space are converted to linear. - fn tag(&self, input: &El, mut n: Vec) -> Vec { - let space = input.attr("colorspace").or_else(|| self.root.attr("colorspace")).unwrap_or(""); - if input.attr("colorspace").is_some() && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) && n.len() >= 3 { - n.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); - } - n - } -} - -fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { - match (channel.kind(), n) { + match (channel.kind(), values.as_slice()) { (_, [a]) => [*a; 3], - (texturecraft_core::ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], + (ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], (_, [r, g, b, ..]) => { let mean = (r + g + b) / 3.0; [mean; 3] @@ -319,9 +75,11 @@ fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { } } -/// The literal number of `input`, if it is one. -fn literal(shader: &El, name: &str) -> Option { - shader.input(name).and_then(|i| i.attr("value")).and_then(numbers).and_then(|n| n.first().copied()) +fn app_value(channel: Channel, value: craft_materialx::Value) -> Value { + match value { + craft_materialx::Value::Constant { values, colorspace } => Value::Constant(constant(channel, &values, colorspace.as_deref())), + craft_materialx::Value::Image(file) => Value::Image(file), + } } /// Read the material called `material` (default: the first) from a `.mtlx` document. @@ -330,79 +88,30 @@ pub fn read_materialx(bytes: &[u8], material: Option<&str>) -> Result } fn read_inner(bytes: &[u8], material: Option<&str>) -> Result { - if bytes.len() > MAX_BYTES { - return Err(FormatError::TooLarge(format!("the MaterialX document is over {} MiB", MAX_BYTES >> 20))); - } - let top = parse_xml(bytes)?; - let root = top.children.iter().find(|c| c.name == "materialx").ok_or_else(|| malformed(KIND, "no element"))?; - let mut doc = Doc::new(root); - let materials: Vec<&El> = root.children.iter().filter(|c| c.name == "surfacematerial").collect(); - let mat = match material { - Some(name) => materials - .iter() - .copied() - .find(|m| m.attr("name") == Some(name)) - .ok_or_else(|| FormatError::Invalid(format!("no material named {name:?} (found: {})", names(&materials))))?, - None => materials.first().copied().ok_or_else(|| FormatError::Unsupported("the document has no surfacematerial".into()))?, - }; - let mut out = Material { name: mat.attr("name").unwrap_or("Material").to_owned(), channels: Vec::new(), uv_tiling: [1.0, 1.0], warnings: Vec::new() }; - let shader = mat - .input("surfaceshader") - .and_then(|i| i.attr("nodename")) - .and_then(|n| doc.nodes.get(n).copied()) - .ok_or_else(|| malformed(KIND, "the material has no surface shader"))?; - let (kind, table) = match shader.name.as_str() { - "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR), - "standard_surface" => (Shader::Standard, STANDARD), - "gltf_pbr" => (Shader::Gltf, GLTF), - other => return Err(FormatError::Unsupported(format!("the surface shader is a {other}; open_pbr_surface, standard_surface and gltf_pbr are read"))), - }; - // Emission is off by default in OpenPBR and standard_surface. - let emits = match kind { - Shader::OpenPbr => { - shader.input("emission_luminance").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission_luminance").is_some_and(|v| v > 0.0)) - } - Shader::Standard => shader.input("emission").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission").is_some_and(|v| v > 0.0)), - Shader::Gltf => true, - }; - let weight = match kind { - Shader::OpenPbr => literal(shader, "base_weight"), - Shader::Standard => literal(shader, "base"), - Shader::Gltf => None, - }; - if weight.is_some_and(|w| (w - 1.0).abs() > 1e-6) { - doc.warnings.push("the base weight isn't 1; it was ignored".into()); - } - for &(input, channel) in table { - let Some(el) = shader.input(input) else { continue }; - if channel == Channel::Emissive && !emits && kind != Shader::Gltf { - doc.warnings.push(format!("{input} was skipped: the shader's emission is 0")); - continue; - } - match doc.resolve(el, None, 0) { - Found::Constant(n) => out.channels.push((channel, Value::Constant(to_constant(channel, &n)))), - Found::Image(f) => out.channels.push((channel, Value::Image(f))), - Found::None => {} + let document = craft_materialx::Document::parse(bytes).map_err(map_error)?; + let shared = document.read_material(material).map_err(map_error)?; + let mut channels = Vec::new(); + for (input, value) in shared.inputs { + if let Some(channel) = channel(shared.shader, &input) { + channels.push((channel, app_value(channel, value))); } } - // The displacement shader's `displacement` input is the height. - if let Some(d) = mat.input("displacementshader").and_then(|i| i.attr("nodename")).and_then(|n| doc.nodes.get(n).copied()) - && let Some(i) = d.input("displacement") - { - match doc.resolve(i, None, 0) { - Found::Constant(n) => out.channels.push((Channel::Height, Value::Constant(to_constant(Channel::Height, &n)))), - Found::Image(f) => out.channels.push((Channel::Height, Value::Image(f))), - Found::None => {} - } + if let Some(value) = shared.displacement { + channels.push((Channel::Height, app_value(Channel::Height, value))); } - out.uv_tiling = doc.tiling.unwrap_or([1.0, 1.0]); - out.warnings = doc.warnings; - Ok(out) + Ok(Material { name: shared.name, channels, uv_tiling: shared.uv_tiling, warnings: shared.warnings }) } -fn names(materials: &[&El]) -> String { - let n: Vec<&str> = materials.iter().filter_map(|m| m.attr("name")).collect(); - if n.is_empty() { "none".into() } else { n.join(", ") } +fn map_error(error: craft_materialx::Error) -> FormatError { + use craft_materialx::Error; + match error { + Error::Xml(xml) if xml.is_limit() => FormatError::TooLarge(xml.to_string()), + Error::MissingMaterial(name) => FormatError::Invalid(format!("no material named {name:?}")), + Error::Unsupported(message) => FormatError::Unsupported(message), + Error::Malformed(message) => malformed(KIND, message), + Error::Root => malformed(KIND, "no element"), + Error::Xml(other) => malformed(KIND, other), + } } #[cfg(test)] @@ -456,6 +165,24 @@ mod tests { assert_eq!(read_materialx(extreme.as_bytes(), None).unwrap().uv_tiling, [1000.0, 0.001], "clamped like a fill's UV scale"); } + #[test] + fn nodegraph_input_without_output_uses_the_first_output() { + let xml = r#" + + + + + + + + +"#; + for _ in 0..50 { + let material = read_materialx(xml.as_bytes(), None).unwrap(); + assert_eq!(get(&material, Channel::BaseColor), Some(&Value::Image("first.png".into()))); + } + } + #[test] fn emission_is_off_unless_the_shader_emits() { let x = OPENPBR.replace(r#""#, ""); From bf25c1c5364260012c499e6b6f682c5d0eb3b739 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 06:33:26 +0000 Subject: [PATCH 047/115] Move TextureCraft STL parsing to craft-mesh --- Cargo.lock | 6 ++ Cargo.toml | 1 + crates/formats/Cargo.toml | 1 + crates/formats/src/mesh_import/stl.rs | 114 ++++++++++-------------- crates/formats/src/mesh_import/tests.rs | 17 ++++ 5 files changed, 73 insertions(+), 66 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 66ad4529..1efde862 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -828,6 +828,11 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-mesh" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89b3a8436bd0d09c3748#d6ed8c20f12188c1f39c89b3a8436bd0d09c3748" + [[package]] name = "craft-quit" version = "0.1.0" @@ -4388,6 +4393,7 @@ version = "0.6.1" dependencies = [ "base64 0.22.1", "craft-materialx", + "craft-mesh", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index 5fa07cf3..cc958885 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,6 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +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 = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 50654ab8..d78d4d7a 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-materialx = { workspace = true } +craft-mesh = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/mesh_import/stl.rs b/crates/formats/src/mesh_import/stl.rs index 9b39bf2c..fd288a27 100644 --- a/crates/formats/src/mesh_import/stl.rs +++ b/crates/formats/src/mesh_import/stl.rs @@ -1,78 +1,60 @@ -//! STL (binary and ascii). Facets keep their own corners, so shading is flat; there are no UVs. +//! STL (binary and ASCII), read by the shared bounded mesh importer. -use texturecraft_geom::glam::Vec3; +use texturecraft_geom::glam::{Vec3, Vec4}; use super::{RawMesh, check_triangles}; -use crate::{Result, malformed}; +use crate::{FormatError, Result}; const KIND: &str = "STL"; pub(crate) fn read(bytes: &[u8]) -> Result { - let count = bytes.get(80..84).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize); - let binary_len = count.and_then(|c| c.checked_mul(50)).and_then(|n| n.checked_add(84)); - let looks_ascii = bytes.iter().position(|b| !b.is_ascii_whitespace()).and_then(|i| bytes.get(i..i + 5)) == Some(b"solid".as_slice()); - let tris = match (count, binary_len) { - // Exact size wins: many binary files also start with "solid". - (Some(c), Some(len)) if len == bytes.len() => binary(bytes, c)?, - _ if looks_ascii => ascii(bytes)?, - (Some(c), Some(len)) if len < bytes.len() => binary(bytes, c)?, - _ => return Err(malformed(KIND, "neither a complete binary STL nor an ascii STL")), - }; + let scene = craft_mesh::stl::read(bytes, &craft_mesh::Limits::default()).map_err(|e| FormatError::Invalid(e.to_string()))?; let mut raw = RawMesh::default(); - check_triangles(0, tris.len())?; - let mut normals = Vec::with_capacity(tris.len() * 3); - for t in &tris { - let n = (t[1] - t[0]).cross(t[2] - t[0]).try_normalize().unwrap_or(Vec3::Y); - raw.positions.extend_from_slice(t); - normals.extend_from_slice(&[n; 3]); + raw.warnings = scene.warnings; + + let mut tri_count = 0; + let mut vertex_colors = Vec::new(); + let has_colors = !scene.materials.is_empty(); + for mesh in scene.meshes { + // The shared model groups colored facets into parts. Position indices still reflect + // source order, so merge the parts back into STL order for TextureCraft's raw mesh. + let mut triangles = Vec::new(); + for part in mesh.parts { + let material = part.material.and_then(|i| scene.materials.get(i)); + let color = material.map(|m| Vec4::from_array(m.base_color)); + for tri in part.triangles() { + let first_position = tri.iter().map(|c| c.position).min().unwrap_or(u32::MAX); + triangles.push((first_position, tri, color)); + } + } + triangles.sort_by_key(|(first_position, _, _)| *first_position); + for (_, tri, color) in triangles { + check_triangles(tri_count, 1)?; + tri_count += 1; + let mut points = [Vec3::ZERO; 3]; + for (i, corner) in tri.into_iter().enumerate() { + let p = mesh.positions.get(corner.position as usize).ok_or_else(|| FormatError::Invalid(format!("{KIND}: position index out of range")))?; + points[i] = Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32); + } + // Recompute per-facet normals as TextureCraft's old importer did; stored STL + // normals are often zero or disagree with the vertex winding. + let normal = (points[1] - points[0]).cross(points[2] - points[0]).try_normalize().unwrap_or(Vec3::Y); + raw.positions.extend_from_slice(&points); + raw.normals.get_or_insert_with(Vec::new).extend_from_slice(&[normal; 3]); + if has_colors { + // The shared reader normalizes STL's color extensions to linear RGBA. + // Uncolored facets alongside colored ones receive its neutral gray material. + let color = color.unwrap_or(Vec4::new(0.6, 0.6, 0.6, 1.0)); + vertex_colors.extend_from_slice(&[color; 3]); + } + } + } + if raw.positions.is_empty() { + return Err(crate::malformed(KIND, "no facets")); + } + if has_colors { + raw.colors = Some(vertex_colors); } - raw.normals = Some(normals); raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect())); Ok(raw) } - -fn binary(bytes: &[u8], count: usize) -> Result> { - check_triangles(0, count)?; - let mut out = Vec::with_capacity(count); - for i in 0..count { - let f = |k: usize| -> Result { - let o = 84 + i * 50 + 12 + k * 4; - let b = bytes.get(o..o + 4).ok_or_else(|| malformed(KIND, "truncated facet"))?; - Ok(f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - }; - let v = |c: usize| -> Result { Ok(Vec3::new(f(c * 3)?, f(c * 3 + 1)?, f(c * 3 + 2)?)) }; - out.push([v(0)?, v(1)?, v(2)?]); - } - Ok(out) -} - -fn ascii(bytes: &[u8]) -> Result> { - let text = std::str::from_utf8(bytes).map_err(|_| malformed(KIND, "ascii STL is not text"))?; - let mut out = Vec::new(); - let mut facet: Vec = Vec::new(); - let mut words = text.split_whitespace(); - while let Some(w) = words.next() { - match w { - "vertex" => { - let mut c = [0.0f32; 3]; - for v in &mut c { - let tok = words.next().ok_or_else(|| malformed(KIND, "truncated vertex"))?; - *v = tok.parse().map_err(|_| malformed(KIND, format!("bad number \"{tok}\"")))?; - } - facet.push(Vec3::from(c)); - } - "endfacet" => { - for i in 1..facet.len().saturating_sub(1) { - check_triangles(out.len(), 1)?; - out.push([facet[0], facet[i], facet[i + 1]]); - } - facet.clear(); - } - _ => {} - } - } - if out.is_empty() { - return Err(malformed(KIND, "no facets")); - } - Ok(out) -} diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index e55f8eae..80078488 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -372,6 +372,23 @@ fn stl_ascii_and_binary() { assert_eq!(import_mesh_bytes("c.stl", &b).unwrap().mesh.triangle_count(), 2); } +#[test] +fn stl_shared_reader_keeps_flat_normals_and_surfaces_shared_repairs_and_colors() { + let mut bytes = stl_binary(); + // VisCAM/SolidView: bit 15 marks a facet color; red occupies bits 10..14. + bytes[132..134].copy_from_slice(&0xfc00u16.to_le_bytes()); + // Some exporters leave the header count at zero despite having facets. + bytes[80..84].copy_from_slice(&0u32.to_le_bytes()); + let imported = import_mesh_bytes("colored.stl", &bytes).unwrap(); + assert_eq!(imported.mesh.triangle_count(), 2); + assert_eq!(imported.mesh.submeshes.len(), 1); + assert_eq!(imported.mesh.submeshes[0].name, "colored"); + assert_eq!(imported.mesh.positions.len(), 6); + assert_eq!(imported.mesh.normals, vec![Vec3::Z; 6]); + assert!(imported.mesh.colors.iter().any(|c| c.x > 0.99 && c.y < 0.01 && c.z < 0.01)); + assert!(imported.report.warnings.iter().any(|w| w.contains("counts no facets"))); +} + /// Every prefix and some corruptions of a valid file: errors, never panics (and never an /// error from the panic guard, which would mean a parser panicked). pub(crate) fn hammer(name: &str, good: &[u8]) { From 1bf3707aeca5a5ca902277f5dd61363811d56617 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 06:41:49 +0000 Subject: [PATCH 048/115] Cover interleaved STL color part order --- crates/formats/src/mesh_import/tests.rs | 26 ++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index 80078488..ef592129 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -377,14 +377,34 @@ fn stl_shared_reader_keeps_flat_normals_and_surfaces_shared_repairs_and_colors() let mut bytes = stl_binary(); // VisCAM/SolidView: bit 15 marks a facet color; red occupies bits 10..14. bytes[132..134].copy_from_slice(&0xfc00u16.to_le_bytes()); + // A third facet repeats that color after an uncolored facet. The shared reader groups its + // parts by color, so the adapter must restore the source facet order. + bytes.extend([0.0f32; 3].iter().flat_map(|v| v.to_le_bytes())); + for v in [[0.0f32, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]] { + bytes.extend(v.iter().flat_map(|x| x.to_le_bytes())); + } + bytes.extend(0xfc00u16.to_le_bytes()); // Some exporters leave the header count at zero despite having facets. bytes[80..84].copy_from_slice(&0u32.to_le_bytes()); let imported = import_mesh_bytes("colored.stl", &bytes).unwrap(); - assert_eq!(imported.mesh.triangle_count(), 2); + assert_eq!(imported.mesh.triangle_count(), 3); assert_eq!(imported.mesh.submeshes.len(), 1); assert_eq!(imported.mesh.submeshes[0].name, "colored"); - assert_eq!(imported.mesh.positions.len(), 6); - assert_eq!(imported.mesh.normals, vec![Vec3::Z; 6]); + assert_eq!( + imported.mesh.positions, + vec![ + Vec3::ZERO, + Vec3::X, + Vec3::new(1.0, 1.0, 0.0), + Vec3::ZERO, + Vec3::new(1.0, 1.0, 0.0), + Vec3::Y, + Vec3::Z, + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(1.0, 1.0, 1.0) + ] + ); + assert_eq!(imported.mesh.normals, vec![Vec3::Z; 9]); assert!(imported.mesh.colors.iter().any(|c| c.x > 0.99 && c.y < 0.01 && c.z < 0.01)); assert!(imported.report.warnings.iter().any(|w| w.contains("counts no facets"))); } From b982d660088b651b7568eef4a19e8d040ca0f12f Mon Sep 17 00:00:00 2001 From: Morion Tutoriales <100455929+MorionTutoriales@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:28:43 -0500 Subject: [PATCH 049/115] fix(compose): retain curvature cache layout variants (#459) --- crates/compose/src/curvature_sizes.rs | 50 +++++++++++++++++++++------ 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index d04e7f62..ab01f627 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -125,8 +125,9 @@ fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: sizes }; - // One layout per curvature map, with the most recently used map at the end - cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature))); + // Keep distinct layouts: thumbnails and the viewport alternate on the same bake. + // Replacing only this variant prevents them from repeatedly rebuilding each other. + cache.retain(|entry| entry.0.strong_count() > 0 && !is_entry_for(entry, curvature, key, scales)); let sizes = Arc::new(sizes); cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); trim_cache(&mut cache, CACHE_BYTES); @@ -338,6 +339,7 @@ mod tests { #[test] fn unused_maps_are_evicted_even_while_undo_keeps_the_sources_alive() { + let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let sources: Vec<_> = (0..=CACHE_MAPS).map(|_| Arc::new(vec![0.5; 16])).collect(); let scales = BlockScales::default(); let key = ((4, 4), (4, 4), (4, 4)); @@ -408,18 +410,46 @@ mod tests { } } + // Cache lifecycle tests must not evict each other's entries in parallel. + static CACHE_TESTS: Mutex<()> = Mutex::new(()); + #[test] - fn a_new_layout_replaces_the_sizes_of_the_old_one() { + fn alternating_layouts_reuse_their_cached_sizes() { + let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let curvature = Arc::new(vec![0.5; 16]); let scales = BlockScales::default(); - let entries_for_curvature = || { - let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count() - }; + let viewport_key = ((4, 4), (4, 4), (4, 4)); + let thumbnail_key = ((4, 4), (4, 4), (2, 2)); + let viewport = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() }); + let thumbnail = store(&curvature, thumbnail_key, &scales, CurvatureSizes { levels: Vec::new() }); - store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() }); - store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() }); - assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached"); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "a thumbnail must not evict the viewport layout"); + assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "both layouts stay reusable"); + let mut set = texturecraft_core::TextureSet::new("Tiles", 0, 4); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 2); + let scaled = set.block_scales(); + assert_ne!(scaled, scales); + assert!(cached(&curvature, viewport_key, &scaled).is_none(), "different tile scales cannot read the unscaled result"); + let scaled_sizes = store(&curvature, viewport_key, &scaled, CurvatureSizes { levels: Vec::new() }); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scaled).unwrap(), &scaled_sizes)); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "scale variants also coexist"); + let replacement = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() }); + assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &replacement)); + assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "updating one layout keeps the other"); + } + + #[test] + fn layout_variants_obey_the_entry_limit() { + let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let key = |size| ((4, 4), (4, 4), (size, size)); + for size in 1..=CACHE_MAPS as u32 + 1 { + store(&curvature, key(size), &scales, CurvatureSizes { levels: Vec::new() }); + } + assert!(cached(&curvature, key(1), &scales).is_none(), "layout variants cannot grow without bound"); + assert!(cached(&curvature, key(CACHE_MAPS as u32 + 1), &scales).is_some(), "the newest layout stays cached"); } #[test] From 73c9f8f70546064d119a6be0c973fa319d2e05ac Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:13:08 +0100 Subject: [PATCH 050/115] Bound FBX instance control-point work (#466) Co-authored-by: FredApps --- crates/formats/src/mesh_import/fbx.rs | 30 +++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 5e975ba2..22599844 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -32,6 +32,8 @@ const MIN_VERSION: i64 = 6000; const MAX_DEPTH: usize = 64; /// Memory budget for parsed nodes and properties (arrays are held as f64). const MAX_DECODED_BYTES: usize = 1 << 31; +/// Maximum control points transformed across all mesh instances in one import. +const MAX_INSTANCE_POINTS: usize = 200_000_000; /// Approximate memory charged per node and per scalar property. const NODE_COST: usize = 96; const PROP_COST: usize = 32; @@ -550,6 +552,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let base_colors = base_colors(&materials, &textures, &videos, &connections, files); let global = global_transform(root("GlobalSettings").or_else(|| objects.child("GlobalSettings"))); let mut sink = PolygonSink::default(); + let mut remaining_points = MAX_INSTANCE_POINTS; let no_slots = Vec::new(); for (geom, model) in instances { let Some(g) = geometries.get(&geom) else { continue }; @@ -564,7 +567,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } }; let names = model.as_ref().and_then(|m| slots.get(m)).unwrap_or(&no_slots); - add_geometry(&mut sink, g, global * m, names)?; + add_geometry(&mut sink, g, global * m, names, &mut remaining_points)?; } let mut raw = sink.finish(); raw.base_colors = base_colors; @@ -783,9 +786,12 @@ impl Layer<'_> { } } -fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String]) -> Result<()> { +fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String], remaining_points: &mut usize) -> Result<()> { let vertices = geometry.child("Vertices").map(Node::arr).unwrap_or_default(); check_vertices(vertices.len() / 3)?; + *remaining_points = remaining_points + .checked_sub(vertices.len() / 3) + .ok_or_else(|| FormatError::TooLarge(format!("FBX instances exceed the {MAX_INSTANCE_POINTS} control-point work limit")))?; let points: Vec = vertices.as_chunks::<3>().0.iter().map(|c| transform.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); @@ -839,3 +845,23 @@ fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: Ok(()) } + +#[cfg(test)] +mod instance_budget_tests { + use super::*; + + #[test] + fn instance_points_are_charged_before_transforming_each_copy() { + let geometry = Node { + name: "Geometry".into(), + props: vec![], + children: vec![Node { name: "Vertices".into(), props: vec![Prop::Arr(vec![0.0; 9])], children: vec![] }], + }; + let mut sink = PolygonSink::default(); + let mut remaining = 5; + add_geometry(&mut sink, &geometry, Mat4::IDENTITY, &[], &mut remaining).unwrap(); + assert_eq!(remaining, 2); + assert!(matches!(add_geometry(&mut sink, &geometry, Mat4::IDENTITY, &[], &mut remaining), Err(FormatError::TooLarge(_)))); + assert_eq!(remaining, 2); + } +} From 277bbf3cf1057b856a151741b048bc26389f584e Mon Sep 17 00:00:00 2001 From: Morion Tutoriales <100455929+MorionTutoriales@users.noreply.github.com> Date: Fri, 13 Nov 2026 05:20:01 -0500 Subject: [PATCH 051/115] Import glTF scenes that have no nodes array (#438) (#457) * Import glTF scenes that have no nodes array (#438) The gltf crate requires scene.nodes, but the glTF 2.0 schema lists no required properties for a scene. Blender writes such scenes for scenes with no exported objects, so a file whose default scene was fine failed with 'missing field nodes'. Treat a missing array as empty before the document is built. * Test GLB import with an empty scene --------- Co-authored-by: FredApps --- crates/formats/src/mesh_import/gltf.rs | 28 ++++++++++++++++- crates/formats/src/mesh_import/tests.rs | 42 +++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 21658033..136e3e0c 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -20,8 +20,34 @@ pub(crate) fn read(bytes: &[u8]) -> Result { crate::guard(KIND, || read_inner(bytes)) } +/// Loads and validates the document like `gltf::Gltf::from_slice`, except that a scene without a +/// `nodes` array is an empty scene. The `gltf` crate declares the field as required, but the +/// glTF 2.0 schema lists no required properties for a scene, and exporters write such scenes +/// for scenes that contain no objects. +fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { + let (json, blob) = if bytes.starts_with(b"glTF") { + let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?; + let blob = glb.bin.take().map(std::borrow::Cow::into_owned); + (glb.json.into_owned(), blob) + } else { + (bytes.to_vec(), None) + }; + let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?; + if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) { + for scene in scenes { + if let Some(scene) = scene.as_object_mut() { + scene.entry("nodes").or_insert_with(|| serde_json::Value::Array(Vec::new())); + } + } + } + let json = serde_json::to_vec(&value).map_err(|e| malformed(KIND, e))?; + let root = gltf::json::Root::from_slice(&json).map_err(|e| malformed(KIND, e))?; + let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?; + Ok((document, blob)) +} + fn read_inner(bytes: &[u8]) -> Result { - let gltf::Gltf { document, blob } = gltf::Gltf::from_slice(bytes).map_err(|e| malformed(KIND, e))?; + let (document, blob) = parse(bytes)?; check_buffer_uris(&document)?; let buffers = gltf::import_buffers(&document, None, blob).map_err(|e| match e { gltf::Error::ExternalReferenceInSliceImport => FormatError::Unsupported( diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index e55f8eae..a78e5742 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -118,6 +118,48 @@ fn glb_two_materials_mirrored_node() { m.validate().unwrap(); } +/// A scene without a `nodes` array is legal glTF (Blender writes one for a scene with no exported +/// objects); it must not stop the default scene from importing. +#[test] +fn gltf_scene_without_nodes_imports_the_default_scene() { + let mut json: serde_json::Value = serde_json::from_slice(&embedded_gltf()).unwrap(); + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }, { "nodes": [0] }]); + json["scene"] = 1.into(); + let im = import_mesh_bytes("scene.gltf", &serde_json::to_vec(&json).unwrap()).unwrap(); + assert_eq!(im.report.triangles, 2); + // Only an empty scene: nothing to import, but a clear error rather than a parse failure. + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }]); + json["scene"] = 0.into(); + let err = import_mesh_bytes("scene.gltf", &serde_json::to_vec(&json).unwrap()).unwrap_err(); + assert!(!err.to_string().contains("missing field"), "{err}"); +} + +#[test] +fn glb_scene_without_nodes_keeps_binary_mesh_in_default_scene() { + let original = glb(true, true); + let jlen = u32::from_le_bytes(original[12..16].try_into().unwrap()) as usize; + let mut json: serde_json::Value = serde_json::from_slice(&original[20..20 + jlen]).unwrap(); + json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }, { "nodes": [0] }]); + json["scene"] = 1.into(); + let mut js = serde_json::to_vec(&json).unwrap(); + while !js.len().is_multiple_of(4) { + js.push(b' '); + } + let bin_chunk = &original[20 + jlen..]; + let mut glb = Vec::new(); + glb.extend(b"glTF"); + glb.extend(2u32.to_le_bytes()); + glb.extend(((20 + js.len() + bin_chunk.len()) as u32).to_le_bytes()); + glb.extend((js.len() as u32).to_le_bytes()); + glb.extend(b"JSON"); + glb.extend(js); + glb.extend(bin_chunk); + let im = import_mesh_bytes("scene.glb", &glb).unwrap(); + assert_eq!(im.report.triangles, 2); + assert_eq!(im.mesh.materials, ["Red", "Material_1"]); + assert_outward(&im.mesh); +} + #[test] fn gltf_embedded_buffers_and_missing_attributes() { let im = import_mesh_bytes("scene.gltf", &embedded_gltf()).unwrap(); From 9f4ef44bd883d17c6f205f75c0d8c7050b6d6429 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:41:00 +0100 Subject: [PATCH 052/115] Decode half-float Alembic properties (#467) Co-authored-by: FredApps --- crates/formats/src/mesh_import/abc/mod.rs | 3 +- crates/formats/src/mesh_import/abc/tests.rs | 32 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/abc/mod.rs b/crates/formats/src/mesh_import/abc/mod.rs index fd9a7f46..5a19982c 100644 --- a/crates/formats/src/mesh_import/abc/mod.rs +++ b/crates/formats/src/mesh_import/abc/mod.rs @@ -217,7 +217,7 @@ impl<'a> Ogawa<'a> { let value_bytes = match property.pod { 0..=2 => 1, - 3 | 4 => 2, + 3 | 4 | 9 => 2, 5 | 6 | 10 => 4, 7 | 8 | 11 => 8, other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))), @@ -233,6 +233,7 @@ impl<'a> Ogawa<'a> { 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(), 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + 9 => raw.as_chunks::<2>().0.iter().map(|c| half::f16::from_bits(u16::from_le_bytes(*c)).to_f64()).collect(), 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), }) diff --git a/crates/formats/src/mesh_import/abc/tests.rs b/crates/formats/src/mesh_import/abc/tests.rs index dfba3ba9..fecb0623 100644 --- a/crates/formats/src/mesh_import/abc/tests.rs +++ b/crates/formats/src/mesh_import/abc/tests.rs @@ -243,6 +243,38 @@ fn strip_alone_keeps_uvs_flipped_to_v_down() { } } +#[test] +fn half_float_uvs_import_without_losing_values() { + let mut a = Abc { w: Writer::new() }; + let pp = a.array("P", "", F32, 3, &f32s(&[0.0, 0.0, 0.0, 0.5, 1.0, 0.0, 1.0, 0.0, 0.0])); + let fi = a.array(".faceIndices", "", I32, 1, &i32s(&[0, 1, 2])); + let fc = a.array(".faceCounts", "", I32, 1, &i32s(&[3])); + let uv_bytes: Vec = [0u16, 0, 0x3800, 0x3c00, 0x3c00, 0].iter().flat_map(|x| x.to_le_bytes()).collect(); + let uv = a.array("uv", "", 9, 2, &uv_bytes); + let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc, uv]); + let mesh = a.object(vec![geom], &[]); + let top = a.object(vec![], &[("m", "", mesh)]); + let imported = crate::import_mesh_bytes("m.abc", &a.archive(top, &["schema=AbcGeom_PolyMesh_v1"])).unwrap(); + assert!(!imported.report.uvs_generated); + for (p, uv) in imported.mesh.positions.iter().zip(&imported.mesh.uvs) { + assert_eq!(*uv, texturecraft_geom::glam::Vec2::new(p.x, 1.0 - p.y)); + } +} + +#[test] +fn half_float_values_preserve_special_values() { + let mut a = Abc { w: Writer::new() }; + let raw: Vec = [0xc000u16, 0x0001, 0x7c00, 0x7e00].iter().flat_map(|x| x.to_le_bytes()).collect(); + let p = a.array("values", "", 9, 1, &raw); + let property = Prop { name: p.name.into(), meta: p.meta, kind: PropKind::Array, pod: 9, extent: 1, group: p.group }; + let mut ogawa = Ogawa { b: &a.w.b, budget: MAX_DECODED_BYTES, indexed_meta: Vec::new() }; + let values = ogawa.values(&property).unwrap(); + assert_eq!(values[0], -2.0); + assert_eq!(values[1], 2f64.powi(-24)); + assert_eq!(values[2], f64::INFINITY); + assert!(values[3].is_nan()); +} + #[test] fn hdf5_and_garbage_are_clear_errors() { let e = read(b"\x89HDF\r\n\x1a\n rest of an hdf5 file").err().unwrap().to_string(); From fe6ede90be015606d7d7c35664486ad5c446a6e6 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:59:42 +0100 Subject: [PATCH 053/115] Ignore repeated FBX geometry connections (#468) Co-authored-by: FredApps --- crates/formats/src/mesh_import/fbx.rs | 3 +++ crates/formats/src/mesh_import/scene_tests.rs | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 22599844..86eaa52e 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -544,6 +544,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { attribute_of.insert(parent, *a); } } + // Repeated connections describe the same instance; keep distinct model placements in order. + let mut seen_instances = HashSet::new(); + instances.retain(|instance| seen_instances.insert(instance.clone())); let placed: HashSet<&String> = instances.iter().map(|(g, _)| g).collect(); let mut unplaced: Vec = geometries.keys().filter(|g| !placed.contains(g)).cloned().collect(); unplaced.sort_unstable(); diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 09515423..a5a86c4f 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -415,6 +415,24 @@ fn fbx_ascii_and_z_up() { check_fbx_scene(&import_mesh_bytes("z.fbx", &binary_fbx(&scene(true), 7700, true)).unwrap().mesh, true); } +#[test] +fn fbx_duplicate_geometry_connections_do_not_duplicate_instances() { + let mut nodes = scene(false); + let connections = nodes.iter_mut().find(|node| node.name == "Connections").unwrap(); + for _ in 0..50 { + connections.children.push(n("C", vec![P::S("OO"), P::L(10), P::L(21)], vec![])); + } + let imported = import_mesh_bytes("scene.fbx", ascii_fbx(&nodes).as_bytes()).unwrap(); + assert_eq!(imported.report.triangles, 3); + + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + objects.children.push(n("Model", vec![P::L(22), P::S("Other\u{0}\u{1}Model"), P::S("Mesh")], vec![])); + let connections = nodes.iter_mut().find(|node| node.name == "Connections").unwrap(); + connections.children.push(n("C", vec![P::S("OO"), P::L(10), P::L(22)], vec![])); + let imported = import_mesh_bytes("scene.fbx", ascii_fbx(&nodes).as_bytes()).unwrap(); + assert_eq!(imported.report.triangles, 6, "a different model must remain a distinct instance"); +} + /// The scene of [`scene`] (Y up) as FBX 6.1 writes it: geometry inside the Model, objects named /// `Class::Name`, `Properties60`, `Connect` records, GlobalSettings inside Objects. const FBX61: &str = r#"; FBX 6.1.0 project file From 8e83ac66f10c5efca9d986b77f6254d4a2c00c7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Mittelst=C3=A4dt?= <62167861+TheGalitube@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:09:02 +0100 Subject: [PATCH 054/115] Cap FBX cameras during import (#450) Fixes #445 Co-authored-by: GPT-6-Luna Co-authored-by: FredApps --- crates/formats/src/mesh_import/fbx.rs | 3 +++ crates/formats/src/mesh_import/scene_tests.rs | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 86eaa52e..0d61ce67 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -576,6 +576,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { raw.base_colors = base_colors; // In file order; FBX 6's built-in "Producer" views are not the scene's cameras. for o in objects.children.iter().filter(|o| o.name == "Model" && o.class() == "Camera" && !o.object_name().starts_with("Producer ")) { + if raw.cameras.len() >= super::MAX_CAMERAS { + break; + } let Some(id) = o.id_at(0) else { continue }; if let Ok(m) = world(&models, &parents, &id) { raw.cameras.push(camera(o, attribute_of.get(&id).copied().unwrap_or(o), global * m)); diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index a5a86c4f..00a97922 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -299,6 +299,18 @@ fn fbx_binary_32_and_64_bit_compressed_or_not() { } /// [`scene`] with a diffuse color on Red and an embedded diffuse texture on Blue. +#[test] +fn fbx_camera_models_are_capped_during_import() { + let mut nodes = scene(false); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + for id in 100..199 { + objects.children.push(n("Model", vec![P::L(id), P::S("Camera\\u{0}\\u{1}Model"), P::S("Camera")], vec![])); + } + + let raw = fbx::read(&binary_fbx(&nodes, 7500, true)).unwrap(); + assert_eq!(raw.cameras.len(), MAX_CAMERAS); +} + fn textured_scene(png: &[u8]) -> Vec { let mut nodes = scene(false); let objects = nodes.iter_mut().find(|n| n.name == "Objects").unwrap(); From afc1ee169b7f40c49a670448157d8d1f21f4ba28 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:52:34 +0100 Subject: [PATCH 055/115] Preserve invalid ASCII FBX array values (#469) Co-authored-by: FredApps --- crates/formats/src/mesh_import/fbx.rs | 87 ++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 0d61ce67..08087283 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -130,14 +130,15 @@ impl Node { if let Some(a) = self.child("a") { return a.arr(); } - Cow::Owned(self.props.iter().filter_map(Prop::num).collect()) + Cow::Owned(self.props.iter().map(|p| p.num().unwrap_or(f64::NAN)).collect()) } /// The numbers of entry `name` in Properties70 (`P: name, type, subtype, flags, values`) or /// Properties60 (`Property: name, type, flags, values`). fn property(&self, name: &str) -> Option> { let list = self.child("Properties70").or_else(|| self.child("Properties60"))?; - list.children.iter().find(|p| p.str_at(0) == name).map(|p| p.props.iter().filter_map(Prop::num).collect()) + let first_value = if list.name == "Properties70" { 4 } else { 3 }; + list.children.iter().find(|p| p.str_at(0) == name).map(|p| p.props.iter().skip(first_value).map(|v| v.num().unwrap_or(f64::NAN)).collect()) } fn vec3(&self, name: &str, default: Vec3) -> Vec3 { @@ -803,6 +804,14 @@ fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex"); let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", ""); + if vertices.iter().chain(polygon_indices.iter()).any(|v| !v.is_finite()) + || [&normals, &uvs, &materials] + .into_iter() + .flatten() + .any(|layer| layer.data.iter().any(|v| !v.is_finite()) || layer.index.as_ref().is_some_and(|index| index.iter().any(|v| !v.is_finite()))) + { + return Err(malformed(KIND, "mesh array contains a non-numeric or non-finite value")); + } let normal_transform = Mat3::from_mat4(transform).inverse().transpose(); let flip = transform.determinant() < 0.0; let (mut corners, mut polygon_index, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); @@ -856,6 +865,80 @@ fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: mod instance_budget_tests { use super::*; + #[test] + fn ascii_array_keeps_invalid_values_in_place() { + let (nodes, _) = parse_ascii( + br#"FBXHeaderExtension: { FBXVersion: 7400 } +Vertices: 1, 1.#INF, 3, "x", 5 +"#, + ) + .unwrap(); + let values = nodes[1].arr(); + assert_eq!(values.len(), 5); + assert!(values[1].is_nan() && values[3].is_nan()); + assert_eq!((values[0], values[2], values[4]), (1.0, 3.0, 5.0)); + } + + #[test] + fn ascii_bad_vertex_is_rejected() { + let (nodes, _) = parse_ascii( + br#"FBXHeaderExtension: { FBXVersion: 7400 } +Geometry: { Vertices: 0, 0, 0, 1, -1.#IND, 0, 0, 1, 0 +PolygonVertexIndex: 0, 1, -3 } +"#, + ) + .unwrap(); + let mut remaining = usize::MAX; + let result = add_geometry(&mut PolygonSink::default(), &nodes[1], Mat4::IDENTITY, &[], &mut remaining); + assert!(result.is_err()); + } + + #[test] + fn ascii_bad_index_and_uv_are_rejected() { + for payload in [ + "PolygonVertexIndex: 0, oops, -3", + "PolygonVertexIndex: 0, 1, -3\nLayerElementUV: 0 { MappingInformationType: \"ByPolygonVertex\"\nReferenceInformationType: \"Direct\"\nUV: 0, 0, oops, 1, 1, 0 }", + ] { + let source = format!("FBXHeaderExtension: {{ FBXVersion: 7400 }}\nGeometry: {{ Vertices: 0, 0, 0, 1, 0, 0, 0, 1, 0\n{payload} }}"); + let (nodes, _) = parse_ascii(source.as_bytes()).unwrap(); + let mut remaining = usize::MAX; + assert!(add_geometry(&mut PolygonSink::default(), &nodes[1], Mat4::IDENTITY, &[], &mut remaining).is_err()); + } + } + + #[test] + fn ascii_transform_metadata_does_not_shift_values() { + let (nodes, _) = parse_ascii( + br#"FBXHeaderExtension: { FBXVersion: 7400 } +Model: { Properties70: { P: "Lcl Translation", "Lcl Translation", "", "A", 1, 2, 3 } } +"#, + ) + .unwrap(); + assert_eq!(nodes[1].property("Lcl Translation"), Some(vec![1.0, 2.0, 3.0])); + let (nodes, _) = parse_ascii( + br#"FBXHeaderExtension: { FBXVersion: 7400 } +Model: { Properties60: { Property: "Lcl Translation", "Lcl Translation", "A", 1, 2, 3 } } +"#, + ) + .unwrap(); + assert_eq!(nodes[1].property("Lcl Translation"), Some(vec![1.0, 2.0, 3.0])); + } + + #[test] + fn malformed_transform_value_keeps_its_position_in_both_property_formats() { + for (list, entry) in [ + ("Properties70", "P: \"Lcl Translation\", \"Lcl Translation\", \"\", \"A\", 1, oops, 3"), + ("Properties60", "Property: \"Lcl Translation\", \"Lcl Translation\", \"A\", 1, oops, 3"), + ] { + let source = format!("FBXHeaderExtension: {{ FBXVersion: 7400 }}\nModel: {{ {list}: {{ {entry} }} }}"); + let (nodes, _) = parse_ascii(source.as_bytes()).unwrap(); + let values = nodes[1].property("Lcl Translation").unwrap(); + assert_eq!(values.len(), 3); + assert_eq!((values[0], values[2]), (1.0, 3.0)); + assert!(values[1].is_nan()); + } + } + #[test] fn instance_points_are_charged_before_transforming_each_copy() { let geometry = Node { From 386630ee85cb22679295b24013575d1aecb39ad2 Mon Sep 17 00:00:00 2001 From: Prajwal Raj Date: Fri, 13 Nov 2026 17:28:42 +0530 Subject: [PATCH 056/115] Stop reading Alembic indexed metadata after 255 entries (#464) * fix(formats): stop reading Alembic indexed metadata after 255 entries (#447) Objects and properties refer to indexed metadata with one byte, and 0xff already means the metadata is stored inline, so only entries 0 to 254 can ever be used. The reader kept every entry, so a block of zero bytes cost a whole String in memory for each byte of file. It now stops once 255 entries are held. * test(formats): verify indexed metadata during archive import (#447) --- crates/formats/src/mesh_import/abc/mod.rs | 23 +++++++++++++----- crates/formats/src/mesh_import/abc/tests.rs | 26 +++++++++++++++++++++ 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/crates/formats/src/mesh_import/abc/mod.rs b/crates/formats/src/mesh_import/abc/mod.rs index 5a19982c..b0a0ef22 100644 --- a/crates/formats/src/mesh_import/abc/mod.rs +++ b/crates/formats/src/mesh_import/abc/mod.rs @@ -281,19 +281,30 @@ fn read_inner(bytes: &[u8]) -> Result { if root.len() < 6 || !(0..6).all(|i| is_data(i) != (i == 2)) { return Err(malformed(KIND, "the archive group does not have the Alembic layout")); } - // Indexed metadata: a u8 length before each string. let block = o.data(root[5])?; - let mut c = Cursor { b: block, pos: 0 }; - while c.pos < block.len() { - let n = c.u8()? as usize; - o.indexed_meta.push(c.string(n)?); - } + read_indexed_meta(block, &mut o.indexed_meta)?; let mut sink = PolygonSink::default(); let mut walk = Walk { o, sink: &mut sink, visits: 0 }; walk.object(root[2], Mat4::IDENTITY, "", 0)?; Ok(sink.finish()) } +/// The most indexed metadata entries that can ever be used: objects and properties refer to one +/// with a single byte, and 0xff already means "stored inline", so only 0 to 254 are reachable. +const MAX_INDEXED_META: usize = 255; + +/// Indexed metadata: a u8 length before each string. `out` starts with the empty entry 0. Reading +/// stops once `out` holds [`MAX_INDEXED_META`] entries, because no later entry can be referred to +/// and an empty one costs a whole `String` in memory for one byte of file. +fn read_indexed_meta(block: &[u8], out: &mut Vec) -> Result<()> { + let mut c = Cursor { b: block, pos: 0 }; + while c.pos < block.len() && out.len() < MAX_INDEXED_META { + let n = c.u8()? as usize; + out.push(c.string(n)?); + } + Ok(()) +} + struct Walk<'a, 'b> { o: Ogawa<'a>, sink: &'b mut PolygonSink, diff --git a/crates/formats/src/mesh_import/abc/tests.rs b/crates/formats/src/mesh_import/abc/tests.rs index fecb0623..92f18620 100644 --- a/crates/formats/src/mesh_import/abc/tests.rs +++ b/crates/formats/src/mesh_import/abc/tests.rs @@ -323,3 +323,29 @@ fn self_referencing_groups_are_bounded() { let bytes = a.archive(at, &[]); assert!(read(&bytes).is_err()); } + +#[test] +fn indexed_metadata_stops_at_the_entries_a_byte_can_index() { + // One real entry followed by a million empty ones: a byte each in the file, a `String` each + // in memory, and no index past 254 can be used anyway. + let mut block = vec![3, b'a', b'b', b'c']; + block.extend(std::iter::repeat_n(0u8, 1_000_000)); + let mut kept = vec![String::new()]; + read_indexed_meta(&block, &mut kept).unwrap(); + assert_eq!(kept.len(), MAX_INDEXED_META); + assert_eq!(kept.get(1).map(String::as_str), Some("abc")); + + // The mesh schema comes from metadata index 1 even when the table has unreachable entries. + let mut a = Abc { w: Writer::new() }; + let pp = a.array("P", "", F32, 3, &f32s(&[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0])); + let fi = a.array(".faceIndices", "", I32, 1, &i32s(&[0, 1, 2])); + let fc = a.array(".faceCounts", "", I32, 1, &i32s(&[3])); + let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc]); + let mesh = a.object(vec![geom], &[]); + let top = a.object(vec![], &[("tri", "", mesh)]); + let mut metas = vec!["schema=AbcGeom_PolyMesh_v1"]; + metas.extend(std::iter::repeat_n("", 5_000)); + let raw = read(&a.archive(top, &metas)).unwrap(); + assert_eq!(raw.positions, [Vec3::X, Vec3::Y, Vec3::ZERO]); + assert_eq!(raw.groups, vec![(DEFAULT_MATERIAL.into(), "tri".into(), vec![0, 1, 2])]); +} From a616e5ed06d6235e9a9030e20ce65aa1a91f221e Mon Sep 17 00:00:00 2001 From: Morion Date: Fri, 13 Nov 2026 08:53:59 -0500 Subject: [PATCH 057/115] experiment: scope invalidation of newly added material resources --- crates/engine/examples/material_probe.rs | 55 ++++++++++++++++++++++++ crates/engine/src/session.rs | 25 +++++++++-- 2 files changed, 77 insertions(+), 3 deletions(-) create mode 100644 crates/engine/examples/material_probe.rs diff --git a/crates/engine/examples/material_probe.rs b/crates/engine/examples/material_probe.rs new file mode 100644 index 00000000..0179b8d2 --- /dev/null +++ b/crates/engine/examples/material_probe.rs @@ -0,0 +1,55 @@ +use serde_json::json; +use std::{ + hash::{DefaultHasher, Hash, Hasher}, + time::Instant, +}; +use texturecraft_engine::{ + Session, + compose::{DisplayKind, tile_bytes}, + core::LayerId, + execute, file_cmds, + geom::primitives, +}; +fn drain(s: &mut Session, label: &str) { + let dirty: Vec<_> = s.caches.iter().map(|c| c.dirty.len()).collect(); + let t = Instant::now(); + let mut peak = 0f64; + let mut slices = 0; + while s.pending_tiles() > 0 { + let a = Instant::now(); + s.update_for(30., || t.elapsed().as_secs_f64() * 1000.); + peak = peak.max(a.elapsed().as_secs_f64() * 1000.); + slices += 1; + } + println!("{} dirty={:?} compose_ms={:.1} max_slice_ms={:.1} slices={}", label, dirty, t.elapsed().as_secs_f64() * 1000., peak, slices); +} +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let mut donor = Session::new_project("probe", primitives::plane(2., 1), "builtin:plane", None, 128)?; + donor.import_resource_bytes("unique-material-probe.png", std::fs::read(&args[2])?)?; + let layer = execute(&mut donor, "layer.add.image", &json!({"name":"unique-material-probe.png"}))?; + let bytes = donor.smart_material_bytes(LayerId(layer["layer"].as_u64().unwrap()), "Image material")?; + let t = Instant::now(); + let mut s = file_cmds::open_path(&args[1])?; + println!("load_ms={:.1}", t.elapsed().as_secs_f64() * 1000.); + drain(&mut s, "open"); + execute(&mut s, "layer.select", &json!({"layer":10}))?; + execute(&mut s, "material.apply", &json!({"material":"gold_polished"}))?; + drain(&mut s, "simple"); + let t = Instant::now(); + s.add_smart_material_bytes(&bytes)?; + println!("apply_ms={:.1}", t.elapsed().as_secs_f64() * 1000.); + drain(&mut s, "smart"); + let mut hash = DefaultHasher::new(); + for (i, c) in s.caches.iter().enumerate() { + let empty = Default::default(); + let baked = s.doc.baked.get(&i).unwrap_or(&empty); + for (x, y) in texturecraft_engine::compose::all_tiles(c.size.0, c.size.1) { + for k in DisplayKind::ALL { + tile_bytes(&c.composite, baked, k, x, y).hash(&mut hash); + } + } + } + println!("display_hash={:x}", hash.finish()); + Ok(()) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 9d58670b..695bfab4 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -576,15 +576,34 @@ impl Session { pub(crate) fn invalidate_changed(&mut self, other: &Document) { self.follow_uv_layouts(&other.project); self.sync_caches(); - let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::>(); - let all = resources(other) != resources(&self.doc); + // Retain broad invalidation on removal or replacement. A newly added resource + // can also satisfy an existing, previously unresolved image reference. + let all = other.resources.iter().any(|(name, old)| !self.doc.resources.get(name).is_some_and(|new| Arc::ptr_eq(old, new))); + let added: BTreeSet<_> = self.doc.resources.keys().filter(|name| !other.resources.contains_key(*name)).collect(); + let uses_added = |ts: usize| { + use texturecraft_core::{EffectKind, Fill, Source}; + let uses_source = |src: &Source| matches!(src, Source::Image { name, .. } if added.contains(name)); + let uses_fill = |f: &Fill| f.sources.values().any(uses_source) || f.link.as_ref().is_some_and(|l| added.contains(&l.package)); + let project = &self.doc.project; + !added.is_empty() + && project.texture_sets.get(ts).is_some_and(|set| { + project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { + matches!(&layer.kind, LayerKind::Fill(f) if uses_fill(f)) + || layer.mask.iter().flat_map(|m| &m.effects).chain(&layer.content_effects).any(|e| match &e.kind { + EffectKind::Fill { source, .. } => uses_source(source), + EffectKind::Material(f) => uses_fill(f), + _ => false, + }) + }) + }) + }; let (empty, images) = (BakedMaps::default(), Default::default()); let key = |d: &Document, ts: usize| { let stack = d.project.texture_sets.get(ts).map(|s| s.stack.as_slice()).unwrap_or_default(); StackKey::new(&d.project, &d.pixels, d.baked.get(&ts).unwrap_or(&empty), &images, ts, stack) }; for ts in 0..self.caches.len() { - if (all || key(other, ts) != key(&self.doc, ts)) + if (all || key(other, ts) != key(&self.doc, ts) || uses_added(ts)) && let Some(c) = self.caches.get_mut(ts) { c.invalidate_all(); From d5675e090b176aad1347767c5c52a31fd2e54016 Mon Sep 17 00:00:00 2001 From: Morion Date: Fri, 13 Nov 2026 09:38:39 -0500 Subject: [PATCH 058/115] Keep cached layer composites across unrelated image imports --- crates/compose/src/below.rs | 41 +++++++++++++++--- crates/compose/tests/cache_and_instances.rs | 48 +++++++++++++++++++++ 2 files changed, 84 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cf675d4f..ec597eb4 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -10,11 +10,11 @@ use std::collections::{BTreeSet, HashMap, VecDeque}; use std::sync::Arc; use texturecraft_core::project::MAX_DEPTH; -use texturecraft_core::{BakedMap, Channel, Layer, LayerId, LayerKind, Project, TextureSet}; +use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet}; use texturecraft_texel::TileImage; use crate::eval::{Inputs, PaintTarget}; -use crate::store::{BakedMaps, ImageStore, PixelStore}; +use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore}; /// Default byte budget of a [`BelowCache`], per nesting level it holds (see /// [`BelowCache::limit`]). @@ -78,7 +78,7 @@ pub struct StackKey { layers: Vec, pixels: Vec<(LayerId, Option, Shared)>, baked: (u32, Vec<(BakedMap, usize)>), - images: Vec<(String, usize)>, + images: Vec<(String, ImageIdentity)>, } impl StackKey { @@ -111,8 +111,29 @@ impl StackKey { layer.chain(pixels.masks.get(id).map(|img| (*id, None, Shared(img.clone())))) }) .collect(); - let mut images: Vec<(String, usize)> = images.iter().map(|(n, i)| (n.clone(), Arc::as_ptr(i) as usize)).collect(); - images.sort(); + let mut names = BTreeSet::new(); + if !images.is_empty() { + let mut record = |source: &Source| { + if let Source::Image { name, .. } = source + && let Some((name, _)) = images.get_key_value(name) + { + names.insert(name); + } + }; + for layer in tree.iter().filter_map(|id| project.layers.get(id)) { + if let LayerKind::Fill(fill) = &layer.kind { + fill.sources.values().for_each(&mut record); + } + for effect in layer.mask.iter().flat_map(|m| &m.effects).chain(&layer.content_effects) { + match &effect.kind { + EffectKind::Fill { source, .. } => record(source), + EffectKind::Material(fill) => fill.sources.values().for_each(&mut record), + _ => {} + } + } + } + } + let images = names.into_iter().map(|name| (name.clone(), ImageIdentity(Arc::downgrade(&images[name])))).collect(); Some(StackKey { set, roots, @@ -124,6 +145,16 @@ impl StackKey { } } +// Keep the allocation identity stable even when an image is removed between composites. +#[derive(Debug)] +struct ImageIdentity(std::sync::Weak); + +impl PartialEq for ImageIdentity { + fn eq(&self, other: &Self) -> bool { + self.0.ptr_eq(&other.0) + } +} + /// An image compared by tile identity: holding the clone keeps its tiles alive, and a tile /// rewritten since is a different allocation (copy-on-write), so pointer equality means the /// same pixels without reading them. diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index d7df0258..02009a06 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -573,3 +573,51 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { assert!(!check_cached(&f, 0, hot).is_empty()); } } + +#[test] +fn image_dependency_probe() { + use std::sync::Arc; + use std::time::Instant; + use texturecraft_compose::{ImageRes, ImageStore}; + + let mut f = fixture(); + let hot = heavy_stack(&mut f); + let bottom = f.project.texture_sets[0].stack[0]; + let LayerKind::Fill(fill) = &mut f.project.layer_mut(bottom).unwrap().kind else { panic!("expected fill") }; + fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() }); + let image = |value| Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[value; 4]], srgb: false }); + let mut images = ImageStore::default(); + let baked = Default::default(); + let tiles = all_tiles(RES, RES); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot)); + let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), RES); + for stage in ["cold", "resolve", "unused1", "unused2", "unused3", "replace", "remove"] { + match stage { + "resolve" => { + images.insert("used".into(), image(1.0)); + } + "replace" => { + images.insert("used".into(), image(0.4)); + } + "remove" => { + images.remove("used"); + } + "cold" => {} + _ => { + images.insert(stage.into(), image(0.5)); + } + } + f.pixels.layer_mut(hot, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); + let inp = inputs(&f, 0, &images, &baked); + let start = Instant::now(); + composite_tiles_cached(&inp, &mut out, &tiles[..1], Some(&mut cache)); + let retained = cache.len() - 1; + composite_tiles_cached(&inp, &mut out, &tiles[1..], Some(&mut cache)); + println!("{stage}: {:?}, retained other tiles {retained}", start.elapsed()); + assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}"); + let mut expected = Composite::new(&f.project.texture_sets[0].channel_list(), RES); + composite_tiles(&inp, &mut expected, &tiles); + assert!(out == expected, "{stage}"); + } +} From 1a742d3fa4105c3da1f956811b671cbc1fc23e48 Mon Sep 17 00:00:00 2001 From: Morion Date: Fri, 13 Nov 2026 12:38:58 -0500 Subject: [PATCH 059/115] Frame-sliced recomposites filter a run of tiles once (#475) A stack with a neighbourhood filter (blur, high pass, bevel, glow...) made a recomposite spread over frames many times slower than the same recomposite in one call: every chunk filtered its own surroundings again, and on a machine with many threads the filter's per-texel parallel steps cost more to hand out than to run on a region of a few tiles. - Neighbourhood filters split their per-texel work into tasks of at least 16384 texels. Each texel is computed on its own, so results do not change. - Session::update_for tells the compositor which dirty tiles follow the chunk in its block (up to 64). The compositor filters the chunk and those tiles at once and keeps the fields for the composites that follow, compared by everything the stack reads, and drops them at the end of the pass, after an edit, and under a live stroke. Results are identical to the one-call composite: tests cover cold, warm and partly evicted hot-layer caches, an edit mid-pass and a live stroke. perf::bench_sliced_filters_4k times both paths. --- crates/compose/src/below.rs | 47 ++++++- crates/compose/src/eval.rs | 113 +++++++++++++---- crates/compose/src/lib.rs | 4 +- crates/compose/tests/cache_and_instances.rs | 133 ++++++++++++++++++++ crates/engine/src/session.rs | 15 +++ crates/engine/tests/it/perf.rs | 38 ++++++ 6 files changed, 324 insertions(+), 26 deletions(-) diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cf675d4f..25d086e9 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -13,7 +13,7 @@ use texturecraft_core::project::MAX_DEPTH; use texturecraft_core::{BakedMap, Channel, Layer, LayerId, LayerKind, Project, TextureSet}; use texturecraft_texel::TileImage; -use crate::eval::{Inputs, PaintTarget}; +use crate::eval::{Fields, Inputs, PaintTarget}; use crate::store::{BakedMaps, ImageStore, PixelStore}; /// Default byte budget of a [`BelowCache`], per nesting level it holds (see @@ -40,11 +40,47 @@ pub struct BelowCache { /// Tiles of the whole pass a caller splits into several composites (0: each composite is a /// pass). A pass larger than the cache records only what fits. pub pass: usize, + /// Tiles the caller composites next in this pass, after those of the coming composite (empty: none, or a pass that is one + /// composite). A stack with neighbourhood filters then filters the coming tiles and these at once and keeps the result for + /// the composites that follow, instead of filtering each small chunk's surroundings again. + pub ahead: Vec<(u32, u32)>, + pub(crate) held: Option, +} + +/// Neighbourhood-filter fields kept between the composites of one pass. +pub(crate) struct HeldFields { + /// Everything the fields read. + pub key: Arc, + /// The working size they were built at. + pub size: (u32, u32), + /// The tiles every layer's fields hold. + pub stack_tiles: BTreeSet<(u32, u32)>, + /// The tiles the hot layer's fields hold (the same tiles when the stack was not split). + pub hot_tiles: BTreeSet<(u32, u32)>, + pub fields: Arc, +} + +impl std::fmt::Debug for HeldFields { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HeldFields").field("stack_tiles", &self.stack_tiles.len()).field("hot_tiles", &self.hot_tiles.len()).finish_non_exhaustive() + } } impl Default for BelowCache { fn default() -> Self { - BelowCache { hot: None, key: None, tiles: HashMap::new(), order: VecDeque::new(), clock: 0, bytes: 0, budget: BELOW_BUDGET, levels: 1, pass: 0 } + BelowCache { + hot: None, + key: None, + tiles: HashMap::new(), + order: VecDeque::new(), + clock: 0, + bytes: 0, + budget: BELOW_BUDGET, + levels: 1, + pass: 0, + ahead: Vec::new(), + held: None, + } } } @@ -184,12 +220,19 @@ impl BelowCache { self.order.clear(); self.bytes = 0; self.key = None; + // Held fields tell the hot layer's tiles from the others' + self.held = None; } pub fn bytes(&self) -> usize { self.bytes } + /// Whether neighbourhood-filter fields are kept for the composites that follow (see [`BelowCache::ahead`]). + pub fn holds_fields(&self) -> bool { + self.held.is_some() + } + /// The byte limit: the budget for the top level and as much again for a hot layer nested in /// folders (each tile then holds the stack at two or more levels). pub fn limit(&self) -> usize { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index fe0bdb23..0815124d 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -18,7 +18,7 @@ use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; -use crate::below::{Band, BelowCache, Level}; +use crate::below::{Band, BelowCache, HeldFields, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; @@ -434,15 +434,27 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; +/// Texels one parallel task of a neighbourhood filter handles at least. Compositing in frame slices filters regions of a few tiles: split per texel, +/// handing that little work to every thread costs far more than the work itself. Each texel is computed on its own, so the split does not change results. +const MIN_PARALLEL_TEXELS: usize = 1 << 14; + +/// How many lines of `length` texels make a parallel task of at least [`MIN_PARALLEL_TEXELS`]. +fn lines_per_task(length: usize) -> usize { + (MIN_PARALLEL_TEXELS / length.max(1)).max(1) +} + /// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel. pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) { let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; - let mut fixed: Vec = data.par_iter().map(to_fixed).collect(); + let mut fixed: Vec = data.par_iter().with_min_len(MIN_PARALLEL_TEXELS).map(to_fixed).collect(); blur_rows(&mut fixed, width, radius); let mut columns = transpose(&fixed, width, height); blur_rows(&mut columns, height, radius); - data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); + data.par_iter_mut() + .with_min_len(MIN_PARALLEL_TEXELS) + .zip(transpose(&columns, height, width)) + .for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } /// The box blurs `blur` runs along each axis @@ -453,7 +465,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { if w == 0 { return; } - data.par_chunks_mut(w).for_each(|row| { + data.par_chunks_mut(w).with_min_len(lines_per_task(w)).for_each(|row| { let mut tmp = vec![0i64; row.len()]; for _ in 0..BLUR_BOX_PASSES { box_line(row, &mut tmp, r); @@ -481,7 +493,7 @@ fn box_line(src: &[i64], dst: &mut [i64], r: usize) { fn transpose(src: &[i64], w: usize, h: usize) -> Vec { let mut out = vec![0i64; src.len()]; if h > 0 { - out.par_chunks_mut(h).enumerate().for_each(|(x, col)| { + out.par_chunks_mut(h).with_min_len(lines_per_task(h)).enumerate().for_each(|(x, col)| { for (y, d) in col.iter_mut().enumerate() { *d = src.get(y * w + x).copied().unwrap_or(0); } @@ -698,9 +710,10 @@ fn filter_region( 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(); + let mut sums: Vec = + orig.par_chunks(comps).with_min_len(MIN_PARALLEL_TEXELS).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)| { + data.par_chunks_mut(comps).with_min_len(MIN_PARALLEL_TEXELS).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 @@ -749,7 +762,7 @@ fn filter_region( /// Clamp filtered masks to 0..1, and turn filtered content back into straight values. fn unpremultiply(data: &mut [f32], comps: usize) { - data.par_chunks_mut(comps).for_each(|px| match px { + data.par_chunks_mut(comps).with_min_len(MIN_PARALLEL_TEXELS).for_each(|px| match px { [v] => *v = v.clamp(0.0, 1.0), [r, g, b, cov] => { *cov = cov.clamp(0.0, 1.0); @@ -1661,7 +1674,7 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)]) } /// Tiles per side of the blocks a composite works through (bounds neighbourhood-filter memory). -const BLOCK: u32 = 16; +pub const BLOCK: u32 = 16; /// [`composite_tiles`], serving everything but the hot layer from `below` where it can (and /// filling it). Results are identical to [`composite_tiles`]. @@ -1681,14 +1694,50 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, for t in tiles { blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t); } - for block in blocks.values() { + let channels = set.channel_list(); + let hot = split.as_deref().and_then(<[Level]>::last); + // Fields are only kept without a live stroke (its preview is not part of what a stack key compares) + let holds = below.is_some() && inp.preview.is_none() && has_neighbourhood(inp, &set.stack); + let key = if holds { StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack).map(Arc::new) } else { None }; + let size = (inp.gbuf.width, inp.gbuf.height); + for (at, block) in &blocks { + let lacks = |tile: &(u32, u32)| below.as_deref().zip(split.as_deref()).is_none_or(|(cache, _)| cache.tile(*tile).is_none()); + let fresh: Vec<(u32, u32)> = block.iter().copied().filter(lacks).collect(); + let held = below.as_deref().and_then(|cache| cache.held.as_ref()).filter(|held| { + key.as_ref().is_some_and(|key| **key == *held.key) + && held.size == size + && fresh.iter().all(|tile| held.stack_tiles.contains(tile)) + && block.iter().all(|tile| held.hot_tiles.contains(tile)) + }); + let ahead: Vec<(u32, u32)> = match (&key, below.as_deref()) { + (Some(_), Some(cache)) if held.is_none() => { + cache.ahead.iter().copied().filter(|tile| (tile.1 / BLOCK, tile.0 / BLOCK) == *at && !block.contains(tile)).collect() + } + _ => Vec::new(), + }; + let fields: Arc = match (held, &key) { + (Some(held), _) => held.fields.clone(), + (None, Some(key)) if !ahead.is_empty() => { + // These tiles and the ones that follow them, filtered at once and kept + let wide: Vec<(u32, u32)> = block.iter().chain(&ahead).copied().collect(); + let wide_fresh: Vec<(u32, u32)> = wide.iter().copied().filter(lacks).collect(); + let fields = Arc::new(block_fields(inp, &channels, &set.stack, hot, &wide_fresh, &wide)); + let hot_tiles: std::collections::BTreeSet<(u32, u32)> = wide.iter().copied().collect(); + let stack_tiles = if hot.is_some() && wide_fresh.len() < wide.len() { wide_fresh.into_iter().collect() } else { hot_tiles.clone() }; + if let Some(cache) = below.as_deref_mut() { + cache.held = Some(HeldFields { key: key.clone(), size, stack_tiles, hot_tiles, fields: fields.clone() }); + } + fields + } + _ => Arc::new(block_fields(inp, &channels, &set.stack, hot, &fresh, block)), + }; let quota = match below.as_deref() { Some(_) if fits => usize::MAX, Some(b) => b.limit().saturating_sub(b.bytes()) / tile_bytes, None => 0, }; let cached = below.as_deref().zip(split.as_deref()); - let records = composite_block(inp, &set.stack, out, block, cached, quota); + let records = composite_block(inp, &set.stack, out, block, cached, quota, &fields); if let Some(b) = below.as_deref_mut() { for t in block { b.touch(*t); @@ -1698,6 +1747,34 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, } } } + // Nothing follows in this pass: its fields are not kept past it + if let Some(cache) = below.filter(|cache| cache.ahead.is_empty()) { + cache.held = None; + } +} + +/// Whether a layer drawn by `stack` has a neighbourhood filter in its mask or content effects. +fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { + let working_width = inp.gbuf.width; + let mut order = Vec::new(); + draw_order(inp.project, stack, 0, &mut order); + order.into_iter().any(|id| { + let masked = layer_mask(inp.project, id).is_some_and(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); + masked || inp.project.content_layer(id).is_some_and(|layer| !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some()) + }) +} + +/// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`), +/// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`. +fn block_fields(inp: &Inputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { + match hot { + Some(hot) if fresh.len() < tiles.len() => { + let mut fields = fields_of(inp, channels, stack, fresh); + fields.extend(fields_of(inp, channels, &[hot.at], tiles)); + fields + } + _ => fields_of(inp, channels, stack, tiles), + } } /// Rows of a tile composited as one parallel task. @@ -1719,6 +1796,7 @@ fn composite_block( tiles: &[(u32, u32)], below: Option<(&BelowCache, &[Level])>, quota: usize, + fields: &Fields, ) -> Vec<((u32, u32), Vec)> { let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); let (w, h) = (out.resolution, out.height); @@ -1726,15 +1804,6 @@ fn composite_block( let cached = |t: (u32, u32)| below.and_then(|(b, _)| b.tile(t)); let fresh: Vec<(u32, u32)> = tiles.iter().copied().filter(|t| cached(*t).is_none()).collect(); let recorded: std::collections::BTreeSet<(u32, u32)> = if split.is_some() { fresh.iter().copied().take(quota).collect() } else { Default::default() }; - // Off the path, layers are only evaluated on tiles the cache lacks. - let fields = match split.and_then(<[Level]>::last) { - Some(hot) if fresh.len() < tiles.len() => { - let mut fields = fields_of(inp, &channels, stack, &fresh); - fields.extend(fields_of(inp, &channels, &[hot.at], tiles)); - fields - } - _ => fields_of(inp, &channels, stack, tiles), - }; let lanes: Vec = channels.iter().map(|c| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed }).collect(); let stride: usize = lanes.iter().map(|l| l.n).sum(); let nlev = split.map_or(0, <[Level]>::len); @@ -1747,8 +1816,8 @@ fn composite_block( .map(|&((tx, ty), band)| { let warm = cached((tx, ty)).and_then(|b| b.get(band as usize)); let record = warm.is_none() && recorded.contains(&(tx, ty)); - let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, &fields, warm.is_some())); - let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(&fields)) } else { Vec::new() }; + let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, fields, warm.is_some())); + let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(fields)) } else { Vec::new() }; let rows = (BAND * TILE) as usize; let mut accs = vec![defaults; nlev]; let mut masks = vec![0.0f32; nlev]; diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 46c3c6b5..2499c073 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -20,8 +20,8 @@ pub mod thumb; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ - Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_at, mask_image, pad_tiles, + BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, + flatten_layer, mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index d7df0258..bd8efe80 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -573,3 +573,136 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { assert!(!check_cached(&f, 0, hot).is_empty()); } } + +/// Composite every tile in chunks of `chunk`, telling the cache the `ahead` tiles that follow each chunk, as a pass spread over frames does. +fn run_sliced(f: &Fixture, cache: &mut BelowCache, chunk: usize, ahead: usize) -> Composite { + let all = all_tiles(RES, RES); + let (images, baked) = (Default::default(), Default::default()); + let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), RES); + for (index, tiles) in all.chunks(chunk).enumerate() { + let done = (index * chunk + tiles.len()).min(all.len()); + cache.ahead = all.iter().skip(done).take(ahead).copied().collect(); + composite_tiles_cached(&inputs(f, 0, &images, &baked), &mut out, tiles, Some(&mut *cache)); + assert_eq!(cache.holds_fields(), !cache.ahead.is_empty(), "fields are kept exactly while tiles follow (chunk {chunk}, ahead {ahead})"); + } + out +} + +#[test] +fn filter_fields_kept_across_the_chunks_of_a_pass_composite_exactly() { + let mut f = fixture(); + let top = heavy_stack(&mut f); + let blurred_fill = f.project.texture_sets[0].stack[1]; + let want = reference(&f, 0); + for hot in [None, Some(top), Some(blurred_fill)] { + // Short and long runs of kept tiles: chunks inside a run reuse it, chunks past its end filter again + for (chunk, ahead) in [(1, 1), (1, 5), (3, 4), (5, 16), (2, 0)] { + let mut cache = BelowCache::default(); + cache.set_hot(hot); + assert!(run_sliced(&f, &mut cache, chunk, ahead) == want, "a cold sliced pass differs (hot {hot:?}, chunk {chunk}, ahead {ahead})"); + // The hot-layer cache is warm now: only the hot layer's fields are needed + assert!(run_sliced(&f, &mut cache, chunk, ahead) == want, "a warm sliced pass differs (hot {hot:?}, chunk {chunk}, ahead {ahead})"); + } + } + + // A cache too small for the set drops tiles while a run of kept fields is in use: those tiles need every layer's fields again + let mut full = BelowCache::default(); + full.set_hot(Some(top)); + run(&f, 0, &all_tiles(RES, RES), Some(&mut full)); + let tile_bytes = full.tile_bytes().unwrap(); + for tiles_held in [2, 5, 9] { + for (chunk, ahead) in [(1, 5), (3, 4), (2, 16)] { + let mut cache = BelowCache::default(); + cache.budget = tiles_held * tile_bytes; + cache.set_hot(Some(top)); + for pass in 0..3 { + assert!(run_sliced(&f, &mut cache, chunk, ahead) == want, "pass {pass} differs with {tiles_held} cached tiles (chunk {chunk}, ahead {ahead})"); + } + } + } +} + +#[test] +fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { + let mut f = fixture(); + let top = heavy_stack(&mut f); + let all = all_tiles(RES, RES); + let (first, rest) = all.split_at(3); + let mut cache = BelowCache::default(); + cache.set_hot(Some(top)); + + // Fields are kept for the tiles after the first chunk… + cache.ahead = rest.to_vec(); + let mut out = run(&f, 0, first, Some(&mut cache)); + assert!(cache.holds_fields()); + + // …then the blurred mask of the hot layer changes before they are composited + let mask = f.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); + mask.effects[1].kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); + let (images, baked) = (Default::default(), Default::default()); + cache.ahead = Vec::new(); + composite_tiles_cached(&inputs(&f, 0, &images, &baked), &mut out, &all, Some(&mut cache)); + assert!(out == reference(&f, 0), "fields kept from before an edit were used after it"); + assert!(!cache.holds_fields()); + + // A live stroke is not part of what kept fields are compared by: it composites without them + let preview = stroke(top); + cache.ahead = rest.to_vec(); + let mut live = run_with(&f, 0, first, Some(&mut cache), Some(&preview)); + assert!(!cache.holds_fields()); + let mut inp = inputs(&f, 0, &images, &baked); + inp.preview = Some(&preview); + composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache)); + assert!(live == run_with(&f, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs"); +} + +/// Kept fields hold a layer off the hot path only over the tiles the cache lacked when they were built. A tile the cache drops +/// while they are in use needs that layer's fields again. +#[test] +fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { + const SIZE: u32 = 512; + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, SIZE, SIZE); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, SIZE)); + let mut f = Fixture { project, mesh, gbuf, pixels: PixelStore::default() }; + add(&mut f, 0, fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None); + // A pattern with detail on every tile, so a tile composited without its blur shows + let mut blurred = Mask::new(MaskBackground::Black); + blurred.effects.push(effect(&mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + blurred.effects.push(effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); + add(&mut f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred)); + // A paint layer on top leaves the blurred layer in sight + let hot = add(&mut f, 0, LayerKind::Paint, None); + paint_rect_at(&mut f, hot, SIZE, (10, 10), (40, 40), 0.2); + + let mut all = all_tiles(SIZE, SIZE); + all.sort_by_key(|&(x, y)| (y, x)); + let channels = f.project.texture_sets[0].channel_list(); + let (images, baked) = (Default::default(), Default::default()); + let mut want = Composite::new(&channels, SIZE); + composite_tiles(&inputs(&f, 0, &images, &baked), &mut want, &all); + + // The cache holds the two bottom rows of tiles, and no more than that + let rows = (SIZE / TILE) as usize; + let (above, bottom) = all.split_at(all.len() - 2 * rows); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot)); + let mut out = Composite::new(&channels, SIZE); + composite_tiles_cached(&inputs(&f, 0, &images, &baked), &mut out, bottom, Some(&mut cache)); + assert_eq!(cache.len(), bottom.len()); + cache.budget = cache.bytes(); + + // One tile at a time with every later tile ahead: the first composite keeps fields for the whole set, the blurred layer's + // only over the rows above. Recording those rows then drops the bottom ones from the cache before their turn + let mut out = Composite::new(&channels, SIZE); + for (index, tile) in all.iter().enumerate() { + cache.ahead = all.iter().skip(index + 1).copied().collect(); + composite_tiles_cached(&inputs(&f, 0, &images, &baked), &mut out, &[*tile], Some(&mut cache)); + if index == 0 { + assert!(cache.holds_fields()); + } + } + assert!(above.len() > bottom.len()); + assert!(out == want, "a tile dropped from the cache was composited with fields that lack the layers off the hot path"); +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 9d58670b..ca7f6521 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -817,6 +817,8 @@ impl Session { images: &self.images, bounds: self.mesh.bounds(), }; + // A pass spread over frames tells the compositor what comes next, so neighbourhood filters run once over a run of tiles + cache.below.ahead = if budget_ms.is_finite() { tiles_ahead(&cache.dirty, &tiles) } else { Vec::new() }; texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); // The composited tiles and the neighbours their padding reached change. let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); @@ -977,6 +979,19 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> { } /// Valid texture set resolutions: powers of two from 128 to 8192. +/// Dirty tiles a neighbourhood filter runs over ahead of the chunk being composited (see [`tiles_ahead`]). +const FILTER_AHEAD: usize = 64; + +/// The dirty tiles composited after `chunk` in its 16 × 16 tile blocks, in the order [`next_chunk`] takes them, at most [`FILTER_AHEAD`]. +fn tiles_ahead(dirty: &BTreeSet<(u32, u32)>, chunk: &[(u32, u32)]) -> Vec<(u32, u32)> { + let block = |&(x, y): &(u32, u32)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK); + let blocks: BTreeSet<(u32, u32)> = chunk.iter().map(block).collect(); + let mut ahead: Vec<(u32, u32)> = dirty.iter().copied().filter(|tile| blocks.contains(&block(tile))).collect(); + ahead.sort_by_key(|tile| (block(tile), tile.1, tile.0)); + ahead.truncate(FILTER_AHEAD); + ahead +} + pub fn check_resolution(r: u32) -> Result { if (128..=8192).contains(&r) && r.is_power_of_two() { Ok(r) diff --git a/crates/engine/tests/it/perf.rs b/crates/engine/tests/it/perf.rs index e4691b6a..4b97420d 100644 --- a/crates/engine/tests/it/perf.rs +++ b/crates/engine/tests/it/perf.rs @@ -397,3 +397,41 @@ fn bench_layer_thumbs_4k() { } eprintln!(" every target once: {:.1} ms ({} pictures)", total.as_secs_f64() * 1e3, targets.len()); } + +/// A full recomposite in one call against the same one spread over frames, as the UI runs it, with and without a blurred mask +/// in the stack: neighbourhood filters are what a frame slice pays for apart from its own tiles. +#[test] +#[ignore] +fn bench_sliced_filters_4k() { + for blur in [false, true] { + let mut s = Session::new_project("sliced", primitives::sphere(1.0, 64, 32), "builtin:sphere", None, 4096).unwrap(); + s.viewport = Vec2::new(800.0, 800.0); + let run = |s: &mut Session, id: &str, p: Value| execute(s, id, &p).unwrap(); + run(&mut s, "layer.add.fill", json!({"color": [0.6, 0.5, 0.4], "roughness": 0.6})); + run(&mut s, "layer.add.fill", json!({"color": [0.1, 0.3, 0.6]})); + run(&mut s, "mask.add.black", Value::Null); + run(&mut s, "effect.add.generator", json!({"generator": "position", "level": 0.5})); + if blur { + run(&mut s, "effect.add.filter", json!({"filter": "blur", "radius": 8})); + } + s.update(); + + s.caches[0].invalidate_all(); + let t = Instant::now(); + s.update(); + let direct = t.elapsed(); + + s.caches[0].invalidate_all(); + let clock = Instant::now(); + let ms = || clock.elapsed().as_secs_f64() * 1000.0; + let (mut frames, mut worst) = (0, Duration::ZERO); + while s.pending_tiles() > 0 { + let t = Instant::now(); + s.update_for(30.0, ms); + worst = worst.max(t.elapsed()); + frames += 1; + } + let label = if blur { "blurred mask" } else { "no filter" }; + println!("[sliced 4096², {label}] one call {direct:.2?}; in 30 ms slices {frames} frames, worst {worst:.2?}, total {:.2?}", clock.elapsed()); + } +} From 74d213272d08b67fc0abaa4e6d9db3e30734f4f3 Mon Sep 17 00:00:00 2001 From: Morion Date: Fri, 13 Nov 2026 14:20:27 -0500 Subject: [PATCH 060/115] Release kept filter fields when a stroke begins during a sliced pass (#475) Fields kept for the coming composites stayed allocated for as long as a stroke lasted while tiles still followed, because the end-of-pass cleanup only runs when none do. A stroke already kept them from being used; now it also drops them. The test keeps fields first, then starts the stroke. --- crates/compose/src/eval.rs | 6 +++++ crates/compose/tests/cache_and_instances.rs | 25 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 0815124d..16bf2bd3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1700,6 +1700,12 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, let holds = below.is_some() && inp.preview.is_none() && has_neighbourhood(inp, &set.stack); let key = if holds { StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack).map(Arc::new) } else { None }; let size = (inp.gbuf.width, inp.gbuf.height); + // Fields kept before a stroke began are not used under it, nor held while it lasts + if key.is_none() + && let Some(cache) = below.as_deref_mut() + { + cache.held = None; + } for (at, block) in &blocks { let lacks = |tile: &(u32, u32)| below.as_deref().zip(split.as_deref()).is_none_or(|(cache, _)| cache.tile(*tile).is_none()); let fresh: Vec<(u32, u32)> = block.iter().copied().filter(lacks).collect(); diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index bd8efe80..b5dd0602 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -706,3 +706,28 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { assert!(above.len() > bottom.len()); assert!(out == want, "a tile dropped from the cache was composited with fields that lack the layers off the hot path"); } + +/// A stroke that starts while fields are kept must not leave them allocated for as long as it lasts, even though tiles still follow. +#[test] +fn a_live_stroke_releases_the_fields_kept_before_it_started() { + let mut f = fixture(); + let top = heavy_stack(&mut f); + let all = all_tiles(RES, RES); + let (first, rest) = all.split_at(3); + let mut cache = BelowCache::default(); + cache.set_hot(Some(top)); + + cache.ahead = rest.to_vec(); + run(&f, 0, first, Some(&mut cache)); + assert!(cache.holds_fields()); + + // The stroke begins with tiles still following: the pass is not over, so nothing else would clear them + let preview = stroke(top); + let mut live = run_with(&f, 0, first, Some(&mut cache), Some(&preview)); + assert!(!cache.holds_fields(), "fields kept before the stroke stay allocated while it lasts"); + let (images, baked) = (Default::default(), Default::default()); + let mut inp = inputs(&f, 0, &images, &baked); + inp.preview = Some(&preview); + composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache)); + assert!(live == run_with(&f, 0, &all, None, Some(&preview)), "a stroke that starts during a sliced pass differs"); +} From b89badcd6f883751f79960f93c554fb77f063885 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 15:42:13 -0500 Subject: [PATCH 061/115] Budget the total payload of one .mcmat (#499) * formats: budget the total payload of one .mcmat * formats: format the .mcmat map-limit test --- crates/formats/src/mcmat.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/formats/src/mcmat.rs b/crates/formats/src/mcmat.rs index 55b6f6ee..441bae10 100644 --- a/crates/formats/src/mcmat.rs +++ b/crates/formats/src/mcmat.rs @@ -20,6 +20,10 @@ const FORMAT: &str = "craft-material"; const VERSION: u32 = 1; /// Largest entry read (maps are at most 8192² × 16 bits, compressed). const MAX_ENTRY: u64 = 512 << 20; +/// Most map entries one manifest may name (a material has at most nine usages). +const MAX_MAPS: usize = 64; +/// Largest total payload read from one `.mcmat`: maps and source together (audit: TextureCraft #4). +const MAX_TOTAL: u64 = 1 << 30; const KIND: &str = "MaterialCraft material"; #[derive(Clone, Debug, PartialEq, Deserialize)] @@ -69,6 +73,7 @@ fn malformed(msg: impl Into) -> FormatError { /// Read `.mcmat` bytes. pub fn read_mcmat(bytes: &[u8]) -> Result { let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| malformed(e.to_string()))?; + let mut total = 0u64; let mut read = |name: &str| -> Result> { let mut out = Vec::new(); let f = z.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?; @@ -76,6 +81,10 @@ pub fn read_mcmat(bytes: &[u8]) -> Result { if out.len() as u64 > MAX_ENTRY { return Err(FormatError::TooLarge(name.to_string())); } + total = total.saturating_add(out.len() as u64); + if total > MAX_TOTAL { + return Err(FormatError::TooLarge(format!("{KIND} payload (over {MAX_TOTAL} bytes)"))); + } Ok(out) }; let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|e| malformed(format!("material.json: {e}")))?; @@ -85,6 +94,9 @@ pub fn read_mcmat(bytes: &[u8]) -> Result { if manifest.version > VERSION { return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version))); } + if manifest.maps.len() > MAX_MAPS { + return Err(malformed(format!("{} maps, over the {MAX_MAPS} map limit", manifest.maps.len()))); + } let maps = manifest.maps.iter().map(|m| Ok((m.usage.clone(), read(&m.file)?))).collect::>>()?; let source = read(&manifest.source)?; Ok(PortableMaterial { manifest, maps, source }) @@ -167,6 +179,22 @@ mod tests { assert!(read_mcmat(b"junk").is_err()); } + #[test] + fn an_unbounded_map_list_is_refused() { + let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect(); + let manifest = + serde_json::json!({"format": FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); + let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); + let o = zip::write::SimpleFileOptions::default(); + z.start_file("material.json", o).unwrap(); + z.write_all(manifest.to_string().as_bytes()).unwrap(); + z.start_file("maps/baseColor.png", o).unwrap(); + z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); + z.start_file("source.mcraft", o).unwrap(); + z.write_all(b"pkg").unwrap(); + assert!(read_mcmat(&z.finish().unwrap().into_inner()).is_err()); + } + #[test] fn mesh_maps_encode_as_16_bit() { let png = mesh_map_png(2, 1, &[0.0, 0.25, 0.5, 1.0]).unwrap(); From 73083d418a2b680867d823e6542bdefb20f92d1e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 17:02:27 -0500 Subject: [PATCH 062/115] formats: cap default resource image decode at 64 M texels (#506) Imported images still used the 16384-pixel edge limit with no texel ceiling, so a small 16k square PNG expanded to multi-gigabyte RGBA f32 buffers. Default resource decoding now refuses more than 8192 square texels from the header, and the engine import path uses the same budget. --- crates/engine/src/resource_cmds.rs | 2 +- crates/formats/src/image_res.rs | 15 +++++++++++++-- crates/formats/src/lib.rs | 4 ++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 54876d19..67665c4e 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -38,7 +38,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX)) + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) } /// Add an image within a decoded texel budget, inside the caller's edit diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 85590d9d..bcff2435 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -1,6 +1,6 @@ //! Decoding imported image resources (fills, alphas, stencils). -use crate::{FormatError, MAX_IMAGE_SIZE, Result}; +use crate::{FormatError, MAX_IMAGE_SIZE, MAX_RESOURCE_TEXELS, Result}; /// A decoded image: RGBA as 0..1 floats in the file's own encoding (8/16-bit files stay /// sRGB-encoded; `srgb` says so), row-major, top row first. @@ -15,7 +15,7 @@ pub struct DecodedImage { /// Decode PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR bytes. pub fn decode_image(bytes: &[u8]) -> Result { - decode_image_within(bytes, u64::MAX) + decode_image_within(bytes, MAX_RESOURCE_TEXELS) } /// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the @@ -100,4 +100,15 @@ mod tests { assert!(matches!(decode_image_within(&png, 63), Err(FormatError::TooLarge(_)))); assert!(decode_image(&png).is_ok()); } + + #[test] + fn the_default_decoder_refuses_more_than_the_resource_texel_budget_from_the_header() { + // An 18-byte TGA header: 16384² is inside the edge limit but far over 64 M texels. + let mut header = [0u8; 18]; + header[2] = 2; + header[12..14].copy_from_slice(&16_384u16.to_le_bytes()); + header[14..16].copy_from_slice(&16_384u16.to_le_bytes()); + header[16] = 24; + assert!(matches!(decode_image(&header), Err(FormatError::TooLarge(_)))); + } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 6e57432e..d8550531 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -95,6 +95,10 @@ pub(crate) fn guard(kind: &'static str, f: impl FnOnce() -> Result) -> Res /// Largest image edge accepted or produced anywhere in this crate. pub const MAX_IMAGE_SIZE: u32 = 16_384; +/// Most texels an imported image resource may decode to by default (8192 × 8192). +/// Larger images are refused from their header before any pixels are decoded. +pub const MAX_RESOURCE_TEXELS: u64 = 1 << 26; + /// Read a whole file, refusing files over `cap` bytes. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { From 0fa3a392fd61b3e02a86e8136bfbaa178be76100 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 17:23:06 -0500 Subject: [PATCH 063/115] formats: create atomic-write temps exclusively so a planted symlink is never followed (#502) --- crates/formats/src/lib.rs | 48 +++++++++++++++++++++++--- crates/formats/src/project_file/mod.rs | 6 ++-- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index d8550531..3708d737 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -112,15 +112,53 @@ pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { Ok(std::fs::read(path)?) } -/// Write `bytes` to `path` atomically: `.tmp` first, then rename over the target. +/// Create a new temporary file beside `path`, refusing to reuse an existing (possibly symlinked) name. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf, std::fs::File)> { + let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("out"); + for attempt in 0..100u32 { + let tmp = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) { + Ok(file) => return Ok((tmp, file)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e.into()), + } + } + Err(FormatError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not create a temporary file"))) +} + +/// Write `bytes` to `path` atomically: a new temporary file first, then rename over the target. #[cfg(not(target_arch = "wasm32"))] pub fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(".tmp"); - let tmp = std::path::PathBuf::from(tmp); - let res = std::fs::write(&tmp, bytes).and_then(|_| std::fs::rename(&tmp, path)); + use std::io::Write; + let (tmp, mut file) = create_temp(path)?; + let res = file.write_all(bytes).and_then(|_| file.sync_all()); + drop(file); + let res = res.and_then(|_| std::fs::rename(&tmp, path)); if res.is_err() { let _ = std::fs::remove_file(&tmp); } Ok(res?) } + +#[cfg(all(test, unix))] +mod atomic_tests { + use super::write_atomic; + + #[test] + fn write_atomic_does_not_follow_a_planted_temp_symlink() -> std::io::Result<()> { + let dir = std::env::temp_dir().join(format!("tc-atomic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir)?; + let target = dir.join("out.png"); + let victim = dir.join("victim.txt"); + std::fs::write(&victim, b"safe")?; + std::os::unix::fs::symlink(&victim, dir.join("out.png.tmp"))?; + write_atomic(&target, b"new").map_err(std::io::Error::other)?; + assert_eq!(std::fs::read(&victim)?, b"safe"); + assert_eq!(std::fs::read(&target)?, b"new"); + let _ = std::fs::remove_dir_all(&dir); + Ok(()) + } +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 8390220a..e982d761 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -101,11 +101,9 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result> { /// Save atomically: `.tmp` first, then rename over `path`. #[cfg(not(target_arch = "wasm32"))] pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(".tmp"); - let tmp = std::path::PathBuf::from(tmp); + let (tmp, file) = crate::create_temp(path)?; let res = (|| -> Result<()> { - let mut file = std::io::BufWriter::new(std::fs::File::create(&tmp)?); + let mut file = std::io::BufWriter::new(file); write_project(&mut file, pf)?; file.into_inner().map_err(|e| e.into_error())?.sync_all()?; std::fs::rename(&tmp, path)?; From 9ed81da8cbcfff0bf11d362f0e83fa4baa9d1300 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 17:28:04 -0500 Subject: [PATCH 064/115] formats: account for the USDC path table's real allocation (#507) The PATHS table charged 64 bytes per entry but allocates Option (about 80), letting a small declared count exceed the decoded-byte budget, and had no entry ceiling. Charge the real element size and cap the table at four million paths. --- crates/formats/src/mesh_import/usd/usdc.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 221c7b4a..0a07b637 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -15,6 +15,9 @@ const MIN_VERSION: (u8, u8, u8) = (0, 4, 0); const MAX_SECTIONS: usize = 64; /// Items in one table or array. const MAX_ITEMS: usize = 1 << 28; +/// Entries in the PATHS table. The declared count is tiny in the file but each entry is a +/// materialised path, so it needs its own ceiling as well as the decoded-byte budget. +const MAX_PATHS: usize = 4_000_000; /// Spec types. const SPEC_ATTRIBUTE: i64 = 1; @@ -248,7 +251,11 @@ impl<'a> Crate<'a> { let index = s.ints(n, 4, budget)?; let elements = s.ints(n, 4, budget)?; let jumps = s.ints(n, 4, budget)?; - budget.take(total.saturating_mul(64))?; + if total > MAX_PATHS { + return Err(FormatError::TooLarge(format!("the USD path table has {total} entries (limit {MAX_PATHS})"))); + } + // Charge what the vector really allocates, not a guessed 64 bytes per entry. + budget.take(total.saturating_mul(std::mem::size_of::>()))?; self.paths = vec![None; total]; let mut work: Vec<(usize, Option)> = vec![(0, None)]; let mut steps = 0usize; From 5e4f511f178d6691d052123321e194113c1bcae0 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sat, 14 Nov 2026 21:18:26 -0500 Subject: [PATCH 065/115] Added CODE_STYLE (not referenced by AGENTS) as helper for maintaining better code quality --- CODE_STYLE.md | 77 ++++++++++++++++++++++++++++ docs/helpful-pr-review-guidelines.md | 36 +------------ 2 files changed, 79 insertions(+), 34 deletions(-) create mode 100644 CODE_STYLE.md diff --git a/CODE_STYLE.md b/CODE_STYLE.md new file mode 100644 index 00000000..86dcc057 --- /dev/null +++ b/CODE_STYLE.md @@ -0,0 +1,77 @@ +# Code style + +Style conventions for MaterialCraft's Rust code. +Read alongside [AGENTS.md](AGENTS.md) for repository requirements. + +## Naming and Rust conventions + +- Use descriptive names that explain purpose; include units where useful. Avoid misleading names + and abbreviations whose meaning is unclear in context. +- Follow Rust naming conventions: `snake_case` for functions, variables, fields, and modules; + `UpperCamelCase` for types and traits; `SCREAMING_SNAKE_CASE` for constants and statics. +- Conventional Rust names are not cryptic abbreviations. Keep names such as `fmt`, `iter`, `len`, + `args`, `err`, `id`, and `ui` when their meaning is clear. Do not expand them just to make them + longer. +- Keep standard file and directory names such as `lib.rs`, `main.rs`, `mod.rs`, `src`, `tests`, + `examples`, and `benches`. Rust keywords such as `mut`, `ref`, `impl`, and `mod` are language + syntax, not naming problems. +- Short names are appropriate in a clear local context: `i` for an index, `x` and `y` for + coordinates, `w` and `h` for image dimensions, and conventional generic parameters such as `T`. + Use more descriptive names when scope or ambiguity makes those hard to follow. + +## Magic numbers + +- Give non-obvious limits, thresholds, sizes, and tuning values descriptive named constants + instead of leaving unexplained numeric literals in the code. +- Name constants for their purpose, with units where useful, rather than for their literal value. + Keep them in the narrowest useful scope. +- Reuse an existing constant when it represents the same concept. Equal numeric values alone do + not mean two concepts should share a constant. +- Explain the origin or rationale of non-obvious coefficients and tolerances in a short comment. + Use standard library constants for standard mathematical values. +- Keep literals inline when their role is clear, such as zero initialization, incrementing by one, + or dividing by two to find a midpoint. Do not introduce names such as `ZERO` or `TWO` that add + no meaning. +- Apply this guidance to tests too; clear fixture values and expected results can remain literal. + +## Formatting and spacing + +- Let `cargo fmt` and the repository's [rustfmt.toml](rustfmt.toml) handle mechanical formatting. + Do not introduce a competing indentation or line-wrapping convention. +- Use one blank line between distinct logical steps: input preparation, validation, computation, + mutation, and result construction. +- Keep closely related statements together. Do not add a blank line after every declaration or + fragment a single operation with extra spacing. +- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before + the next statement. +- Put a blank line before a comment introducing a new step, with no blank line between the + comment and the code it explains. +- Keep documentation and attributes attached to their declarations. +- Separate function definitions with one blank line. Avoid extra empty lines just inside braces + or between every field, argument, or statement. +- In tests, separate preparation, action, and verification with blank lines when those phases + are distinct; keep related assertions together. + +## Source organization + +- Give each struct or enum its own source file, with its implementation beside it. Use the full + type name in `snake_case`, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings`. +- Preserve conventional crate roots and module entry points such as `lib.rs`, `main.rs`, and + `mod.rs`. Follow the command and node module placement required by `AGENTS.md`. +- Prefer singular folder names for new domain modules, such as `map`, `setting`, or `tracing`. + Keep standard Rust directories and repository-mandated paths unchanged. +- Group related types into focused modules rather than collecting unrelated types in one large file. +- Apply these preferences to new types and source organization changes within scope. Do not + reorganize unrelated existing code to enforce them. + +## Comments + +- Explain intent or a non-obvious constraint rather than narrating the code. +- Use short `//` comments. Avoid block comments and wrapped prose in ordinary implementation + comments; adjacent comment lines should each express a concise point. +- Do not add trailing punctuation to ordinary code comments. +- Preserve explanations of guards and invariants. Remove stale or redundant comments without + losing necessary rationale. +- API documentation, required license headers, and examples may use conventional multiline + formatting and punctuation. +- Apply the same comment guidance to production code and tests. diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md index 098b6ae1..fbe4f69d 100644 --- a/docs/helpful-pr-review-guidelines.md +++ b/docs/helpful-pr-review-guidelines.md @@ -8,7 +8,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - Review-only requests call for findings; requests to fix or improve also authorize focused local edits - A review may conclude that no changes are needed. If the PR meets the applicable standards and no actionable issues are found, leave it unchanged. Do not invent findings, add unnecessary tests, or make edits merely to produce a diff. Report what was checked and any remaining validation limits - Apply all review standards across the entire affected method, including existing code and relevant tests -- Complete naming, spacing, and comment cleanup throughout it +- Read and apply [CODE_STYLE.md](../CODE_STYLE.md) throughout that scope - Make additional correctness or performance changes when supported by evidence and appropriate validation - Separate substantial changes that address an independent problem, explaining why - Apply the same scope to standalone functions and inspect relevant callers when verifying behavior @@ -27,6 +27,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi ## Optimization and simplicity - Prefer the smallest complete solution that is efficient and easy to understand +- Keep control flow direct and share repeated logic when it makes the code simpler - Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access - For loops, batches, and streaming operations, trace allocations and buffer lifetimes across multiple iterations, including outputs retained from earlier iterations. Identify work that belongs once per operation rather than once per item, using the full selection when making retention decisions - Consider caching, batching, and parallelism when measurements justify their complexity and memory cost @@ -35,39 +36,6 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations - Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity -## Clarity, naming, and spacing - -- Clean up the functions or methods being changed and their relevant tests within the scope above -- Use descriptive names that explain purpose; include units where useful -- Avoid cryptic abbreviations, misleading names, and unexplained production constants -- Keep control flow direct and share repeated logic when it makes the code simpler -- Use a single blank line to separate logical steps, such as input preparation, validation, computation, mutation, and result construction, when those steps are distinct -- Keep closely related statements together; avoid spacing that fragments a single operation or inserts a blank line after every declaration -- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before the next statement -- Keep comments attached to the code they explain; put a blank line before a comment introducing a new step, with no blank line between the comment and that step -- Keep documentation and attributes attached to their declarations -- Separate function definitions with one blank line; avoid extra empty lines immediately inside braces or between every field, argument, or statement -- Group tests into preparation, action, and verification with blank lines where those phases are distinct; keep related assertions together -- Apply this spacing consistently throughout affected functions, methods, and tests, and follow the repository's formatter for mechanical formatting - -## Source organization - -- Keep each class, enum, or struct in its own source file, with its implementation beside it -- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust -- Use singular folder names, such as `map`, `setting`, or `tracing` -- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file -- Apply these preferences to new types and source organization changes within scope; follow mandatory repository layout rules and leave unrelated existing structure alone - -## Comments - -- Use short, single-line comments; adjacent comment lines should each express a concise point -- Avoid block comments and wrapped prose in ordinary implementation comments -- Explain intent or a non-obvious constraint rather than narrating the code -- No trailing punctuation on ordinary code comments -- Preserve explanations of guards and invariants; remove stale or redundant comments without losing necessary rationale -- API documentation, required license headers, and examples may use their conventional multiline formatting and punctuation -- Apply these standards to both production code and tests - ## Validation and reporting - Run relevant tests and required repository checks with the project's expected toolchain From 75502053dbbb3577056d0f3e241a05d611f7ef7f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 04:18:22 -0500 Subject: [PATCH 066/115] formats: stop copying whole OBJ and glTF inputs before parsing (#503) * formats: stop copying whole OBJ and glTF inputs before parsing * formats: format the mesh-import copy changes --- crates/formats/src/mesh_import/gltf.rs | 8 ++++---- crates/formats/src/mesh_import/obj.rs | 11 ++++++++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 136e3e0c..92e52f72 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -28,9 +28,9 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { let (json, blob) = if bytes.starts_with(b"glTF") { let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?; let blob = glb.bin.take().map(std::borrow::Cow::into_owned); - (glb.json.into_owned(), blob) + (glb.json, blob) } else { - (bytes.to_vec(), None) + (std::borrow::Cow::Borrowed(bytes), None) }; let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?; if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) { @@ -40,8 +40,8 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { } } } - let json = serde_json::to_vec(&value).map_err(|e| malformed(KIND, e))?; - let root = gltf::json::Root::from_slice(&json).map_err(|e| malformed(KIND, e))?; + // Consume the DOM directly rather than serialising it back to a second full-size buffer. + let root: gltf::json::Root = serde_json::from_value(value).map_err(|e| malformed(KIND, e))?; let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?; Ok((document, blob)) } diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 2f284704..bf949625 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -1,5 +1,7 @@ //! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn. +use std::io::{BufReader, Read}; + use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use super::{RawMesh, check_triangles, check_vertices}; @@ -27,12 +29,15 @@ fn read_inner(bytes: &[u8]) -> Result { } let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect(); - let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); + let prefix = "mtllib texturecraft-usemtl.mtl\n"; + + // Feed the prefix and the borrowed (or lossily converted) body as one reader: neither a + // whole-file copy nor an extra string is needed before tobj parses it. + let mut source = BufReader::new(prefix.as_bytes().chain(text.as_bytes())); // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; - let (models, materials) = - tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; + let (models, materials) = tobj::load_obj_buf(&mut source, &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; let materials = materials.unwrap_or_default(); let mut raw = RawMesh::default(); From e89799153365731247b21bd696fac733029d81fe Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 09:59:44 +0000 Subject: [PATCH 067/115] test: allow instrumented high-DPI preview to settle --- crates/ui-egui/tests/it/shelf_hover_preview.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index c7ad071a..64a997e2 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -155,6 +155,11 @@ fn high_dpi_smart_material_hover_stays_within_the_renderer_limit() { check_high_dpi_orb_hover(1, "Steel Painted Worn"); } +// Coverage instrumentation makes the 512px software-rendered preview substantially slower. +fn high_dpi_worker_timeout() -> Duration { + if std::env::var_os("LLVM_PROFILE_FILE").is_some() { Duration::from_secs(600) } else { WORKER_TIMEOUT } +} + fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; @@ -166,7 +171,7 @@ fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { let expected = Some([MAX_PREVIEW_SIZE_PX; 2]); let started = Instant::now(); - while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < WORKER_TIMEOUT { + while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < high_dpi_worker_timeout() { harness.run_steps(1); std::thread::sleep(Duration::from_millis(20)); } From 5f008e72728849aab3573b69a9736e740862585a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 10:21:25 +0000 Subject: [PATCH 068/115] Preserve TextureCraft STL vertex limits --- crates/formats/src/mesh_import/stl.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/mesh_import/stl.rs b/crates/formats/src/mesh_import/stl.rs index fd288a27..e087b711 100644 --- a/crates/formats/src/mesh_import/stl.rs +++ b/crates/formats/src/mesh_import/stl.rs @@ -2,13 +2,13 @@ use texturecraft_geom::glam::{Vec3, Vec4}; -use super::{RawMesh, check_triangles}; +use super::{MAX_VERTICES, RawMesh, check_triangles}; use crate::{FormatError, Result}; const KIND: &str = "STL"; pub(crate) fn read(bytes: &[u8]) -> Result { - let scene = craft_mesh::stl::read(bytes, &craft_mesh::Limits::default()).map_err(|e| FormatError::Invalid(e.to_string()))?; + let scene = craft_mesh::stl::read(bytes, &stl_limits()).map_err(|e| FormatError::Invalid(e.to_string()))?; let mut raw = RawMesh::default(); raw.warnings = scene.warnings; @@ -58,3 +58,18 @@ pub(crate) fn read(bytes: &[u8]) -> Result { raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect())); Ok(raw) } + +/// STL stores three positions per facet; retain the app's established triangle capacity. +fn stl_limits() -> craft_mesh::Limits { + craft_mesh::Limits { max_vertices: MAX_VERTICES, ..craft_mesh::Limits::default() } +} + +#[cfg(test)] +mod tests { + #[test] + fn shared_reader_accepts_the_app_vertex_limit() { + let limits = super::stl_limits(); + assert_eq!(limits.max_vertices, super::MAX_VERTICES); + assert_eq!(limits.max_triangles, texturecraft_geom::MAX_TRIANGLES); + } +} From d7e534a6575ca844ea332156c8d7d645ae3880c0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 10:24:24 +0000 Subject: [PATCH 069/115] Recognize explicit coverage compiler flags --- crates/ui-egui/tests/it/shelf_hover_preview.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index 64a997e2..a18f3404 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -157,7 +157,11 @@ fn high_dpi_smart_material_hover_stays_within_the_renderer_limit() { // Coverage instrumentation makes the 512px software-rendered preview substantially slower. fn high_dpi_worker_timeout() -> Duration { - if std::env::var_os("LLVM_PROFILE_FILE").is_some() { Duration::from_secs(600) } else { WORKER_TIMEOUT } + if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) { + Duration::from_secs(600) + } else { + WORKER_TIMEOUT + } } fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { From 32380b0dc53b0791195b9f24d031ab3b1737b091 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 11:05:14 +0000 Subject: [PATCH 070/115] Preserve MaterialX displacement tiling --- Cargo.lock | 23 ++++++++++++----------- Cargo.toml | 18 +++++++++--------- crates/formats/src/materialx_read.rs | 13 +++++++++++++ 3 files changed, 34 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1efde862..8368bc88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,7 +758,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -771,12 +771,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "fixed_decimal", "icu_decimal", @@ -799,7 +799,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "egui", "serde", @@ -809,7 +809,7 @@ dependencies = [ [[package]] name = "craft-materialx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-xml", "thiserror 2.0.21", @@ -818,7 +818,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-keymap", "craft-quit", @@ -836,7 +836,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89 [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "dispatch2", "egui", @@ -847,7 +847,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -868,7 +868,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "chrono", "dunce", @@ -895,7 +895,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "egui", "objc2 0.6.5", @@ -906,9 +906,10 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index cc958885..09fada6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,22 +66,22 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["serde"] } -craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +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-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 = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } +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). -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } # Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs index 1b3da9ea..4de6abce 100644 --- a/crates/formats/src/materialx_read.rs +++ b/crates/formats/src/materialx_read.rs @@ -148,6 +148,19 @@ mod tests { m.channels.iter().find(|(ch, _)| *ch == c).map(|(_, v)| v) } + #[test] + fn displacement_only_image_supplies_uv_tiling() { + let xml = br#" + + + + + "#; + let material = read_materialx(xml, None).unwrap(); + assert_eq!(get(&material, Channel::Height), Some(&Value::Image("height.png".into()))); + assert_eq!(material.uv_tiling, [4.0, 2.0]); + } + #[test] fn open_pbr_inputs_become_channels() { let m = read_materialx(OPENPBR.as_bytes(), None).unwrap(); From 0d90953467314de4fd30baa10ab6a8a2869d064a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 11:44:04 +0000 Subject: [PATCH 071/115] Share portable materials and preserve SBS links --- Cargo.lock | 23 +++ Cargo.toml | 2 + crates/engine/src/link_cmds.rs | 58 ++++++- crates/engine/tests/it/materialcraft_link.rs | 44 ++++- crates/formats/Cargo.toml | 2 + crates/formats/src/mcmat.rs | 167 +++++++++---------- crates/ui-egui/src/dock.rs | 3 +- docs/architecture.md | 4 +- docs/control-protocol.md | 9 +- 9 files changed, 205 insertions(+), 107 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bcd091ae..63034cc3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -806,6 +806,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mcmat" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=26980ff331efa6ec2cb2b9093dc5a154a8f66bdb#26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-menu" version = "0.1.0" @@ -889,6 +900,16 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=26980ff331efa6ec2cb2b9093dc5a154a8f66bdb#26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -4369,6 +4390,8 @@ name = "texturecraft-formats" version = "0.6.1" dependencies = [ "base64 0.22.1", + "craft-mcmat", + "craft-zip", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index cb9745b5..86b75667 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } # 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 = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index e5122cd9..459d72e5 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Save MaterialCraft package", [], None, - "{layer?, path} — writes the MaterialCraft package (.mcraft) behind a material layer, to open in MaterialCraft", + "{layer?, path} — writes the MaterialCraft source (.mcraft or .sbs) behind a material layer", has_layer, save_source ), @@ -178,7 +178,9 @@ fn save_source(s: &mut Session, p: &Value) -> Result { const CMD: &str = "material.link.saveSource"; let id = layer_param(s, CMD, p)?; let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; - let path = if path.to_ascii_lowercase().ends_with(&format!(".{MCRAFT_EXT}")) { path.to_string() } else { format!("{path}.{MCRAFT_EXT}") }; + let link = link_of(s, CMD, id)?; + let ext = source_extension(&link.package); + let path = if path.to_ascii_lowercase().ends_with(&format!(".{ext}")) { path.to_string() } else { format!("{path}.{ext}") }; let bytes = s.link_package(id)?; texturecraft_formats::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| bad(CMD, e.to_string()))?; Ok(json!({"path": path})) @@ -195,6 +197,10 @@ fn save_source(_: &mut Session, _: &Value) -> Result { pub struct LinkJob { pub layer: LayerId, pub package: Arc>, + /// The source package extension (`mcraft` or `sbs`). + pub source_ext: &'static str, + /// The named graph in a linked material; direct package imports use its default. + pub graph: Option, /// Pixels across (the texture set's resolution). pub size: u32, /// Every parameter's value, by id, in MaterialCraft's typed form. @@ -226,7 +232,7 @@ fn quiet(program: &std::path::Path) -> std::process::Command { c } -/// Open `package` (a `.mcraft` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this +/// Open `package` (a `.mcraft` or `.sbs` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this /// program, or on `PATH`). #[cfg(not(target_arch = "wasm32"))] pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { @@ -236,6 +242,11 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { }) } +/// Source file extensions are chosen from the linked resource name, never an untrusted path. +pub fn source_extension(name: &str) -> &'static str { + if name.to_ascii_lowercase().ends_with(".sbs") { "sbs" } else { MCRAFT_EXT } +} + impl LinkJob { /// Cook through `materialcraft-cli` (`$MATERIALCRAFT_CLI`, next to this program, or on /// `PATH`); returns `.mcmat` bytes. Blocks for the cook (about a second at 2K). @@ -252,7 +263,8 @@ impl LinkJob { std::fs::write(&p, bytes).map_err(|e| other(format!("{name}: {e}")))?; utf8(&p) }; - let src = write("source.mcraft", &self.package)?; + let ext = if self.source_ext == "sbs" { "sbs" } else { MCRAFT_EXT }; + let src = write(&format!("source.{ext}"), &self.package)?; let mut inputs = Map::new(); for (i, (id, png)) in self.inputs.iter().enumerate() { inputs.insert(id.clone(), json!(write(&format!("input{i}.png"), png)?)); @@ -260,7 +272,19 @@ impl LinkJob { let out = dir.join(format!("out.{MCMAT_EXT}")); let params = json!({"path": utf8(&out)?, "size": self.size, "values": self.values, "inputs": inputs}); let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI"); - let run = quiet(&cli).arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()).output().map_err(|e| { + let mut command = quiet(&cli); + if let Some(graph) = &self.graph { + // Opening the source starts on its first graph; select the graph saved in the link. + let script = json!({"open": src, "steps": [ + {"id": "graph.open", "params": {"graph": graph}}, + {"id": "file.exportMaterial", "params": params}, + ]}); + let script_path = write("cook.json", script.to_string().as_bytes())?; + command.arg("batch").arg(script_path); + } else { + command.arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()); + } + let run = command.output().map_err(|e| { other(format!( "MaterialCraft's command line ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT_CLI", cli.display() @@ -301,7 +325,15 @@ impl Session { let bytes = if is_mcraft(bytes) { let ts = self.ts(); let size = self.doc.project.texture_set(ts)?.resolution; - let job = LinkJob { layer: LayerId(0), package: Arc::new(bytes.to_vec()), size, values: Map::new(), inputs: Vec::new() }; + let job = LinkJob { + layer: LayerId(0), + package: Arc::new(bytes.to_vec()), + source_ext: MCRAFT_EXT, + graph: None, + size, + values: Map::new(), + inputs: Vec::new(), + }; cooked = job.run()?; cooked.as_slice() } else { @@ -316,7 +348,7 @@ impl Session { let (id, names) = self.edit(&label, |s| { let ts = s.ts(); let stem = texturecraft_formats::sanitize_resource_name(&m.manifest.name); - let package = unique(s, &format!("{stem}.{MCRAFT_EXT}")); + let package = unique(s, &format!("{stem}.{}", source_extension(&m.manifest.source))); s.doc.resources.insert(package.clone(), Arc::new(m.source.clone())); let link = MaterialLink { name: m.manifest.name.clone(), @@ -345,7 +377,7 @@ impl Session { Ok(id) } - /// The `.mcraft` package behind linked layer `id`. + /// The source package behind linked layer `id`. pub fn link_package(&self, id: LayerId) -> Result>> { let link = link_of(self, "material.link", id)?; self.doc.resources.get(&link.package).cloned().ok_or_else(|| EngineError::Other(format!("the package of {} is missing", link.name))) @@ -376,7 +408,15 @@ impl Session { // UDIM tiles share one cook at the texture set's base resolution let size = self.doc.project.texture_set(texture_set)?.resolution; - Ok(LinkJob { layer: id, package: self.link_package(id)?, size, values, inputs }) + Ok(LinkJob { + layer: id, + package: self.link_package(id)?, + source_ext: source_extension(&link.package), + graph: Some(link.graph.clone()), + size, + values, + inputs, + }) } /// Swap in maps a [`LinkJob`] cooked (`.mcmat` bytes) and the values they were cooked with. diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index ac86d775..5dd63e02 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -21,9 +21,14 @@ fn session() -> Session { /// A `.mcmat` as MaterialCraft writes it: uniform maps, one float input `wear` cooked at `wear`. fn mcmat(roughness: f32, wear: f32) -> Vec { + mcmat_version(roughness, wear, 1) +} + +fn mcmat_version(roughness: f32, wear: f32, version: u32) -> Vec { + let source = if version == 2 { "source.sbs" } else { "source.mcraft" }; let gray = |v: f32| mesh_map_png(4, 1, &[v; 16]).unwrap(); let manifest = json!({ - "format": "craft-material", "version": 1, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], + "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], "maps": [ {"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}, {"usage": "roughness", "file": "maps/roughness.png", "colorSpace": "linear"}, @@ -42,7 +47,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { {"identifier": "bentNormal", "kind": "color"} ], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}, "note": {"t": "text", "v": "x"}}}], - "source": "source.mcraft" + "source": source }); let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); @@ -51,7 +56,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { ("maps/baseColor.png", mesh_map_png(4, 3, &[0.5; 48]).unwrap()), ("maps/roughness.png", gray(roughness)), ("maps/ambientOcclusion.png", gray(1.0)), - ("source.mcraft", b"package bytes".to_vec()), + (source, b"package bytes".to_vec()), ] { z.start_file(name, o).unwrap(); z.write_all(&bytes).unwrap(); @@ -81,6 +86,18 @@ fn map_name(s: &Session, id: LayerId, c: Channel) -> String { } } +#[test] +fn version_two_preserves_the_sbs_source_for_future_cooks() { + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat_version(0.25, 0.5, 2), Place::Selection).unwrap(); + let linked = link(&session, id); + assert!(linked.package.ends_with(".sbs")); + let job = session.link_job(id, &serde_json::Map::new()).unwrap(); + assert_eq!(job.source_ext, "sbs"); + assert_eq!(job.graph.as_deref(), Some("Brick_wall")); + assert_eq!(job.package.as_slice(), b"package bytes"); +} + #[test] fn imports_as_a_linked_fill_with_its_maps() { let mut s = session(); @@ -199,7 +216,7 @@ fn cooks_through_materialcraft_cli_when_available() { let dir = std::env::temp_dir().join(format!("tc-mc-link-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("bricks.mcraft"); - let ok = std::process::Command::new(&cli).args(["new", "bricks"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); + let ok = std::process::Command::new(&cli).args(["new", "pbr"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); assert!(ok.success()); let exposed = dir.join("exposed.mcraft"); let ok = std::process::Command::new(&cli) @@ -217,9 +234,24 @@ fn cooks_through_materialcraft_cli_when_available() { assert_eq!(link(&s, id).size, 128, "cooked at the texture set's resolution"); assert!(link(&s, id).params.iter().any(|p| p.id == "wear")); execute(&mut s, "material.link.set", &json!({"layer": id.0, "id": "wear", "value": 0.8})).unwrap(); - assert_eq!(link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value, json!({"t": "float", "v": 0.8})); - let out = dir.join("back.mcraft"); + let wear = link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value["v"].as_f64().unwrap(); + assert!((wear - 0.8).abs() < 1e-6); + let out = dir.join("back.sbs"); execute(&mut s, "material.link.saveSource", &json!({"layer": id.0, "path": out.to_str().unwrap()})).unwrap(); assert!(std::fs::metadata(&out).unwrap().len() > 0); + + // The portable material can name a graph other than the first in the embedded source. + let multi = dir.join("multi.mcraft"); + let ok = std::process::Command::new(&cli).arg("run").arg(&exposed).arg("graph.duplicate").arg("{}").arg("-o").arg(&multi).status().unwrap(); + assert!(ok.success()); + let portable = dir.join("second.mcmat"); + let params = json!({"graph": 1, "size": 64, "path": portable.to_str().unwrap()}); + let ok = std::process::Command::new(&cli).arg("run").arg(&multi).arg("file.exportMaterial").arg(params.to_string()).status().unwrap(); + assert!(ok.success()); + let second = s.add_linked_material_bytes_at(&std::fs::read(&portable).unwrap(), Place::Selection).unwrap(); + let expected_graph = link(&s, second).graph; + let job = s.link_job(second, &serde_json::Map::new()).unwrap(); + let result = texturecraft_engine::formats::mcmat::read_mcmat(&job.run().unwrap()).unwrap(); + assert_eq!(result.manifest.graph, expected_graph); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 7b458a53..040e6b84 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -9,6 +9,8 @@ license.workspace = true workspace = true [dependencies] +craft-mcmat = { workspace = true } +craft-zip = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/mcmat.rs b/crates/formats/src/mcmat.rs index 1976c73b..5040f320 100644 --- a/crates/formats/src/mcmat.rs +++ b/crates/formats/src/mcmat.rs @@ -1,11 +1,11 @@ //! MaterialCraft portable materials (`.mcmat`, read only): a zip with `material.json` (the //! manifest: maps by usage, exposed parameters, image inputs, presets), `maps/.png` -//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the source -//! `.mcraft` package. TextureCraft keeps its own reader (the apps share the format, not code). +//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the +//! source package. The shared reader handles the portable container and manifest. //! //! Also the 16-bit PNG encoder that hands baked mesh maps to MaterialCraft as graph inputs. -use std::io::{Cursor, Read}; +use std::io::Cursor; use serde::Deserialize; use texturecraft_core::{LinkParam, LinkPreset}; @@ -16,8 +16,7 @@ use crate::{FormatError, Result}; pub const MCMAT_EXT: &str = "mcmat"; /// MaterialCraft's package extension. pub const MCRAFT_EXT: &str = "mcraft"; -const FORMAT: &str = "craft-material"; -const VERSION: u32 = 1; +const VERSION: u32 = 2; /// Largest entry read (maps are at most 8192² × 16 bits, compressed). const MAX_ENTRY: u64 = 512 << 20; /// Most map entries one manifest may name (a material has at most nine usages). @@ -70,68 +69,76 @@ fn malformed(msg: impl Into) -> FormatError { FormatError::Malformed { kind: KIND, msg: msg.into() } } -fn read_entry(name: &str, entry: impl Read, total_bytes: &mut u64) -> Result> { - // Earlier maps remain live while the next entry is read - let remaining_bytes = MAX_TOTAL.saturating_sub(*total_bytes); - let entry_limit = MAX_ENTRY.min(remaining_bytes); - let mut bytes = Vec::new(); - entry.take(entry_limit + 1).read_to_end(&mut bytes).map_err(|error| malformed(format!("{name}: {error}")))?; - if bytes.len() as u64 > MAX_ENTRY { - return Err(FormatError::TooLarge(name.to_string())); +fn shared_error(error: craft_mcmat::Error) -> FormatError { + match error { + craft_mcmat::Error::Version(version) => FormatError::Unsupported(format!("{KIND} version {version} (this version reads up to {VERSION})")), + craft_mcmat::Error::Limit(message) => malformed(message), + craft_mcmat::Error::Archive(ref archive) if archive.is_limit() => FormatError::TooLarge(error.to_string()), + other => malformed(other.to_string()), } - - let next_total = total_bytes.saturating_add(bytes.len() as u64); - if next_total > MAX_TOTAL { - return Err(FormatError::TooLarge(format!("{KIND} payload (over {MAX_TOTAL} bytes)"))); - } - - // Keep spare read capacity from accumulating across retained map entries - bytes.shrink_to_fit(); - *total_bytes = next_total; - - Ok(bytes) } -/// Read `.mcmat` bytes. +/// Read `.mcmat` bytes within TextureCraft's existing per-entry and total payload limits. pub fn read_mcmat(bytes: &[u8]) -> Result { - let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|error| malformed(error.to_string()))?; - let mut total_bytes = 0u64; - let mut read = |name: &str| -> Result> { - let entry = archive.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?; - read_entry(name, entry, &mut total_bytes) + let limits = craft_mcmat::Limits { + min_version: 0, + max_version: VERSION, + max_entries: 100_000, + max_maps: MAX_MAPS, + max_manifest_bytes: MAX_ENTRY, + max_entry_bytes: MAX_ENTRY, + max_total_bytes: MAX_TOTAL, }; - - let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|error| malformed(format!("material.json: {error}")))?; - if manifest.format != FORMAT { - return Err(malformed(format!("format `{}`", manifest.format))); - } - - if manifest.version > VERSION { - return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version))); - } - - if manifest.maps.len() > MAX_MAPS { - return Err(malformed(format!("{} maps, over the {MAX_MAPS} map limit", manifest.maps.len()))); - } - - let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), read(&map.file)?))).collect::>>()?; - let source = read(&manifest.source)?; - + let mut archive = craft_mcmat::Material::open(bytes, limits).map_err(shared_error)?; + // Consume the JSON values rather than cloning the entire untrusted manifest into a second tree. + let parameters = std::mem::take(&mut archive.manifest.parameters) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let inputs = std::mem::take(&mut archive.manifest.inputs) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let presets = std::mem::take(&mut archive.manifest.presets) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let shared = &archive.manifest; + let manifest = Manifest { + format: shared.format.clone(), + version: shared.version, + name: shared.name.clone(), + graph: shared.graph.clone(), + size: shared.size, + maps: shared.maps.iter().map(|m| MapEntry { usage: m.usage.clone(), file: m.file.clone() }).collect(), + parameters, + inputs, + presets, + source: shared.source.clone(), + }; + let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), archive.read(&map.file).map_err(shared_error)?))).collect::>>()?; + let source = archive.read_source().map_err(shared_error)?; Ok(PortableMaterial { manifest, maps, source }) } -/// Whether `bytes` are a zip holding `entry` (`material.json`: a portable material, -/// `package.json`: a MaterialCraft package). -fn zip_has(bytes: &[u8], entry: &str) -> bool { - zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|mut z| z.by_name(entry).is_ok()) -} - +/// Whether `bytes` contain a portable material manifest within the ZIP entry limit. pub fn is_mcmat(bytes: &[u8]) -> bool { - zip_has(bytes, "material.json") + craft_mcmat::is_material(bytes, 100_000) } pub fn is_mcraft(bytes: &[u8]) -> bool { - zip_has(bytes, "package.json") + let Ok(mut archive) = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 100_000, max_total_bytes: 0 }) else { return false }; + // A portable material may itself contain source.sbs, so it is not a source archive. + if archive.has_duplicate_names() || archive.contains("material.json") { + return false; + } + if archive.contains("package.json") { + return true; + } + (0..archive.len()).any(|i| archive.entry_name(i).ok().flatten().is_some_and(|name| !name.contains('/') && name.to_ascii_lowercase().ends_with(".sbs"))) } /// A baked mesh map (`components` floats per texel, 0..1, rows top first) as a 16-bit PNG @@ -161,13 +168,14 @@ mod tests { /// A `.mcmat` as MaterialCraft writes it (see its `formats/src/material.rs`). pub(crate) fn sample(version: u32) -> Vec { + let source = if version >= 2 { "source.sbs" } else { "source.mcraft" }; let manifest = serde_json::json!({ "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], "maps": [{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}], "parameters": [{"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0.0, "max": 1.0, "value": {"t": "float", "v": 0.25}}], "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}}}], - "source": "source.mcraft", "futureField": true + "source": source, "futureField": true }); let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); @@ -175,7 +183,7 @@ mod tests { z.write_all(manifest.to_string().as_bytes()).unwrap(); z.start_file("maps/baseColor.png", o).unwrap(); z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); - z.start_file("source.mcraft", o).unwrap(); + z.start_file(source, o).unwrap(); z.write_all(b"pkg").unwrap(); z.finish().unwrap().into_inner() } @@ -195,15 +203,29 @@ mod tests { assert_eq!(material.maps[0].0, "baseColor"); assert_eq!(crate::decode_image(&material.maps[0].1).unwrap().width, 4); assert_eq!(material.source, b"pkg"); - assert!(matches!(read_mcmat(&sample(2)), Err(FormatError::Unsupported(_)))); + let current = read_mcmat(&sample(2)).unwrap(); + assert_eq!(current.manifest.source, "source.sbs"); + assert_eq!(current.source, b"pkg"); + assert!(matches!(read_mcmat(&sample(3)), Err(FormatError::Unsupported(_)))); assert!(read_mcmat(b"junk").is_err()); } + #[test] + fn recognizes_both_generations_of_source_archive_without_confusing_portable_materials() { + for entry in ["package.json", "package.sbs"] { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(b"source").unwrap(); + let bytes = zip.finish().unwrap().into_inner(); + assert!(is_mcraft(&bytes), "{entry}"); + } + assert!(!is_mcraft(&sample(2)), "a portable material contains source.sbs too"); + } + #[test] fn an_unbounded_map_list_is_refused() { let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect(); - let manifest = - serde_json::json!({"format": FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); + let manifest = serde_json::json!({"format": craft_mcmat::FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new())); let options = zip::write::SimpleFileOptions::default(); archive.start_file("material.json", options).unwrap(); @@ -218,31 +240,6 @@ mod tests { assert!(matches!(result, Err(FormatError::Malformed { .. }))); } - #[test] - fn entry_read_stops_at_the_remaining_payload_budget() { - let payload = vec![7u8; 1024]; - let mut input = Cursor::new(&payload); - let mut total_bytes = MAX_TOTAL - 8; - - let result = read_entry("maps/extra.png", &mut input, &mut total_bytes); - - assert!(matches!(result, Err(FormatError::TooLarge(_)))); - assert_eq!(input.position(), 9, "only one byte beyond the remaining budget is needed to reject the entry"); - assert_eq!(total_bytes, MAX_TOTAL - 8, "a rejected entry does not consume the payload budget"); - } - - #[test] - fn payload_budget_accepts_the_exact_limit_and_empty_entries() { - let mut total_bytes = MAX_TOTAL - 4; - - let bytes = read_entry("map.png", Cursor::new([1, 2, 3, 4]), &mut total_bytes).unwrap(); - - assert_eq!(bytes, [1, 2, 3, 4]); - assert_eq!(total_bytes, MAX_TOTAL); - assert!(read_entry("empty.mcraft", Cursor::new([]), &mut total_bytes).unwrap().is_empty()); - assert!(matches!(read_entry("extra.png", Cursor::new([1]), &mut total_bytes), Err(FormatError::TooLarge(_)))); - } - #[test] fn mesh_maps_encode_as_16_bit() { let png = mesh_map_png(2, 1, &[0.0, 0.25, 0.5, 1.0]).unwrap(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 1d266ee1..fcce9071 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1828,7 +1828,8 @@ fn link_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, link: app.cook_link(layer); } if ui.button(tr("Open in MaterialCraft")).clicked() { - let path = std::env::temp_dir().join(format!("{}.mcraft", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); + let ext = texturecraft_engine::link_cmds::source_extension(&link.package); + let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); let opened = app .session .link_package(layer) diff --git a/docs/architecture.md b/docs/architecture.md index 2ddcd76b..8d5deb43 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -121,10 +121,10 @@ on the CPU by `render::displace` from the composited height. A fill can carry a `MaterialLink` (`core::layer`): a MaterialCraft graph whose cooked maps are the fill's image sources. `engine::link_cmds` imports `.mcmat` files (`formats::mcmat`), keeps the -`.mcraft` package as a resource, and re-cooks by running `materialcraft-cli` with the link's +`.mcraft` or `.sbs` source as a resource, and re-cooks its named graph by running `materialcraft-cli` with the link's values, the texture set's resolution and its baked mesh maps (`LinkJob::run`, on a worker thread in the UI). Every cook stores its maps under fresh resource names, so undo, redo and the decoded -image cache never disagree. The apps share the file format and the command line, never code. +image cache never disagree. The apps share the `craft-mcmat` format library and the command line; neither depends on the other app. ## Commands and automation diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f255a509..0ead3445 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -325,8 +325,9 @@ of a second. A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is documented in MaterialCraft's `docs/control-protocol.md` § Portable materials) becomes a fill layer whose channel sources are its cooked maps and whose `link` (shown by `project.inspect`) holds the -graph's exposed inputs, presets and image inputs. The apps share the format and the command line, -not code. +graph's exposed inputs, presets and image inputs. Both apps use the shared `craft-mcmat` container. +Versions 1 and 2 are accepted; version 1 contains a legacy JSON `.mcraft` source that current +MaterialCraft cannot reopen, so its cooked maps remain usable but re-cooking needs a compatible older version. | Command | Params | |---|---| @@ -334,9 +335,9 @@ not code. | `material.link.set` | `{layer?, id, value, cook?: true}`: a number, `[..]`, a bool, `"#rrggbb"` or a typed `{"t", "v"}`; re-cooks unless `cook: false` | | `material.link.preset` | `{layer?, name, cook?: true}` | | `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) | -| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` package, to open in MaterialCraft | +| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` or `.sbs` source, to open in MaterialCraft | -Re-cooks run `materialcraft-cli run file.exportMaterial {path, size, values, inputs}`: +Re-cooks use `materialcraft-cli batch` to open the saved graph by name and run `file.exportMaterial` with its size, values and inputs: `$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH` (the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`, From f40dc84f72da5e1d23730db3222186b9967133f7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 12:28:11 +0000 Subject: [PATCH 072/115] 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 073/115] 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 b02a3ab44a9adcc9bf857e1044ed3311bb25eee5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 12:56:36 +0000 Subject: [PATCH 074/115] Exercise linked material cooks under coverage --- crates/engine/src/link_cmds.rs | 59 +++++++++++++++++++- crates/engine/tests/it/materialcraft_link.rs | 6 ++ crates/ui-egui/src/preview_worker.rs | 8 ++- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 459d72e5..3a77ae50 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -252,6 +252,11 @@ impl LinkJob { /// `PATH`); returns `.mcmat` bytes. Blocks for the cook (about a second at 2K). #[cfg(not(target_arch = "wasm32"))] pub fn run(&self) -> Result> { + self.run_with_cli(&materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI")) + } + + #[cfg(not(target_arch = "wasm32"))] + fn run_with_cli(&self, cli: &std::path::Path) -> Result> { let other = |e: String| EngineError::Other(e); let n = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("texturecraft-link-{}-{n}", std::process::id())); @@ -271,8 +276,7 @@ impl LinkJob { } let out = dir.join(format!("out.{MCMAT_EXT}")); let params = json!({"path": utf8(&out)?, "size": self.size, "values": self.values, "inputs": inputs}); - let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI"); - let mut command = quiet(&cli); + let mut command = quiet(cli); if let Some(graph) = &self.graph { // Opening the source starts on its first graph; select the graph saved in the link. let script = json!({"open": src, "steps": [ @@ -496,3 +500,54 @@ fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec, texturecraft } names } + +#[cfg(all(test, unix))] +mod subprocess_tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn cook_uses_the_saved_graph_and_source_type_without_global_environment() { + let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("texturecraft-cook-test-{}-{id}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cli = dir.join("materialcraft-cli"); + let script = r#"#!/bin/sh +set -eu +case "$1" in + batch) + grep -F '"graph":"Second"' "$2" >/dev/null + grep -F '"id":"file.exportMaterial"' "$2" >/dev/null + test -f "$(dirname "$2")/source.sbs" + test -f "$(dirname "$2")/input0.png" + cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" + ;; + run) + test "$(basename "$2")" = "source.mcraft" + cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" + ;; + *) exit 1 ;; +esac +"#; + std::fs::write(&cli, script).unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::write(dir.join("result.mcmat"), b"cooked").unwrap(); + let mut job = LinkJob { + layer: LayerId(1), + package: Arc::new(b"source".to_vec()), + source_ext: "sbs", + graph: Some("Second".into()), + size: 64, + values: Map::new(), + inputs: vec![("curvature".into(), b"png".to_vec())], + }; + assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); + job.graph = None; + job.source_ext = "mcraft"; + assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); + job.graph = Some("wrong".into()); + assert!(job.run_with_cli(&cli).is_err()); + assert!(job.run_with_cli(&dir.join("missing")).is_err()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index 5dd63e02..cbe75532 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -96,6 +96,12 @@ fn version_two_preserves_the_sbs_source_for_future_cooks() { assert_eq!(job.source_ext, "sbs"); assert_eq!(job.graph.as_deref(), Some("Brick_wall")); assert_eq!(job.package.as_slice(), b"package bytes"); + let base = std::env::temp_dir().join(format!("texturecraft-sbs-source-{}", std::process::id())); + let saved = execute(&mut session, "material.link.saveSource", &json!({"layer": id.0, "path": base.to_str().unwrap()})).unwrap(); + let path = saved["path"].as_str().unwrap(); + assert!(path.ends_with(".sbs")); + assert_eq!(std::fs::read(path).unwrap(), b"package bytes"); + let _ = std::fs::remove_file(path); } #[test] diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index c979e3e4..e58901b4 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -206,7 +206,13 @@ mod tests { let mut answers = HashMap::new(); let start = Instant::now(); - while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) { + // Instrumented orb baking can take several minutes on coverage runners. + let timeout = if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) { + Duration::from_secs(600) + } else { + Duration::from_secs(120) + }; + while answers.len() < requests_sent && start.elapsed() < timeout { answers.extend(worker.poll()); std::thread::sleep(Duration::from_millis(10)); } From 4864fbbc78b48762a3dc8223f5f824928409fc78 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:01:22 +0000 Subject: [PATCH 075/115] 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 267eff5c1e3e0fe6f34a282525764172192e9481 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:08:27 +0000 Subject: [PATCH 076/115] Pin merged shared material format --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c45a767d..5a2b05d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -818,7 +818,7 @@ dependencies = [ [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26980ff331efa6ec2cb2b9093dc5a154a8f66bdb#26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" +source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" 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=26980ff331efa6ec2cb2b9093dc5a154a8f66bdb#26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" +source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index f0c79815..28c1404c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,8 +70,8 @@ craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0 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-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 = "26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } # 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 6028051a400e3748ac046e20670f47623c0f90c7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:44:48 +0000 Subject: [PATCH 077/115] 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 078/115] 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 b1cdd044874623f78c39da3ed9912b50768f56c7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:47:19 +0000 Subject: [PATCH 079/115] Adopt shared ZIP64 entry-count guard fix --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5a2b05d4..d63a2ff2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -818,7 +818,7 @@ 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=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" 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=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 28c1404c..65ce6e99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,8 +70,8 @@ craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0 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-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-zip = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # 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 e1d4f99da1262d34b324808848602702f1846bdf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:48:44 +0000 Subject: [PATCH 080/115] 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 0486899125c6761d1962c22b8ef1fa3e6f92bbfe Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Sun, 15 Nov 2026 02:59:04 -0500 Subject: [PATCH 081/115] formats: read FBX vertex colors so ID bakes see them (#422) --- crates/formats/src/mesh_import/abc/mod.rs | 2 +- crates/formats/src/mesh_import/dae.rs | 1 + crates/formats/src/mesh_import/fbx.rs | 14 +++++---- crates/formats/src/mesh_import/mod.rs | 25 ++++++++++++++-- crates/formats/src/mesh_import/scene_tests.rs | 29 ++++++++++++++++++- crates/formats/src/mesh_import/usd/mod.rs | 1 + 6 files changed, 62 insertions(+), 10 deletions(-) diff --git a/crates/formats/src/mesh_import/abc/mod.rs b/crates/formats/src/mesh_import/abc/mod.rs index b0a0ef22..e2abf0be 100644 --- a/crates/formats/src/mesh_import/abc/mod.rs +++ b/crates/formats/src/mesh_import/abc/mod.rs @@ -554,7 +554,7 @@ impl Walk<'_, '_> { Vec2::ZERO } }); - corners.push(Corner { p: *p, n, uv }); + corners.push(Corner { p: *p, n, uv, color: None }); } k = end; if !keep_order { diff --git a/crates/formats/src/mesh_import/dae.rs b/crates/formats/src/mesh_import/dae.rs index d23ea61b..bb104455 100644 --- a/crates/formats/src/mesh_import/dae.rs +++ b/crates/formats/src/mesh_import/dae.rs @@ -356,6 +356,7 @@ fn add_geometry(d: &mut Doc, sink: &mut PolygonSink, geom: &El, m: Mat4, bind: & p: m.transform_point3(Vec3::from(pos)), n: n.map(|n| nm * Vec3::from(n)), uv: t.map(|[u, v]| Vec2::new(u, 1.0 - v)), + color: None, }); } next = next.saturating_add(size); diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 08087283..ba54c5b0 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -1,7 +1,7 @@ //! FBX 6.x and 7.x, binary (32- and 64-bit node records, zlib-compressed arrays) and -//! ASCII: mesh geometry with normals, UVs and per-polygon materials from the layer elements, every -//! Model's transform and parent hierarchy, and the file's unit and axis system (converted to -//! meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of +//! ASCII: mesh geometry with normals, UVs, vertex colors and per-polygon materials from the layer +//! elements, every Model's transform and parent hierarchy, and the file's unit and axis system +//! (converted to meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of //! numbering them and lists properties in `Properties60`; both read into the same scene. //! Materials bring their diffuse color and, when the file embeds it (a Video's `Content`), the //! diffuse texture (for high-poly color map bakes); a texture kept as a file beside the FBX comes @@ -803,9 +803,10 @@ fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex"); + let colors = Layer::read(geometry, "LayerElementColor", "Colors", "ColorIndex"); let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", ""); if vertices.iter().chain(polygon_indices.iter()).any(|v| !v.is_finite()) - || [&normals, &uvs, &materials] + || [&normals, &uvs, &colors, &materials] .into_iter() .flatten() .any(|layer| layer.data.iter().any(|v| !v.is_finite()) || layer.index.as_ref().is_some_and(|index| index.iter().any(|v| !v.is_finite()))) @@ -838,7 +839,10 @@ fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: Vec2::ZERO } }); - corners.push(Corner { p: *p, n, uv }); + // FBX color layers hold one RGBA value per item. + let color = + colors.as_ref().and_then(|l| l.get::<4>(k, control_point, polygon_index)).map(|[r, g, b, a]| Vec4::new(r as f32, g as f32, b as f32, a as f32)); + corners.push(Corner { p: *p, n, uv, color }); if last || k + 1 == polygon_indices.len() { if flip { corners.reverse(); diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 42497364..f0231d11 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -2,7 +2,7 @@ //! world-space [`Mesh`] with one submesh per material and part (glTF node, OBJ object, FBX //! model, COLLADA node, USD Mesh prim, Alembic PolyMesh; unnamed parts take the file stem), materials contiguous, //! glTF UV convention (origin top-left, v down), -//! normals (computed when missing), vertex colors (glTF, OBJ, PLY), UVs (auto-unwrapped when +//! normals (computed when missing), vertex colors (glTF, FBX, OBJ, PLY), UVs (auto-unwrapped when //! missing) and MikkTSpace tangents. glTF, FBX, COLLADA and USD cameras come along as the //! project's camera list. @@ -182,10 +182,11 @@ pub(crate) struct Corner { pub p: Vec3, pub n: Option, pub uv: Option, + pub color: Option, } /// Collects polygons into a [`RawMesh`]: fan triangulation, one vertex per unique corner, and -/// normals / UVs kept only when every corner has them (else computed / unwrapped). +/// normals / UVs / colors kept only when every corner has them (else computed / unwrapped / white). #[derive(Default)] pub(crate) struct PolygonSink { /// Part name of the polygons that follow. @@ -193,10 +194,13 @@ pub(crate) struct PolygonSink { raw: RawMesh, normals: Vec, uvs: Vec, + /// Allocated by the first coloured corner, so a scene without colors pays nothing for them. + colors: Option>, missing_normals: bool, missing_uvs: bool, some_uvs: bool, - ids: HashMap<[u32; 8], u32>, + missing_colors: bool, + ids: HashMap<[u32; 12], u32>, polygon: Vec, triangles: usize, } @@ -213,13 +217,24 @@ impl PolygonSink { self.missing_normals |= c.n.is_none(); self.missing_uvs |= c.uv.is_none(); self.some_uvs |= c.uv.is_some(); + self.missing_colors |= c.color.is_none(); let (n, uv) = (c.n.unwrap_or_default(), c.uv.unwrap_or_default()); + // A corner without a color must not merge with one that has it. + let color_key = c.color.map_or([u32::MAX; 4], |v| v.to_array().map(f32::to_bits)); let key = [c.p.x, c.p.y, c.p.z, n.x, n.y, n.z, uv.x, uv.y].map(f32::to_bits); + let key = [key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], color_key[0], color_key[1], color_key[2], color_key[3]]; let id = match self.ids.entry(key) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { let id = self.raw.positions.len(); check_vertices(id + 1)?; + // White stands in for the corners before the first coloured one. + if c.color.is_some() && self.colors.is_none() { + self.colors = Some(vec![Vec4::ONE; id]); + } + if let Some(colors) = self.colors.as_mut() { + colors.push(c.color.unwrap_or(Vec4::ONE)); + } self.raw.positions.push(c.p); self.normals.push(n); self.uvs.push(uv); @@ -242,8 +257,12 @@ impl PolygonSink { if self.missing_uvs && self.some_uvs { self.warn("some polygons have no UVs; the whole mesh was unwrapped automatically".into()); } + if self.missing_colors && self.colors.is_some() { + self.warn("some polygon corners have no color in the color layer; vertex colors were dropped".into()); + } self.raw.normals = (!self.missing_normals).then_some(self.normals); self.raw.uvs = (!self.missing_uvs).then_some(self.uvs); + self.raw.colors = if self.missing_colors { None } else { self.colors.take() }; self.raw } } diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 00a97922..015724a1 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -3,7 +3,7 @@ use std::io::Write as _; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use super::tests::hammer; use super::*; @@ -298,6 +298,33 @@ fn fbx_binary_32_and_64_bit_compressed_or_not() { } } +/// [`scene`] with a per-polygon-vertex color layer: corner `i` gets `(i/8, 1 - i/8, 0.25, 1)`. +fn colored_scene() -> Vec { + let mut nodes = scene(false); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + let geometry = objects.children.iter_mut().find(|node| node.name == "Geometry").unwrap(); + let colors: Vec = (0..7).flat_map(|i| [i as f64 / 8.0, 1.0 - i as f64 / 8.0, 0.25, 1.0]).collect(); + geometry.children.push(layer( + "LayerElementColor", + "ByPolygonVertex", + "IndexToDirect", + vec![n("Colors", vec![P::Doubles(colors)], vec![]), n("ColorIndex", vec![P::Ints((0..7).collect())], vec![])], + )); + nodes +} + +#[test] +fn fbx_vertex_colors_reach_the_mesh_and_high_polys() { + let nodes = colored_scene(); + let expected: Vec = (0..7).map(|i| Vec4::new(i as f32 / 8.0, 1.0 - i as f32 / 8.0, 0.25, 1.0)).collect(); + for (label, bytes) in [("binary", binary_fbx(&nodes, 7400, false)), ("ascii", ascii_fbx(&nodes).into_bytes())] { + let imported = import_mesh_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(imported.mesh.colors, expected, "{label}: the color layer reaches the mesh"); + let high = import_high_poly_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(high.mesh.colors, expected, "{label}: and the high poly used for ID bakes"); + } +} + /// [`scene`] with a diffuse color on Red and an embedded diffuse texture on Blue. #[test] fn fbx_camera_models_are_capped_during_import() { diff --git a/crates/formats/src/mesh_import/usd/mod.rs b/crates/formats/src/mesh_import/usd/mod.rs index e7f9d0fe..9f6f6d41 100644 --- a/crates/formats/src/mesh_import/usd/mod.rs +++ b/crates/formats/src/mesh_import/usd/mod.rs @@ -576,6 +576,7 @@ impl<'a> Stage<'a> { p: m.transform_point3(Vec3::from(p)), n: normals.as_ref().and_then(|pv| pv.get::<3>(at)).map(|v| nm * Vec3::from(v)), uv: uvs.as_ref().and_then(|pv| pv.get::<2>(at)).map(|[u, v]| Vec2::new(u, 1.0 - v)), + color: None, }); } if flip { From 6e8d421260cd2c8d7f1491f8c7580dc43f22f32d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:34:52 +0000 Subject: [PATCH 082/115] Use shared FBX scene and package readers --- Cargo.lock | 20 +- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 1044 +++---------------------- 3 files changed, 128 insertions(+), 938 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d63a2ff2..b27f7dac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -820,7 +820,7 @@ name = "craft-mcmat" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ - "craft-zip", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31)", "serde", "serde_json", "thiserror 2.0.21", @@ -842,7 +842,11 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89b3a8436bd0d09c3748#d6ed8c20f12188c1f39c89b3a8436bd0d09c3748" +source = "git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6#543098150ffc09914b662e61053d8cddf239bbe6" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6)", + "miniz_oxide 0.9.1", +] [[package]] name = "craft-quit" @@ -924,6 +928,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6#543098150ffc09914b662e61053d8cddf239bbe6" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -4417,7 +4431,7 @@ dependencies = [ "craft-materialx", "craft-mcmat", "craft-mesh", - "craft-zip", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31)", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index 65ce6e99..3a263a6c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "543098150ffc09914b662e61053d8cddf239bbe6", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index ba54c5b0..8faf623c 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -1,960 +1,136 @@ -//! FBX 6.x and 7.x, binary (32- and 64-bit node records, zlib-compressed arrays) and -//! ASCII: mesh geometry with normals, UVs, vertex colors and per-polygon materials from the layer -//! elements, every Model's transform and parent hierarchy, and the file's unit and axis system -//! (converted to meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of -//! numbering them and lists properties in `Properties60`; both read into the same scene. -//! Materials bring their diffuse color and, when the file embeds it (a Video's `Content`), the -//! diffuse texture (for high-poly color map bakes); a texture kept as a file beside the FBX comes -//! along when the FBX is packaged with it ([`package`]: a stored zip of the FBX first and the -//! files under their paths below its folder, which [`read`] opens like the FBX). Camera Models become the file's cameras (lens -//! from their camera NodeAttribute, or the Model's own properties in FBX 6). - -use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; -use std::io::Read as _; - -use base64::Engine as _; -use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; - -use super::external::below; -use super::{ - Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh, check_vertices, lens_fov, zip_entry, -}; +//! FBX scene import through the shared bounded reader. +use super::{Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh}; use crate::{FormatError, Result, malformed}; - +use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; const KIND: &str = "FBX"; -const MAGIC: &[u8] = b"Kaydara FBX Binary \0"; -/// A zip package of an FBX and its texture files ([`package`]). -const ZIP_MAGIC: &[u8] = b"PK\x03\x04"; -/// First FBX version with the object/connection layout read here (6.0). -const MIN_VERSION: i64 = 6000; -/// Deepest node nesting (and Model parent chain) followed. -const MAX_DEPTH: usize = 64; -/// Memory budget for parsed nodes and properties (arrays are held as f64). -const MAX_DECODED_BYTES: usize = 1 << 31; -/// Maximum control points transformed across all mesh instances in one import. -const MAX_INSTANCE_POINTS: usize = 200_000_000; -/// Approximate memory charged per node and per scalar property. -const NODE_COST: usize = 96; -const PROP_COST: usize = 32; - -enum Prop { - I(i64), - F(f64), - S(String), - /// Binary data (`R`), such as an embedded image. - Raw(Vec), - Arr(Vec), -} - -impl Prop { - fn num(&self) -> Option { - match self { - Prop::I(v) => Some(*v as f64), - Prop::F(v) => Some(*v), - _ => None, - } - } -} - -struct Node { - name: String, - props: Vec, - children: Vec, -} - -impl Node { - fn child(&self, name: &str) -> Option<&Node> { - self.children.iter().find(|c| c.name == name) - } - - fn all<'a>(&'a self, name: &'a str) -> impl Iterator { - self.children.iter().filter(move |c| c.name == name) - } - - fn int_at(&self, i: usize) -> Option { - match self.props.get(i) { - Some(Prop::I(v)) => Some(*v), - _ => None, - } - } - - /// Object id: the number (7.x) or the `Class::Name` string (6.x). - fn id_at(&self, i: usize) -> Option { - match self.props.get(i) { - Some(Prop::I(v)) => Some(v.to_string()), - Some(Prop::S(s)) if !s.is_empty() => Some(s.clone()), - _ => None, - } - } - - /// An object's name: after its id (7.x) or the id itself (6.x). - fn object_name(&self) -> &str { - clean_name(if self.int_at(0).is_some() { self.str_at(1) } else { self.str_at(0) }) - } - - /// An object's class (`Mesh`, `Camera`, …): after its name. - fn class(&self) -> &str { - self.str_at(if self.int_at(0).is_some() { 2 } else { 1 }) - } - - fn str_at(&self, i: usize) -> &str { - match self.props.get(i) { - Some(Prop::S(s)) => s, - _ => "", - } - } - - fn child_str(&self, name: &str) -> &str { - self.child(name).map_or("", |c| c.str_at(0)) - } - - /// Embedded file bytes of a Video: binary data, or base64 text in ASCII files. - fn content(&self) -> Option> { - let c = self.child("Content")?; - let bytes = match c.props.first()? { - Prop::Raw(b) => b.clone(), - _ => { - let text: String = c.props.iter().filter_map(|p| if let Prop::S(s) = p { Some(s.as_str()) } else { None }).collect(); - base64::engine::general_purpose::STANDARD.decode(text.trim()).ok()? - } - }; - (!bytes.is_empty()).then_some(bytes) - } - - /// Array payload: a binary array, an ASCII `*N { a: ... }` block or a bare value list. - fn arr(&self) -> Cow<'_, [f64]> { - if let Some(Prop::Arr(a)) = self.props.first() { - return Cow::Borrowed(a); - } - if let Some(a) = self.child("a") { - return a.arr(); - } - Cow::Owned(self.props.iter().map(|p| p.num().unwrap_or(f64::NAN)).collect()) - } - - /// The numbers of entry `name` in Properties70 (`P: name, type, subtype, flags, values`) or - /// Properties60 (`Property: name, type, flags, values`). - fn property(&self, name: &str) -> Option> { - let list = self.child("Properties70").or_else(|| self.child("Properties60"))?; - let first_value = if list.name == "Properties70" { 4 } else { 3 }; - list.children.iter().find(|p| p.str_at(0) == name).map(|p| p.props.iter().skip(first_value).map(|v| v.num().unwrap_or(f64::NAN)).collect()) - } - - fn vec3(&self, name: &str, default: Vec3) -> Vec3 { - match self.property(name).as_deref() { - Some([x, y, z, ..]) => Vec3::new(*x as f32, *y as f32, *z as f32), - _ => default, - } - } - - fn number(&self, name: &str) -> Option { - self.property(name)?.first().copied() - } -} - -/// Charges parsed data against [`MAX_DECODED_BYTES`]. -struct Budget(usize); - -impl Budget { - fn charge(&mut self, bytes: usize) -> Result<()> { - self.0 = self.0.checked_sub(bytes).ok_or_else(|| FormatError::TooLarge(format!("the FBX file decodes to more than {MAX_DECODED_BYTES} bytes")))?; - Ok(()) - } -} - -// --------------------------------------------------------------------------------------------- -// Binary. - -struct Binary<'a> { - b: &'a [u8], - pos: usize, - /// 64-bit node records (version 7500 and later). - wide: bool, - budget: Budget, -} - -impl<'a> Binary<'a> { - fn take(&mut self, n: usize) -> Result<&'a [u8]> { - let s = self.pos.checked_add(n).and_then(|end| self.b.get(self.pos..end)).ok_or_else(|| malformed(KIND, "unexpected end of file"))?; - self.pos += n; - Ok(s) - } - - fn bytes(&mut self) -> Result<[u8; N]> { - let mut a = [0u8; N]; - a.copy_from_slice(self.take(N)?); - Ok(a) - } - - fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.bytes()?) as usize) - } - - fn uint(&mut self) -> Result { - Ok(if self.wide { u64::from_le_bytes(self.bytes()?) } else { u32::from_le_bytes(self.bytes()?) as u64 }) - } - - /// The next node ending at or before `limit`, or None at a null record / the end. - fn node(&mut self, limit: usize, depth: usize) -> Result> { - let header = if self.wide { 25 } else { 13 }; - if limit.saturating_sub(self.pos) < header { - return Ok(None); - } - let (end, nprops, plen) = (self.uint()?, self.uint()?, self.uint()?); - let [name_len] = self.bytes()?; - if end == 0 { - return Ok(None); - } - if depth > MAX_DEPTH { - return Err(malformed(KIND, "nodes are nested too deeply")); - } - let end = usize::try_from(end).ok().filter(|e| *e > self.pos && *e <= limit).ok_or_else(|| malformed(KIND, "node end offset out of range"))?; - self.budget.charge(NODE_COST)?; - let name = String::from_utf8_lossy(self.take(name_len as usize)?).into_owned(); - let props_end = usize::try_from(plen).ok().and_then(|p| self.pos.checked_add(p)).filter(|e| *e <= end); - let props_end = props_end.ok_or_else(|| malformed(KIND, format!("properties of \"{name}\" overrun the node")))?; - let mut props = Vec::new(); - for _ in 0..nprops { - if self.pos >= props_end { - return Err(malformed(KIND, format!("\"{name}\" claims more properties than it holds"))); - } - props.push(self.prop()?); - } - if self.pos > props_end { - return Err(malformed(KIND, format!("properties of \"{name}\" overrun their list"))); - } - self.pos = props_end; - let mut children = Vec::new(); - while let Some(c) = self.node(end, depth + 1)? { - children.push(c); - } - self.pos = end; - Ok(Some(Node { name, props, children })) - } - - fn prop(&mut self) -> Result { - self.budget.charge(PROP_COST)?; - let [ty] = self.bytes()?; - Ok(match ty { - b'Y' => Prop::I(i16::from_le_bytes(self.bytes()?) as i64), - b'C' | b'B' => Prop::I(self.bytes::<1>()?[0] as i64), - b'I' => Prop::I(i32::from_le_bytes(self.bytes()?) as i64), - b'L' => Prop::I(i64::from_le_bytes(self.bytes()?)), - b'F' => Prop::F(f32::from_le_bytes(self.bytes()?) as f64), - b'D' => Prop::F(f64::from_le_bytes(self.bytes()?)), - b'S' => { - let n = self.u32()?; - Prop::S(String::from_utf8_lossy(self.take(n)?).into_owned()) - } - b'R' => { - let n = self.u32()?; - self.budget.charge(n)?; - Prop::Raw(self.take(n)?.to_vec()) - } - b'f' | b'd' | b'l' | b'i' | b'b' => Prop::Arr(self.array(ty)?), - other => return Err(malformed(KIND, format!("unknown property type 0x{other:02x}"))), - }) - } - - fn array(&mut self, value_type: u8) -> Result> { - let (count, encoding, stored) = (self.u32()?, self.u32()?, self.u32()?); - let value_bytes = match value_type { - b'd' | b'l' => 8, - b'f' | b'i' => 4, - _ => 1, - }; - let decoded_bytes = count.checked_mul(value_bytes).ok_or_else(|| malformed(KIND, "array too large"))?; - self.budget.charge(count.saturating_mul(8))?; - - let data = self.take(stored)?; - let raw: Cow<[u8]> = match encoding { - 0 if stored == decoded_bytes => Cow::Borrowed(data), - 1 => { - let mut out = Vec::new(); - flate2::read::ZlibDecoder::new(data) - .take(decoded_bytes as u64 + 1) - .read_to_end(&mut out) - .map_err(|e| malformed(KIND, format!("bad compressed array: {e}")))?; - if out.len() != decoded_bytes { - return Err(malformed(KIND, "compressed array has the wrong length")); - } - - Cow::Owned(out) - } - _ => return Err(malformed(KIND, format!("array encoding {encoding} with {stored} bytes for {count} items"))), - }; - - Ok(match value_type { - b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), - b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), - b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), - b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), - _ => raw.iter().map(|b| *b as f64).collect(), - }) - } -} - -fn parse_binary(b: &[u8]) -> Result<(Vec, i64)> { - let mut r = Binary { b, pos: MAGIC.len(), wide: false, budget: Budget(MAX_DECODED_BYTES) }; - let _reserved: [u8; 2] = r.bytes()?; - let version = u32::from_le_bytes(r.bytes()?); - r.wide = version >= 7500; - let mut nodes = Vec::new(); - while let Some(n) = r.node(b.len(), 0)? { - nodes.push(n); - } - Ok((nodes, version as i64)) -} - -// --------------------------------------------------------------------------------------------- -// ASCII. - -#[derive(Clone, Copy)] -enum Tok<'a> { - /// `name:` - Key(&'a str), - Str(&'a [u8]), - Word(&'a str), - Comma, - Open, - Close, -} - -struct Ascii<'a> { - s: &'a [u8], - pos: usize, - budget: Budget, -} - -impl<'a> Ascii<'a> { - /// The next token and the position after it (the position is not advanced). - fn lex(&self) -> Result, usize)>> { - let mut i = self.pos; - loop { - match self.s.get(i) { - None => return Ok(None), - Some(c) if c.is_ascii_whitespace() => i += 1, - Some(b';') => i += self.s.get(i..).unwrap_or_default().iter().position(|c| *c == b'\n').unwrap_or(self.s.len() - i), - Some(_) => break, - } - } - let rest = self.s.get(i..).unwrap_or_default(); - Ok(Some(match rest.first() { - Some(b',') => (Tok::Comma, i + 1), - Some(b'{') => (Tok::Open, i + 1), - Some(b'}') => (Tok::Close, i + 1), - Some(b'"') => { - let len = rest.get(1..).unwrap_or_default().iter().position(|c| *c == b'"').ok_or_else(|| malformed(KIND, "unterminated string"))?; - (Tok::Str(rest.get(1..1 + len).unwrap_or_default()), i + len + 2) - } - _ => { - let len = rest.iter().position(|c| c.is_ascii_whitespace() || b",{}\":;".contains(c)).unwrap_or(rest.len()); - if len == 0 { - return Err(malformed(KIND, format!("unexpected character at byte {i}"))); - } - let word = std::str::from_utf8(rest.get(..len).unwrap_or_default()).map_err(|_| malformed(KIND, "text is not UTF-8"))?; - if rest.get(len) == Some(&b':') { (Tok::Key(word), i + len + 1) } else { (Tok::Word(word), i + len) } - } - })) - } - - /// Nodes until `}` (left for the caller) or the end. - fn nodes(&mut self, depth: usize) -> Result> { - if depth > MAX_DEPTH { - return Err(malformed(KIND, "nodes are nested too deeply")); - } - let mut out = Vec::new(); - while let Some((tok, after)) = self.lex()? { - match tok { - Tok::Close => break, - Tok::Key(name) => { - self.pos = after; - out.push(self.node(name, depth)?); - } - _ => return Err(malformed(KIND, format!("expected a property name at byte {}", self.pos))), - } - } - Ok(out) - } - - fn node(&mut self, name: &str, depth: usize) -> Result { - self.budget.charge(NODE_COST)?; - let mut props = Vec::new(); - // An empty first value (`Content: , "..."`). - if let Some((Tok::Comma, after)) = self.lex()? { - self.pos = after; - } - while let Some((tok, after)) = self.lex()? { - let prop = match tok { - Tok::Str(s) => Some(Prop::S(String::from_utf8_lossy(s).into_owned())), - // `*N` announces an array's length. - Tok::Word(w) if w.starts_with('*') => None, - Tok::Word(w) => Some(w.parse::().map(Prop::I).or_else(|_| w.parse::().map(Prop::F)).unwrap_or_else(|_| Prop::S(w.to_string()))), - _ => break, - }; - self.pos = after; - if let Some(p) = prop { - self.budget.charge(PROP_COST)?; - props.push(p); - } - match self.lex()? { - Some((Tok::Comma, after)) => self.pos = after, - _ => break, - } - } - let mut children = Vec::new(); - if let Some((Tok::Open, after)) = self.lex()? { - self.pos = after; - children = self.nodes(depth + 1)?; - match self.lex()? { - Some((Tok::Close, after)) => self.pos = after, - _ => return Err(malformed(KIND, format!("\"{name}\" is missing its closing brace"))), - } - } - // Long value lists (arrays) are stored compactly. - if props.len() > 1 && props.iter().all(|p| p.num().is_some()) { - props = vec![Prop::Arr(props.iter().filter_map(Prop::num).collect())]; - } - Ok(Node { name: name.to_string(), props, children }) - } -} - -fn parse_ascii(s: &[u8]) -> Result<(Vec, i64)> { - let mut a = Ascii { s, pos: 0, budget: Budget(MAX_DECODED_BYTES) }; - let nodes = a.nodes(0)?; - if a.lex()?.is_some() { - return Err(malformed(KIND, "unbalanced closing brace")); - } - let version = nodes.iter().find(|n| n.name == "FBXHeaderExtension").and_then(|h| h.child("FBXVersion")).and_then(|v| v.int_at(0)); - let version = version.ok_or_else(|| malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)"))?; - Ok((nodes, version)) -} - -// --------------------------------------------------------------------------------------------- -// Scene. - -/// The bytes of the first of a texture's candidate file paths (relative to the FBX's folder) -/// that exists. type Files<'a> = dyn FnMut(&[&str]) -> Option> + 'a; - -/// An FBX, or a package of one and its texture files. -pub(crate) fn read(bytes: &[u8]) -> Result { - if !bytes.starts_with(ZIP_MAGIC) { - return crate::guard(KIND, || read_inner(bytes, &mut |_| None)); +fn limits() -> craft_mesh::Limits { + craft_mesh::Limits { + max_vertices: super::MAX_VERTICES, + max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_data_bytes: 1 << 31, + max_extras: 100_000, + ..Default::default() } +} + +fn package_limits() -> craft_mesh::fbx::package::PackageLimits { + craft_mesh::fbx::package::PackageLimits { + max_entries: MAX_ZIP_ENTRIES as u64, + max_model_bytes: MAX_MESH_FILE_BYTES, + max_texture_bytes: MAX_TEXTURE_BYTES, + max_total_bytes: MAX_MESH_FILE_BYTES, + } +} + +fn convert(e: craft_mesh::Error) -> FormatError { + match e { + craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s), + craft_mesh::Error::Unsupported(s) => FormatError::Unsupported(s), + e => FormatError::Invalid(e.to_string()), + } +} + +pub(crate) fn read(bytes: &[u8]) -> Result { crate::guard(KIND, || { - let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| malformed(KIND, format!("FBX package: {e}")))?; - if zip.len() > MAX_ZIP_ENTRIES { - return Err(FormatError::TooLarge(format!("the FBX package has more than {MAX_ZIP_ENTRIES} entries"))); + if !craft_mesh::fbx::package::is_package(bytes) { + return read_inner(bytes, &mut |_| None); } - let name = zip.file_names().flatten().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(Cow::into_owned); - let name = name.ok_or_else(|| malformed(KIND, "the package contains no FBX file"))?; - let fbx = zip_entry(&mut zip, &name, MAX_MESH_FILE_BYTES) - .ok_or_else(|| FormatError::TooLarge("the packaged FBX is unreadable or larger than 2 GiB".into()))?; - if fbx.starts_with(ZIP_MAGIC) { - return Err(malformed(KIND, "the package holds another package")); - } - read_inner(&fbx, &mut |paths| paths.iter().find_map(|p| zip_entry(&mut zip, &below(p)?, MAX_TEXTURE_BYTES))) + let mut package = craft_mesh::fbx::package::Package::open(bytes, package_limits()).map_err(convert)?; + let fbx = package.model().map_err(convert)?; + read_inner(&fbx, &mut |paths| package.texture(paths)) }) } -/// An FBX whose base color textures are files, as a package holding it (first) and the files -/// `found` has, under their paths below its folder; None when it found none (or `bytes` is a -/// package already). Also the texture paths it could not find. pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) -> Option>) -> Result<(Option>, Vec)> { - if bytes.starts_with(ZIP_MAGIC) { + if craft_mesh::fbx::package::is_package(bytes) { return Ok((None, Vec::new())); } crate::guard(KIND, || { - let (mut files, mut missing): (Vec<(String, Vec)>, Vec) = (Vec::new(), Vec::new()); - read_inner(bytes, &mut |paths| { - if let Some((_, data)) = files.iter().find(|(n, _)| paths.iter().any(|p| below(p).as_ref() == Some(n))) { - return Some(data.clone()); - } - for p in paths { - if let (Some(name), Some(data)) = (below(p), found(p).filter(|d| d.len() as u64 <= MAX_TEXTURE_BYTES)) { - files.push((name, data.clone())); - return Some(data); - } - } - // A texture is missing when none of its paths was found; named by its first. - if let Some(first) = paths.first().filter(|f| !missing.iter().any(|m| m == *f)) { - missing.push(first.to_string()); - } - None - })?; - if files.is_empty() { - return Ok((None, missing)); + let limits = limits(); + let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(convert)?; + if doc.version == 0 { + return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - let total = files.iter().fold(bytes.len() as u64, |t, (_, d)| t.saturating_add(d.len() as u64)); - if total > MAX_MESH_FILE_BYTES { - return Err(FormatError::TooLarge("the FBX and its textures exceed 2 GiB".into())); - } - let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh.fbx"); - Ok((Some(crate::mesh_export::usd::usdz(leaf, bytes, &files)?), missing)) + doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true }).map_err(convert)?; + craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) }) } fn read_inner(bytes: &[u8], files: &mut Files) -> Result { - let (nodes, version) = if bytes.starts_with(MAGIC) { parse_binary(bytes)? } else { parse_ascii(bytes)? }; - if version < MIN_VERSION { - return Err(FormatError::Unsupported(format!("FBX version {version} (re-export as FBX 2006 / 6.1 or newer)"))); + let limits = limits(); + let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(convert)?; + if doc.version == 0 { + return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - let root = |name: &str| nodes.iter().find(|n| n.name == name); - let objects = root("Objects").ok_or_else(|| malformed(KIND, "the file has no Objects"))?; - let (mut geometries, mut models, mut materials) = (HashMap::new(), HashMap::new(), HashMap::new()); - let (mut textures, mut videos, mut attributes) = (HashMap::new(), HashMap::new(), HashMap::new()); - // (geometry, model) instances; an FBX 6 Model holds its geometry itself. - let mut instances: Vec<(String, Option)> = Vec::new(); - for o in &objects.children { - let Some(id) = o.id_at(0) else { continue }; - match o.name.as_str() { - "Geometry" if o.child("Vertices").is_some() => geometries.insert(id, o), - "Model" => { - if o.child("Vertices").is_some() { - geometries.insert(id.clone(), o); - instances.push((id.clone(), Some(id.clone()))); - } - models.insert(id, o) - } - "Material" => materials.insert(id, o), - "Texture" => textures.insert(id, o), - "Video" => videos.insert(id, o), - "NodeAttribute" => attributes.insert(id, o), - _ => None, - }; - } - // Model parents, and each Model's materials in slot order. - let mut parents: HashMap = HashMap::new(); - let mut slots: HashMap> = HashMap::new(); - let mut attribute_of: HashMap = HashMap::new(); - let connections: Vec<&Node> = root("Connections").into_iter().flat_map(|c| c.all("C").chain(c.all("Connect"))).collect(); - for c in &connections { - let (Some(child), Some(parent)) = (c.id_at(1), c.id_at(2)) else { continue }; - if c.str_at(0) != "OO" || child == parent || !models.contains_key(&parent) { - continue; - } - if models.contains_key(&child) { - parents.insert(child, parent); - } else if geometries.contains_key(&child) { - instances.push((child, Some(parent))); - } else if let Some(m) = materials.get(&child) { - slots.entry(parent).or_default().push(material_name(&child, m)); - } else if let Some(a) = attributes.get(&child) { - attribute_of.insert(parent, *a); - } - } - // Repeated connections describe the same instance; keep distinct model placements in order. - let mut seen_instances = HashSet::new(); - instances.retain(|instance| seen_instances.insert(instance.clone())); - let placed: HashSet<&String> = instances.iter().map(|(g, _)| g).collect(); - let mut unplaced: Vec = geometries.keys().filter(|g| !placed.contains(g)).cloned().collect(); - unplaced.sort_unstable(); - instances.extend(unplaced.into_iter().map(|g| (g, None))); - - let base_colors = base_colors(&materials, &textures, &videos, &connections, files); - let global = global_transform(root("GlobalSettings").or_else(|| objects.child("GlobalSettings"))); + let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; + let scene = + doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true }).map_err(convert)?; + let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); + let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); let mut sink = PolygonSink::default(); - let mut remaining_points = MAX_INSTANCE_POINTS; - let no_slots = Vec::new(); - for (geom, model) in instances { - let Some(g) = geometries.get(&geom) else { continue }; - let m = match model.as_ref().and_then(|m| models.get(m).map(|n| (m, n))) { - Some((id, node)) => { - sink.part = node.object_name().to_string(); - world(&models, &parents, id)? * geometric(node) + let mut cameras = Vec::new(); + let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, String::new(), 0usize)).collect(); + let mut visited = 0usize; + let mut points = 0usize; + while let Some((id, parent, inherited, depth)) = stack.pop() { + visited += 1; + if visited > limits.max_nodes || depth > limits.max_depth { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its traversal limit".into())); + } + let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; + let world = parent * to_mat(node.transform); + let part = if node.name.ends_with(" geometry") { inherited } else { node.name.clone() }; + for child in node.children.iter().rev() { + stack.push((*child, world, part.clone(), depth + 1)); + } + if let Some(index) = node.camera { + if cameras.len() < super::MAX_CAMERAS { + if let Some(camera) = scene.cameras.get(index) { + let (fov, ortho) = match camera.projection { + craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), + craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), + }; + cameras.push(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); + } } - None => { - sink.part.clear(); - Mat4::IDENTITY + } + let Some(index) = node.mesh else { continue }; + let mesh = scene.meshes.get(index).ok_or_else(|| malformed(KIND, "mesh index out of range"))?; + points = points.checked_add(mesh.positions.len()).ok_or_else(|| FormatError::TooLarge("FBX instance work overflow".into()))?; + if points > 200_000_000 { + return Err(FormatError::TooLarge("FBX instances exceed the 200000000 control-point work limit".into())); + } + let normal_transform = Mat3::from_mat4(world).inverse().transpose(); + let flip = world.determinant() < 0.0; + sink.part = part; + for group in &mesh.parts { + let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); + for face in group.faces() { + let mut corners = Vec::with_capacity(face.len()); + for c in face { + let p = mesh.positions.get(c.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; + let p = world.transform_point3(Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32)); + let n = mesh.normals.get(c.normal as usize).map(|n| normal_transform * Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); + let uv = mesh.uv_sets.first().and_then(|set| set.get(c.uv as usize)).map(|v| Vec2::new(v[0], v[1])); + let color = mesh.colors.get(c.position as usize).copied().map(Vec4::from_array); + corners.push(Corner { p, n, uv, color }); + } + if flip { + corners.reverse(); + } + sink.polygon(material, &corners)?; } - }; - let names = model.as_ref().and_then(|m| slots.get(m)).unwrap_or(&no_slots); - add_geometry(&mut sink, g, global * m, names, &mut remaining_points)?; + } + } + if visited < scene.nodes.len() { + return Err(malformed(KIND, "cycle in model hierarchy")); + } + for warning in scene.warnings { + sink.warn(warning); } let mut raw = sink.finish(); - raw.base_colors = base_colors; - // In file order; FBX 6's built-in "Producer" views are not the scene's cameras. - for o in objects.children.iter().filter(|o| o.name == "Model" && o.class() == "Camera" && !o.object_name().starts_with("Producer ")) { - if raw.cameras.len() >= super::MAX_CAMERAS { - break; - } - let Some(id) = o.id_at(0) else { continue }; - if let Ok(m) = world(&models, &parents, &id) { - raw.cameras.push(camera(o, attribute_of.get(&id).copied().unwrap_or(o), global * m)); - } - } + raw.cameras = cameras; + raw.base_colors = colors.into_iter().map(|c| RawBaseColor { material: c.name, factor: Vec4::from_array(c.factor), image: c.image }).collect(); Ok(raw) } - -/// A camera Model at `m` with its lens in `lens`: FBX cameras look down +X with +Y up. The -/// vertical field of view comes from the focal length (mm) over the film height (inches). -/// shortcut: `OrthoZoom` is taken as the orthographic half view height in scene units; check it -/// against an exporter's orthographic camera when one is at hand. -fn camera(model: &Node, lens: &Node, m: Mat4) -> RawCamera { - let num = |k: &str| lens.number(k).map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0); - let fov = match num("FocalLength") { - Some(f) => lens_fov(f, num("FilmHeight").unwrap_or(0.612) * 25.4), - None => num("FieldOfViewY").or_else(|| num("FieldOfView")).unwrap_or(40.0), - }; - let ortho = (lens.number("CameraProjectionType") == Some(1.0)).then(|| num("OrthoZoom").unwrap_or(1.0)); - RawCamera::placed(model.object_name().to_string(), m, Vec3::X, fov, ortho) -} - -/// A material's name in the mesh: its object name, or `Material_` when it has none. -fn material_name(id: &str, m: &Node) -> String { - let name = m.object_name(); - if name.is_empty() { format!("Material_{id}") } else { name.to_string() } -} - -/// Preserve material colors independently of textures for ID baking -fn base_colors( - materials: &HashMap, - textures: &HashMap, - videos: &HashMap, - connections: &[&Node], - files: &mut Files, -) -> Vec { - // Texture → its Video, material → its diffuse texture (a property connection wins). - let (mut video_of, mut diffuse) = (HashMap::new(), HashMap::new()); - for c in connections { - let (Some(child), Some(parent)) = (c.id_at(1), c.id_at(2)) else { continue }; - if videos.contains_key(&child) && textures.contains_key(&parent) { - video_of.insert(parent, child); - } else if textures.contains_key(&child) && materials.contains_key(&parent) { - match (c.str_at(0), c.str_at(3)) { - ("OP", "DiffuseColor" | "Maya|baseColor") => { - diffuse.insert(parent, child); - } - ("OO", _) => { - diffuse.entry(parent).or_insert(child); - } - _ => {} - } - } - } - let mut out: Vec = materials - .iter() - .filter_map(|(id, m)| { - let texture = diffuse.get(id); - let (video, tex) = (texture.and_then(|t| video_of.get(t)).and_then(|v| videos.get(v)), texture.and_then(|t| textures.get(t))); - // Embedded content first, then the file the texture (or its video) names. - let image = video.or(tex).and_then(|n| n.content()).or_else(|| [tex, video].into_iter().flatten().find_map(|n| texture_file(n, files))); - let diffuse_color = m.property("DiffuseColor"); - let factor = match diffuse_color.as_deref() { - Some([r, g, b, ..]) => { - let f = m.number("DiffuseFactor").unwrap_or(1.0); - Vec4::new((r * f) as f32, (g * f) as f32, (b * f) as f32, 1.0) - } - _ => Vec4::ONE, - }; - (factor.is_finite() && (image.is_some() || diffuse_color.is_some())).then(|| RawBaseColor { material: material_name(id, m), factor, image }) - }) - .collect(); - out.sort_by(|a, b| a.material.cmp(&b.material)); - out -} - -/// The file a Texture or Video names: its relative path, else its absolute path's file name -/// (looked for in the FBX's folder). -fn texture_file(n: &Node, files: &mut Files) -> Option> { - let relative = n.child_str("RelativeFilename"); - let absolute = [n.child_str("FileName"), n.child_str("Filename")].into_iter().find(|s| !s.is_empty()).unwrap_or_default(); - let leaf = absolute.rsplit(['/', '\\']).next().unwrap_or_default(); - let mut paths: Vec<&str> = Vec::new(); - for p in [relative, leaf] { - if !p.is_empty() && !paths.contains(&p) { - paths.push(p); - } - } - if paths.is_empty() { None } else { files(&paths) } -} - -/// `Name\0\1Class` (binary) or `Class::Name` (ASCII) to `Name`. -fn clean_name(s: &str) -> &str { - match s.split_once("\u{0}\u{1}") { - Some((name, _)) => name, - None => s.split_once("::").map_or(s, |(_, name)| name), - } -} - -/// Unit scale to meters and the file's axis system to Y up (+Z front, +X right). -fn global_transform(settings: Option<&Node>) -> Mat4 { - let get = |name: &str, default: f64| settings.and_then(|s| s.number(name)).filter(|v| v.is_finite()).unwrap_or(default); - let unit = get("UnitScaleFactor", 1.0); - let unit = if unit > 0.0 { unit / 100.0 } else { 0.01 }; - let axis = |a: &str, s: &str, default: f64| (get(a, default) as i64, if get(s, 1.0) < 0.0 { -1.0 } else { 1.0 }); - let [(right, rs), (up, us), (front, fs)] = - [axis("CoordAxis", "CoordAxisSign", 0.0), axis("UpAxis", "UpAxisSign", 1.0), axis("FrontAxis", "FrontAxisSign", 2.0)]; - let basis = |a: i64| [Vec3::X, Vec3::Y, Vec3::Z].get(a as usize).copied().filter(|_| a >= 0); - let rows = match (basis(right), basis(up), basis(front)) { - (Some(r), Some(u), Some(f)) if r.cross(u).dot(f).abs() > 0.5 => Mat3::from_cols(r * rs, u * us, f * fs).transpose(), - _ => Mat3::IDENTITY, - }; - Mat4::from_mat3(rows) * Mat4::from_scale(Vec3::splat(unit as f32)) -} - -/// Euler rotation in degrees, `order` as FBX RotationOrder (0 = XYZ: X applied first). -fn euler(deg: Vec3, order: i64) -> Mat4 { - use Vec3 as V; - let axes = match order { - 1 => [V::X, V::Z, V::Y], - 2 => [V::Y, V::Z, V::X], - 3 => [V::Y, V::X, V::Z], - 4 => [V::Z, V::X, V::Y], - 5 => [V::Z, V::Y, V::X], - _ => [V::X, V::Y, V::Z], - }; - axes.iter().fold(Mat4::IDENTITY, |m, a| Mat4::from_axis_angle(*a, deg.dot(*a).to_radians()) * m) -} - -/// A Model's local transform: T · Roff · Rp · Rpre · R · Rpost⁻¹ · Rp⁻¹ · Soff · Sp · S · Sp⁻¹. -fn local(m: &Node) -> Mat4 { - let t = |name: &str| Mat4::from_translation(m.vec3(name, Vec3::ZERO)); - let order = m.number("RotationOrder").unwrap_or(0.0) as i64; - let (rp, sp) = (m.vec3("RotationPivot", Vec3::ZERO), m.vec3("ScalingPivot", Vec3::ZERO)); - t("Lcl Translation") - * t("RotationOffset") - * Mat4::from_translation(rp) - * euler(m.vec3("PreRotation", Vec3::ZERO), 0) - * euler(m.vec3("Lcl Rotation", Vec3::ZERO), order) - * euler(m.vec3("PostRotation", Vec3::ZERO), 0).inverse() - * Mat4::from_translation(-rp) - * t("ScalingOffset") - * Mat4::from_translation(sp) - * Mat4::from_scale(m.vec3("Lcl Scaling", Vec3::ONE)) - * Mat4::from_translation(-sp) -} - -/// The geometry offset of a Model (not inherited by its children). -fn geometric(m: &Node) -> Mat4 { - Mat4::from_translation(m.vec3("GeometricTranslation", Vec3::ZERO)) - * euler(m.vec3("GeometricRotation", Vec3::ZERO), 0) - * Mat4::from_scale(m.vec3("GeometricScaling", Vec3::ONE)) -} - -fn world(models: &HashMap, parents: &HashMap, id: &str) -> Result { - let mut m = Mat4::IDENTITY; - let mut cur = Some(id); - for _ in 0..=MAX_DEPTH { - let Some(node) = cur.and_then(|c| models.get(c)) else { return Ok(m) }; - m = local(node) * m; - cur = cur.and_then(|c| parents.get(c)).map(String::as_str); - } - Err(malformed(KIND, "the Model hierarchy is nested too deeply (or cyclic)")) -} - -#[derive(Clone, Copy)] -enum Mapping { - PolygonVertex, - ControlPoint, - Polygon, - AllSame, -} - -/// One LayerElement's items, optionally through an index array. -struct Layer<'a> { - mapping: Mapping, - data: Cow<'a, [f64]>, - index: Option>, -} - -impl Layer<'_> { - /// Element `index` names the index array (empty: the data is never indexed). - fn read<'a>(geom: &'a Node, element: &str, data: &str, index: &str) -> Option> { - let el = geom.children.iter().filter(|c| c.name == element).min_by_key(|e| e.int_at(0) != Some(0))?; - let mapping = match el.child_str("MappingInformationType") { - "ByPolygonVertex" => Mapping::PolygonVertex, - "ByVertice" | "ByVertex" | "ByControlPoint" => Mapping::ControlPoint, - "ByPolygon" => Mapping::Polygon, - "AllSame" => Mapping::AllSame, - _ => return None, - }; - let indexed = !index.is_empty() && matches!(el.child_str("ReferenceInformationType"), "IndexToDirect" | "Index"); - let index = if indexed { Some(el.child(index)?.arr()) } else { None }; - Some(Layer { mapping, data: el.child(data)?.arr(), index }) - } - - /// The `W` numbers of polygon vertex `k` (control point `cp`, polygon `poly`). - fn get(&self, k: usize, cp: usize, poly: usize) -> Option<[f64; W]> { - let i = match self.mapping { - Mapping::PolygonVertex => k, - Mapping::ControlPoint => cp, - Mapping::Polygon => poly, - Mapping::AllSame => 0, - }; - let i = match &self.index { - Some(ix) => Some(*ix.get(i)?).filter(|v| *v >= 0.0)? as usize, - None => i, - }; - let start = i.checked_mul(W)?; - self.data.get(start..start.checked_add(W)?)?.try_into().ok() - } -} - -fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String], remaining_points: &mut usize) -> Result<()> { - let vertices = geometry.child("Vertices").map(Node::arr).unwrap_or_default(); - check_vertices(vertices.len() / 3)?; - *remaining_points = remaining_points - .checked_sub(vertices.len() / 3) - .ok_or_else(|| FormatError::TooLarge(format!("FBX instances exceed the {MAX_INSTANCE_POINTS} control-point work limit")))?; - let points: Vec = vertices.as_chunks::<3>().0.iter().map(|c| transform.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); - let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); - let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); - let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex"); - let colors = Layer::read(geometry, "LayerElementColor", "Colors", "ColorIndex"); - let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", ""); - if vertices.iter().chain(polygon_indices.iter()).any(|v| !v.is_finite()) - || [&normals, &uvs, &colors, &materials] - .into_iter() - .flatten() - .any(|layer| layer.data.iter().any(|v| !v.is_finite()) || layer.index.as_ref().is_some_and(|index| index.iter().any(|v| !v.is_finite()))) - { - return Err(malformed(KIND, "mesh array contains a non-numeric or non-finite value")); - } - let normal_transform = Mat3::from_mat4(transform).inverse().transpose(); - let flip = transform.determinant() < 0.0; - let (mut corners, mut polygon_index, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); - - for (k, &v) in polygon_indices.iter().enumerate() { - // The last corner of each polygon is stored as -(index + 1) - let (control_point, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) }; - let p = points - .get(control_point as usize) - .filter(|_| control_point.fract() == 0.0) - .ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?; - let control_point = control_point as usize; - let n = normals.as_ref().and_then(|l| { - let n = l.get(k, control_point, polygon_index).map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32)); - bad_normals += usize::from(n.is_none()); - n - }); - - // A UV layer with holes keeps its layout: missing items read as 0, 0 - let uv = uvs.as_ref().map(|l| match l.get(k, control_point, polygon_index) { - Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), - None => { - bad_uvs += 1; - Vec2::ZERO - } - }); - // FBX color layers hold one RGBA value per item. - let color = - colors.as_ref().and_then(|l| l.get::<4>(k, control_point, polygon_index)).map(|[r, g, b, a]| Vec4::new(r as f32, g as f32, b as f32, a as f32)); - corners.push(Corner { p: *p, n, uv, color }); - if last || k + 1 == polygon_indices.len() { - if flip { - corners.reverse(); - } - let slot = materials.as_ref().and_then(|l| l.get(polygon_index, polygon_index, polygon_index)).map_or(0.0, |[s]| s); - let name = slots.get(slot as usize).filter(|_| slot >= 0.0).map_or("Default", String::as_str); - sink.polygon(name, &corners)?; - corners.clear(); - polygon_index += 1; - } - } - - if bad_normals > 0 { - sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); - } - if bad_uvs > 0 { - sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); - } - - Ok(()) -} - -#[cfg(test)] -mod instance_budget_tests { - use super::*; - - #[test] - fn ascii_array_keeps_invalid_values_in_place() { - let (nodes, _) = parse_ascii( - br#"FBXHeaderExtension: { FBXVersion: 7400 } -Vertices: 1, 1.#INF, 3, "x", 5 -"#, - ) - .unwrap(); - let values = nodes[1].arr(); - assert_eq!(values.len(), 5); - assert!(values[1].is_nan() && values[3].is_nan()); - assert_eq!((values[0], values[2], values[4]), (1.0, 3.0, 5.0)); - } - - #[test] - fn ascii_bad_vertex_is_rejected() { - let (nodes, _) = parse_ascii( - br#"FBXHeaderExtension: { FBXVersion: 7400 } -Geometry: { Vertices: 0, 0, 0, 1, -1.#IND, 0, 0, 1, 0 -PolygonVertexIndex: 0, 1, -3 } -"#, - ) - .unwrap(); - let mut remaining = usize::MAX; - let result = add_geometry(&mut PolygonSink::default(), &nodes[1], Mat4::IDENTITY, &[], &mut remaining); - assert!(result.is_err()); - } - - #[test] - fn ascii_bad_index_and_uv_are_rejected() { - for payload in [ - "PolygonVertexIndex: 0, oops, -3", - "PolygonVertexIndex: 0, 1, -3\nLayerElementUV: 0 { MappingInformationType: \"ByPolygonVertex\"\nReferenceInformationType: \"Direct\"\nUV: 0, 0, oops, 1, 1, 0 }", - ] { - let source = format!("FBXHeaderExtension: {{ FBXVersion: 7400 }}\nGeometry: {{ Vertices: 0, 0, 0, 1, 0, 0, 0, 1, 0\n{payload} }}"); - let (nodes, _) = parse_ascii(source.as_bytes()).unwrap(); - let mut remaining = usize::MAX; - assert!(add_geometry(&mut PolygonSink::default(), &nodes[1], Mat4::IDENTITY, &[], &mut remaining).is_err()); - } - } - - #[test] - fn ascii_transform_metadata_does_not_shift_values() { - let (nodes, _) = parse_ascii( - br#"FBXHeaderExtension: { FBXVersion: 7400 } -Model: { Properties70: { P: "Lcl Translation", "Lcl Translation", "", "A", 1, 2, 3 } } -"#, - ) - .unwrap(); - assert_eq!(nodes[1].property("Lcl Translation"), Some(vec![1.0, 2.0, 3.0])); - let (nodes, _) = parse_ascii( - br#"FBXHeaderExtension: { FBXVersion: 7400 } -Model: { Properties60: { Property: "Lcl Translation", "Lcl Translation", "A", 1, 2, 3 } } -"#, - ) - .unwrap(); - assert_eq!(nodes[1].property("Lcl Translation"), Some(vec![1.0, 2.0, 3.0])); - } - - #[test] - fn malformed_transform_value_keeps_its_position_in_both_property_formats() { - for (list, entry) in [ - ("Properties70", "P: \"Lcl Translation\", \"Lcl Translation\", \"\", \"A\", 1, oops, 3"), - ("Properties60", "Property: \"Lcl Translation\", \"Lcl Translation\", \"A\", 1, oops, 3"), - ] { - let source = format!("FBXHeaderExtension: {{ FBXVersion: 7400 }}\nModel: {{ {list}: {{ {entry} }} }}"); - let (nodes, _) = parse_ascii(source.as_bytes()).unwrap(); - let values = nodes[1].property("Lcl Translation").unwrap(); - assert_eq!(values.len(), 3); - assert_eq!((values[0], values[2]), (1.0, 3.0)); - assert!(values[1].is_nan()); - } - } - - #[test] - fn instance_points_are_charged_before_transforming_each_copy() { - let geometry = Node { - name: "Geometry".into(), - props: vec![], - children: vec![Node { name: "Vertices".into(), props: vec![Prop::Arr(vec![0.0; 9])], children: vec![] }], - }; - let mut sink = PolygonSink::default(); - let mut remaining = 5; - add_geometry(&mut sink, &geometry, Mat4::IDENTITY, &[], &mut remaining).unwrap(); - assert_eq!(remaining, 2); - assert!(matches!(add_geometry(&mut sink, &geometry, Mat4::IDENTITY, &[], &mut remaining), Err(FormatError::TooLarge(_)))); - assert_eq!(remaining, 2); - } -} From a5fb695381e22c07935e2aca3c5b336d70fce32f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:38:53 +0000 Subject: [PATCH 083/115] Preserve strict FBX geometry behavior --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 13 ++++++++++--- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b27f7dac..e94d4e44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6#543098150ffc09914b662e61053d8cddf239bbe6" +source = "git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0#4a84c00372972fb99755cba34978a5e73387c3f0" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6#543098150ffc09914b662e61053d8cddf239bbe6" +source = "git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0#4a84c00372972fb99755cba34978a5e73387c3f0" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 3a263a6c..a4a3231c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "543098150ffc09914b662e61053d8cddf239bbe6", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "4a84c00372972fb99755cba34978a5e73387c3f0", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 8faf623c..7b9fb643 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -8,6 +8,11 @@ fn limits() -> craft_mesh::Limits { craft_mesh::Limits { max_vertices: super::MAX_VERTICES, max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_face_corners: super::MAX_VERTICES, + max_meshes: super::MAX_VERTICES, + max_parts: super::MAX_VERTICES, + max_materials: super::MAX_VERTICES, + max_nodes: super::MAX_VERTICES, max_data_bytes: 1 << 31, max_extras: 100_000, ..Default::default() @@ -52,7 +57,8 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) if doc.version == 0 { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true }).map_err(convert)?; + doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true }) + .map_err(convert)?; craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) }) } @@ -64,8 +70,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; - let scene = - doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true }).map_err(convert)?; + let scene = doc + .scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true }) + .map_err(convert)?; let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); let mut sink = PolygonSink::default(); From 8d593fdebec93c9b5ff8468aa17cad6f97aaa47b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:39:42 +0000 Subject: [PATCH 084/115] Keep FBX UV layers with missing corners --- crates/formats/src/mesh_import/fbx.rs | 46 ++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 7b9fb643..897ebd99 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -111,6 +111,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let normal_transform = Mat3::from_mat4(world).inverse().transpose(); let flip = world.determinant() < 0.0; sink.part = part; + let (mut bad_normals, mut bad_uvs) = (0usize, 0usize); for group in &mesh.parts { let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); for face in group.faces() { @@ -119,7 +120,16 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let p = mesh.positions.get(c.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; let p = world.transform_point3(Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32)); let n = mesh.normals.get(c.normal as usize).map(|n| normal_transform * Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); - let uv = mesh.uv_sets.first().and_then(|set| set.get(c.uv as usize)).map(|v| Vec2::new(v[0], v[1])); + if !mesh.normals.is_empty() && n.is_none() { + bad_normals += 1; + } + let uv = mesh.uv_sets.first().map(|set| match set.get(c.uv as usize) { + Some(v) => Vec2::new(v[0], v[1]), + None => { + bad_uvs += 1; + Vec2::ZERO + } + }); let color = mesh.colors.get(c.position as usize).copied().map(Vec4::from_array); corners.push(Corner { p, n, uv, color }); } @@ -129,6 +139,12 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { sink.polygon(material, &corners)?; } } + if bad_normals > 0 { + sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); + } + if bad_uvs > 0 { + sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); + } } if visited < scene.nodes.len() { return Err(malformed(KIND, "cycle in model hierarchy")); @@ -141,3 +157,31 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { raw.base_colors = colors.into_iter().map(|c| RawBaseColor { material: c.name, factor: Vec4::from_array(c.factor), image: c.image }).collect(); Ok(raw) } + +#[cfg(test)] +mod tests { + #[test] + fn incomplete_uv_layer_keeps_other_uvs() { + let bytes = br#"FBXHeaderExtension: { FBXVersion: 7400 } +Objects: { + Geometry: 1, "Geometry::G", "Mesh" { + Vertices: 0,0,0,1,0,0,0,1,0 + PolygonVertexIndex: 0,1,-3 + LayerElementUV: 0 { + MappingInformationType: "ByPolygonVertex" + ReferenceInformationType: "IndexToDirect" + UV: 0.25,0.5, 0.75,0.5 + UVIndex: 0,1 + } + } + Model: 2, "Model::M", "Mesh" {} +} +Connections: { C: "OO",1,2 } +"#; + let raw = super::read(bytes).unwrap(); + let uvs = raw.uvs.unwrap(); + assert!(uvs.contains(&texturecraft_geom::glam::Vec2::new(0.25, 0.5))); + assert!(uvs.contains(&texturecraft_geom::glam::Vec2::ZERO)); + assert!(raw.warnings.iter().any(|w| w.contains("1 polygon corners have no UV"))); + } +} From 5a70a033cc6cd9e7ea6959db5218a1bf2e6e5959 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:41:48 +0000 Subject: [PATCH 085/115] Use strict shared FBX record parsing --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e94d4e44..63ba1709 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0#4a84c00372972fb99755cba34978a5e73387c3f0" +source = "git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f#17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0#4a84c00372972fb99755cba34978a5e73387c3f0" +source = "git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f#17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a4a3231c..c6f1dcfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "4a84c00372972fb99755cba34978a5e73387c3f0", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 897ebd99..0c9d707f 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -53,7 +53,7 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) } crate::guard(KIND, || { let limits = limits(); - let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(convert)?; + let doc = craft_mesh::fbx::read_document_strict(bytes, &limits).map_err(convert)?; if doc.version == 0 { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } @@ -65,7 +65,7 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let limits = limits(); - let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(convert)?; + let doc = craft_mesh::fbx::read_document_strict(bytes, &limits).map_err(convert)?; if doc.version == 0 { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } From cf85d478a29dc646e92a9b05a00d0c708f1159f7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:42:20 +0000 Subject: [PATCH 086/115] Keep FBX cameras in file order --- crates/formats/src/mesh_import/fbx.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 0c9d707f..470cf433 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -77,6 +77,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); let mut sink = PolygonSink::default(); let mut cameras = Vec::new(); + cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, String::new(), 0usize)).collect(); let mut visited = 0usize; let mut points = 0usize; @@ -87,19 +88,17 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; let world = parent * to_mat(node.transform); - let part = if node.name.ends_with(" geometry") { inherited } else { node.name.clone() }; + let part = if node.name == format!("{inherited} geometry") { inherited } else { node.name.clone() }; for child in node.children.iter().rev() { stack.push((*child, world, part.clone(), depth + 1)); } if let Some(index) = node.camera { - if cameras.len() < super::MAX_CAMERAS { - if let Some(camera) = scene.cameras.get(index) { - let (fov, ortho) = match camera.projection { - craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), - craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), - }; - cameras.push(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); - } + if let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) { + let (fov, ortho) = match camera.projection { + craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), + craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), + }; + *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); } } let Some(index) = node.mesh else { continue }; @@ -153,7 +152,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { sink.warn(warning); } let mut raw = sink.finish(); - raw.cameras = cameras; + raw.cameras = cameras.into_iter().flatten().collect(); raw.base_colors = colors.into_iter().map(|c| RawBaseColor { material: c.name, factor: Vec4::from_array(c.factor), image: c.image }).collect(); Ok(raw) } From f22c9d31a5eb8dc27bbbc761a7ec7271df0269c8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:44:07 +0000 Subject: [PATCH 087/115] Preserve FBX parent connection precedence --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 14 +++++++++++--- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 63ba1709..3de76013 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f#17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f" +source = "git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc#f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f#17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc#f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index c6f1dcfc..88363c22 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 470cf433..d63cf89a 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -57,8 +57,12 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) if doc.version == 0 { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true }) - .map_err(convert)?; + doc.scene_with_options( + &limits, + &mut craft_mesh::no_external, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true }, + ) + .map_err(convert)?; craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) }) } @@ -71,7 +75,11 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; let scene = doc - .scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true }) + .scene_with_options( + &limits, + &mut craft_mesh::no_external, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true }, + ) .map_err(convert)?; let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); From fa817f859210c6e42d6384b964a945801301d8be Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:46:16 +0000 Subject: [PATCH 088/115] Preserve FBX material slot behavior --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3de76013..e457fa9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc#f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc" +source = "git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12#e91ff8718535fa2c963f2442fcc6de4a9eaada12" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12)", "miniz_oxide 0.9.1", ] @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc#f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc" +source = "git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12#e91ff8718535fa2c963f2442fcc6de4a9eaada12" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 88363c22..a8cbab52 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "e91ff8718535fa2c963f2442fcc6de4a9eaada12", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). From 4b0621384eb4b710cd58bc55be7f72370287b753 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:48:50 +0000 Subject: [PATCH 089/115] Bound shared binary FBX allocations --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e457fa9e..cf520318 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12#e91ff8718535fa2c963f2442fcc6de4a9eaada12" +source = "git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df#fd97d5b1fe1c28c11dc57ad411b38d30065711df" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df)", "miniz_oxide 0.9.1", ] @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12#e91ff8718535fa2c963f2442fcc6de4a9eaada12" +source = "git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df#fd97d5b1fe1c28c11dc57ad411b38d30065711df" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a8cbab52..021f9c80 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "e91ff8718535fa2c963f2442fcc6de4a9eaada12", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "fd97d5b1fe1c28c11dc57ad411b38d30065711df", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). From 48885c910f3a5ded9d7cc5f163d0ba8b75d7dd1a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:49:20 +0000 Subject: [PATCH 090/115] Ignore unused cyclic FBX models --- crates/formats/src/mesh_import/fbx.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index d63cf89a..7c65bf50 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -87,6 +87,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let mut cameras = Vec::new(); cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, String::new(), 0usize)).collect(); + let mut reached = vec![false; scene.nodes.len()]; let mut visited = 0usize; let mut points = 0usize; while let Some((id, parent, inherited, depth)) = stack.pop() { @@ -95,6 +96,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { return Err(FormatError::TooLarge("FBX hierarchy exceeds its traversal limit".into())); } let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; + if let Some(seen) = reached.get_mut(id) { + *seen = true; + } let world = parent * to_mat(node.transform); let part = if node.name == format!("{inherited} geometry") { inherited } else { node.name.clone() }; for child in node.children.iter().rev() { @@ -153,7 +157,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); } } - if visited < scene.nodes.len() { + if scene.nodes.iter().enumerate().any(|(i, node)| node.mesh.is_some() && !reached.get(i).copied().unwrap_or(false)) { return Err(malformed(KIND, "cycle in model hierarchy")); } for warning in scene.warnings { From b6115309aa0cc2a29a07c226f296a9e644aacf5d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:51:13 +0000 Subject: [PATCH 091/115] Preserve FBX object connection handling --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cf520318..7d5b1adb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df#fd97d5b1fe1c28c11dc57ad411b38d30065711df" +source = "git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12#1ef59f89052096ad20353635258ef00177962c12" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12#1ef59f89052096ad20353635258ef00177962c12" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df#fd97d5b1fe1c28c11dc57ad411b38d30065711df" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 021f9c80..acc6c6a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "fd97d5b1fe1c28c11dc57ad411b38d30065711df", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "1ef59f89052096ad20353635258ef00177962c12", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 7c65bf50..9763af2c 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -60,7 +60,7 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) doc.scene_with_options( &limits, &mut craft_mesh::no_external, - &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true }, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, ) .map_err(convert)?; craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) @@ -78,7 +78,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { .scene_with_options( &limits, &mut craft_mesh::no_external, - &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true }, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, ) .map_err(convert)?; let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); From 9fa832274acb219e52254ac9e44ffee152ddc22a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:55:20 +0000 Subject: [PATCH 092/115] Adopt FBX integration lint fixes --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7d5b1adb..88c4e71c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12#1ef59f89052096ad20353635258ef00177962c12" +source = "git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232#afea2ec3c56b14dccf3d006bbad47592d85b0232" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12#1ef59f89052096ad20353635258ef00177962c12" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232#afea2ec3c56b14dccf3d006bbad47592d85b0232" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index acc6c6a3..0792af3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "1ef59f89052096ad20353635258ef00177962c12", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "afea2ec3c56b14dccf3d006bbad47592d85b0232", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). From e6c149cbd6cba6db35497e11fe35bf10dda05833 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:56:07 +0000 Subject: [PATCH 093/115] Simplify shared FBX camera selection --- crates/formats/src/mesh_import/fbx.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 9763af2c..890dfccb 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -104,14 +104,14 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { for child in node.children.iter().rev() { stack.push((*child, world, part.clone(), depth + 1)); } - if let Some(index) = node.camera { - if let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) { - let (fov, ortho) = match camera.projection { - craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), - craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), - }; - *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); - } + if let Some(index) = node.camera + && let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) + { + let (fov, ortho) = match camera.projection { + craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), + craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), + }; + *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); } let Some(index) = node.mesh else { continue }; let mesh = scene.meshes.get(index).ok_or_else(|| malformed(KIND, "mesh index out of range"))?; From e2ff5144cd65e72415c4a28d62ad620765672c93 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:58:03 +0000 Subject: [PATCH 094/115] Bound FBX color seam staging --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 88c4e71c..fa9af7d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232#afea2ec3c56b14dccf3d006bbad47592d85b0232" +source = "git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1#0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1#0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232#afea2ec3c56b14dccf3d006bbad47592d85b0232" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 0792af3b..a34b9a78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "afea2ec3c56b14dccf3d006bbad47592d85b0232", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). From 59a7c022a1bcd32d18d87528ef3fdfef7edfcd15 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:01:11 +0000 Subject: [PATCH 095/115] Bound FBX hierarchy traversal memory --- crates/formats/src/mesh_import/fbx.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 890dfccb..7db5d789 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -86,7 +86,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let mut sink = PolygonSink::default(); let mut cameras = Vec::new(); cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); - let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, String::new(), 0usize)).collect(); + // Keep parent indices rather than copying names into every pending child: a hostile + // hierarchy may fan one very long model name out to many children. + let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, None::, 0usize)).collect(); let mut reached = vec![false; scene.nodes.len()]; let mut visited = 0usize; let mut points = 0usize; @@ -100,9 +102,14 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { *seen = true; } let world = parent * to_mat(node.transform); - let part = if node.name == format!("{inherited} geometry") { inherited } else { node.name.clone() }; + let parent_name = inherited.and_then(|i| scene.nodes.get(i)).map_or("", |n| n.name.as_str()); + let synthetic = node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); + let next_parent = if synthetic { inherited } else { Some(id) }; for child in node.children.iter().rev() { - stack.push((*child, world, part.clone(), depth + 1)); + if stack.len() >= limits.max_data_bytes / std::mem::size_of::<(usize, Mat4, Option, usize)>() { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); + } + stack.push((*child, world, next_parent, depth + 1)); } if let Some(index) = node.camera && let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) @@ -121,7 +128,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let normal_transform = Mat3::from_mat4(world).inverse().transpose(); let flip = world.determinant() < 0.0; - sink.part = part; + sink.part = if synthetic { parent_name.to_string() } else { node.name.clone() }; let (mut bad_normals, mut bad_uvs) = (0usize, 0usize); for group in &mesh.parts { let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); From 12168ad47537ff5fbd55e56fe757de66f62c5970 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:01:25 +0000 Subject: [PATCH 096/115] Bound FBX root traversal allocation --- crates/formats/src/mesh_import/fbx.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 7db5d789..ab8248ea 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -88,6 +88,10 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); // Keep parent indices rather than copying names into every pending child: a hostile // hierarchy may fan one very long model name out to many children. + let stack_limit = limits.max_data_bytes / std::mem::size_of::<(usize, Mat4, Option, usize)>(); + if scene.roots.len() > stack_limit { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); + } let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, None::, 0usize)).collect(); let mut reached = vec![false; scene.nodes.len()]; let mut visited = 0usize; @@ -106,7 +110,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let synthetic = node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); let next_parent = if synthetic { inherited } else { Some(id) }; for child in node.children.iter().rev() { - if stack.len() >= limits.max_data_bytes / std::mem::size_of::<(usize, Mat4, Option, usize)>() { + if stack.len() >= stack_limit { return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); } stack.push((*child, world, next_parent, depth + 1)); From da1e2df96da227cfb9fb0684107219720c45f78c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:02:01 +0000 Subject: [PATCH 097/115] Keep root FBX model names --- crates/formats/src/mesh_import/fbx.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index ab8248ea..e8fbee03 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -107,7 +107,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let world = parent * to_mat(node.transform); let parent_name = inherited.and_then(|i| scene.nodes.get(i)).map_or("", |n| n.name.as_str()); - let synthetic = node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); + let synthetic = inherited.is_some() && node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); let next_parent = if synthetic { inherited } else { Some(id) }; for child in node.children.iter().rev() { if stack.len() >= stack_limit { From b81a54228fda4fa3fbe5485658ed87b2c6b9f27f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:10:16 +0000 Subject: [PATCH 098/115] Preserve FBX placement and polygon order --- Cargo.lock | 8 +++--- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 40 ++++++++++++++------------- 3 files changed, 26 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fa9af7d8..3cf85cc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1#0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1" +source = "git+https://github.com/storytold/craft-libs?rev=d0abb8772cd5e33ae4e2174e4a1760ede822466a#d0abb8772cd5e33ae4e2174e4a1760ede822466a" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d0abb8772cd5e33ae4e2174e4a1760ede822466a)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1#0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=d0abb8772cd5e33ae4e2174e4a1760ede822466a#d0abb8772cd5e33ae4e2174e4a1760ede822466a" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a34b9a78..e30b64aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d0abb8772cd5e33ae4e2174e4a1760ede822466a", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index e8fbee03..58a01aea 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -74,8 +74,8 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; - let scene = doc - .scene_with_options( + let (scene, placements) = doc + .scene_with_placements( &limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, @@ -86,34 +86,34 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let mut sink = PolygonSink::default(); let mut cameras = Vec::new(); cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); - // Keep parent indices rather than copying names into every pending child: a hostile - // hierarchy may fan one very long model name out to many children. - let stack_limit = limits.max_data_bytes / std::mem::size_of::<(usize, Mat4, Option, usize)>(); + // Bound the stored world matrices and pending node indices together: neither depends on + // copying model names, even when a hierarchy fans out widely. + let placement_bytes = + scene.nodes.len().checked_mul(std::mem::size_of::>()).ok_or_else(|| FormatError::TooLarge("FBX hierarchy size overflow".into()))?; + let remaining = limits.max_data_bytes.checked_sub(placement_bytes).ok_or_else(|| FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into()))?; + let stack_limit = remaining / std::mem::size_of::<(usize, Mat4, usize)>(); if scene.roots.len() > stack_limit { return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); } - let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, None::, 0usize)).collect(); - let mut reached = vec![false; scene.nodes.len()]; + let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, 0usize)).collect(); + let mut worlds = vec![None; scene.nodes.len()]; let mut visited = 0usize; let mut points = 0usize; - while let Some((id, parent, inherited, depth)) = stack.pop() { + while let Some((id, parent, depth)) = stack.pop() { visited += 1; if visited > limits.max_nodes || depth > limits.max_depth { return Err(FormatError::TooLarge("FBX hierarchy exceeds its traversal limit".into())); } let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; - if let Some(seen) = reached.get_mut(id) { - *seen = true; - } let world = parent * to_mat(node.transform); - let parent_name = inherited.and_then(|i| scene.nodes.get(i)).map_or("", |n| n.name.as_str()); - let synthetic = inherited.is_some() && node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); - let next_parent = if synthetic { inherited } else { Some(id) }; + if let Some(slot) = worlds.get_mut(id) { + *slot = Some(world); + } for child in node.children.iter().rev() { if stack.len() >= stack_limit { return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); } - stack.push((*child, world, next_parent, depth + 1)); + stack.push((*child, world, depth + 1)); } if let Some(index) = node.camera && let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) @@ -124,6 +124,11 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { }; *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); } + } + for placement in placements { + let id = placement.node; + let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "placement index out of range"))?; + let world = worlds.get(id).copied().flatten().ok_or_else(|| malformed(KIND, "cycle in model hierarchy"))?; let Some(index) = node.mesh else { continue }; let mesh = scene.meshes.get(index).ok_or_else(|| malformed(KIND, "mesh index out of range"))?; points = points.checked_add(mesh.positions.len()).ok_or_else(|| FormatError::TooLarge("FBX instance work overflow".into()))?; @@ -132,7 +137,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let normal_transform = Mat3::from_mat4(world).inverse().transpose(); let flip = world.determinant() < 0.0; - sink.part = if synthetic { parent_name.to_string() } else { node.name.clone() }; + sink.part = placement.model.and_then(|i| scene.nodes.get(i)).map_or_else(String::new, |n| n.name.clone()); let (mut bad_normals, mut bad_uvs) = (0usize, 0usize); for group in &mesh.parts { let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); @@ -168,9 +173,6 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); } } - if scene.nodes.iter().enumerate().any(|(i, node)| node.mesh.is_some() && !reached.get(i).copied().unwrap_or(false)) { - return Err(malformed(KIND, "cycle in model hierarchy")); - } for warning in scene.warnings { sink.warn(warning); } From e664e65d94e01aad3b9537e3ce651128430b440f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:16:46 +0000 Subject: [PATCH 099/115] Use shared OBJ reader --- Cargo.lock | 9 +- Cargo.toml | 3 +- crates/formats/Cargo.toml | 1 - crates/formats/src/mesh_import/obj.rs | 168 +++++++++++--------------- 4 files changed, 72 insertions(+), 109 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d63a2ff2..735177a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,7 +842,7 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89b3a8436bd0d09c3748#d6ed8c20f12188c1f39c89b3a8436bd0d09c3748" +source = "git+https://github.com/storytold/craft-libs?rev=284b0d815b69178cf4eb67321b7cc6c03202553c#284b0d815b69178cf4eb67321b7cc6c03202553c" [[package]] name = "craft-quit" @@ -4434,7 +4434,6 @@ dependencies = [ "texturecraft-geom", "texturecraft-texel", "thiserror 2.0.21", - "tobj", "zip", ] @@ -4631,12 +4630,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "tobj" -version = "4.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eb8e04167c1c0c76b5de63226fd733485ad63ef71e40de31e16272f47b099e2" - [[package]] name = "tokio" version = "1.53.3" diff --git a/Cargo.toml b/Cargo.toml index 65ce6e99..4ae5db65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,7 +49,6 @@ wgpu = "30" rfd = "0.17" zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } -tobj = { version = "4", default-features = false } flate2 = "1" lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] } quick-xml = "0.41" @@ -69,7 +68,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "284b0d815b69178cf4eb67321b7cc6c03202553c", default-features = false, features = ["stl", "obj"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 756b2a78..92cc20d3 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -19,7 +19,6 @@ texturecraft-geom = { workspace = true } texturecraft-compose = { workspace = true } image = { workspace = true } gltf = { workspace = true } -tobj = { workspace = true } flate2 = { workspace = true } lz4_flex = { workspace = true } half = { workspace = true } diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index bf949625..2a9ad167 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -1,12 +1,9 @@ -//! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn. - -use std::io::{BufReader, Read}; - +//! Wavefront OBJ through the shared bounded mesh reader. +use super::{MAX_VERTICES, RawMesh, check_vertices}; +use crate::{FormatError, Result, malformed}; +use std::collections::HashMap; use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; -use super::{RawMesh, check_triangles, check_vertices}; -use crate::{Result, malformed}; - const KIND: &str = "OBJ"; pub(crate) fn read(bytes: &[u8]) -> Result { @@ -14,102 +11,77 @@ pub(crate) fn read(bytes: &[u8]) -> Result { } fn read_inner(bytes: &[u8]) -> Result { - let text = String::from_utf8_lossy(bytes); - - // A synthetic library lets tobj assign usemtl names without reading external MTL files - let mut names: Vec<&str> = Vec::new(); - for line in text.lines().map(str::trim) { - if line.split_whitespace().next() == Some("usemtl") - && let Some((_, name)) = line.split_once(' ') - && !name.trim().is_empty() - && !names.contains(&name.trim()) - { - names.push(name.trim()); - } - } - - let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect(); - let prefix = "mtllib texturecraft-usemtl.mtl\n"; - - // Feed the prefix and the borrowed (or lossily converted) body as one reader: neither a - // whole-file copy nor an extra string is needed before tobj parses it. - let mut source = BufReader::new(prefix.as_bytes().chain(text.as_bytes())); - - // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates - let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; - let (models, materials) = tobj::load_obj_buf(&mut source, &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; - let materials = materials.unwrap_or_default(); - + let limits = craft_mesh::Limits { + max_vertices: MAX_VERTICES, + max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_face_corners: MAX_VERTICES, + max_meshes: MAX_VERTICES, + max_parts: MAX_VERTICES, + max_materials: MAX_VERTICES, + max_data_bytes: super::MAX_MESH_FILE_BYTES as usize, + ..Default::default() + }; + let options = craft_mesh::obj::ReadOptions { strict: true, preserve_runs: true, ignore_material_libraries: true }; + let scene = craft_mesh::obj::read_with_options(bytes, &limits, &mut craft_mesh::no_external, &options).map_err(|e| match e { + craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s), + e => FormatError::Invalid(e.to_string()), + })?; + let any_uvs = scene.meshes.iter().flat_map(|mesh| mesh.parts.iter()).flat_map(|part| part.corners.iter()).any(|c| c.uv != craft_mesh::NONE); + let any_colors = scene.meshes.iter().any(|mesh| !mesh.colors.is_empty()); let mut raw = RawMesh::default(); - let any_uvs = models.iter().any(|m| !m.mesh.indices.is_empty() && m.mesh.texcoords.len() == (m.mesh.positions.len() / 3) * 2); - let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), any_uvs.then(Vec::new), Vec::new()); - let mut partial_uvs = false; - for model in &models { - let mesh = &model.mesh; - if mesh.indices.is_empty() { - continue; - } - let vertex_count = mesh.positions.len() / 3; - check_vertices(raw.positions.len().saturating_add(vertex_count))?; - - // Corners per face; without arities every face is a triangle - let arities: Vec = - if mesh.face_arities.is_empty() { vec![3; mesh.indices.len() / 3] } else { mesh.face_arities.iter().map(|a| *a as usize).collect() }; - check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; - let base = raw.positions.len() as u32; - raw.positions.extend(mesh.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); - if mesh.normals.len() == vertex_count * 3 { - if let Some(v) = &mut normals { - v.extend(mesh.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); - } - } else { - normals = None; - } - if let Some(v) = &mut uvs { - if mesh.texcoords.len() == vertex_count * 2 { - // OBJ UVs have their origin bottom-left - v.extend(mesh.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); - } else { - v.extend(std::iter::repeat_n(Vec2::ZERO, vertex_count)); - partial_uvs = true; - } - } - - // `v x y z r g b`: objects without colors are white - match mesh.vertex_color.len() == vertex_count * 3 { - true => colors.extend(mesh.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), - false => colors.extend(std::iter::repeat_n(Vec4::ONE, vertex_count)), - } - - let name = match mesh.material_id { - Some(id) => materials.get(id).map(|mat| mat.name.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Material_{id}")), - None => "Default".to_string(), - }; - if let Some(i) = mesh.indices.iter().find(|i| **i as usize >= vertex_count) { - return Err(malformed(KIND, format!("face index {i} out of range"))); - } - - // tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem - let part = if model.name == "unnamed_object" { "" } else { model.name.as_str() }; - let (mut rest, mut corners) = (mesh.indices.as_slice(), Vec::new()); - for arity in arities { - let Some((face, tail)) = rest.split_at_checked(arity) else { break }; - rest = tail; - corners.clear(); - corners.extend(face.iter().map(|i| base + i)); - if arity >= 3 { - raw.polygon(&name, part, &corners); + let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); + let (mut missing_normals, mut missing_uvs) = (false, false); + for mesh in &scene.meshes { + for part in &mesh.parts { + let material = part.material.and_then(|i| scene.materials.get(i)).map_or("Default", |m| m.name.as_str()); + let name = if part.name.is_empty() { mesh.name.as_str() } else { part.name.as_str() }; + // OBJ model/material runs have independent v/vt/vn deduplication. + let mut ids = HashMap::new(); + for face in part.faces() { + let mut polygon = Vec::with_capacity(face.len()); + for corner in face { + let id = if let Some(id) = ids.get(corner) { + *id + } else { + let position = mesh.positions.get(corner.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; + check_vertices(raw.positions.len().saturating_add(1))?; + // Bound both the output pools and the per-run corner map before growth. + let staging = raw + .positions + .len() + .checked_add(1) + .and_then(|n| n.checked_mul(64)) + .and_then(|n| ids.len().checked_add(1).and_then(|m| m.checked_mul(48)).and_then(|m| n.checked_add(m))); + if staging.is_none_or(|n| n > limits.max_data_bytes) { + return Err(FormatError::TooLarge("OBJ mesh exceeds the memory limit".into())); + } + let id = u32::try_from(raw.positions.len()).map_err(|_| FormatError::TooLarge("OBJ vertex count".into()))?; + raw.positions.push(Vec3::new(position[0] as f32, position[1] as f32, position[2] as f32)); + let normal = mesh.normals.get(corner.normal as usize).map(|n| Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); + missing_normals |= normal.is_none(); + normals.push(normal.unwrap_or_default()); + if any_uvs { + let uv = mesh.uv_sets.first().and_then(|set| set.get(corner.uv as usize)).map(|v| Vec2::new(v[0], v[1])); + missing_uvs |= uv.is_none(); + uvs.push(uv.unwrap_or_default()); + } + if any_colors { + colors.push(mesh.colors.get(corner.position as usize).copied().map(Vec4::from_array).unwrap_or(Vec4::ONE)); + } + ids.insert(*corner, id); + id + }; + polygon.push(id); + } + raw.polygon(material, name, &polygon); } } } - - if partial_uvs { + if missing_uvs { raw.warnings.push("some objects have no UVs; default UVs were assigned".into()); } - - raw.normals = normals; - raw.uvs = uvs; - raw.colors = models.iter().any(|model| !model.mesh.vertex_color.is_empty()).then_some(colors); - + raw.normals = (!missing_normals).then_some(normals); + raw.uvs = any_uvs.then_some(uvs); + raw.colors = any_colors.then_some(colors); Ok(raw) } From ecf313f325a4fb624a35b0c6aabb5ea09ff86440 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:29:05 -0500 Subject: [PATCH 100/115] 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 0d18d7afb71955e133a8c9b81b89cb8b64ab0b5d Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Sun, 15 Nov 2026 20:32:35 +0100 Subject: [PATCH 101/115] Add mesh replacement backend and reimport safeguards (#230) Add file.changeMesh for trusted local callers while preserving layers, remembered mesh paths, imported images and bake resources. Retain unchanged-layout paint preservation, cache/cage invalidation and stale-bake cancellation safeguards. The temporary Change mesh menu entry is removed. The Project Configuration 3D Mesh UI will follow separately. Contributor: @vangel76. Validated by fresh Ubuntu and Windows CI at the exact head-equivalent tree; QA confirmed the new dependency inputs and named backend/safety regressions. --- crates/engine/src/file_cmds.rs | 110 +++++++++++++++++++++++ crates/engine/src/preserve.rs | 67 +++++++++++++- crates/engine/tests/it/bake.rs | 39 ++++++++ crates/ui-egui/src/bake_job.rs | 2 + crates/ui-egui/src/lib.rs | 11 ++- crates/ui-egui/src/updates_ui.rs | 2 +- crates/ui-egui/tests/bake_preview.rs | 2 + crates/ui-egui/tests/it/bake_job_mesh.rs | 43 +++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/features.md | 3 +- 10 files changed, 275 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/tests/it/bake_job_mesh.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index a728fd6c..e4d17f53 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -37,6 +37,15 @@ pub fn specs() -> Vec { always, reimport ), + cmd!( + "file.changeMesh", + "Change mesh", + [], + None, + "{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index", + always, + change_mesh + ), cmd!( "file.exportTextures", "Export textures", @@ -438,6 +447,16 @@ fn reimport(s: &mut Session, p: &Value) -> Result { Ok(reply) } +#[cfg(not(target_arch = "wasm32"))] +fn change_mesh(s: &mut Session, p: &Value) -> Result { + let path = native::path_param(p, "path", "file.changeMesh")?; + let file = native::read_mesh("file.changeMesh", path)?; + let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?; + // Only after the swap succeeded: Reimport mesh and Save keep following the new file. + s.doc.project.mesh_path = native::absolute(path); + Ok(reply) +} + #[cfg(not(target_arch = "wasm32"))] impl Session { /// The file the mesh was imported from, when it is still there: what Reimport mesh reads again. @@ -471,6 +490,19 @@ impl Session { let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); next.path = self.path.clone(); + next.sync_images(); + // The high polys and the skew map stay. The cage is sampled by triangle index and + // barycentrics, so it stays only for an identical mesh; the low poly's base colours are + // read again from the new mesh. + next.bake_meshes = self.bake_meshes.clone(); + next.bake_meshes.low_base_color = Default::default(); + if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { + next.bake_meshes.cage = None; + next.log.push("the cage mesh was dropped: the low-poly mesh changed".into()); + } + if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { + next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into()); + } next.modified = true; next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); @@ -621,6 +653,8 @@ use unsupported as save_copy; #[cfg(target_arch = "wasm32")] use unsupported as reimport; #[cfg(target_arch = "wasm32")] +use unsupported as change_mesh; +#[cfg(target_arch = "wasm32")] use unsupported as export_textures; #[cfg(target_arch = "wasm32")] use unsupported as export_mesh; @@ -764,6 +798,82 @@ f 1/1 2/2 3/3 let _ = std::fs::remove_dir_all(&dir); } + /// A project built on one mesh moves to another mesh file with its layers intact, even when + /// it carries its own copy of the mesh (a plain reimport would only re-read that copy). + #[test] + fn change_mesh_swaps_the_mesh_and_keeps_the_layers() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let quad = dir.join("quad.obj"); + std::fs::write(&quad, "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n").unwrap(); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("quad.obj", &std::fs::read(&quad).unwrap(), 128, "quad").unwrap(); + crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let layers = s.doc.project.layers.len(); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({})).is_err(), "a path is required"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": tri.display().to_string()})).unwrap(); + assert_eq!(s.mesh.triangle_count(), 1, "the new mesh is in use"); + assert_eq!(s.doc.project.mesh_file, "tri.obj"); + assert_eq!(s.doc.project.layers.len(), layers, "the layers stay"); + std::fs::remove_dir_all(&dir).ok(); + } + + /// Open A, change to B, edit B on disk: Reimport mesh (also after save and reopen) must read B, + /// not A. A failed change leaves the remembered path alone. + #[test] + fn change_mesh_remembers_the_new_file_for_reimport() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_path_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let obj = |x: f32| format!("v 0 0 0\nv {x} 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"); + let (a, b) = (dir.join("a.obj"), dir.join("b.obj")); + std::fs::write(&a, obj(1.0)).unwrap(); + std::fs::write(&b, obj(2.0)).unwrap(); + let width = |s: &Session| s.mesh.positions.iter().map(|p| p.x).fold(0.0_f32, f32::max); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "file.new", &json!({"mesh": a.display().to_string(), "resolution": 128})).unwrap(); + let a_abs = s.remembered_mesh_path().map(str::to_string).unwrap(); + // A failed change (unreadable file) keeps A. + let missing = dir.join("missing.obj"); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({"path": missing.display().to_string()})).is_err()); + assert_eq!(s.remembered_mesh_path(), Some(a_abs.as_str())); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert_eq!(width(&s), 2.0); + let b_abs = s.remembered_mesh_path().map(str::to_string).expect("B is remembered"); + assert_ne!(a_abs, b_abs); + // The remembered path survives save and reopen. + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.remembered_mesh_path(), Some(b_abs.as_str())); + // Edit B, then Reimport from the remembered path: B's edits arrive, not A. + std::fs::write(&b, obj(3.0)).unwrap(); + let remembered = reopened.remembered_mesh_path().map(str::to_string).unwrap(); + crate::execute(&mut reopened, "file.reimportMesh", &json!({"path": remembered})).unwrap(); + assert_eq!(width(&reopened), 3.0); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let a = dir.join("a.obj"); + std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + // Same triangle count, other vertices. + let b = dir.join("b.obj"); + std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); + let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + s.bake_meshes.cage = Some(cage); + let _ = s.bake_meshes.low_base_color.set(Err("old".into())); + // The same mesh again keeps the cage but not the cached colours. + crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_some()); + assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh"); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() { // A GLB quad whose mesh and node have no name: its one part is named after the file. diff --git a/crates/engine/src/preserve.rs b/crates/engine/src/preserve.rs index 38544edc..d68f20bc 100644 --- a/crates/engine/src/preserve.rs +++ b/crates/engine/src/preserve.rs @@ -16,8 +16,14 @@ use crate::Session; const REACH: f32 = 0.05; /// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s -/// document) from `old`'s UV layout. Returns how many texels found the old surface. +/// document) from `old`'s UV layout. Returns how many texels found the old surface; +/// a texture set where none does keeps its pixels as they are. Nothing is re-projected when the +/// UV layout and topology are unchanged (same triangles, materials and UVs): the pixels already +/// sit where they belong, however far the mesh moved. pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { + if same_layout(&old.mesh, &next.mesh) { + return 0; + } let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius()); let mut found = 0; for ts in 0..next.set_count() { @@ -52,7 +58,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { ((tx, ty), src) }) .collect(); - found += table.values().flatten().filter(|p| p[0].is_finite()).count(); + let matched = table.values().flatten().filter(|p| p[0].is_finite()).count(); + found += matched; + // No old surface within reach anywhere (a moved or unrelated mesh): the paint stays where it is. + if matched == 0 { + continue; + } let map = |x: f32, y: f32| { let (xi, yi) = (x as u32, y as u32); table.get(&(xi / TILE, yi / TILE)).and_then(|t| t.get(((yi % TILE) * TILE + xi % TILE) as usize)).filter(|p| p[0].is_finite()).map(|p| (p[0], p[1])) @@ -63,6 +74,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { found } +/// Same index buffer, same UVs per vertex and the same material ranges. +fn same_layout(a: &texturecraft_geom::Mesh, b: &texturecraft_geom::Mesh) -> bool { + let ranges = |m: &texturecraft_geom::Mesh| m.submeshes.iter().map(|s| (s.material, s.start, s.count)).collect::>(); + a.indices == b.indices && a.uvs == b.uvs && ranges(a) == ranges(b) +} + #[cfg(test)] mod tests { use super::*; @@ -104,4 +121,50 @@ mod tests { } assert!(right > 10_000 && wrong == 0, "{right} right, {wrong} wrong"); } + + #[test] + fn a_mesh_with_no_surface_in_reach_keeps_the_paint_where_it_is() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..64 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // The same plane far away and with mirrored UVs (so the layout differs and the unchanged-layout + // shortcut is not taken): nothing of the old surface is within reach. + let mut mesh = (*s.mesh).clone(); + for p in &mut mesh.positions { + p.x += 100.0; + } + for uv in &mut mesh.uvs { + *uv = Vec2::new(1.0 - uv.x, uv.y); + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there"); + } + + #[test] + fn a_translated_mesh_with_the_same_uvs_keeps_every_pixel() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..128 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // Slid along its own surface by a fraction of the plane: half of it still overlaps the old one. + let mut mesh = (*s.mesh).clone(); + let shift = mesh.radius() * 0.5; + for p in &mut mesh.positions { + p.x += shift; + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + for x in 0..128 { + assert_eq!(img.get(x, 40)[3], 65535, "texel {x} of the painted row moved"); + assert_eq!(img.get(x, 41)[3], 0, "texel {x} of the next row got paint"); + } + } } diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 85b0142c..62afeb63 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -612,3 +612,42 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() { assert_eq!(session.doc.baked, original.baked); assert_eq!(session.history_labels(), history); } + +/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay, +/// the project counts as changed, and image resources are decoded in the new session. +#[test] +fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { + let mut s = plane_session(); + let plane = s.mesh.as_ref().clone(); + let high = temp_file("change_high.obj", &obj(&plane, 0.002, f32::MAX, [1.0; 3])); + execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap(); + execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap(); + // 1x1 PNG as an image resource. + let png = [ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, + 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00, + 0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + ]; + s.import_resource_bytes("dot.png", png.to_vec()).unwrap(); + s.modified = false; + let mesh_id = s.mesh_id; + + let mut low = String::new(); + for p in &plane.positions { + low += &format!("v {} {} {}\n", p.x, p.y, p.z); + } + for uv in &plane.uvs { + low += &format!("vt {} {}\n", uv.x, 1.0 - uv.y); + } + for t in plane.indices.as_chunks::<3>().0 { + low += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1); + } + let low = temp_file("change_low.obj", &low); + execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap(); + + assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh"); + assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays"); + assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays"); + assert!(s.modified, "the project differs from the saved one"); + assert_eq!(s.images.len(), 1, "image resources are decoded in the new session"); +} diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index f585d326..4b60f6f0 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -5,4 +5,6 @@ pub struct BakeJob { pub queue: Vec, pub current: Option, pub total: usize, + /// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied. + pub mesh_id: u64, } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..b80b1790 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -327,7 +327,7 @@ impl TextureCraftApp { } let total = sets.len(); - self.bake = Some(BakeJob { queue: sets, current: None, total }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -393,6 +393,15 @@ impl TextureCraftApp { return; }; + if job.mesh_id != self.session.mesh_id { + // The mesh was swapped under the job: stop it and drop its result. + if let Some(running) = &job.current { + running.progress.cancel.store(true, Ordering::Relaxed); + } + self.bake = None; + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); if let Some(running) = &job.current { let set_index = running.set_index; diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index fa1e6c4b..20736bdd 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -263,7 +263,7 @@ mod tests { assert!(!safe_to_close(h.state()), "unsaved changes"); h.state_mut().session.modified = false; - h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0 }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0 }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 6860bdc4..1703abde 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -125,9 +125,11 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { result_sender.send(Ok(output)).unwrap(); let app = harness.state_mut(); app.start_bake(vec![0]); + let mesh_id = app.session.mesh_id; app.bake = Some(BakeJob { queue: Vec::new(), total: 1, + mesh_id, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs new file mode 100644 index 00000000..60f6f03e --- /dev/null +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -0,0 +1,43 @@ +//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps +//! the mesh meanwhile, the job is cancelled and its result is dropped. + +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use egui_kittest::Harness; +use texturecraft_engine::bake::Progress; +use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; + +/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. +fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let progress = Arc::new(Progress::new()); + let (tx, receiver) = std::sync::mpsc::channel(); + let (maps_tx, maps) = std::sync::mpsc::channel(); + let id = mesh_id(h.state().session.mesh_id); + // Leak the sender so the channel stays empty instead of closed. + std::mem::forget(tx); + std::mem::forget(maps_tx); + let running = + RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; + h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); + (h, progress) +} + +#[test] +fn a_job_on_a_swapped_mesh_is_cancelled_and_dropped() { + let (mut h, progress) = harness_with_job(|current| current + 1); + h.step(); + assert!(h.state().bake.is_none(), "the job is dropped"); + assert!(progress.cancel.load(Ordering::Relaxed), "and its worker is told to stop"); +} + +#[test] +fn a_job_on_the_current_mesh_keeps_running() { + let (mut h, progress) = harness_with_job(|current| current); + h.step(); + assert!(h.state().bake.is_some(), "the job stays"); + assert!(!progress.cancel.load(Ordering::Relaxed)); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..00f1ba79 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -1,6 +1,7 @@ //! One integration-test executable avoids linking the same dependencies for every feature. //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. +mod bake_job_mesh; mod bake_mode; mod brush_drag; mod brush_section_reset; diff --git a/docs/features.md b/docs/features.md index a51352da..a456a371 100644 --- a/docs/features.md +++ b/docs/features.md @@ -80,7 +80,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. - Reimport a changed mesh and your painted strokes stay on the surface. + Reimport a changed mesh and your painted strokes stay on the surface. The + `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). From 7f40386c97921040a4d0c5f1fda474e07ba6e508 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:38:33 -0500 Subject: [PATCH 102/115] Reuse shared PLY body decoding without changing strict import policy Keep the app header grammar, geometry and colour interpretation while replacing the local scalar and endian reader with craft-mesh Rows. Co-authored-by: bflatastic Co-authored-by: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> --- Cargo.toml | 2 +- crates/formats/src/mesh_import/ply.rs | 144 +++++++++++--------------- 2 files changed, 60 insertions(+), 86 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 65ce6e99..d3e84c46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ 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-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl", "ply"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/ply.rs b/crates/formats/src/mesh_import/ply.rs index 34e1c1da..fdfa981f 100644 --- a/crates/formats/src/mesh_import/ply.rs +++ b/crates/formats/src/mesh_import/ply.rs @@ -10,40 +10,20 @@ const KIND: &str = "PLY"; /// Longest polygon accepted (a list count above this is treated as corruption). const MAX_FACE_VERTICES: usize = 4096; -#[derive(Clone, Copy, PartialEq)] -enum Ty { - I8, - U8, - I16, - U16, - I32, - U32, - F32, - F64, -} +use craft_mesh::ply::{Encoding as SharedEncoding, Header, Rows, Scalar as Ty}; -impl Ty { - fn parse(s: &str) -> Option { - Some(match s { - "char" | "int8" => Ty::I8, - "uchar" | "uint8" => Ty::U8, - "short" | "int16" => Ty::I16, - "ushort" | "uint16" => Ty::U16, - "int" | "int32" => Ty::I32, - "uint" | "uint32" => Ty::U32, - "float" | "float32" => Ty::F32, - "double" | "float64" => Ty::F64, - _ => return None, - }) - } - fn size(self) -> usize { - match self { - Ty::I8 | Ty::U8 => 1, - Ty::I16 | Ty::U16 => 2, - Ty::I32 | Ty::U32 | Ty::F32 => 4, - Ty::F64 => 8, - } - } +fn parse_type(s: &str) -> Option { + Some(match s { + "char" | "int8" => Ty::I8, + "uchar" | "uint8" => Ty::U8, + "short" | "int16" => Ty::I16, + "ushort" | "uint16" => Ty::U16, + "int" | "int32" => Ty::I32, + "uint" | "uint32" => Ty::U32, + "float" | "float32" => Ty::F32, + "double" | "float64" => Ty::F64, + _ => return None, + }) } struct Property { @@ -66,55 +46,16 @@ enum Encoding { Be, } -/// Reads scalars from the body in either encoding. -struct Body<'a> { - data: &'a [u8], - pos: usize, - enc: Encoding, -} - -impl Body<'_> { - fn next_token(&mut self) -> Option<&str> { - let rest = self.data.get(self.pos..)?; - let start = rest.iter().position(|b| !b.is_ascii_whitespace())?; - let len = rest.get(start..)?.iter().position(|b| b.is_ascii_whitespace()).unwrap_or(rest.len() - start); - self.pos += start + len; - std::str::from_utf8(rest.get(start..start + len)?).ok() - } - - fn read(&mut self, ty: Ty) -> Result { - if self.enc == Encoding::Ascii { - let tok = self.next_token().ok_or_else(|| malformed(KIND, "unexpected end of data"))?; - return tok.parse::().map_err(|_| malformed(KIND, format!("bad number \"{tok}\""))); - } - let n = ty.size(); - let bytes = self.data.get(self.pos..self.pos + n).ok_or_else(|| malformed(KIND, "unexpected end of data"))?; - self.pos += n; - let mut b = [0u8; 8]; - b.get_mut(..n).unwrap_or_default().copy_from_slice(bytes); - if self.enc == Encoding::Be { - b.get_mut(..n).unwrap_or_default().reverse(); - } - Ok(match ty { - Ty::I8 => b[0] as i8 as f64, - Ty::U8 => b[0] as f64, - Ty::I16 => i16::from_le_bytes([b[0], b[1]]) as f64, - Ty::U16 => u16::from_le_bytes([b[0], b[1]]) as f64, - Ty::I32 => i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::U32 => u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64, - Ty::F64 => f64::from_le_bytes(b), - }) - } - - fn remaining(&self) -> usize { - self.data.len().saturating_sub(self.pos) - } -} - pub(crate) fn read(bytes: &[u8]) -> Result { let (elements, enc, body_start) = header(bytes)?; - let mut body = Body { data: bytes.get(body_start..).unwrap_or_default(), pos: 0, enc }; + // Keep the strict app header grammar and mesh policy; delegate only wire scalars. + let encoding = match enc { + Encoding::Ascii => SharedEncoding::Ascii, + Encoding::Le => SharedEncoding::Little, + Encoding::Be => SharedEncoding::Big, + }; + let shared_header = Header { encoding, elements: Vec::new(), body: body_start, comments: Vec::new() }; + let mut body = Rows::new(&shared_header, bytes); let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); // Elements may appear in any order, so take the vertex count from the header. @@ -149,17 +90,17 @@ pub(crate) fn read(bytes: &[u8]) -> Result { match p.list { None => { if let Some(v) = vals.get_mut(k) { - *v = body.read(p.ty)?; + *v = body.value(p.ty).map_err(|e| malformed(KIND, e.to_string()))?; } } Some(ct) => { - let len = body.read(ct)?; + let len = body.value(ct).map_err(|e| malformed(KIND, e.to_string()))?; if !(0.0..=MAX_FACE_VERTICES as f64).contains(&len) { return Err(malformed(KIND, format!("bad list length {len}"))); } poly.clear(); for _ in 0..len as usize { - let v = body.read(p.ty)?; + let v = body.value(p.ty).map_err(|e| malformed(KIND, e.to_string()))?; if face_list == Some(k) { if !(0.0..nverts as f64).contains(&v) { return Err(malformed(KIND, format!("face index {v} out of range"))); @@ -240,13 +181,13 @@ fn header(bytes: &[u8]) -> Result<(Vec, Encoding, usize)> { } ["property", "list", ct, ty, name] => { let el = elements.last_mut().ok_or_else(|| malformed(KIND, "property before element"))?; - let (ct, ty) = (Ty::parse(ct), Ty::parse(ty)); + let (ct, ty) = (parse_type(ct), parse_type(ty)); let (Some(ct), Some(ty)) = (ct, ty) else { return Err(malformed(KIND, format!("bad list types in \"{line}\""))) }; el.props.push(Property { name: name.to_string(), ty, list: Some(ct) }); } ["property", ty, name] => { let el = elements.last_mut().ok_or_else(|| malformed(KIND, "property before element"))?; - let ty = Ty::parse(ty).ok_or_else(|| malformed(KIND, format!("bad property type {ty}")))?; + let ty = parse_type(ty).ok_or_else(|| malformed(KIND, format!("bad property type {ty}")))?; el.props.push(Property { name: name.to_string(), ty, list: None }); } ["ply"] | [] | ["comment", ..] | ["obj_info", ..] => {} @@ -256,3 +197,36 @@ fn header(bytes: &[u8]) -> Result<(Vec, Encoding, usize)> { let enc = enc.ok_or_else(|| malformed(KIND, "header has no format line"))?; Ok((elements, enc, pos)) } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod shared_rows_tests { + use super::*; + + #[test] + fn binary_scalar_endianness_matches_ascii() { + for (format, big) in [("binary_little_endian", false), ("binary_big_endian", true)] { + let mut bytes = + format!("ply\nformat {format} 1.0\nelement vertex 1\nproperty short x\nproperty float y\nproperty double z\nend_header\n").into_bytes(); + bytes.extend(if big { (-123i16).to_be_bytes() } else { (-123i16).to_le_bytes() }); + bytes.extend(if big { 1.25f32.to_be_bytes() } else { 1.25f32.to_le_bytes() }); + bytes.extend(if big { (-2.5f64).to_be_bytes() } else { (-2.5f64).to_le_bytes() }); + assert_eq!(read(&bytes).unwrap().positions, vec![Vec3::new(-123.0, 1.25, -2.5)]); + bytes.pop(); + assert!(read(&bytes).is_err()); + } + let ascii = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty short x\nproperty float y\nproperty double z\nend_header\n -123 \t1.25\r\n -2.5 "; + assert_eq!(read(ascii).unwrap().positions, vec![Vec3::new(-123.0, 1.25, -2.5)]); + } + + #[test] + fn strict_header_and_invalid_face_policy_remain_local() { + for extra in ["unknown directive\n", "property nonsense x\n"] { + let bytes = format!("ply\nformat ascii 1.0\nelement vertex 1\n{extra}end_header\n0"); + assert!(read(bytes.as_bytes()).is_err()); + } + assert!(read(b"ply\nformat ascii 1.0\ncomment \xff\nend_header\n").is_err()); + let bytes = b"ply\nformat ascii 1.0\nelement face 1\nproperty list uchar int vertex_indices\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nend_header\n3 0 0 1\n0 0 0\n"; + assert!(read(bytes).is_err()); // Do not turn a bad face into a warning/skip. + } +} From 646fa2e454b4ce6e71857972b34bd83e08d13ed0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:50:57 -0500 Subject: [PATCH 103/115] Use shared USD Crate LZ4 decompression Preserve TextureCraft scene/material policy, integer packing and writing; replace only bounded LZ4 framing reads. Depends on craft-libs #1738. Co-authored-by: bflatastic --- Cargo.lock | 10 +++++++++ Cargo.toml | 1 + crates/formats/Cargo.toml | 1 + crates/formats/src/mesh_import/usd/codec.rs | 23 +-------------------- crates/formats/src/mesh_import/usd/tests.rs | 15 ++++++++++++++ 5 files changed, 28 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d63a2ff2..b821ec91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -903,6 +903,15 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-usd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=556d02941ad3b97b1d109e9c08d4477d647deb1f#556d02941ad3b97b1d109e9c08d4477d647deb1f" +dependencies = [ + "lz4_flex", + "thiserror 2.0.21", +] + [[package]] name = "craft-window" version = "0.1.0" @@ -4417,6 +4426,7 @@ dependencies = [ "craft-materialx", "craft-mcmat", "craft-mesh", + "craft-usd", "craft-zip", "exr", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 65ce6e99..f9890f38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/texturecraft" [workspace.dependencies] +craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "556d02941ad3b97b1d109e9c08d4477d647deb1f" } # internal texturecraft-core = { path = "crates/core" } texturecraft-texel = { path = "crates/texel" } diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 756b2a78..21cf0443 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +craft-usd.workspace = true craft-materialx = { workspace = true } craft-mesh = { workspace = true } craft-mcmat = { workspace = true } diff --git a/crates/formats/src/mesh_import/usd/codec.rs b/crates/formats/src/mesh_import/usd/codec.rs index a336db33..f1e0e7ee 100644 --- a/crates/formats/src/mesh_import/usd/codec.rs +++ b/crates/formats/src/mesh_import/usd/codec.rs @@ -104,28 +104,7 @@ pub(crate) fn numeric(t: u8) -> Option<(Scalar, usize)> { /// Decompress Crate's LZ4 framing into at most `max_out` bytes. pub(crate) fn decompress(input: &[u8], max_out: usize) -> Result> { - let bad = |e: lz4_flex::block::DecompressError| malformed(KIND, format!("LZ4 data: {e}")); - let (&chunks, mut rest) = input.split_first().ok_or_else(|| malformed(KIND, "empty compressed block"))?; - // LZ4 expands at most ~255×: never allocate more than the input can produce. - let mut out = vec![0u8; max_out.min(input.len().saturating_mul(256).saturating_add(64))]; - let written = if chunks == 0 { - lz4_flex::block::decompress_into(rest, &mut out).map_err(bad)? - } else { - if chunks > 127 { - return Err(malformed(KIND, "bad LZ4 chunk count")); - } - let mut total = 0usize; - for _ in 0..chunks { - let size = rest.get(..4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes).ok_or_else(|| malformed(KIND, "truncated LZ4 chunk"))?; - let size = usize::try_from(size).map_err(|_| malformed(KIND, "negative LZ4 chunk size"))?; - let chunk = rest.get(4..4usize.saturating_add(size)).ok_or_else(|| malformed(KIND, "truncated LZ4 chunk"))?; - rest = rest.get(4 + size..).unwrap_or_default(); - total += lz4_flex::block::decompress_into(chunk, out.get_mut(total..).unwrap_or_default()).map_err(bad)?; - } - total - }; - out.truncate(written); - Ok(out) + craft_usd::decompress(input, max_out).map_err(|e| malformed(KIND, e.to_string())) } /// Crate's LZ4 framing for one chunk (inputs are far below LZ4's ~2 GB chunk limit). diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index 1797093b..8b85a611 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -420,6 +420,21 @@ fn integer_coding_round_trips() { assert!(codec::decompress(&[0, 0xF0], 10).is_err()); } +#[test] +fn shared_crate_lz4_retains_chunk_and_budget_policy() { + let mut frame = vec![2]; + for raw in [b"abc".as_slice(), b"def".as_slice()] { + let block = lz4_flex::block::compress(raw); + frame.extend((block.len() as i32).to_le_bytes()); + frame.extend(block); + } + frame.extend(b"old reader ignores this tail"); + assert_eq!(codec::decompress(&frame, 6).unwrap(), b"abcdef"); + assert!(codec::decompress(&frame, 5).is_err()); + assert!(codec::decompress(&[1, 255, 255, 255, 255], 64).is_err()); + assert!(codec::decompress(&[128], 64).is_err()); +} + #[test] fn malformed_usd_never_panics() { // A small two-material mesh keeps the byte loops fast. From 8003210b64f8763d57a87febca0d752b0e7039de Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:10:14 -0500 Subject: [PATCH 104/115] Use shared bounded USD integer delta decoding Keep the existing aggregate decoded byte budget, integer writer and scene mapping. Depends on craft-libs #1742 and TextureCraft #531. Co-authored-by: bflatastic --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/formats/src/mesh_import/usd/codec.rs | 43 ++++----------------- crates/formats/src/mesh_import/usd/tests.rs | 7 ++++ 4 files changed, 16 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b821ec91..e1531265 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -906,7 +906,7 @@ dependencies = [ [[package]] name = "craft-usd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=556d02941ad3b97b1d109e9c08d4477d647deb1f#556d02941ad3b97b1d109e9c08d4477d647deb1f" +source = "git+https://github.com/storytold/craft-libs?rev=456abf7b7a2e6919b5a16e35fa2bf4e796f88674#456abf7b7a2e6919b5a16e35fa2bf4e796f88674" dependencies = [ "lz4_flex", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index f9890f38..a609cb19 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/texturecraft" [workspace.dependencies] -craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "556d02941ad3b97b1d109e9c08d4477d647deb1f" } +craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "456abf7b7a2e6919b5a16e35fa2bf4e796f88674" } # internal texturecraft-core = { path = "crates/core" } texturecraft-texel = { path = "crates/texel" } diff --git a/crates/formats/src/mesh_import/usd/codec.rs b/crates/formats/src/mesh_import/usd/codec.rs index f1e0e7ee..4d0f0343 100644 --- a/crates/formats/src/mesh_import/usd/codec.rs +++ b/crates/formats/src/mesh_import/usd/codec.rs @@ -119,43 +119,14 @@ pub(crate) fn encoded_ints_len(n: usize, width: usize) -> usize { if n == 0 { 0 } else { width.saturating_add(n.saturating_mul(2).saturating_add(7) / 8).saturating_add(n.saturating_mul(width)) } } -fn read_signed(b: &[u8], at: usize, width: usize) -> Option { - let s = b.get(at..at.checked_add(width)?)?; - Some(match width { - 1 => i64::from(i8::from_le_bytes(s.try_into().ok()?)), - 2 => i64::from(i16::from_le_bytes(s.try_into().ok()?)), - 4 => i64::from(i32::from_le_bytes(s.try_into().ok()?)), - _ => i64::from_le_bytes(s.try_into().ok()?), - }) -} - -/// Decode `n` integers of `width` (4 or 8) bytes; 32-bit values are sign-extended (reinterpret -/// as u32 for unsigned data). +/// Decode packed integers after the caller charges its aggregate decoded-byte budget. pub(crate) fn decode_ints(data: &[u8], n: usize, width: usize) -> Result> { - let err = || malformed(KIND, "truncated integer array"); - if n == 0 { - return Ok(Vec::new()); - } - let common = read_signed(data, 0, width).ok_or_else(err)?; - let codes_at = width; - let mut at = codes_at + n.div_ceil(4); - let mut out = Vec::with_capacity(n); - let mut prev = 0i64; - for i in 0..n { - let code = (data.get(codes_at + i / 4).ok_or_else(err)? >> (2 * (i % 4))) & 3; - let delta = match code { - 0 => common, - c => { - let w = (width >> (3 - c as usize)).max(1); - let v = read_signed(data, at, w).ok_or_else(err)?; - at += w; - v - } - }; - prev = if width == 4 { i64::from((prev as i32).wrapping_add(delta as i32)) } else { prev.wrapping_add(delta) }; - out.push(prev); - } - Ok(out) + let width = match width { + 4 => craft_usd::integers::Width::I32, + 8 => craft_usd::integers::Width::I64, + _ => return Err(malformed(KIND, "unsupported integer width")), + }; + craft_usd::integers::decode(data, n, width, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } /// Encode integers of `width` (4 or 8) bytes (values must fit the width). diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index 8b85a611..cd77be5c 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -420,6 +420,13 @@ fn integer_coding_round_trips() { assert!(codec::decompress(&[0, 0xF0], 10).is_err()); } +#[test] +fn shared_integer_decoder_rejects_unsupported_width_and_oversized_output() { + assert!(codec::decode_ints(&[], 1, 3).is_err()); + assert!(codec::decode_ints(&[], super::MAX_DECODED_BYTES / 8 + 1, 8).is_err()); + assert!(codec::decode_ints(&[], 0, 4).unwrap().is_empty()); +} + #[test] fn shared_crate_lz4_retains_chunk_and_budget_policy() { let mut frame = vec![2]; From 939b12bfd01a5afa28228eeea0934080f4ec3f72 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:18:23 -0500 Subject: [PATCH 105/115] Use fallible shared USD Crate LZ4 writing Propagate compression errors through USD writer values, sections and finish. Bound worst-case output reservation by the existing 2GiB app ceiling; preserve normal wire bytes and scene policy. Co-authored-by: bflatastic --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/formats/src/mesh_export/usdc.rs | 32 +++++++++++---------- crates/formats/src/mesh_import/usd/codec.rs | 7 ++--- crates/formats/src/mesh_import/usd/tests.rs | 12 +++++++- crates/formats/src/mesh_import/usd/usdc.rs | 4 +-- 6 files changed, 35 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e1531265..6f241cfe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -906,7 +906,7 @@ dependencies = [ [[package]] name = "craft-usd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=456abf7b7a2e6919b5a16e35fa2bf4e796f88674#456abf7b7a2e6919b5a16e35fa2bf4e796f88674" +source = "git+https://github.com/storytold/craft-libs?rev=02ab4e01ef584345c4c5fc43d3bad2e9fdfc28bf#02ab4e01ef584345c4c5fc43d3bad2e9fdfc28bf" dependencies = [ "lz4_flex", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a609cb19..d391cee5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/texturecraft" [workspace.dependencies] -craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "456abf7b7a2e6919b5a16e35fa2bf4e796f88674" } +craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "02ab4e01ef584345c4c5fc43d3bad2e9fdfc28bf" } # internal texturecraft-core = { path = "crates/core" } texturecraft-texel = { path = "crates/texel" } diff --git a/crates/formats/src/mesh_export/usdc.rs b/crates/formats/src/mesh_export/usdc.rs index 35900e28..2066476e 100644 --- a/crates/formats/src/mesh_export/usdc.rs +++ b/crates/formats/src/mesh_export/usdc.rs @@ -154,7 +154,7 @@ impl Writer { UsdValue::Ints(v) if v.len() >= codec::MIN_COMPRESSED_ARRAY => { let at = self.offset(); self.out.extend_from_slice(&(v.len() as u64).to_le_bytes()); - self.ints(&v.iter().map(|&i| i64::from(i)).collect::>()); + self.ints(&v.iter().map(|&i| i64::from(i)).collect::>())?; rep(ty::INT, codec::IS_ARRAY | codec::IS_COMPRESSED, at) } UsdValue::Ints(v) => self.raw_array(ty::INT, v.len(), v.iter().flat_map(|i| i.to_le_bytes())), @@ -174,10 +174,11 @@ impl Writer { } /// Compressed integers: their compressed size, then the LZ4-framed coding. - fn ints(&mut self, v: &[i64]) { - let comp = codec::compress(&codec::encode_ints(v, 4)); + fn ints(&mut self, v: &[i64]) -> Result<()> { + let comp = codec::compress(&codec::encode_ints(v, 4))?; self.out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); self.out.extend_from_slice(&comp); + Ok(()) } fn spec(&mut self, path: usize, kind: i64, fields: Vec<(&str, u64)>) { @@ -303,7 +304,7 @@ impl Writer { self.out.extend_from_slice(&(v as u64).to_le_bytes()); } - fn sections(&mut self) { + fn sections(&mut self) -> Result<()> { let mut toc = Vec::new(); let start = self.offset(); let mut raw = Vec::new(); @@ -311,7 +312,7 @@ impl Writer { raw.extend_from_slice(t.as_bytes()); raw.push(0); } - let comp = codec::compress(&raw); + let comp = codec::compress(&raw)?; self.u64(self.tokens.len()); self.u64(raw.len()); self.u64(comp.len()); @@ -327,9 +328,9 @@ impl Writer { let start = self.offset(); let fields = std::mem::take(&mut self.fields); self.u64(fields.len()); - self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::>()); + self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::>())?; let reps: Vec = fields.iter().flat_map(|f| f.1.to_le_bytes()).collect(); - let comp = codec::compress(&reps); + let comp = codec::compress(&reps)?; self.u64(comp.len()); self.out.extend_from_slice(&comp); self.section(&mut toc, "FIELDS", start); @@ -337,7 +338,7 @@ impl Writer { let start = self.offset(); let sets = std::mem::take(&mut self.fieldsets); self.u64(sets.len()); - self.ints(&sets); + self.ints(&sets)?; self.section(&mut toc, "FIELDSETS", start); let start = self.offset(); @@ -345,7 +346,7 @@ impl Writer { self.u64(self.paths.len()); self.u64(self.paths.len()); for column in &table { - self.ints(column); + self.ints(column)?; } self.section(&mut toc, "PATHS", start); @@ -353,7 +354,7 @@ impl Writer { let specs = std::mem::take(&mut self.specs); self.u64(specs.len()); for k in 0..3 { - self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::>()); + self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::>())?; } self.section(&mut toc, "SPECS", start); @@ -371,6 +372,7 @@ impl Writer { if let Some(slot) = self.out.get_mut(16..24) { slot.copy_from_slice(&toc_at.to_le_bytes()); } + Ok(()) } } @@ -400,9 +402,9 @@ impl Writer { Ok(()) } - fn finish(mut self) -> Vec { - self.sections(); - self.out + fn finish(mut self) -> Result> { + self.sections()?; + Ok(self.out) } } @@ -413,7 +415,7 @@ pub(crate) fn write(layer: &UsdLayer) -> Result> { w.add_prim_paths(0, "/", root); w.root_spec(&root.name)?; w.prim_specs(&format!("/{}", root.name), root)?; - Ok(w.finish()) + w.finish() } #[cfg(test)] @@ -504,7 +506,7 @@ mod tests { for (path, value) in attrs.into_iter().zip([points, counts, indices]) { w.spec(path, SPEC_ATTRIBUTE, vec![("default", value)]); } - let bytes = w.finish(); + let bytes = w.finish().unwrap(); let m = crate::import_mesh_bytes("crafted.usdc", &bytes).unwrap().mesh; assert_eq!(m.triangle_count(), 1, "the class prim itself is not drawn"); diff --git a/crates/formats/src/mesh_import/usd/codec.rs b/crates/formats/src/mesh_import/usd/codec.rs index 4d0f0343..982bb868 100644 --- a/crates/formats/src/mesh_import/usd/codec.rs +++ b/crates/formats/src/mesh_import/usd/codec.rs @@ -108,10 +108,9 @@ pub(crate) fn decompress(input: &[u8], max_out: usize) -> Result> { } /// Crate's LZ4 framing for one chunk (inputs are far below LZ4's ~2 GB chunk limit). -pub(crate) fn compress(input: &[u8]) -> Vec { - let mut out = vec![0u8]; - out.extend_from_slice(&lz4_flex::block::compress(input)); - out +pub(crate) fn compress(input: &[u8]) -> Result> { + // Keep one compressed output reservation within the app's decoded-data ceiling. + craft_usd::compress::compress(input, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } /// Upper bound of the encoded size of `n` integers of `width` bytes. diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index cd77be5c..44e01443 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -416,10 +416,20 @@ fn integer_coding_round_trips() { let wide = vec![i64::MAX, i64::MIN, 0, 1 << 40]; assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8), 4, 8).unwrap(), wide); let big: Vec = (0..5000u32).flat_map(|i| (i % 7).to_le_bytes()).collect(); - assert_eq!(codec::decompress(&codec::compress(&big), big.len()).unwrap(), big); + assert_eq!(codec::decompress(&codec::compress(&big).unwrap(), big.len()).unwrap(), big); assert!(codec::decompress(&[0, 0xF0], 10).is_err()); } +#[test] +fn shared_crate_lz4_writer_preserves_bytes() { + for len in [0, 1, 15, 16, 255, 4096] { + let data: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + let mut previous = vec![0]; + previous.extend(lz4_flex::block::compress(&data)); + assert_eq!(codec::compress(&data).unwrap(), previous); + } +} + #[test] fn shared_integer_decoder_rejects_unsupported_width_and_oversized_output() { assert!(codec::decode_ints(&[], 1, 3).is_err()); diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index aeff1e76..292229b5 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -660,7 +660,7 @@ mod tests { } fn compressed_ints(out: &mut Vec, v: &[i64]) { - let comp = codec::compress(&codec::encode_ints(v, 4)); + let comp = codec::compress(&codec::encode_ints(v, 4)).unwrap(); out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); out.extend_from_slice(&comp); } @@ -721,7 +721,7 @@ mod tests { compressed_ints(&mut b, &idx); let i64_at = b.len() as u64; b.extend_from_slice(&(n as u64).to_le_bytes()); - let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::>(), 8)); + let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::>(), 8)).unwrap(); b.extend_from_slice(&(comp.len() as u64).to_le_bytes()); b.extend_from_slice(&comp); let c = crate_over(&b, (0, 8, 0)); From 8a1baa35acefff455bedc4aad061543e8d7f7506 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:35:21 -0500 Subject: [PATCH 106/115] Use bounded shared USD integer delta encoding Preserve packed wire values and propagate bounded scratch/output allocation failures through USD export. Co-authored-by: bflatastic --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/formats/src/mesh_export/usdc.rs | 2 +- crates/formats/src/mesh_import/usd/codec.rs | 52 ++++----------------- crates/formats/src/mesh_import/usd/tests.rs | 11 ++++- crates/formats/src/mesh_import/usd/usdc.rs | 4 +- 6 files changed, 22 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6f241cfe..1102579e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -906,7 +906,7 @@ dependencies = [ [[package]] name = "craft-usd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=02ab4e01ef584345c4c5fc43d3bad2e9fdfc28bf#02ab4e01ef584345c4c5fc43d3bad2e9fdfc28bf" +source = "git+https://github.com/storytold/craft-libs?rev=f7655fb3ea59d6b21681700c0ff880823f5bb709#f7655fb3ea59d6b21681700c0ff880823f5bb709" dependencies = [ "lz4_flex", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index d391cee5..e731ff47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/texturecraft" [workspace.dependencies] -craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "02ab4e01ef584345c4c5fc43d3bad2e9fdfc28bf" } +craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f7655fb3ea59d6b21681700c0ff880823f5bb709" } # internal texturecraft-core = { path = "crates/core" } texturecraft-texel = { path = "crates/texel" } diff --git a/crates/formats/src/mesh_export/usdc.rs b/crates/formats/src/mesh_export/usdc.rs index 2066476e..b071e215 100644 --- a/crates/formats/src/mesh_export/usdc.rs +++ b/crates/formats/src/mesh_export/usdc.rs @@ -175,7 +175,7 @@ impl Writer { /// Compressed integers: their compressed size, then the LZ4-framed coding. fn ints(&mut self, v: &[i64]) -> Result<()> { - let comp = codec::compress(&codec::encode_ints(v, 4))?; + let comp = codec::compress(&codec::encode_ints(v, 4)?)?; self.out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); self.out.extend_from_slice(&comp); Ok(()) diff --git a/crates/formats/src/mesh_import/usd/codec.rs b/crates/formats/src/mesh_import/usd/codec.rs index 982bb868..4221e390 100644 --- a/crates/formats/src/mesh_import/usd/codec.rs +++ b/crates/formats/src/mesh_import/usd/codec.rs @@ -128,50 +128,14 @@ pub(crate) fn decode_ints(data: &[u8], n: usize, width: usize) -> Result Vec { - if values.is_empty() { - return Vec::new(); - } - let wrap = |v: i64| if width == 4 { i64::from(v as i32) } else { v }; - let mut prev = 0i64; - let deltas: Vec = values - .iter() - .map(|&v| { - let d = wrap(v.wrapping_sub(prev)); - prev = v; - d - }) - .collect(); - let mut counts = std::collections::HashMap::new(); - for d in &deltas { - *counts.entry(*d).or_insert(0usize) += 1; - } - let common = counts.into_iter().max_by_key(|&(v, c)| (c, v)).map_or(0, |(v, _)| v); - let mut out = Vec::with_capacity(encoded_ints_len(values.len(), width)); - out.extend_from_slice(&common.to_le_bytes()[..width]); - let codes_at = out.len(); - out.resize(codes_at + values.len().div_ceil(4), 0); - for (i, &d) in deltas.iter().enumerate() { - let small = |bits: u32| d >= -(1i64 << (bits - 1)) && d < (1i64 << (bits - 1)); - let code: u8 = if d == common { - 0 - } else if small(width as u32 * 2) { - 1 - } else if small(width as u32 * 4) { - 2 - } else { - 3 - }; - if code > 0 { - let w = (width >> (3 - code as usize)).max(1); - out.extend_from_slice(&d.to_le_bytes()[..w]); - } - if let Some(b) = out.get_mut(codes_at + i / 4) { - *b |= code << (2 * (i % 4)); - } - } - out +/// Encode packed integers with a combined scratch/output reservation cap. +pub(crate) fn encode_ints(values: &[i64], width: usize) -> Result> { + let width = match width { + 4 => craft_usd::integers::Width::I32, + 8 => craft_usd::integers::Width::I64, + _ => return Err(malformed(KIND, "unsupported integer width")), + }; + craft_usd::integers::encode(values, width, super::MAX_DECODED_BYTES).map_err(|e| malformed(KIND, e.to_string())) } /// Error for counts that cannot be real (more items than bytes left could describe). diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index 44e01443..c8a8cf25 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -408,13 +408,13 @@ fn usd_extension_detects_the_encoding() { fn integer_coding_round_trips() { let values: Vec = vec![0, 1, 2, 3, 3, 3, -5, 1000, -70000, i64::from(i32::MAX), i64::from(i32::MIN), 7, 7, 7, 8]; for width in [4, 8] { - let enc = codec::encode_ints(&values, width); + let enc = codec::encode_ints(&values, width).unwrap(); assert!(enc.len() <= codec::encoded_ints_len(values.len(), width)); assert_eq!(codec::decode_ints(&enc, values.len(), width).unwrap(), values); assert!(codec::decode_ints(&enc[..enc.len() - 1], values.len(), width).is_err()); } let wide = vec![i64::MAX, i64::MIN, 0, 1 << 40]; - assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8), 4, 8).unwrap(), wide); + assert_eq!(codec::decode_ints(&codec::encode_ints(&wide, 8).unwrap(), 4, 8).unwrap(), wide); let big: Vec = (0..5000u32).flat_map(|i| (i % 7).to_le_bytes()).collect(); assert_eq!(codec::decompress(&codec::compress(&big).unwrap(), big.len()).unwrap(), big); assert!(codec::decompress(&[0, 0xF0], 10).is_err()); @@ -509,3 +509,10 @@ fn loose_layer_textures_are_packaged() { assert_eq!((f.name, f.bytes == out.bytes, f.warnings.len()), (format!("t.{ext}"), true, 1), "{ext}"); } } + +#[test] +fn shared_integer_writer_preserves_tie_wire_and_rejects_invalid_width() { + assert_eq!(codec::encode_ints(&[1, 3, 4, 6], 4).unwrap(), vec![2, 0, 0, 0, 17, 1, 1]); + assert!(codec::encode_ints(&[1], 3).is_err()); + assert!(codec::encode_ints(&[], 8).unwrap().is_empty()); +} diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 292229b5..fb925765 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -660,7 +660,7 @@ mod tests { } fn compressed_ints(out: &mut Vec, v: &[i64]) { - let comp = codec::compress(&codec::encode_ints(v, 4)).unwrap(); + let comp = codec::compress(&codec::encode_ints(v, 4).unwrap()).unwrap(); out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); out.extend_from_slice(&comp); } @@ -721,7 +721,7 @@ mod tests { compressed_ints(&mut b, &idx); let i64_at = b.len() as u64; b.extend_from_slice(&(n as u64).to_le_bytes()); - let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::>(), 8)).unwrap(); + let comp = codec::compress(&codec::encode_ints(&(0..n as i64).map(|i| i << 33).collect::>(), 8).unwrap()).unwrap(); b.extend_from_slice(&(comp.len() as u64).to_le_bytes()); b.extend_from_slice(&comp); let c = crate_over(&b, (0, 8, 0)); From df2c0b81db9e9eca4f714a944ff5ec7f72b7a9b1 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 15 Nov 2026 21:09:57 +0000 Subject: [PATCH 107/115] 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 108/115] 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 109/115] 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 110/115] 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 111/115] 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()); From fcc957b4ea191ca7abb0034a547aa751ed911e71 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:25:59 +0100 Subject: [PATCH 112/115] Accept trailing propertyless PLY elements as before The shared ASCII row reader counts the delimiter after the last value as read, so a trailing element without properties (e.g. `element edge 1` after the last vertex row) was rejected by the per-element byte bound. Propertyless elements read nothing: skip their rows and bound their count by the bytes the previous reader saw. Adds a regression test. --- crates/formats/src/mesh_import/ply.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/formats/src/mesh_import/ply.rs b/crates/formats/src/mesh_import/ply.rs index fdfa981f..de29820c 100644 --- a/crates/formats/src/mesh_import/ply.rs +++ b/crates/formats/src/mesh_import/ply.rs @@ -60,7 +60,18 @@ pub(crate) fn read(bytes: &[u8]) -> Result { let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); // Elements may appear in any order, so take the vertex count from the header. let nverts: usize = elements.iter().filter(|e| e.name == "vertex").map(|e| e.count).fold(0, usize::saturating_add); + // The shared ASCII reader counts the delimiter after a value as read; the previous reader + // left it in the remaining bytes. Only an element without properties can notice the difference. + let ascii_slack = usize::from(enc == Encoding::Ascii); for el in &elements { + // An element without properties reads nothing, so its rows are skipped. Its count stays + // bounded by the bytes left, as the previous reader counted them. + if el.props.is_empty() { + if el.count > body.remaining().saturating_add(ascii_slack) { + return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count))); + } + continue; + } // Every item takes at least one byte, so the count can never exceed what is left. if el.count > body.remaining() { return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count))); @@ -203,6 +214,14 @@ fn header(bytes: &[u8]) -> Result<(Vec, Encoding, usize)> { mod shared_rows_tests { use super::*; + #[test] + fn trailing_propertyless_element_after_a_newline_still_opens() { + let bytes = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement edge 1\nend_header\n0 0 0\n"; + assert_eq!(read(bytes).unwrap().positions, vec![Vec3::new(0.0, 0.0, 0.0)]); + let huge = b"ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nelement edge 3\nend_header\n0 0 0\n"; + assert!(read(huge).is_err()); + } + #[test] fn binary_scalar_endianness_matches_ascii() { for (format, big) in [("binary_little_endian", false), ("binary_big_endian", true)] { From 7cb641f74233790d5f1cab0149517ff3888fcc7d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:15:14 +0100 Subject: [PATCH 113/115] Keep rejecting propertyless PLY vertex elements A vertex element without x, y, z must still fail with "vertices have no x, y, z" instead of being skipped as a propertyless element. Adds a regression test. --- crates/formats/src/mesh_import/ply.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/formats/src/mesh_import/ply.rs b/crates/formats/src/mesh_import/ply.rs index de29820c..fd923ee8 100644 --- a/crates/formats/src/mesh_import/ply.rs +++ b/crates/formats/src/mesh_import/ply.rs @@ -70,6 +70,10 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if el.count > body.remaining().saturating_add(ascii_slack) { return Err(malformed(KIND, format!("element \"{}\" claims {} items but the file is too short", el.name, el.count))); } + // A vertex element still needs positions, as below. + if el.name == "vertex" { + return Err(malformed(KIND, "vertices have no x, y, z")); + } continue; } // Every item takes at least one byte, so the count can never exceed what is left. @@ -222,6 +226,14 @@ mod shared_rows_tests { assert!(read(huge).is_err()); } + #[test] + fn propertyless_vertex_element_is_still_rejected() { + let bytes = b"ply\nformat ascii 1.0\nelement vertex 1\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n3 0 0 0\n"; + let Err(e) = read(bytes) else { panic!("a vertex element without x, y, z must not open") }; + let err = e.to_string(); + assert!(err.contains("vertices have no x, y, z"), "{err}"); + } + #[test] fn binary_scalar_endianness_matches_ascii() { for (format, big) in [("binary_little_endian", false), ("binary_big_endian", true)] { From a5590884f059273c33864ab0e671658559cabd1f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:49:55 +0100 Subject: [PATCH 114/115] OBJ: treat groups as objects, as tobj did craft-mesh main (b952ca02) adds ReadOptions::groups_as_objects for tobj-compatible reads: each g starts a new object, repeated group names are kept and smoothing changes don't split runs. Setting it keeps TextureCraft's previous part naming and fixes the E0063 build error. --- crates/formats/src/mesh_import/obj.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 2a9ad167..267aa8ea 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -21,7 +21,7 @@ fn read_inner(bytes: &[u8]) -> Result { max_data_bytes: super::MAX_MESH_FILE_BYTES as usize, ..Default::default() }; - let options = craft_mesh::obj::ReadOptions { strict: true, preserve_runs: true, ignore_material_libraries: true }; + let options = craft_mesh::obj::ReadOptions { strict: true, preserve_runs: true, ignore_material_libraries: true, groups_as_objects: true }; let scene = craft_mesh::obj::read_with_options(bytes, &limits, &mut craft_mesh::no_external, &options).map_err(|e| match e { craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s), e => FormatError::Invalid(e.to_string()), From 5913ee3584eae12d537611c7ad3c195a9905c02c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 06:27:28 -0500 Subject: [PATCH 115/115] docs: prefer shared Craft libraries for reusable code --- AGENTS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index c9b40de3..9a78849f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -229,3 +229,7 @@ after every arc of work that builds and passes. - `docs/releasing.md`: release builds and signing. - `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent. - `log/` (local, gitignored): the dev log. + +## Shared Craft libraries + +Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage.