diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 9b5771e7bd..b031cf4c44 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -19,7 +19,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::color::{BlendMode, Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId}; use vectorcraft_geom::hit::fill_contains; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, BezPath, CubicBez, FillRule, PathData, Point, Rect, shapes}; use vectorcraft_pathops::{self as po, BoolOp}; use crate::catalog::{EffectInfo, Lengths}; @@ -43,7 +43,7 @@ pub(crate) fn catalog() -> Vec { id: HALFTONE, label: "Vector Halftone…", menu: &["Effect", "Color Effects"], - params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", + params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), raster: false, lengths: Lengths::default(), @@ -63,6 +63,12 @@ pub enum DotShape { Square, Diamond, Line, + /// Round dots that grow into squares meeting corner to corner at 50% (a checkerboard), then + /// round holes, as the Euclidean spot function draws them. + Euclidean, + /// Elongated dots that join along their long side at 40% into chains, along their short side + /// at 60%, then elongated holes. + Elliptical, } impl DotShape { @@ -73,6 +79,8 @@ impl DotShape { "square" => DotShape::Square, "diamond" => DotShape::Diamond, "line" | "lines" => DotShape::Line, + "euclidean" => DotShape::Euclidean, + "elliptical" => DotShape::Elliptical, _ => return None, }) } @@ -94,10 +102,149 @@ impl DotShape { DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)), // Cells along a row join into a line as thick as the tone. DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))), + DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, 1.0, &EUCLIDEAN)), + DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, elliptical_ratio(), &ELLIPTICAL)), } } } +/// The Elliptical dot's height over its width: the ratio at which a dot exactly as wide as its +/// cell, clipped to the cell's diamond, covers 40% of the cell. +fn elliptical_ratio() -> f64 { + static R: OnceLock = OnceLock::new(); + *R.get_or_init(|| { + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if quadrant_area(1.0, mid, 1.0) < 0.4 { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) +} + +/// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5. +const SIZE_STEPS: usize = 512; + +static EUCLIDEAN: OnceLock> = OnceLock::new(); +static ELLIPTICAL: OnceLock> = OnceLock::new(); + +/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the ellipse with height `ratio × a` whose part +/// inside the diamond |x| + |y| ≤ 1 covers that tone of the cell [-1, 1]². +fn dot_sizes(ratio: f64) -> Vec { + (0..=SIZE_STEPS) + .map(|k| { + // A quadrant of the cell has area 1. + let target = k as f64 / SIZE_STEPS as f64 * 0.5; + let (mut lo, mut hi) = (0.0, 1.0 / ratio); + for _ in 0..50 { + let mid = (lo + hi) / 2.0; + if quadrant_area(mid, mid * ratio, 1.0) < target { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) + .collect() +} + +/// The area of the first quadrant of the ellipse with semi-axes `a`, `b` clipped to x + y ≤ `h`. +fn quadrant_area(a: f64, b: f64, h: f64) -> f64 { + use vectorcraft_geom::kurbo::ParamCurveArea; + quadrant(a, b, h).iter().map(|c| c.signed_area()).sum() +} + +/// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤ +/// `h`, from its point on the x axis to its point on the y axis, as cubic curves. +fn quadrant(a: f64, b: f64, h: f64) -> Vec { + use std::f64::consts::FRAC_PI_2; + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let arc = |out: &mut Vec, t0: f64, t1: f64| { + if t1 <= t0 { + return; + } + let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); + let d = (t1 - t0) / n; + let k = 4.0 / 3.0 * (d / 4.0).tan(); + for i in 0..n as usize { + let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0)); + let (p0, p3) = (at(u0), at(u1)); + let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos()); + let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos()); + out.push(CubicBez::new(p0, c1, c2, p3)); + } + }; + let line = |p: Point, q: Point| CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q); + let mut out = vec![]; + let r = a.hypot(b); + if r <= h { + arc(&mut out, 0.0, FRAC_PI_2); + return out; + } + let (phi, alpha) = (b.atan2(a), (h / r).acos()); + let (ts, te) = (phi - alpha, phi + alpha); + let start = if ts > 0.0 { + arc(&mut out, 0.0, ts); + at(ts) + } else { + Point::new(h, 0.0) + }; + let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) }; + out.push(line(start, end)); + arc(&mut out, te, FRAC_PI_2); + out +} + +/// `curves` reversed, each curve run backwards. +fn reversed(curves: &[CubicBez]) -> Vec { + curves.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect() +} + +/// `curves` with each point mapped by `f`. +fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec { + curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect() +} + +/// The quadrant of the spot for tone `u` (0..0.5) in a cell of half side `h`, its dot `ratio` as +/// tall as wide, its sizes from `table` ([`dot_sizes`]). +fn spot_quadrant(u: f64, h: f64, ratio: f64, table: &OnceLock>) -> Vec { + let sizes = table.get_or_init(|| dot_sizes(ratio)); + let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64; + let i = (x.floor() as usize).min(SIZE_STEPS - 1); + let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); + let a = lo + (hi - lo) * (x - i as f64); + quadrant(a * h, a * ratio * h, h) +} + +/// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to +/// half tone, an ellipse (`ratio` as tall as wide) clipped to the cell's diamond, with the tone's +/// area; past half, the cell with the dot of the opposite tone cut out at each corner, so the dark +/// joins up and the light becomes holes. +fn spot(t: f64, h: f64, ratio: f64, table: &OnceLock>) -> BezPath { + let mut bp = BezPath::new(); + let mut add = |curves: Vec, first: bool| { + for (k, c) in curves.iter().enumerate() { + if k == 0 { + if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + } + bp.curve_to(c.p1, c.p2, c.p3); + } + }; + if t <= 0.5 { + let q1 = spot_quadrant(t, h, ratio, table); + add(q1.clone(), true); + add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false); + add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false); + add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false); + } else { + // Round the corners counterclockwise, each one's hole the dot of the opposite tone. + let q1 = spot_quadrant(1.0 - t.min(1.0), h, ratio, table); + add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); + add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); + add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); + add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + } + bp.close_path(); + bp +} + /// One screen: its ink and angle, and how to read its tone from a sampled pixel. struct Screen { paint: Color, @@ -399,6 +546,7 @@ pub fn halftone_art(d: &Document, n: &Node) -> Option { mod tests { use super::*; use vectorcraft_doc::Effect; + use vectorcraft_geom::Shape; /// A black square's samples: `side` points of black from (10, 10), white around it. fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) { @@ -464,6 +612,69 @@ mod tests { assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2); } + /// Is `p` (in cells of side 1) inside the dot `shape` draws for tone `t`? + fn covers(shape: DotShape, t: f64, p: (f64, f64)) -> bool { + fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1)) + } + + #[test] + fn spot_dots_cover_the_tone() { + for shape in [DotShape::Euclidean, DotShape::Elliptical] { + for k in 1..100 { + let t = f64::from(k) / 100.0; + let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0; + assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}"); + let b = shape.path(t, 2.0).control_bounds().unwrap(); + assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}"); + } + } + assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical))); + } + + #[test] + fn euclidean_dots_meet_corner_to_corner_at_half() { + let s = DotShape::Euclidean; + // Round dots apart from their neighbors below half. + assert!(!covers(s, 0.45, (0.49, 0.0)) && !covers(s, 0.45, (0.0, 0.49)) && covers(s, 0.45, (0.3, 0.0))); + // At half the dot is the diamond reaching the middle of each side: a checkerboard. + for p in [(0.49, 0.0), (-0.49, 0.0), (0.0, 0.49), (0.0, -0.49)] { + assert!(covers(s, 0.5, p), "{p:?}"); + } + assert!(!covers(s, 0.5, (0.26, 0.26)) && covers(s, 0.5, (0.24, 0.24))); + // Past half the light becomes round holes at the corners. + assert!(covers(s, 0.55, (0.0, 0.499)) && covers(s, 0.55, (0.499, 0.0)) && !covers(s, 0.55, (0.49, 0.49))); + assert!(covers(s, 0.99, (0.3, 0.3))); + } + + #[test] + fn elliptical_dots_join_along_their_length_then_their_width() { + let s = DotShape::Elliptical; + // Below 40% the dots stand apart. + assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45))); + // From 40% they reach their neighbors along x, making chains, but not along y. + assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45))); + // Up to 60% the light still runs along the top edge between the corner holes. + assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3))); + // Past 60% the dark joins across the top edge too, leaving elongated holes. + assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49))); + // The holes are longer along x than along y. + assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {}", elliptical_ratio()); + // Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall. + let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap(); + assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}"); + } + + #[test] + fn spot_shapes_make_dots_through_the_screen() { + for shape in [DotShape::Euclidean, DotShape::Elliptical] { + let h = Halftone::of(&effect(json!({"frequency": 18, "shape": format!("{shape:?}")}))).unwrap(); + assert_eq!(h.shape, shape); + let (s, b) = black_square(60.0, &h); + let (layers, dots) = h.layers(&s, b, None); + assert!(layers.len() == 1 && (150..=320).contains(&dots), "{shape:?}: {dots}"); + } + } + #[test] fn the_caps_refuse_too_many_cells() { let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap(); diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index b54e92932c..9677f23ad6 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] @@ -28,7 +28,9 @@ pub fn specs() -> Vec { fn halftone(s: &mut Session, p: &Value) -> Result { const C: &str = "object.vectorHalftone"; let shape = match text_param(p, "shape", C)? { - Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?, + Some(v) => { + DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))? + } None => DotShape::Circle, }; let frequency = number_or(p, "frequency", 20.0, C)?; diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index 98a8515c16..ebc54223f6 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -47,7 +47,15 @@ pub(super) fn options>(list: &[(I, &str)]) -> Vec<(String, Label)> /// Vector Halftone adds Keep Original. The Color row depends on two values, so the rows are built /// from `fields`. pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { - let shapes = [("circle", "Circle"), ("ellipse", "Ellipse"), ("square", "Square"), ("diamond", "Diamond"), ("line", "Line")]; + let shapes = [ + ("circle", "Circle"), + ("ellipse", "Ellipse"), + ("square", "Square"), + ("diamond", "Diamond"), + ("line", "Line"), + ("euclidean", "Euclidean"), + ("elliptical", "Elliptical"), + ]; let mut rows = vec![ Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into()))), Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch), diff --git a/docs/mcp.md b/docs/mcp.md index 55886fae8f..8ffe40b45c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15588,7 +15588,7 @@ effects keep their colours. ## Vector halftone `object.vectorHalftone` turns the selection into vector dots, lines or shapes sized by its -tone (mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the +tone (the `shape` values are those of the live effect below, Euclidean and Elliptical dots included; mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the art that can't be decoded is sampled as blank (no dots, or full dots with `invert`), and the result carries the `warning` that Flatten Transparency gives: @@ -17619,7 +17619,7 @@ Object › Vector Halftone without Keep Original, and the Appearance panel reope | Parameter | Values (default) | Does | |---|---|---| -| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line` (`circle`) | The dot shape; lines join along a row | +| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line`, `euclidean`, `elliptical` (`circle`) | The dot shape; lines join along a row; `euclidean` dots are round, meet corner to corner at 50% and turn into round holes past it; `elliptical` dots are long, join into chains along their length at 40% and on every side at 60%, then turn into long holes | | `frequency` | lines per inch 1…300 (20) | Cells per inch of the screen | | `angle` | degrees (45) | The screen angle; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it | | `mode` | `mono`, `cmyk` (`mono`) | One screen following lightness, or four ink screens following the art's ink amounts, multiplied over each other | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index db42c0d72c..8e956a2c75 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1460,6 +1460,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). + - Vector Halftone (Object › Vector Halftone and the live effect) has Euclidean and Elliptical dot shapes: Euclidean dots meet corner to corner at 50% and become round holes past it; Elliptical dots join into chains at 40% and on every side at 60%, then become long holes. Each dot covers its cell's tone. - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown.