From e0404360e4cf7f7cd1cd7a59ffcc364a27b20ae2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:42:10 +0100 Subject: [PATCH 01/29] 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 02/29] 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 03/29] 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 04/29] 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 05/29] 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 e03e6fae6a677a505caf6ac9c971a61e62f177d9 Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Thu, 12 Nov 2026 17:56:19 +0100 Subject: [PATCH 06/29] 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 07/29] 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 08/29] 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 09/29] 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 10/29] 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 11/29] 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 02:28:43 -0500 Subject: [PATCH 12/29] 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 13/29] 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 14/29] 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 15/29] 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 16/29] 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 17/29] 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 18/29] 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 19/29] 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 20/29] 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 21/29] 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 22/29] 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 23/29] 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 24/29] 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 25/29] 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 26/29] 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 27/29] 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 28/29] 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 29/29] 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();