From 7d75b77f71a0895c0f5b5473684d5f7283f17898 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 30 Nov 2026 23:02:46 +0100 Subject: [PATCH 1/2] Fill: Place Along Path scripted pattern (#17430) Edit > Fill > Pattern > Script > Place Along Path lays the pattern tile along the path selected in the Paths panel: tiles centred on the path, the first on the start point, turned with the path, a step of the tile's shorter side plus Spacing apart, placed while they end before the path does, every other tile mirrored with Alternate patterns. The dialog has the 10 controls with their check boxes and greying rules; without a selected path the fill is refused with "No path selected" and the dialog does not open. Path sampling by arc length lives in the vector crate. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/scripted_pattern.rs | 188 ++++++++++++- crates/engine-paint/src/cmd/fill_cmds.rs | 60 ++++- .../src/fill_script_brick_tests.rs | 6 +- .../src/fill_script_place_along_path_tests.rs | 247 ++++++++++++++++++ crates/engine-paint/src/lib.rs | 2 + crates/ui-egui/src/dialogs/fill_script_ui.rs | 125 +++++++-- .../src/dialogs/fill_script_ui_tests.rs | 48 ++++ crates/vector/src/flatten.rs | 48 ++++ 8 files changed, 692 insertions(+), 32 deletions(-) create mode 100644 crates/engine-paint/src/fill_script_place_along_path_tests.rs diff --git a/crates/compose/src/scripted_pattern.rs b/crates/compose/src/scripted_pattern.rs index 9def7a7493..e91c28c008 100644 --- a/crates/compose/src/scripted_pattern.rs +++ b/crates/compose/src/scripted_pattern.rs @@ -1,10 +1,12 @@ //! Scripted patterns: Edit › Fill › Pattern with Script on lays the chosen pattern out as separate tiles instead of a -//! plain repeat. Brick Fill is the first script; the others extend [`SCRIPTS`] and [`controls`] with their own layout. +//! plain repeat. Brick Fill and Place Along Path paint; the others extend [`SCRIPTS`] and [`controls`] with their own +//! layout. //! //! Every script shares the per-tile Color and Brightness randomness ([`Jitter`]): at 0 a tile keeps the pattern's //! exact colours, above 0 each placed tile drifts by its own random amount. Areas no tile covers stay transparent. use photocraft_geom::Rect; +use photocraft_vector::flatten::Polyline; use crate::pattern::{Placement, Tile}; @@ -19,7 +21,7 @@ pub const SCRIPTS: [(&str, &str); 6] = [ ]; /// The scripts that paint today; the rest are listed but answer "not supported yet". -pub const SUPPORTED: [&str; 1] = ["brickFill"]; +pub const SUPPORTED: [&str; 2] = ["brickFill", "placeAlongPath"]; /// The parameter value of a script name, matched without regard to case. pub fn script_key(name: &str) -> Option<&'static str> { @@ -35,11 +37,18 @@ pub struct Control { pub max: f64, /// The most digits shown after the decimal mark. pub decimals: u32, + /// A check box: 1 when ticked, 0 when not. + pub toggle: bool, } impl Control { const fn new(key: &'static str, default: f64, min: f64, max: f64, decimals: u32) -> Control { - Control { key, default, min, max, decimals } + Control { key, default, min, max, decimals, toggle: false } + } + + /// A check box, ticked by default when `on`. + const fn toggle(key: &'static str, on: bool) -> Control { + Control { key, default: if on { 1.0 } else { 0.0 }, min: 0.0, max: 1.0, decimals: 0, toggle: true } } /// `v` inside the range; a non-finite value takes the factory value. @@ -70,6 +79,28 @@ pub fn controls(script: &str, width: u32, height: u32) -> Option> { Control::new("patternRotateAngle", 0.0, -180.0, 180.0, 0), ]) } + "placeAlongPath" => Some(vec![ + Control::new("patternScale", 1.0, 0.1, 1.25, 2), + Control::new("spacing", 0.0, -50.0, 150.0, 0), + Control::toggle("adjustSpacingToFit", false), + Control::new("angleFromPath", 0.0, -90.0, 90.0, 0), + Control::new("distanceFromPath", 0.0, 0.0, 200.0, 0), + Control::toggle("alternatePatterns", true), + Control::new("scaleProgression", 100.0, 90.0, 110.0, 0), + Control::toggle("skipSymbolRotation", false), + Control::new("colorRandomness", 0.05, 0.0, 1.0, 2), + Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2), + ]), + _ => None, + } +} + +/// The value that greys `key` while it is ticked, in a script's dialog: Adjust spacing to fit sets the spacing itself and +/// Skip symbol rotation keeps tiles upright, so neither Spacing nor Angle from path applies. +pub fn greyed_by(script: &str, key: &str) -> Option<&'static str> { + match (script, key) { + ("placeAlongPath", "spacing") => Some("adjustSpacingToFit"), + ("placeAlongPath", "angleFromPath") => Some("skipSymbolRotation"), _ => None, } } @@ -228,3 +259,154 @@ impl BrickFill { out } } + +/// Place Along Path: tiles one after another along each subpath of the selected path, the first centred on the start +/// point and each turned with the path; a tile is placed only while it ends before the path does. Later tiles lie over +/// earlier ones. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PlaceAlongPath { + /// Tile size as a fraction (0.1..1.25). + pub scale: f64, + /// Pixels added to the step between tile centres (the tile's shorter side); negative packs them closer. + pub spacing: f64, + /// Stretch the steps so the last tile ends exactly at the path's end; Spacing does not apply. + pub fit: bool, + /// Turn of each tile against the path direction, degrees counter-clockwise. + pub angle: f64, + /// How far the tiles sit off the path, in pixels, to the left of its direction. + pub distance: f64, + /// Every other tile mirrored top to bottom, starting with the first (measured with one pattern). + pub alternate: bool, + /// Each tile's size against the one before, in percent. + pub progression: f64, + /// Tiles stay upright instead of following the path direction; Angle from path does not apply. + pub upright: bool, + pub jitter: Jitter, +} + +/// Most tiles one fill lays along its paths: bounds the work of a huge path at the tightest step. +const MAX_PATH_TILES: usize = 100_000; + +/// The polylines of `path` that Place Along Path walks, flattened finely enough for the tile positions. +pub fn path_lines(path: &photocraft_doc::Path) -> Vec { + photocraft_vector::flatten::flatten_path(path, 0.1) +} + +/// One tile on the path: its centre on the path, the path's unit direction there, its scale, and (subpath, index). +#[derive(Clone, Copy, Debug)] +struct OnPath { + point: (f64, f64), + dir: (f64, f64), + scale: f64, + id: (i64, i64), +} + +impl PlaceAlongPath { + /// The tiles along a path `len` long, for a `w` x `h` pattern at `scale`: (arc length of the centre, tile scale), + /// at most `budget` of them (taken from it). + fn positions(&self, len: f64, (w, h): (f64, f64), scale: f64, budget: &mut usize) -> Vec<(f64, f64)> { + let progression = if self.progression.is_finite() && self.progression > 0.0 { self.progression / 100.0 } else { 1.0 }; + let spacing = if self.fit || !self.spacing.is_finite() { 0.0 } else { self.spacing }; + let mut out: Vec<(f64, f64)> = Vec::new(); + let (mut at, mut k) = (0.0, scale); + while *budget > 0 && k.is_finite() && k >= crate::pattern::MIN_PLACEMENT_SCALE { + // The first tile always sits on the start point; the others only while they end before the path does. + if !out.is_empty() && at + w * k / 2.0 > len + 1e-9 { + break; + } + out.push((at, k)); + *budget -= 1; + // At least a pixel between tile centres, so every layout ends. + at += (w.min(h) * k + spacing).max(1.0); + k = f64::from((k * progression) as f32); + } + if self.fit + && let Some(&(last, k)) = out.last() + && last > 0.0 + { + let stretch = (len - w * k / 2.0).max(0.0) / last; + for p in &mut out { + p.0 *= stretch; + } + } + out + } + + /// The tiles of a `width` x `height` pattern laid along `lines` over `rect` (row-major straight RGBA, transparent + /// where no tile lies). + pub fn render(&self, tile: &Tile, width: u32, height: u32, lines: &[Polyline], rect: Rect) -> Vec<[f32; 4]> { + let len = rect.width() as usize * rect.height() as usize; + let mut out = vec![[0.0f32; 4]; len]; + if len == 0 || width == 0 || height == 0 { + return out; + } + // At the f32 precision the placement maps with, so the tile bounds here are the ones it samples. + let scale = if self.scale.is_finite() && self.scale > 0.0 { f64::from(self.scale as f32) } else { 1.0 }; + let size = (f64::from(width), f64::from(height)); + let mut budget = MAX_PATH_TILES; + for (n, line) in lines.iter().enumerate() { + let places = self.positions(line.length(), size, scale, &mut budget); + let at: Vec = places.iter().map(|p| p.0).collect(); + for (k, ((point, dir), &(_, scale))) in line.sample(&at).into_iter().zip(&places).enumerate() { + self.draw(tile, size, OnPath { point, dir, scale, id: (n as i64, k as i64) }, rect, &mut out); + } + } + out + } + + /// Draws tile `on` of a `size` pattern over what `out` (laid over `rect`) holds. + fn draw(&self, tile: &Tile, size: (f64, f64), on: OnPath, rect: Rect, out: &mut [[f32; 4]]) { + let (tw, th) = (size.0 * on.scale, size.1 * on.scale); + let turn = if self.angle.is_finite() { self.angle } else { 0.0 }; + // Counter-clockwise on screen (y down) is against the path's own turn. + let angle = if self.upright { 0.0 } else { -on.dir.1.atan2(on.dir.0).to_degrees() + turn }; + let distance = if self.distance.is_finite() { self.distance } else { 0.0 }; + let centre = (on.point.0 + on.dir.1 * distance, on.point.1 - on.dir.0 * distance); + let (c, s) = (angle.to_radians().cos(), angle.to_radians().sin()); + let (hx, hy) = (-tw / 2.0, -th / 2.0); + let origin = (centre.0 + hx * c + hy * s, centre.1 - hx * s + hy * c); + let place = Placement::anchored(origin, true, (0.0, 0.0), on.scale as f32, angle as f32); + // The pixels the turned tile can reach, inside `rect`. + let (ex, ey) = (c.abs() * tw / 2.0 + s.abs() * th / 2.0, s.abs() * tw / 2.0 + c.abs() * th / 2.0); + let clamp = |v: f64, lo: i32, hi: i32| if v.is_nan() { lo } else { v.clamp(f64::from(lo), f64::from(hi)) as i32 }; + let (x0, x1) = (clamp((centre.0 - ex).floor(), rect.x0, rect.x1), clamp((centre.0 + ex).ceil(), rect.x0, rect.x1)); + let (y0, y1) = (clamp((centre.1 - ey).floor(), rect.y0, rect.y1), clamp((centre.1 + ey).ceil(), rect.y0, rect.y1)); + // Mirrored top to bottom: each pixel is read from its reflection across the tile's middle line. + let mirror = self.alternate && on.id.1 % 2 == 0; + let axis = (c, -s); + let stride = rect.width() as usize; + for y in y0..y1 { + for x in x0..x1 { + let (mut px, mut py) = (f64::from(x) + 0.5, f64::from(y) + 0.5); + if mirror { + let (dx, dy) = (px - centre.0, py - centre.1); + let along = dx * axis.0 + dy * axis.1; + (px, py) = (centre.0 + 2.0 * along * axis.0 - dx, centre.1 + 2.0 * along * axis.1 - dy); + } + let (u, v) = place.map(px, py); + if !(0.0..size.0).contains(&u) || !(0.0..size.1).contains(&v) { + continue; + } + let mut q = tile.sample_area(&place, px, py); + let d = self.jitter.offsets(on.id.0, on.id.1); + for ch in 0..3 { + if d[ch] != 0.0 { + q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); + } + } + // The new tile over what lies under it. + let i = (y - rect.y0) as usize * stride + (x - rect.x0) as usize; + let under = out[i]; + let a = q[3] + under[3] * (1.0 - q[3]); + if a > 0.0 { + let mut mixed = [0.0f32; 4]; + for ch in 0..3 { + mixed[ch] = (q[ch] * q[3] + under[ch] * under[3] * (1.0 - q[3])) / a; + } + mixed[3] = a.min(1.0); + out[i] = mixed; + } + } + } + } +} diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index bd5228cd88..bd387e2fc7 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -139,7 +139,7 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { // With a script the pattern is laid out tile by tile instead of repeated. if let Some(script) = script(p)? { out["script"] = json!(script); - Source::Pixels(area, scripted(p, script, &tile, &pat, area)?) + Source::Pixels(area, scripted(s, p, script, &tile, &pat, area)?) } else { // Photoshop's Fill uses the canvas origin. let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, (0.0, 0.0), scale, angle); @@ -210,15 +210,25 @@ fn script(p: &Value) -> Result> { } /// The scripted pattern `script` laid out over `area`, with its values from `p` (each clamped to its range, the factory -/// value when missing) and an optional whole-number `seed` for the per-tile randomness. -fn scripted(p: &Value, script: &str, tile: &photocraft_compose::pattern::Tile, pat: &photocraft_doc::pattern::Pattern, area: Rect) -> Result> { - use photocraft_compose::scripted_pattern::{BrickFill, Jitter, controls}; - let controls = - controls(script, pat.width, pat.height).ok_or_else(|| bad(format!("the `{script}` script is not supported yet; only brickFill paints today")))?; +/// value when missing; a check box takes true or false) and an optional whole-number `seed` for the per-tile randomness. +/// Place Along Path lays the tiles along the document path `path` names ("work", "layer" or a saved path's name). +fn scripted( + s: &Session, + p: &Value, + script: &str, + tile: &photocraft_compose::pattern::Tile, + pat: &photocraft_doc::pattern::Pattern, + area: Rect, +) -> Result> { + use photocraft_compose::scripted_pattern::{BrickFill, Jitter, PlaceAlongPath, controls, path_lines}; + let controls = controls(script, pat.width, pat.height) + .ok_or_else(|| bad(format!("the `{script}` script is not supported yet; only brickFill and placeAlongPath paint today")))?; let mut values = std::collections::HashMap::new(); for c in &controls { let v = match p.get(c.key) { None | Some(Value::Null) => c.default, + Some(Value::Bool(on)) if c.toggle => f64::from(u8::from(*on)), + Some(v) if c.toggle => return Err(bad(format!("`{}` must be true or false, not {v}", c.key))), Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(format!("`{}` must be a number {}..{}, not {v}", c.key, c.min, c.max)))?, }; values.insert(c.key, c.clamp(v)); @@ -229,10 +239,48 @@ fn scripted(p: &Value, script: &str, tile: &photocraft_compose::pattern::Tile, p }; let get = |k: &str| values.get(k).copied().unwrap_or_default(); let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed }; + if script == "placeAlongPath" { + let lines = path_lines(&selected_path(s, p)?); + let on = |k: &str| get(k) >= 0.5; + let layout = PlaceAlongPath { + scale: get("patternScale"), + spacing: get("spacing"), + fit: on("adjustSpacingToFit"), + angle: get("angleFromPath"), + distance: get("distanceFromPath"), + alternate: on("alternatePatterns"), + progression: get("scaleProgression"), + upright: on("skipSymbolRotation"), + jitter, + }; + return Ok(layout.render(tile, pat.width, pat.height, &lines, area)); + } let brick = BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter }; Ok(brick.render(tile, pat.width, pat.height, area)) } +/// The path Place Along Path follows: the one `path` names, as the Paths panel selected it ("work", "layer" for the +/// active layer's shape path or vector mask, or a saved path's name). Without one nothing is filled. +fn selected_path(s: &Session, p: &Value) -> Result { + const NONE: &str = "No path selected. Please select at least one path"; + let name = match p.get("path") { + // A plain message, as it is the user's to act on: the reference application's alert names no parameter. + None | Some(Value::Null) => return Err(EngineError::Other(NONE.into())), + Some(Value::String(name)) => name.as_str(), + Some(v) => return Err(bad(format!("`path` must be a path name, not {v}"))), + }; + let st = s.active().ok_or(EngineError::NoDocument)?; + let path = match name { + "work" => st.doc.work_path.as_ref(), + "layer" => st.active_layer.and_then(|id| st.doc.layer(id)).and_then(|l| match &l.content { + photocraft_doc::LayerContent::Shape(shape) => Some(&shape.path), + _ => l.vector_mask.as_ref().map(|v| &v.path), + }), + name => st.doc.paths.iter().find(|q| q.name == name).map(|q| &q.path), + }; + path.cloned().ok_or_else(|| EngineError::Other(NONE.into())) +} + /// The reference application refuses Fill on the Quick Mask with a colour-only blend mode, Preserve Transparency or /// History contents, and leaves the channel as it was (#17489). fn check_quick_mask(contents: &str, mode: BlendMode, preserve: bool) -> Result<()> { diff --git a/crates/engine-paint/src/fill_script_brick_tests.rs b/crates/engine-paint/src/fill_script_brick_tests.rs index a541190710..69b398f3f2 100644 --- a/crates/engine-paint/src/fill_script_brick_tests.rs +++ b/crates/engine-paint/src/fill_script_brick_tests.rs @@ -1,7 +1,7 @@ //! #17428: Edit › Fill › Pattern with Script on lays the pattern out tile by tile. `edit.fill` takes `script` and the //! script's values; Brick Fill paints rows of whole tiles from the canvas origin with every second row shifted left by -//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the five -//! listed scripts without a layout yet answer "not supported". +//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the listed +//! scripts without a layout yet answer "not supported". use serde_json::{Value, json}; @@ -163,7 +163,7 @@ fn an_unknown_script_is_an_error_and_the_unbuilt_ones_are_unsupported() { let before = undo_label(&s); let err = s.execute("edit.fill", brick(json!({"script": "noSuchScript"}))).unwrap_err().to_string(); assert!(err.contains("unknown script"), "{err}"); - for script in ["crossWeave", "placeAlongPath", "randomFill", "spiral", "symmetryFill"] { + for script in ["crossWeave", "randomFill", "spiral", "symmetryFill"] { let err = s.execute("edit.fill", brick(json!({"script": script}))).unwrap_err().to_string(); assert!(err.contains("not supported"), "{script}: {err}"); } diff --git a/crates/engine-paint/src/fill_script_place_along_path_tests.rs b/crates/engine-paint/src/fill_script_place_along_path_tests.rs new file mode 100644 index 0000000000..88f6eef0d5 --- /dev/null +++ b/crates/engine-paint/src/fill_script_place_along_path_tests.rs @@ -0,0 +1,247 @@ +//! #17430: Edit › Fill › Pattern with the Place Along Path script lays the pattern tile along the selected path +//! (`path`: "work", "layer" or a saved path's name). On a straight path the tiles are centred on the line, the first on +//! the start point, a step of the tile's shorter side apart, the last ending where the path does, every other tile +//! mirrored top to bottom. Without a selected path the fill is refused and nothing changes. + +use serde_json::{Value, json}; + +use crate::Session; + +const RED: [u8; 3] = [255, 0, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; +const GREEN: [u8; 3] = [0, 255, 0]; + +/// A 600 x 400 white document with an empty pixel layer on top (active) and the 40 x 30 probe pattern defined: left +/// half red, right half blue, the bottom-right 20 x 15 quarter green, so a turn and a mirror show. The saved path +/// "line" runs from (50,200) to (550,200). +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + for (rect, color) in [([0, 0, 20, 30], "#ff0000"), ([20, 0, 20, 15], "#0000ff"), ([20, 15, 20, 15], "#00ff00")] { + s.execute("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + } + s.execute("edit.definePattern", json!({"name": "probe", "rect": [0, 0, 40, 30]})).unwrap(); + s.execute("file.new", json!({"width": 600, "height": 400, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + set_path(&mut s, "line", json!([[50, 200], [550, 200]])); + s +} + +/// Saves an open path `name` through `knots`. +fn set_path(s: &mut Session, name: &str, knots: Value) { + s.execute("path.set", json!({"name": name, "path": {"subpaths": [{"closed": false, "knots": knots}]}})).unwrap(); +} + +/// Place Along Path along "line" with both randomness values at 0 and `extra` values on top. +fn along(extra: Value) -> Value { + let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "placeAlongPath", "path": "line", "colorRandomness": 0, "brightnessRandomness": 0}); + for (k, v) in extra.as_object().into_iter().flatten() { + p[k] = v.clone(); + } + p +} + +fn pixel(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn rgb8(px: [f32; 4]) -> [u8; 3] { + [0, 1, 2].map(|c| (px[c] * 255.0).round() as u8) +} + +/// The painted pixels' bounds, (x0, y0, x1, y1) exclusive, if any. +fn bounds(s: &Session) -> Option<(i32, i32, i32, i32)> { + let mut b: Option<(i32, i32, i32, i32)> = None; + for y in 0..400 { + for x in 0..600 { + if pixel(s, x, y)[3] > 0.0 { + b = Some(b.map_or((x, y, x + 1, y + 1), |(x0, y0, x1, y1)| (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)))); + } + } + } + b +} + +/// The colour runs along row `y` between `from` and `to`. +fn runs(s: &Session, y: i32, from: i32, to: i32) -> Vec<(i32, [u8; 3])> { + let mut out: Vec<(i32, [u8; 3])> = Vec::new(); + for x in from..to { + let c = rgb8(pixel(s, x, y)); + if out.last().is_none_or(|(_, last)| *last != c) { + out.push((x, c)); + } + } + out +} + +fn undo_label(s: &Session) -> Option { + s.active().unwrap().history.undo_label().map(str::to_string) +} + +#[test] +fn tiles_step_along_a_straight_path_from_its_start_to_its_end() { + let mut s = session(); + let r = s.execute("edit.fill", along(json!({}))).unwrap(); + assert_eq!(r["script"], "placeAlongPath"); + // Centred on the line, the first tile on the start point, the last ending at the path's end. + assert_eq!(bounds(&s), Some((30, 185, 550, 215))); + // Each tile lies over the one before, 30 px on: 20 px of red, then the 10 px of the earlier tile left showing. The + // first, third, ... are mirrored, so their upper half shows green where the pattern has blue. + let top = runs(&s, 190, 30, 130); + assert_eq!(top, vec![(30, RED), (50, GREEN), (60, RED), (80, BLUE), (90, RED), (110, GREEN), (120, RED)]); + let bottom = runs(&s, 210, 30, 130); + assert_eq!(bottom, vec![(30, RED), (50, BLUE), (60, RED), (80, GREEN), (90, RED), (110, BLUE), (120, RED)]); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); +} + +#[test] +fn alternate_patterns_off_leaves_every_tile_as_the_pattern() { + let mut s = session(); + s.execute("edit.fill", along(json!({"alternatePatterns": false}))).unwrap(); + assert_eq!(runs(&s, 190, 30, 100), vec![(30, RED), (50, BLUE), (60, RED), (80, BLUE), (90, RED)]); +} + +#[test] +fn tiles_turn_with_the_path_unless_rotation_is_skipped() { + // Down the canvas: each tile turns a quarter, so it is 30 px wide across the path. + let mut s = session(); + set_path(&mut s, "line", json!([[300, 50], [300, 350]])); + s.execute("edit.fill", along(json!({}))).unwrap(); + let (x0, _, x1, _) = bounds(&s).unwrap(); + assert_eq!((x0, x1), (285, 315)); + // Upright tiles stay 40 px wide. + let mut s = session(); + set_path(&mut s, "line", json!([[300, 50], [300, 350]])); + s.execute("edit.fill", along(json!({"skipSymbolRotation": true, "angleFromPath": 45}))).unwrap(); + let (x0, _, x1, _) = bounds(&s).unwrap(); + assert_eq!((x0, x1), (280, 320)); +} + +#[test] +fn distance_spacing_and_scale_move_the_tiles() { + let mut plain = session(); + plain.execute("edit.fill", along(json!({}))).unwrap(); + let plain = bounds(&plain).unwrap(); + // Distance lifts the tiles off the path, to the left of its direction (up for a path heading right). + let mut s = session(); + s.execute("edit.fill", along(json!({"distanceFromPath": 50}))).unwrap(); + let lifted = bounds(&s).unwrap(); + assert!(lifted.1 < plain.1 && lifted.3 < plain.3, "{lifted:?} above {plain:?}"); + // More spacing leaves gaps between the tiles. + let mut s = session(); + s.execute("edit.fill", along(json!({"spacing": 20}))).unwrap(); + assert!(pixel(&s, 72, 200)[3] == 0.0 && pixel(&s, 85, 200)[3] > 0.99, "a gap after the first tile"); + // A smaller scale makes smaller tiles. + let mut s = session(); + s.execute("edit.fill", along(json!({"patternScale": 0.5}))).unwrap(); + let small = bounds(&s).unwrap(); + assert!(small.3 - small.1 < plain.3 - plain.1, "{small:?} lower than {plain:?}"); + // A growing scale progression makes later tiles taller. + let mut s = session(); + s.execute("edit.fill", along(json!({"scaleProgression": 110}))).unwrap(); + let grown = bounds(&s).unwrap(); + assert!(grown.3 - grown.1 > plain.3 - plain.1, "{grown:?} taller than {plain:?}"); +} + +#[test] +fn adjust_spacing_to_fit_ignores_spacing_and_ends_at_the_path_end() { + let mut fit = session(); + fit.execute("edit.fill", along(json!({"adjustSpacingToFit": true}))).unwrap(); + let mut wide = session(); + wide.execute("edit.fill", along(json!({"adjustSpacingToFit": true, "spacing": 37}))).unwrap(); + assert_eq!(runs(&fit, 190, 0, 600), runs(&wide, 190, 0, 600), "Spacing does not apply"); + // A path whose length leaves a remainder: the steps stretch so the last tile still ends at the path end. + let mut s = session(); + set_path(&mut s, "line", json!([[50, 200], [565, 200]])); + s.execute("edit.fill", along(json!({"adjustSpacingToFit": true}))).unwrap(); + assert_eq!(bounds(&s).map(|b| (b.0, b.2)), Some((30, 565))); + let mut s = session(); + set_path(&mut s, "line", json!([[50, 200], [565, 200]])); + s.execute("edit.fill", along(json!({}))).unwrap(); + assert!(bounds(&s).unwrap().2 < 565, "without it the last tile stops short"); +} + +#[test] +fn without_a_selected_path_nothing_is_filled() { + let mut s = session(); + let before = undo_label(&s); + let mut p = along(json!({})); + p.as_object_mut().unwrap().remove("path"); + for p in [p, along(json!({"path": "no such path"})), along(json!({"path": "work"})), along(json!({"path": "layer"}))] { + let err = s.execute("edit.fill", p.clone()).unwrap_err().to_string(); + assert!(err.contains("No path selected"), "{p}: {err}"); + } + assert_eq!(undo_label(&s), before, "no history state"); + assert_eq!(bounds(&s), None, "no pixels"); +} + +#[test] +fn the_work_path_and_the_layer_path_can_be_followed() { + let mut s = session(); + s.execute("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[50, 100], [200, 100]]}]}})).unwrap(); + s.execute("edit.fill", along(json!({"path": "work"}))).unwrap(); + assert_eq!(bounds(&s).map(|b| (b.1, b.3)), Some((85, 115))); +} + +#[test] +fn the_fill_stays_in_the_selection_with_mode_and_opacity() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 400})).unwrap(); + s.execute("edit.fill", along(json!({"opacity": 50}))).unwrap(); + assert!((pixel(&s, 35, 200)[3] - 0.5).abs() < 0.01, "half opacity"); + assert_eq!(pixel(&s, 150, 200)[3], 0.0, "outside the selection"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&s, 35, 200)[3], 0.0, "one history state"); + // A blend mode applies too: Multiply over the empty layer still paints the tile's colour. + s.execute("select.deselect", json!({})).unwrap(); + s.execute("edit.fill", along(json!({"mode": "multiply"}))).unwrap(); + assert_eq!(rgb8(pixel(&s, 35, 200)), RED); +} + +#[test] +fn bad_values_are_errors() { + let mut s = session(); + for bad in [json!({"path": 3}), json!({"adjustSpacingToFit": 1}), json!({"alternatePatterns": "yes"}), json!({"spacing": "far"})] { + assert!(s.execute("edit.fill", along(bad.clone())).is_err(), "{bad}"); + } + assert_eq!(bounds(&s), None); +} + +#[test] +fn never_panics_on_odd_paths_or_values() { + let paths = [ + json!([[300, 200]]), + json!([[300, 200], [300, 200]]), + json!([[300, 200], [300, 200], [400, 200]]), + json!([[-1e12, 200], [1e12, 200]]), + json!([[1e15, 1e15], [-1e15, -1e15]]), + json!([[0, 0], [600, 400], [0, 400], [600, 0]]), + ]; + let values = [ + json!({}), + json!({"patternScale": 1e9, "spacing": -1e12, "scaleProgression": 1e9}), + json!({"patternScale": 0, "scaleProgression": 0, "distanceFromPath": 1e12, "angleFromPath": -1e9}), + json!({"adjustSpacingToFit": true, "colorRandomness": 1, "brightnessRandomness": 1, "seed": 7}), + ]; + for knots in &paths { + for v in &values { + let mut s = session(); + set_path(&mut s, "line", knots.clone()); + s.execute("edit.fill", along(v.clone())).unwrap_or_else(|e| panic!("{knots} {v}: {e}")); + } + } + // A closed curved path and an empty one. + let mut s = session(); + let curve = json!({"subpaths": [{"closed": true, "knots": [ + {"anchor": [300, 100], "in": [250, 100], "out": [350, 100]}, + {"anchor": [300, 300], "in": [350, 300], "out": [250, 300]} + ]}]}); + s.execute("path.set", json!({"name": "line", "path": curve})).unwrap(); + s.execute("edit.fill", along(json!({}))).unwrap(); + assert!(bounds(&s).is_some()); + s.execute("path.set", json!({"name": "line", "path": {"subpaths": []}})).unwrap(); + s.execute("edit.fill", along(json!({}))).unwrap(); +} diff --git a/crates/engine-paint/src/lib.rs b/crates/engine-paint/src/lib.rs index 21025b6ed9..c57facf661 100644 --- a/crates/engine-paint/src/lib.rs +++ b/crates/engine-paint/src/lib.rs @@ -48,6 +48,8 @@ mod fill_quick_mask_refusals_tests; #[cfg(test)] mod fill_script_brick_tests; #[cfg(test)] +mod fill_script_place_along_path_tests; +#[cfg(test)] mod mixer_indexed_bitmap_tests; #[cfg(test)] mod mixer_toggle_commands_tests; diff --git a/crates/ui-egui/src/dialogs/fill_script_ui.rs b/crates/ui-egui/src/dialogs/fill_script_ui.rs index 4d042d0eff..59b30d32b7 100644 --- a/crates/ui-egui/src/dialogs/fill_script_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_script_ui.rs @@ -11,7 +11,8 @@ use craft::ui::runtime::env::Label; use craft::ui::runtime::memory::{MemoryStage, SaveKey}; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::value_drag::SliderScale; -use photocraft_compose::scripted_pattern::{BrickFill, Control, Jitter, SCRIPTS, controls}; +use photocraft_compose::scripted_pattern::{BrickFill, Control, Jitter, PlaceAlongPath, SCRIPTS, controls, greyed_by}; +use photocraft_vector::flatten::Polyline; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; @@ -50,6 +51,12 @@ fn label(key: &str) -> Label { "colorRandomness" => tl!("Color randomness"), "brightnessRandomness" => tl!("Brightness randomness"), "patternRotateAngle" => tl!("Pattern rotate angle"), + "adjustSpacingToFit" => tl!("Adjust spacing to fit"), + "angleFromPath" => tl!("Angle from path"), + "distanceFromPath" => tl!("Distance from path"), + "alternatePatterns" => tl!("Alternate patterns"), + "scaleProgression" => tl!("Scale progression"), + "skipSymbolRotation" => tl!("Skip symbol rotation"), _ => tl!("Value"), }) } @@ -57,9 +64,9 @@ fn label(key: &str) -> Label { /// The unit shown after a value's field, if any. fn unit(key: &str) -> Option