From 053be2fb4e37fad0b49f78476aaad384bd51bc14 Mon Sep 17 00:00:00 2001 From: superplay2021 Date: Sun, 8 Nov 2026 12:56:26 +0200 Subject: [PATCH] Fix resumed Pen alignment and document-space stroke previews --- crates/ui-egui/src/panels/preset_panels.rs | 1 + crates/ui-egui/src/tools/shape_stroke_ui.rs | 91 +++++++++++++++++++ .../src/tools/shape_stroke_ui/tests.rs | 89 ++++++++++++++++++ crates/ui-egui/src/tools/vector_ui.rs | 4 +- .../src/tools/vector_ui/pen_path_ops_tests.rs | 31 +++++++ crates/ui-egui/src/tools/vector_ui/shapes.rs | 9 +- crates/ui-egui/src/tools/vector_ui/tests.rs | 27 +++++- docs/pixel-aligned-strokes.md | 8 ++ 8 files changed, 255 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/preset_panels.rs b/crates/ui-egui/src/panels/preset_panels.rs index d59ac670f9..c54f8e50c2 100644 --- a/crates/ui-egui/src/panels/preset_panels.rs +++ b/crates/ui-egui/src/panels/preset_panels.rs @@ -777,6 +777,7 @@ mod tests { Tool::EllipseShape, Tool::Triangle, Tool::Polygon, + Tool::Star, Tool::CustomShape, Tool::Line, Tool::Pen, diff --git a/crates/ui-egui/src/tools/shape_stroke_ui.rs b/crates/ui-egui/src/tools/shape_stroke_ui.rs index ea5b04d942..a8de9a07b6 100644 --- a/crates/ui-egui/src/tools/shape_stroke_ui.rs +++ b/crates/ui-egui/src/tools/shape_stroke_ui.rs @@ -133,6 +133,97 @@ pub fn paint_shape_preview(painter: &egui::Painter, shape: &photocraft_doc::Shap mod editor; +/// Cache document pixels independently of zoom: the view only transforms the textured quad. +#[derive(Clone)] +struct DocumentDragCache { + shape: photocraft_doc::ShapeLayer, + visible: photocraft_geom::Rect, + canvas: photocraft_geom::Rect, + bounds: photocraft_geom::Rect, + texture: egui::TextureHandle, + options: egui::TextureOptions, +} + +/// Clip the document render before allocation. Oversized zoomed-out views use the bounded +/// legacy proxy with alignment disabled rather than making eligibility depend on zoom. +fn document_preview_bounds(compiled: &photocraft_vector::CompiledShape, visible: photocraft_geom::Rect) -> Option { + let bounds = compiled.bounds()?.intersect(&visible); + // Bound each dimension as well as area: a long, thin stroke can otherwise exceed + // the texture limit even when its pixel count is small. + (!bounds.is_empty() && bounds.width() <= 2048 && bounds.height() <= 2048).then_some(bounds) +} + +/// Rasterize aligned strokes in document pixels, then project that coverage into the view. +/// Curves, diagonals and ineligible widths therefore retain committed antialiasing at any zoom. +pub(crate) fn paint_document_shape_preview( + painter: &egui::Painter, + shape: &photocraft_doc::ShapeLayer, + transform: &photocraft_geom::Affine, + canvas: photocraft_geom::Rect, +) { + use photocraft_geom::{Point, Rect}; + let clip = painter.clip_rect(); + let Some(inverse) = transform.inverse() else { return }; + if !clip.is_finite() || clip.is_negative() { + return; + } + let points = [clip.left_top(), clip.right_top(), clip.right_bottom(), clip.left_bottom()].map(|p| inverse.apply(Point::new(p.x as f64, p.y as f64))); + let visible = Rect::new( + (points.iter().map(|p| p.x).fold(f64::INFINITY, f64::min).floor() as i32).saturating_sub(1), + (points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min).floor() as i32).saturating_sub(1), + (points.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max).ceil() as i32).saturating_add(1), + (points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max).ceil() as i32).saturating_add(1), + ); + let id = egui::Id::unique("shape-document-drag-render"); + // Exact pixel-grid zooms stay crisp. Other transforms filter document coverage just as + // displaying a rotated or fractionally positioned rasterized document requires. + let integer = |v: f64| (v - v.round()).abs() < 1e-6; + let options = if transform.m[1].abs() < 1e-6 + && transform.m[2].abs() < 1e-6 + && transform.m[0].abs() >= 1.0 + && transform.m[3].abs() >= 1.0 + && [transform.m[0], transform.m[3], transform.m[4], transform.m[5]].into_iter().all(integer) + { + egui::TextureOptions::NEAREST + } else { + egui::TextureOptions::LINEAR + }; + let cached = painter.ctx().data(|d| d.get_temp::(id)); + let cache = cached.filter(|c| c.shape == *shape && c.visible == visible && c.canvas == canvas && c.options == options).or_else(|| { + let compiled = photocraft_vector::CompiledShape::with_frames(shape, photocraft_vector::DEFAULT_TOLERANCE, visible, canvas); + let bounds = document_preview_bounds(&compiled, visible)?; + let rgba = compiled.render_rgba(bounds); + let bytes: Vec = rgba.iter().flat_map(|p| p.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + let texture = painter.ctx().load_texture( + "shape-document-drag", + egui::ColorImage::from_rgba_unmultiplied([bounds.width() as usize, bounds.height() as usize], &bytes), + options, + ); + Some(DocumentDragCache { shape: shape.clone(), visible, canvas, bounds, texture, options }) + }); + let Some(cache) = cache else { + let zoom = transform.m[0].hypot(transform.m[1]); + let mut proxy = shape.clone(); + proxy.path = photocraft_vector::pixel_aligned_line_fill_path(shape).unwrap_or_else(|| shape.path.clone()).transform(transform); + proxy.live = None; + if let Some(stroke) = &mut proxy.stroke { + stroke.width *= zoom as f32; + } + proxy.pixel_align_stroke = false; + paint_shape_preview(painter, &proxy); + return; + }; + let b = cache.bounds; + let mut mesh = egui::Mesh::with_texture(cache.texture.id()); + for (x, y, u, v) in [(b.x0, b.y0, 0.0, 0.0), (b.x1, b.y0, 1.0, 0.0), (b.x1, b.y1, 1.0, 1.0), (b.x0, b.y1, 0.0, 1.0)] { + let p = transform.apply(Point::new(f64::from(x), f64::from(y))); + mesh.vertices.push(egui::epaint::Vertex { pos: egui::pos2(p.x as f32, p.y as f32), uv: egui::pos2(u, v), color: egui::Color32::WHITE }); + } + mesh.indices.extend([0, 1, 2, 0, 2, 3]); + painter.add(egui::Shape::mesh(mesh)); + painter.ctx().data_mut(|d| d.insert_temp(id, cache)); +} + pub use editor::{StrokeEditor, button}; fn open_frame_id() -> egui::Id { diff --git a/crates/ui-egui/src/tools/shape_stroke_ui/tests.rs b/crates/ui-egui/src/tools/shape_stroke_ui/tests.rs index dac6d995ec..eac0271e82 100644 --- a/crates/ui-egui/src/tools/shape_stroke_ui/tests.rs +++ b/crates/ui-egui/src/tools/shape_stroke_ui/tests.rs @@ -1,4 +1,93 @@ use super::*; + +/// Zoom and rotation project committed document coverage, including ineligible half-pixel strokes. +#[test] +fn pixel_align_preview_texture_matches_document_coverage_before_zoom() { + use photocraft_doc::{Fill, ShapeLayer}; + use photocraft_geom::{Affine, Point, Rect as PixelRect}; + for (curved, path) in [(false, photocraft_vector::shapes::rect(20.0, 20.0, 40.0, 30.0)), (true, photocraft_vector::shapes::ellipse(20.0, 20.0, 40.0, 30.0))] + { + for width in [0.5, 1.0, 2.0] { + for dashed in [false, true] { + for zoom in [0.5, 1.0, 2.0, 3.0] { + for angle in [0.0, 0.3] { + let shape = ShapeLayer { + path: path.clone(), + fill: None, + stroke: Some(ShapeStroke { + width, + paint: Fill::Solid(photocraft_doc::Color::BLACK), + dashes: if dashed { vec![3.0, 2.0] } else { vec![] }, + dash_offset: 0.5, + ..Default::default() + }), + pixel_align_stroke: true, + ..Default::default() + }; + let ctx = egui::Context::default(); + let transform = Affine::scale(zoom).then(&Affine::rotate(angle)).then(&Affine::translate(40.0, 40.0)); + let mut output = ctx.run_ui(Default::default(), |ui| { + let ctx = ui.ctx(); + let painter = + ctx.layer_painter(egui::LayerId::background()).with_clip_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0))); + paint_document_shape_preview(&painter, &shape, &transform, PixelRect::new(0, 0, 200, 200)); + }); + let cache = + ctx.data(|d| d.get_temp::(egui::Id::unique("shape-document-drag-render"))).expect("document preview cache"); + let image = output.textures_delta.set.get(&cache.texture.id()).expect("uploaded preview"); + let egui::ImageData::Color(image) = &image[0].image; + let compiled = photocraft_vector::CompiledShape::new(&shape, photocraft_vector::DEFAULT_TOLERANCE, cache.visible); + let rgba = compiled.render_rgba(cache.bounds); + let expected: Vec<_> = rgba + .iter() + .map(|p| { + egui::Color32::from_rgba_unmultiplied( + (p[0] * 255.0).round() as u8, + (p[1] * 255.0).round() as u8, + (p[2] * 255.0).round() as u8, + (p[3] * 255.0).round() as u8, + ) + }) + .collect(); + assert_eq!(image.pixels, expected, "width={width}, angle={angle}"); + if curved { + assert!(rgba.iter().any(|p| p[3] > 0.0 && p[3] < 1.0), "curve antialiasing"); + } else if !dashed { + let edge = compiled.render_rgba(PixelRect::new(35, 20, 36, 21))[0][3]; + assert_eq!(edge, if width == 0.5 { 0.25 } else { 1.0 }); + } + let mesh = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id == cache.texture.id() => Some(mesh), + _ => None, + }) + .expect("projected quad"); + let corner = transform.apply(Point::new(f64::from(cache.bounds.x0), f64::from(cache.bounds.y0))); + assert_eq!(mesh.vertices[0].pos, egui::pos2(corner.x as f32, corner.y as f32)); + output.textures_delta.clear(); + } + } + } + } + } +} + +/// Huge previews retain a bounded allocation instead of rasterizing an unbounded document. +#[test] +fn pixel_align_document_preview_rejects_oversized_raster_allocations() { + let shape = photocraft_doc::ShapeLayer { + path: photocraft_vector::shapes::rect(0.0, 0.0, 100_000.0, 100_000.0), + fill: Some(photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)), + pixel_align_stroke: true, + ..Default::default() + }; + let visible = photocraft_geom::Rect::new(0, 0, 100_000, 100_000); + let compiled = photocraft_vector::CompiledShape::new(&shape, photocraft_vector::DEFAULT_TOLERANCE, visible); + assert!(document_preview_bounds(&compiled, visible).is_none()); + assert!(document_preview_bounds(&compiled, photocraft_geom::Rect::new(0, 0, 10_000, 1)).is_none(), "thin textures still need a dimension limit"); +} use egui::accesskit::Role; use egui::{Key, Modifiers, PointerButton, Pos2, Rect, Vec2, pos2}; use egui_kittest::{ diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index abe63e7121..ab7f978023 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -272,10 +272,10 @@ pub(crate) fn capture_pen_owner(app: &PhotocraftApp) -> Option { PenTarget::Path { name: "work".into(), append: false } }; let mut options = app.ui.tool_options.clone(); - // Combining starts with the layer's displayed setting without replacing the user's + // Combining or resuming starts with the layer's displayed setting without replacing the user's // New Layer default merely because a different target was selected. if options.vector_mode == "shape" - && pen::pen_path_op(&options).is_some() + && (pen::pen_path_op(&options).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.resumes.as_ref().is_some_and(|r| r.layer.is_some()))) && let Some(LayerContent::Shape(shape)) = st.active_layer.and_then(|id| st.doc.layer(id)).map(|layer| &layer.content) { options.pixel_align_stroke = shape.pixel_align_stroke; diff --git a/crates/ui-egui/src/tools/vector_ui/pen_path_ops_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_path_ops_tests.rs index f7956cb2ad..af6fd8a530 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen_path_ops_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen_path_ops_tests.rs @@ -40,6 +40,8 @@ fn pixel_align_pen_append_and_resume_apply_the_captured_setting() { if resume { draw(&mut app, &[(80.0, 20.0), (80.0, 80.0)]); assert!(app.ui.pen.as_ref().unwrap().resumes.is_some()); + // An explicit draft edit overrides the inherited layer value. + app.ui.pen.as_mut().unwrap().owner.as_mut().unwrap().options.pixel_align_stroke = enabled; assert!(super::pen_commit(&mut app, false)); } else { draw(&mut app, &[(110.0, 110.0), (140.0, 110.0), (140.0, 140.0), (110.0, 140.0)]); @@ -61,6 +63,35 @@ fn pixel_align_pen_append_and_resume_apply_the_captured_setting() { } } +/// Resuming inherits the layer setting once and leaves the New Layer default untouched. +#[test] +fn pixel_align_resumed_pen_inherits_layer_before_any_checkbox_edit() { + for enabled in [false, true] { + let mut app = app(); + let before = app + .run( + "shape.create", + json!({"kind":"path", "pixelAlignStroke":enabled, + "fill":null,"stroke":{"width":1},"path":{"subpaths":[{"closed":false,"knots":[ + {"anchor":[20,20]},{"anchor":[80,20]} + ]}]}}), + ) + .unwrap(); + app.ui.tool_options.vector_mode = "shape".into(); + app.ui.tool_options.pen_path_op = "newLayer".into(); + app.ui.tool_options.pixel_align_stroke = !enabled; + draw(&mut app, &[(80.0, 20.0), (80.0, 80.0)]); + assert_eq!(app.ui.pen.as_ref().unwrap().owner.as_ref().unwrap().options.pixel_align_stroke, enabled); + assert!(super::pen_commit(&mut app, false)); + assert_eq!(app.run("shape.info", json!({})).unwrap()["pixelAlignStroke"], enabled); + assert_eq!(app.ui.tool_options.pixel_align_stroke, !enabled); + app.session.undo(); + assert_eq!(app.run("shape.info", json!({})).unwrap()["path"], before["path"]); + app.session.redo(); + assert_eq!(app.run("shape.info", json!({})).unwrap()["pixelAlignStroke"], enabled); + } +} + /// The checkbox shows the existing target, and an in-flight edit must not stale its draft. #[test] fn pixel_align_pen_checkbox_controls_the_target_and_pending_draft() { diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 2216370d09..1acb085fc9 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -259,10 +259,15 @@ pub fn draw_shape_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &Vie let x = xf.to_screen(1.0, 0.0) - origin; let y = xf.to_screen(0.0, 1.0) - origin; let transform = Affine { m: [x.x as f64, x.y as f64, y.x as f64, y.y as f64, origin.x as f64, origin.y as f64] }; - let shape = preview_for_view(shape, &transform, f64::from(xf.zoom)); // This lightweight screen overlay retains the existing display-colour behaviour; document // rendering still goes through its format/profile path when the shape is committed. - crate::shape_stroke_ui::paint_shape_preview(painter, &shape); + if shape.pixel_align_stroke { + let canvas = app.session.active().map_or(photocraft_geom::Rect::EMPTY, |st| st.doc.bounds()); + crate::shape_stroke_ui::paint_document_shape_preview(painter, &shape, &transform, canvas); + } else { + let shape = preview_for_view(shape, &transform, f64::from(xf.zoom)); + crate::shape_stroke_ui::paint_shape_preview(painter, &shape); + } let accent = Tokens::get(painter.ctx()).accent; for (pts, _) in path_lines(&path, &|q| xf.to_screen(q[0] as f32, q[1] as f32)) { // The accent path over a dark halo: visible on any pixels (#172). diff --git a/crates/ui-egui/src/tools/vector_ui/tests.rs b/crates/ui-egui/src/tools/vector_ui/tests.rs index e42dba6eec..c640a7f37f 100644 --- a/crates/ui-egui/src/tools/vector_ui/tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/tests.rs @@ -1643,6 +1643,31 @@ fn pixel_align_preview_preserves_shape_and_path_modes() { } } +/// The actual drag painter must not promote a fractional document stroke at 200% zoom. +#[test] +fn pixel_align_shape_drag_keeps_fractional_width_coverage_at_double_zoom() { + let mut app = app(); + app.ui.tool_options.pixel_align_stroke = true; + app.ui.tool_options.shape_fill = false; + app.ui.tool_options.stroke_width = 0.5; + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(Default::default(), |ui| { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + let xf = ViewXform { rect, zoom: 2.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + super::shapes::draw_shape_preview(&app, &painter, &xf, Tool::Rectangle, [20.0, 20.0], [60.0, 50.0], Default::default()); + }); + let texture = output.shapes.iter().find_map(|s| match &s.shape { + egui::Shape::Mesh(mesh) => Some(mesh.texture_id), + _ => None, + }); + let image = texture.and_then(|id| output.textures_delta.set.get(&id)).map(|delta| delta[0].image.clone()); + output.textures_delta.clear(); + let egui::ImageData::Color(image) = image.expect("document coverage quad texture"); + assert!(image.pixels.iter().any(|p| p.a() == 64), "a 0.5px centered edge retains quarter coverage at 200% zoom"); + assert!(image.pixels.iter().all(|p| p.a() < 255), "zoom must not make a half-pixel stroke eligible for opaque alignment"); +} + /// A filled Line Tool preview must render the same crisp pixels as its committed shape. #[test] fn pixel_align_live_line_preview_matches_commit() { @@ -1685,7 +1710,7 @@ fn pixel_align_live_line_preview_matches_commit() { #[test] fn pixel_align_reset_restores_shape_mode_without_resetting_pen_mode() { let mut app = app(); - for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::CustomShape, Tool::Line] { + for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Star, Tool::CustomShape, Tool::Line] { app.ui.tool_options.shape_mode = "path".into(); app.ui.tool_options.vector_mode = "shape".into(); app.ui.tool_options.pixel_align_stroke = true; diff --git a/docs/pixel-aligned-strokes.md b/docs/pixel-aligned-strokes.md index 13232f9c9e..f45b63599e 100644 --- a/docs/pixel-aligned-strokes.md +++ b/docs/pixel-aligned-strokes.md @@ -77,6 +77,14 @@ Widths other than 1 px and inside/outside stroke alignment keep legacy rendering Fractional-coordinate strokes are not rounded. Curves, including ellipses, are not snapped or thresholded. They remain antialiased. +Aligned shape-tool previews rasterize in document pixels before the view transform, +so zoom cannot make a fractional-width stroke eligible. Integer grid zooms use +nearest filtering; rotated or fractional views filter the document coverage. +The visible preview raster is capped at 2048 pixels per dimension (4,194,304 +pixels total). Larger visible bounds +fall back to the bounded vector proxy with stroke alignment disabled, avoiding +zoom-dependent eligibility without allocating an unbounded document raster. + Filled Line/ArrowLine alignment requires live parameters matching the current path, and is disabled for density/feather masks. A point edit or transform that drops live line metadata leaves the filled path on the legacy renderer. A Line