mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 19:04:25 +01:00
Merge main into feat/new-document-profiles
This commit is contained in:
commit
22a19db2cd
515 files changed
+43774
-3189
No files matched your search
@@ -267,6 +267,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/flip-vertical-2.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
|
||||
| `assets/icons/folder-open.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
|
||||
| `assets/icons/frame.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
|
||||
| `assets/icons/graduation-cap.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | Learn panel, Explore tutorials button |
|
||||
| `assets/icons/grid-3x3.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
|
||||
| `assets/icons/group.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
|
||||
| `assets/icons/hand.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
|
||||
|
||||
Generated
+1
@@ -6326,6 +6326,7 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"futures-lite",
|
||||
"image",
|
||||
"log",
|
||||
"muda",
|
||||
|
||||
@@ -122,10 +122,13 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
## Progress log
|
||||
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
@@ -138,6 +141,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
|
||||
- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
|
||||
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
|
||||
- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged.
|
||||
- 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn.
|
||||
|
||||
@@ -107,6 +107,9 @@ wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
|
||||
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
|
||||
# through winit and rfd.
|
||||
wayland-backend = { version = "0.3", features = ["client_system"] }
|
||||
# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same
|
||||
# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus.
|
||||
futures-lite = "2"
|
||||
|
||||
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
|
||||
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
|
||||
|
||||
@@ -651,6 +651,7 @@ mod portable {
|
||||
|
||||
impl Answer {
|
||||
/// The answer to `request` when it couldn't be read: `why`, or no files.
|
||||
#[cfg(any(test, target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn failed(request: Request, why: String) -> Self {
|
||||
match request {
|
||||
Request::Text => Self::Text(Err(why)),
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::portal_save;
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::tablet;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::{linux_screen_color, tablet};
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::{mac_save_format, mac_screen_color, mac_tablet};
|
||||
|
||||
@@ -354,8 +354,10 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
@@ -378,9 +380,11 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Load Actions… refuses a file over its size limit without reading all of it.
|
||||
read_head: Some(Box::new(read_file_head)),
|
||||
write: Some(Box::new(write_file)),
|
||||
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
// Background Save and Export write from a worker thread.
|
||||
write_shared: Some(std::sync::Arc::new(write_file)),
|
||||
save_write: Some(std::sync::Arc::new(fileio::write_save_file)),
|
||||
save_stream: Some(std::sync::Arc::new(fileio::write_save_file_with)),
|
||||
// Native saves stream into the file as they are encoded.
|
||||
stream_shared: Some(std::sync::Arc::new(|p: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
|
||||
fileio::write_file_with(p, fill).map_err(|e| e.to_string())
|
||||
@@ -406,6 +410,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Linux: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the XDG desktop
|
||||
//! portal's color sampler ([`portal`]). A thread of its own asks the portal and waits for the
|
||||
//! person, so the UI keeps drawing; it sends the color to the UI and wakes the window. The dialog's
|
||||
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
|
||||
|
||||
mod portal;
|
||||
mod request;
|
||||
|
||||
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
|
||||
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let (ui, window) = (ui.clone(), parent.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
// The thread names the window and holds it until the export that names it is dropped.
|
||||
let (handle, export) = match window.as_deref() {
|
||||
Some(window) => {
|
||||
let (handle, export) = super::portal_save::exported_parent(window);
|
||||
(handle, Some(export))
|
||||
}
|
||||
None => (String::new(), None),
|
||||
};
|
||||
let picked = portal::connect(zbus::blocking::connection::Builder::session()).and_then(|conn| portal::pick(&conn, &handle));
|
||||
drop(export);
|
||||
drop(window);
|
||||
let answer = picked.map_err(|failure| {
|
||||
log::warn!("the portal's screen color sampler gave no color: {}", failure.detail());
|
||||
failure.message().to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
"the screen color sampler failed".to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
//! The XDG desktop portal's `Screenshot.PickColor`
|
||||
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html>):
|
||||
//! the call returns a request path at once, and the request's `Response` signal later carries the
|
||||
//! color the person picked, as sRGB components from 0 to 1, or a code for a cancel or another end.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use zbus::blocking::{Connection, Proxy};
|
||||
use zbus::zvariant::{OwnedValue, Value};
|
||||
|
||||
/// How long the portal has to return a request path for `PickColor`. VectorCraft's own limit,
|
||||
/// 25 seconds as libdbus's default for a method call. The portal returns the path before it shows
|
||||
/// the sampler, so the person's time with the sampler does not count.
|
||||
const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
|
||||
|
||||
/// Why no color came back, as the status bar shows it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Failure {
|
||||
/// No session bus, no portal, or a portal without the Screenshot interface's `PickColor`.
|
||||
Unavailable(String),
|
||||
/// The portal did not return a request path in time, or it left the bus before it answered.
|
||||
NoAnswer(String),
|
||||
/// The portal ended the request without a color, or its answer can't be read.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
/// The status bar's message (English; the status bar translates it).
|
||||
pub(super) fn message(&self) -> &'static str {
|
||||
match self {
|
||||
Failure::Unavailable(_) => "this system has no screen color sampler",
|
||||
Failure::NoAnswer(_) => "the screen color sampler did not answer",
|
||||
Failure::Failed(_) => "the screen color sampler failed",
|
||||
}
|
||||
}
|
||||
|
||||
/// What went wrong, for the log.
|
||||
pub(super) fn detail(&self) -> &str {
|
||||
match self {
|
||||
Failure::Unavailable(d) | Failure::NoAnswer(d) | Failure::Failed(d) => d,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// D-Bus errors that mean the session has no portal, or none that answers `PickColor`.
|
||||
const UNAVAILABLE: &[&str] = &[
|
||||
"org.freedesktop.DBus.Error.ServiceUnknown",
|
||||
"org.freedesktop.DBus.Error.NameHasNoOwner",
|
||||
"org.freedesktop.DBus.Error.UnknownMethod",
|
||||
"org.freedesktop.DBus.Error.UnknownInterface",
|
||||
"org.freedesktop.DBus.Error.UnknownObject",
|
||||
];
|
||||
|
||||
/// The connection `builder` makes, with [`CALL_TIMEOUT`] for its method calls.
|
||||
pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<'_>>) -> Result<Connection, Failure> {
|
||||
builder.and_then(|b| b.method_timeout(CALL_TIMEOUT).build()).map_err(|e| Failure::Unavailable(e.to_string()))
|
||||
}
|
||||
|
||||
/// Shows the portal's color sampler over the window `parent` names and waits for the color, `None`
|
||||
/// when the person canceled it. `conn`'s method timeout bounds the call; the wait for the person
|
||||
/// after it has no bound, and ends when the portal answers or leaves the bus.
|
||||
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
let token = super::request::token("vectorcraft_color").map_err(Failure::Failed)?;
|
||||
// Made before the call: a portal can send its answer before the call returns.
|
||||
let replies = super::request::Responses::new(conn).map_err(Failure::Failed)?;
|
||||
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
|
||||
.map_err(|e| Failure::Failed(e.to_string()))?;
|
||||
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
|
||||
let call = proxy.call_method("PickColor", &(parent, options)).map_err(|e| call_failure(&e))?;
|
||||
let reply = replies.wait(&call).map_err(Failure::NoAnswer)?;
|
||||
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| Failure::Failed(e.to_string()))?;
|
||||
answer(code, &results)
|
||||
}
|
||||
|
||||
/// The [`Failure`] for an error the `PickColor` call returned. zbus reports a call that outlives
|
||||
/// the connection's method timeout as an `InputOutput` error of kind `TimedOut`.
|
||||
fn call_failure(e: &zbus::Error) -> Failure {
|
||||
match e {
|
||||
zbus::Error::MethodError(name, ..) if UNAVAILABLE.contains(&name.as_str()) => Failure::Unavailable(e.to_string()),
|
||||
zbus::Error::InputOutput(io) if io.kind() == std::io::ErrorKind::TimedOut => Failure::NoAnswer(e.to_string()),
|
||||
_ => Failure::Failed(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color in a `Response` with `code` and `results`: response 0 carries it, 1 is a cancel, and
|
||||
/// any other code ends the request without one. The components are passed on as given;
|
||||
/// `screen_color::sampled` clamps them to 0 to 1, as for the other systems' samplers.
|
||||
fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f32; 3]>, Failure> {
|
||||
match code {
|
||||
0 => {}
|
||||
1 => return Ok(None),
|
||||
_ => return Err(Failure::Failed(format!("the portal ended the request (response {code})"))),
|
||||
}
|
||||
let color = results.get("color").ok_or_else(|| Failure::Failed("no color in the portal's answer".into()))?;
|
||||
// Matched field by field: zvariant's tuple conversion panics on a structure with fewer fields.
|
||||
match &**color {
|
||||
Value::Structure(s) => match s.fields() {
|
||||
[Value::F64(r), Value::F64(g), Value::F64(b)] => Ok(Some([*r, *g, *b].map(|v| v as f32))),
|
||||
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
|
||||
},
|
||||
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
|
||||
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
|
||||
}
|
||||
|
||||
fn failed<T: std::fmt::Debug>(r: Result<T, Failure>) -> bool {
|
||||
matches!(r, Err(Failure::Failed(_)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picked_color_keeps_its_srgb_values() {
|
||||
assert_eq!(answer(0, &color((0.25, 0.5, 0.75))), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert_eq!(answer(0, &color((0.0, 1.0, 0.0))), Ok(Some([0.0, 1.0, 0.0])));
|
||||
// Outside 0 to 1: passed on for `screen_color::sampled` to clamp.
|
||||
assert_eq!(answer(0, &color((-0.5, 1.5, 1.0))), Ok(Some([-0.5, 1.5, 1.0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_needs_no_color() {
|
||||
assert_eq!(answer(1, &HashMap::new()), Ok(None));
|
||||
assert_eq!(answer(1, &color((0.25, 0.5, 0.75))), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_response_codes_are_failures() {
|
||||
for code in [2, 3, u32::MAX] {
|
||||
assert!(failed(answer(code, &color((0.25, 0.5, 0.75)))), "{code}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_success_without_a_valid_color_is_a_failure() {
|
||||
assert!(failed(answer(0, &HashMap::new())));
|
||||
let wrong = HashMap::from([("color".into(), OwnedValue::from(1_u32))]);
|
||||
assert!(failed(answer(0, &wrong)));
|
||||
// Fewer fields, more fields, and fields of another type: an error, not a panic.
|
||||
for wrong in [Value::from((0.5, 0.5)), Value::from((0.5, 0.5, 0.5, 0.5)), Value::from((1_u32, 0.5, 0.5)), Value::from(vec![0.5, 0.5, 0.5])] {
|
||||
let wrong = HashMap::from([("color".into(), OwnedValue::try_from(wrong).unwrap())]);
|
||||
assert!(failed(answer(0, &wrong)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_errors_say_whether_the_system_has_a_sampler() {
|
||||
let reply = |name: &str| {
|
||||
let call = zbus::Message::method_call("/org/freedesktop/portal/desktop", "PickColor").unwrap().build(&()).unwrap();
|
||||
let error = zbus::Message::error(&call.header(), name).unwrap().build(&("detail",)).unwrap();
|
||||
zbus::Error::from(error)
|
||||
};
|
||||
for name in UNAVAILABLE {
|
||||
assert!(matches!(call_failure(&reply(name)), Failure::Unavailable(_)), "{name}");
|
||||
}
|
||||
assert!(matches!(call_failure(&reply("org.freedesktop.portal.Error.NotAllowed")), Failure::Failed(_)));
|
||||
let timed_out = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::TimedOut.into()));
|
||||
assert!(matches!(call_failure(&timed_out), Failure::NoAnswer(_)));
|
||||
let broken = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::BrokenPipe.into()));
|
||||
assert!(matches!(call_failure(&broken), Failure::Failed(_)));
|
||||
let messages = [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())].map(|f| f.message());
|
||||
assert_eq!(
|
||||
messages,
|
||||
["this system has no screen color sampler", "the screen color sampler did not answer", "the screen color sampler failed"]
|
||||
);
|
||||
assert_eq!(call_failure(&broken).detail(), broken.to_string());
|
||||
}
|
||||
|
||||
/// Every language that translates the sampler's other messages translates these too. The
|
||||
/// i18n tests of `vectorcraft-ui-egui` do not read this crate's messages.
|
||||
#[test]
|
||||
fn the_messages_are_translated_where_the_sampler_is() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
const OPEN: &str = "the screen color sampler is already open";
|
||||
let langs: Vec<Lang> = Lang::all().filter(|&lang| message(lang, OPEN) != OPEN).collect();
|
||||
assert!(!langs.is_empty(), "no language translates {OPEN:?}");
|
||||
for lang in langs {
|
||||
for failure in [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())] {
|
||||
assert_ne!(message(lang, failure.message()), failure.message(), "{}", lang.code());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
|
||||
fn private_bus() -> Option<(Daemon, String)> {
|
||||
use std::io::BufRead as _;
|
||||
let spawning = crate::spawning();
|
||||
let daemon = std::process::Command::new("dbus-daemon")
|
||||
.args(["--session", "--nofork", "--print-address=1"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
drop(spawning);
|
||||
let Ok(daemon) = daemon else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return None;
|
||||
};
|
||||
let mut daemon = Daemon(daemon);
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
|
||||
Some((daemon, address.trim().to_string()))
|
||||
}
|
||||
|
||||
/// Stops the private bus when the test ends, unwinding included.
|
||||
struct Daemon(std::process::Child);
|
||||
|
||||
impl Drop for Daemon {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
|
||||
fn client(address: &str) -> Connection {
|
||||
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
|
||||
}
|
||||
|
||||
/// The portal's name, owned on the private bus at `address` before any call, so the bus never
|
||||
/// starts an installed portal in its place.
|
||||
fn portal(address: &str) -> Connection {
|
||||
zbus::blocking::connection::Builder::address(address).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap()
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: an answer that comes before the call returns is kept; answers on
|
||||
/// other request paths or from other connections are ignored; a cancel gives no color; and a
|
||||
/// portal that leaves the bus while the person picks ends the wait.
|
||||
#[test]
|
||||
fn the_answer_is_the_portals_response_on_the_returned_path() {
|
||||
use zbus::blocking::MessageIterator;
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
|
||||
let Some((_daemon, address)) = private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let server = portal(address);
|
||||
let impostor = zbus::blocking::connection::Builder::address(address).unwrap().build().unwrap();
|
||||
let incoming = MessageIterator::from(&server);
|
||||
let worker = std::thread::spawn(move || {
|
||||
let mut calls = Vec::new();
|
||||
for msg in incoming {
|
||||
let msg = msg.unwrap();
|
||||
let header = msg.header();
|
||||
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("PickColor") {
|
||||
continue;
|
||||
}
|
||||
let (parent, options): (String, HashMap<String, OwnedValue>) = msg.body().deserialize().unwrap();
|
||||
let token = String::try_from(options.get("handle_token").unwrap().try_clone().unwrap()).unwrap();
|
||||
assert!(token.starts_with("vectorcraft_color_"));
|
||||
assert!(token.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_'));
|
||||
assert!(!calls.iter().any(|(_, old)| old == &token));
|
||||
calls.push((parent, token));
|
||||
// A portal older than version 0.9 answers on a path of its own, not the token's.
|
||||
let path = format!("/org/freedesktop/portal/desktop/request/independent/pick_{}", calls.len());
|
||||
let handle = OwnedObjectPath::try_from(path.as_str()).unwrap();
|
||||
if calls.len() == 4 {
|
||||
server.reply(&header, &handle).unwrap();
|
||||
assert!(server.release_name("org.freedesktop.portal.Desktop").unwrap());
|
||||
break;
|
||||
}
|
||||
let to = header.sender().cloned().map(zbus::names::BusName::from);
|
||||
// Another connection can't end the wait by claiming the portal left.
|
||||
impostor
|
||||
.emit_signal(
|
||||
to.clone(),
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"NameOwnerChanged",
|
||||
&("org.freedesktop.portal.Desktop", server.unique_name().unwrap().as_str(), ""),
|
||||
)
|
||||
.unwrap();
|
||||
let wrong = color((1.0, 0.0, 0.0));
|
||||
impostor.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
|
||||
let unrelated = "/org/freedesktop/portal/desktop/request/unrelated";
|
||||
server.emit_signal(to.clone(), unrelated, "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
|
||||
let code = if calls.len() == 2 { 1_u32 } else { 0_u32 };
|
||||
server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &color((0.25, 0.5, 0.75)))).unwrap();
|
||||
// The reply that names the path goes last: every answer above came before it.
|
||||
server.reply(&header, &handle).unwrap();
|
||||
}
|
||||
calls
|
||||
});
|
||||
let client = client(address);
|
||||
assert_eq!(pick(&client, "x11:12"), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert_eq!(pick(&client, "wayland:example"), Ok(None));
|
||||
assert_eq!(pick(&client, ""), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert!(matches!(pick(&client, ""), Err(Failure::NoAnswer(_))));
|
||||
let calls = worker.join().unwrap();
|
||||
assert_eq!(calls.iter().map(|(parent, _)| parent.as_str()).collect::<Vec<_>>(), ["x11:12", "wayland:example", "", ""]);
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: a portal without `PickColor` ends the request as a system without a
|
||||
/// sampler, and the sampler's connection gives the call [`CALL_TIMEOUT`].
|
||||
#[test]
|
||||
fn a_portal_without_pick_color_ends_the_request() {
|
||||
let Some((_daemon, address)) = private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let server = portal(address);
|
||||
let incoming = zbus::blocking::MessageIterator::from(&server);
|
||||
let worker = std::thread::spawn(move || {
|
||||
for msg in incoming {
|
||||
let msg = msg.unwrap();
|
||||
let header = msg.header();
|
||||
if header.member().map(|m| m.as_str()) == Some("PickColor") {
|
||||
server.reply_error(&header, "org.freedesktop.DBus.Error.UnknownMethod", &("no PickColor",)).unwrap();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let client = client(address);
|
||||
assert_eq!(client.method_timeout(), Some(CALL_TIMEOUT));
|
||||
let failure = pick(&client, "");
|
||||
assert!(matches!(failure, Err(Failure::Unavailable(_))), "{failure:?}");
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! The answer to the color sampler's XDG desktop portal request
|
||||
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>).
|
||||
//! The wait ends with the request's `Response`, or with an error when the portal leaves the bus
|
||||
//! first.
|
||||
|
||||
use std::io::Read as _;
|
||||
|
||||
use futures_lite::{StreamExt as _, future};
|
||||
use zbus::blocking::{Connection, MessageIterator};
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
|
||||
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
|
||||
/// token is unique and can't be guessed, as the Request documentation asks.
|
||||
pub(super) fn token(prefix: &str) -> Result<String, String> {
|
||||
let mut bytes = [0; 16];
|
||||
std::fs::File::open("/dev/urandom")
|
||||
.and_then(|mut file| file.read_exact(&mut bytes))
|
||||
.map_err(|e| format!("could not create a portal request token: {e}"))?;
|
||||
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
|
||||
Ok(format!("{prefix}_{random}"))
|
||||
}
|
||||
|
||||
/// Subscriptions made before a portal method call, on every request path: a portal older than
|
||||
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
|
||||
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
|
||||
pub(super) struct Responses {
|
||||
replies: MessageIterator,
|
||||
owners: MessageIterator,
|
||||
}
|
||||
|
||||
impl Responses {
|
||||
pub(super) fn new(conn: &Connection) -> Result<Self, String> {
|
||||
let reply_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender(DESKTOP)
|
||||
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
|
||||
.and_then(|b| b.member("Response"))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
let owner_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender("org.freedesktop.DBus")
|
||||
.and_then(|b| b.path("/org/freedesktop/DBus"))
|
||||
.and_then(|b| b.interface("org.freedesktop.DBus"))
|
||||
.and_then(|b| b.member("NameOwnerChanged"))
|
||||
.and_then(|b| b.arg(0, DESKTOP))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
Ok(Self {
|
||||
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
|
||||
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `Response` on the request path `call` returned, from the connection that returned it.
|
||||
/// An error when that connection leaves the bus first, or the bus connection closes.
|
||||
pub(super) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
|
||||
enum Event {
|
||||
Reply(Option<zbus::Result<zbus::Message>>),
|
||||
Owner(Option<zbus::Result<zbus::Message>>),
|
||||
}
|
||||
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
|
||||
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
|
||||
let mut replies = self.replies.into_inner();
|
||||
let mut owners = self.owners.into_inner();
|
||||
future::block_on(async {
|
||||
loop {
|
||||
let event = future::or(async { Event::Reply(replies.next().await) }, async { Event::Owner(owners.next().await) }).await;
|
||||
match event {
|
||||
Event::Reply(reply) => {
|
||||
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
|
||||
let header = reply.header();
|
||||
if header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
|
||||
{
|
||||
return Ok(reply);
|
||||
}
|
||||
}
|
||||
Event::Owner(message) => {
|
||||
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
|
||||
if owner_disappeared(&message, &portal)? {
|
||||
return Err("the desktop portal disappeared while waiting for its answer".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
|
||||
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
|
||||
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
|
||||
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
|
||||
return Ok(false);
|
||||
}
|
||||
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
|
||||
Ok(name == DESKTOP && old == portal && new != portal)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_bus_can_report_portal_owner_loss() {
|
||||
let changed = |sender, name, old, new| {
|
||||
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
|
||||
.unwrap()
|
||||
.sender(sender)
|
||||
.unwrap()
|
||||
.build(&(name, old, new))
|
||||
.unwrap()
|
||||
};
|
||||
let forged = changed(":1.42", DESKTOP, ":1.7", "");
|
||||
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
|
||||
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
|
||||
assert!(owner_disappeared(&real, ":1.7").unwrap());
|
||||
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
|
||||
assert!(!owner_disappeared(&other, ":1.7").unwrap());
|
||||
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
|
||||
assert!(!owner_disappeared(&old, ":1.7").unwrap());
|
||||
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
|
||||
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,6 @@ trait Backend {
|
||||
fn suspend(&mut self, window: &Self::Window);
|
||||
fn restore(&mut self, window: &Self::Window);
|
||||
fn build(&mut self, request: &Request) -> Option<Self::Cursor>;
|
||||
fn current(&self) -> Option<Self::Cursor>;
|
||||
fn set(&mut self, cursor: &Self::Cursor);
|
||||
}
|
||||
|
||||
@@ -73,9 +72,10 @@ impl<B: Backend> State<B> {
|
||||
&& *key == request.key
|
||||
&& *owned == window
|
||||
{
|
||||
if self.backend.current().as_ref() != Some(cursor) {
|
||||
self.backend.set(cursor);
|
||||
}
|
||||
// AppKit can show the system arrow when the pointer moves while
|
||||
// `NSCursor.currentCursor` (the app's last set cursor) still reads as ours, so a
|
||||
// comparison would keep the arrow. Setting the cursor again costs nothing.
|
||||
self.backend.set(cursor);
|
||||
return;
|
||||
}
|
||||
self.release();
|
||||
@@ -135,9 +135,6 @@ impl Backend for AppKit {
|
||||
fn build(&mut self, request: &Request) -> Option<Self::Cursor> {
|
||||
build(&request.bitmap)
|
||||
}
|
||||
fn current(&self) -> Option<Self::Cursor> {
|
||||
Some(NSCursor::currentCursor())
|
||||
}
|
||||
fn set(&mut self, cursor: &Self::Cursor) {
|
||||
cursor.set();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ use std::cell::Cell;
|
||||
struct Fake {
|
||||
window: Option<u8>,
|
||||
suspended: Vec<u8>,
|
||||
current: Option<Key>,
|
||||
sets: usize,
|
||||
builds: usize,
|
||||
restores: Vec<u8>,
|
||||
@@ -27,17 +26,12 @@ impl Backend for Fake {
|
||||
fn restore(&mut self, w: &u8) {
|
||||
self.suspended.retain(|v| v != w);
|
||||
self.restores.push(*w);
|
||||
self.current = None;
|
||||
}
|
||||
fn build(&mut self, r: &Request) -> Option<Key> {
|
||||
self.builds += 1;
|
||||
(!self.fail).then_some(r.key)
|
||||
}
|
||||
fn current(&self) -> Option<Key> {
|
||||
self.current
|
||||
}
|
||||
fn set(&mut self, cursor: &Key) {
|
||||
self.current = Some(*cursor);
|
||||
fn set(&mut self, _: &Key) {
|
||||
self.sets += 1;
|
||||
}
|
||||
}
|
||||
@@ -66,19 +60,16 @@ fn deliver(state: &mut State<Fake>, request: Option<Request>) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_cursor_ownership_deduplicates_reasserts_and_restores() {
|
||||
fn mac_cursor_ownership_reasserts_every_pass_and_restores() {
|
||||
let req = request(1.0);
|
||||
let mut state = fake_state();
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.suspended, [1]);
|
||||
assert_eq!((state.backend.builds, state.backend.sets), (1, 1));
|
||||
// The pointer moves and AppKit shows the system arrow, but the app's current cursor
|
||||
// still reads as ours. The next pass sets it again without rebuilding or re-suspending.
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.sets, 1);
|
||||
// Simulate a platform fallback replacing the cursor after finalization. The next pass
|
||||
// reasserts; this proves the protocol, not AppKit timing or absence of transient flicker.
|
||||
state.backend.current = None;
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.sets, 2);
|
||||
assert_eq!((state.backend.builds, state.backend.sets, state.backend.suspended.len()), (1, 2, 1));
|
||||
deliver(&mut state, None);
|
||||
assert_eq!(state.backend.restores, [1]);
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
|
||||
@@ -32,6 +32,8 @@ mod cursor_theme;
|
||||
mod gpu;
|
||||
mod hang_watch;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_screen_color;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_stylus;
|
||||
mod logging;
|
||||
#[cfg(all(target_os = "macos", feature = "wgpu"))]
|
||||
|
||||
@@ -102,13 +102,22 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Sav
|
||||
log::warn!("the portal's save dialog picked a file name that isn't UTF-8: nothing is saved");
|
||||
return Ok(None);
|
||||
};
|
||||
let filter = results.get("current_filter").and_then(|v| {
|
||||
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
|
||||
Some(label)
|
||||
});
|
||||
let filter = results.get("current_filter").and_then(|v| filter_label(v));
|
||||
Ok(Some(Saved { path, filter }))
|
||||
}
|
||||
|
||||
/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of
|
||||
/// another shape.
|
||||
fn filter_label(value: &Value<'_>) -> Option<String> {
|
||||
match value {
|
||||
Value::Structure(s) => match s.fields() {
|
||||
[Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere
|
||||
/// (`file://host/`) or another scheme.
|
||||
fn file_uri_path(uri: &str) -> Option<Vec<u8>> {
|
||||
@@ -233,6 +242,13 @@ fn parent(window: &winit::window::Window) -> (String, Option<wayland::Export>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`parent`] for another dialog of the portal (the screen color sampler, `linux_screen_color`):
|
||||
/// the identifier stays valid until the second value is dropped.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn exported_parent(window: &winit::window::Window) -> (String, impl Send + 'static) {
|
||||
parent(window)
|
||||
}
|
||||
|
||||
/// The portal's identifier of `window`: its X11 id, else empty (no Wayland export is made off
|
||||
/// Linux).
|
||||
#[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
@@ -396,6 +412,36 @@ mod tests {
|
||||
assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster"]);
|
||||
}
|
||||
|
||||
/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more
|
||||
/// fields, a string) gives the path alone; `uris` of another shape is an error.
|
||||
#[test]
|
||||
fn an_answer_of_another_shape_is_not_read() {
|
||||
let malformed = [
|
||||
Value::from(("SVG".to_string(),)),
|
||||
Value::from(("SVG".to_string(), vec![(0u32,)])),
|
||||
Value::from(("SVG".to_string(), vec![("*.svg".to_string(), 0u32)])),
|
||||
Value::from((1u32, vec![(0u32, "*.svg".to_string())])),
|
||||
Value::from(("SVG".to_string(), vec![(0u32, "*.svg".to_string())], 1u32)),
|
||||
Value::from("SVG"),
|
||||
];
|
||||
for filter in malformed {
|
||||
let mut r = results("file:///tmp/card", None);
|
||||
r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap());
|
||||
assert_eq!(answer(0, &r), Ok(Some(Saved { path: "/tmp/card".into(), filter: None })));
|
||||
}
|
||||
let malformed = [
|
||||
Value::from(vec![1u32]),
|
||||
Value::from(vec![("file:///tmp/card".to_string(),)]),
|
||||
Value::from(Vec::<String>::new()),
|
||||
Value::from("file:///tmp/card"),
|
||||
];
|
||||
for uris in malformed {
|
||||
let mut r = HashMap::new();
|
||||
r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap());
|
||||
assert!(answer(0, &r).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel (1) and a dialog closed another way (2) answer no file; an answer without a local file
|
||||
/// is an error, and rfd shows the dialog instead.
|
||||
#[test]
|
||||
@@ -486,10 +532,7 @@ mod tests {
|
||||
}
|
||||
let Ok((_parent, _title, options)) = msg.body().deserialize::<(String, String, HashMap<String, OwnedValue>)>() else { break };
|
||||
let text = |key: &str| options.get(key).and_then(|v| String::try_from(v.try_clone().ok()?).ok());
|
||||
let filter = options.get("current_filter").and_then(|v| {
|
||||
let (label, _): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
|
||||
Some(label)
|
||||
});
|
||||
let filter = options.get("current_filter").and_then(|v| filter_label(v));
|
||||
let calls = log.lock().map(|mut l| {
|
||||
l.push((text("current_name"), filter));
|
||||
l.len()
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<!-- @license lucide-static v1.49.0 - ISC -->
|
||||
<svg
|
||||
class="lucide lucide-graduation-cap"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z" />
|
||||
<path d="M22 10v6" />
|
||||
<path d="M6 12.5V16a6 3 0 0 0 12 0v-3.5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 497 B |
+12
-9
@@ -370,11 +370,14 @@ pub struct ArtBrush {
|
||||
pub scale: ArtScale,
|
||||
/// Width in percent.
|
||||
pub width: f64,
|
||||
/// How the width varies along a stroke: `None` (Fixed) always `width`; Pressure goes from
|
||||
/// `width` at the lightest pen pressure to [`Self::width_max`] at the heaviest.
|
||||
/// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the
|
||||
/// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure
|
||||
/// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing
|
||||
/// and Rotation from −180° to 180° (half way at 0°).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_mode: Option<Variation>,
|
||||
/// The width at the heaviest pen pressure (%), for Pressure (`width` without one).
|
||||
/// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or
|
||||
/// at 180° (`width` without one).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_max: Option<f64>,
|
||||
pub flip_along: bool,
|
||||
@@ -388,11 +391,11 @@ impl ArtBrush {
|
||||
/// The range of the width (%).
|
||||
pub const WIDTH_RANGE: (f64, f64) = (1.0, 1000.0);
|
||||
|
||||
/// The widths (%) at the lightest and the heaviest pen pressure: `width` for both unless the
|
||||
/// width follows the pressure.
|
||||
/// The widths (%) where the pen reads 0 and 1 for the width's mode (the lightest and the
|
||||
/// heaviest pressure, for Pressure): `width` for both unless the width follows the pen.
|
||||
pub fn width_range(&self) -> (f64, f64) {
|
||||
match self.width_mode {
|
||||
Some(Variation::Pressure) => (self.width, self.width_max.unwrap_or(self.width)),
|
||||
Some(m) if m.follows_pen() => (self.width, self.width_max.unwrap_or(self.width)),
|
||||
_ => (self.width, self.width),
|
||||
}
|
||||
}
|
||||
@@ -713,8 +716,8 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0);
|
||||
// The width follows the pen's pressure or stays fixed.
|
||||
if a.width_mode != Some(Variation::Pressure) {
|
||||
// The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed.
|
||||
if !a.width_mode.is_some_and(Variation::follows_pen) {
|
||||
a.width_mode = None;
|
||||
}
|
||||
a.width_max = a.width_max.map(|w| within(w, ArtBrush::WIDTH_RANGE, a.width));
|
||||
@@ -806,7 +809,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
let mut out = match &brush.kind {
|
||||
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
};
|
||||
|
||||
@@ -1371,6 +1371,62 @@ fn art_brush_width_follows_the_pressure() {
|
||||
assert!(plain.get("width_mode").is_none() && plain.get("width_max").is_none(), "{plain}");
|
||||
}
|
||||
|
||||
/// Art Brush Options: Width on Tilt goes from Width with the pen lying flat to the second width
|
||||
/// upright, and on Bearing or Rotation from Width at −180° to the second width at 180°, along the
|
||||
/// stroke as the pen recorded it; each mode reads only its own input.
|
||||
#[test]
|
||||
fn art_brush_width_follows_tilt_bearing_and_rotation() {
|
||||
let brush = |mode: Variation| {
|
||||
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut b.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(mode), Some(300.0));
|
||||
}
|
||||
b
|
||||
};
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
|
||||
// Tilt, upright at the start (300 %: 6 pt either side of 4 pt art) to flat at the end (50 %: 1 pt).
|
||||
let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
|
||||
let out = draw(&brush(Variation::Tilt), &upright_to_flat);
|
||||
assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
|
||||
assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0));
|
||||
assert!(near(half_width(&out, 49.0, 51.0), 3.5, 0.15), "{}", half_width(&out, 49.0, 51.0));
|
||||
// Bearing and Rotation: half way at 0°, a quarter of the way at −90°, three quarters at 90°.
|
||||
for (mode, angle, half) in [
|
||||
(Variation::Bearing, 0.0, 3.5),
|
||||
(Variation::Bearing, -90.0, 2.25),
|
||||
(Variation::Bearing, 90.0, 4.75),
|
||||
(Variation::Rotation, -90.0, 2.25),
|
||||
(Variation::Rotation, 90.0, 4.75),
|
||||
] {
|
||||
let st = if mode == Variation::Bearing { posed(Some(0.5), Some(angle), None) } else { posed(None, None, Some(angle)) };
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, 2.0 * half, 1e-6), "{mode:?} {angle}: {h}");
|
||||
}
|
||||
// Each mode reads its own input: without it (the pressure, or another of the pen's values
|
||||
// recorded instead), the art is half way between the two widths.
|
||||
let others = [
|
||||
(Variation::Tilt, posed(None, Some(90.0), Some(90.0))),
|
||||
(Variation::Tilt, pressed(vec![(0.0, 0.0), (1.0, 1.0)])),
|
||||
(Variation::Bearing, posed(Some(0.0), None, Some(90.0))),
|
||||
(Variation::Rotation, posed(Some(0.0), Some(90.0), None)),
|
||||
(Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0))),
|
||||
];
|
||||
for (mode, st) in others {
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, 7.0, 1e-6), "{mode:?}: {h}");
|
||||
}
|
||||
// The pen's modes are kept when a definition is read, and Random is read as Fixed.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "t", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "tilt", "width_max": 300.0},
|
||||
{"name": "b", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "bearing", "width_max": 300.0},
|
||||
{"name": "r", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "rotation", "width_max": 300.0},
|
||||
{"name": "x", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "random", "width_max": 300.0},
|
||||
]));
|
||||
let modes: Vec<_> = lib.iter().map(|b| if let BrushKind::Art(a) = &b.kind { a.width_mode } else { None }).collect();
|
||||
assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]);
|
||||
}
|
||||
|
||||
/// Definitions from files and commands are kept within their ranges.
|
||||
#[test]
|
||||
fn sanitize_keeps_values_within_their_ranges() {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurveNearest;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::track::{Rng, Track, normal, seed_of, tracks};
|
||||
@@ -503,9 +503,10 @@ fn art_on_run(
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
}
|
||||
|
||||
/// An art brush's art along `bp`. With a width that follows the pen's pressure, the art is as
|
||||
/// wide as the pressure recorded at each point of the stroke gives (half way without a recording).
|
||||
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&PressureProfile>) -> Vec<Node> {
|
||||
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
|
||||
/// or rotation), the art is as wide as what `stroke` recorded at each point gives (half way
|
||||
/// without a recording).
|
||||
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec<Node> {
|
||||
let Some((art, b)) = oriented(&a.art, a.direction, a.flip_along, a.flip_across) else { return vec![] };
|
||||
let (light, heavy) = a.width_range();
|
||||
let width = light.max(heavy);
|
||||
@@ -522,7 +523,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre
|
||||
}
|
||||
// A run past the start of a closed track wraps round to it.
|
||||
let at = if s > l { s - l } else { s };
|
||||
let p = pressure.map_or(PressureProfile::MID, |p| p.at(at / l)).clamp(0.0, 1.0);
|
||||
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
|
||||
|
||||
@@ -3,7 +3,7 @@ name = "vectorcraft-cad"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader"
|
||||
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -16,11 +16,18 @@
|
||||
//! and the art of every page goes on one artboard; each comes back as a warning. Printer escape
|
||||
//! sequences and PJL lines around the instructions are skipped.
|
||||
//!
|
||||
//! [`export`] writes the visible art over a region as an HP-GL or HP-GL/2 plot, and
|
||||
//! [`export_regions`] one plot per region with one pen numbering: see [`write`].
|
||||
//!
|
||||
//! - `lex`: the bytes as instructions, numbers, labels and PE data.
|
||||
//! - `plot`: the instructions played on the pen, as shapes.
|
||||
//! - `write`: the writer, paths to pen moves.
|
||||
|
||||
mod lex;
|
||||
mod plot;
|
||||
pub mod write;
|
||||
|
||||
pub use write::{HpglOptions, HpglOutput, Origin, Version, export, export_regions};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,265 @@
|
||||
//! Polylines cut by a region: each segment is split where it crosses the region's edges, and the
|
||||
//! pieces whose middle lies inside are kept, joined where they meet.
|
||||
|
||||
use vectorcraft_geom::{FillRule, Point, Rect};
|
||||
|
||||
/// A clipping region: closed rings (each closes implicitly) and the rule that decides inside.
|
||||
pub(super) struct Region {
|
||||
rings: Vec<Vec<Point>>,
|
||||
rule: FillRule,
|
||||
bounds: Rect,
|
||||
}
|
||||
|
||||
impl Region {
|
||||
/// The region of `rings` under `rule`; `None` when it has no ring of three points or more.
|
||||
pub fn new(rings: Vec<Vec<Point>>, rule: FillRule) -> Option<Self> {
|
||||
let rings: Vec<Vec<Point>> = rings.into_iter().filter(|r| r.len() >= 3).collect();
|
||||
let bounds = rings.iter().flatten().fold(None, |b: Option<Rect>, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?;
|
||||
Some(Self { rings, rule, bounds })
|
||||
}
|
||||
|
||||
/// The edges this region has, which [`Region::cut`] tests each segment against.
|
||||
fn edges(&self) -> u64 {
|
||||
self.rings.iter().map(|r| r.len() as u64).sum()
|
||||
}
|
||||
|
||||
/// Does `p` lie on one of the region's edges (within a millionth of a point)?
|
||||
fn on_edge(&self, p: Point) -> bool {
|
||||
self.rings.iter().any(|ring| {
|
||||
ring.iter().enumerate().any(|(i, &a)| {
|
||||
let b = ring[(i + 1) % ring.len()];
|
||||
let ab = b - a;
|
||||
let len2 = ab.hypot2();
|
||||
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(a + ab * t).distance(p) <= 1e-6
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `p` inside (non-zero winding or an odd number of crossings), or on an edge?
|
||||
fn contains(&self, p: Point) -> bool {
|
||||
if self.on_edge(p) {
|
||||
return true;
|
||||
}
|
||||
let mut winding = 0i64;
|
||||
for ring in &self.rings {
|
||||
for (i, &a) in ring.iter().enumerate() {
|
||||
let b = ring[(i + 1) % ring.len()];
|
||||
if a.y <= p.y {
|
||||
if b.y > p.y && cross(a, b, p) > 0.0 {
|
||||
winding += 1;
|
||||
}
|
||||
} else if b.y <= p.y && cross(a, b, p) < 0.0 {
|
||||
winding -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
match self.rule {
|
||||
FillRule::NonZero => winding != 0,
|
||||
FillRule::EvenOdd => winding % 2 != 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where segment `a`–`b` crosses this region's edges, as fractions of its length strictly
|
||||
/// between 0 and 1, sorted.
|
||||
fn crossings(&self, a: Point, b: Point) -> Vec<f64> {
|
||||
let mut ts = vec![];
|
||||
for ring in &self.rings {
|
||||
for (i, &c) in ring.iter().enumerate() {
|
||||
let d = ring[(i + 1) % ring.len()];
|
||||
if let Some(t) = intersect(a, b, c, d)
|
||||
&& t > 1e-12
|
||||
&& t < 1.0 - 1e-12
|
||||
{
|
||||
ts.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|x, y| (*x - *y).abs() <= 1e-12);
|
||||
ts
|
||||
}
|
||||
|
||||
/// The parts of polyline `line` inside the region, each a polyline of two points or more.
|
||||
/// Every test of a point or a segment against an edge takes one from `budget`; `None` when
|
||||
/// the budget runs out first.
|
||||
pub fn cut(&self, line: &[Point], budget: &mut u64) -> Option<Vec<Vec<Point>>> {
|
||||
let edges = self.edges();
|
||||
let mut out: Vec<Vec<Point>> = vec![];
|
||||
let mut cur: Vec<Point> = vec![];
|
||||
for w in line.windows(2) {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
// A segment wholly off the region's box lies outside it.
|
||||
let near = overlaps(Rect::from_points(a, b), self.bounds);
|
||||
let ts = if near {
|
||||
spend(budget, edges)?;
|
||||
self.crossings(a, b)
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let mut from = 0.0;
|
||||
for to in ts.into_iter().chain([1.0]) {
|
||||
let (p, q) = (a.lerp(b, from), a.lerp(b, to));
|
||||
// Each piece between crossings is tested on its own: its edge and winding tests.
|
||||
let inside = if near {
|
||||
spend(budget, edges.saturating_mul(2))?;
|
||||
self.contains(p.midpoint(q))
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if inside {
|
||||
if cur.last().is_none_or(|l| l.distance(p) > 1e-9) {
|
||||
flush(&mut out, &mut cur);
|
||||
cur.push(p);
|
||||
}
|
||||
cur.push(q);
|
||||
} else {
|
||||
flush(&mut out, &mut cur);
|
||||
}
|
||||
from = to;
|
||||
}
|
||||
}
|
||||
flush(&mut out, &mut cur);
|
||||
// A closed line that leaves the region and comes back: its last piece ends where its
|
||||
// first starts, at the line's start, and the two are one piece.
|
||||
if line.len() > 2
|
||||
&& line.first() == line.last()
|
||||
&& out.len() >= 2
|
||||
&& let (Some(end), Some(start)) = (out.last().and_then(|l| l.last()), out.first().and_then(|l| l.first()))
|
||||
&& end.distance(*start) <= 1e-9
|
||||
{
|
||||
let first = out.remove(0);
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.extend(first.into_iter().skip(1));
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Take `n` from `budget`; `None` when it holds less.
|
||||
fn spend(budget: &mut u64, n: u64) -> Option<()> {
|
||||
*budget = budget.checked_sub(n)?;
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn flush(out: &mut Vec<Vec<Point>>, cur: &mut Vec<Point>) {
|
||||
let line = std::mem::take(cur);
|
||||
if line.len() >= 2 {
|
||||
out.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
|
||||
}
|
||||
|
||||
/// Which side of line `a`–`b` point `p` lies on (positive: left).
|
||||
fn cross(a: Point, b: Point, p: Point) -> f64 {
|
||||
(b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y)
|
||||
}
|
||||
|
||||
/// Where segment `a`–`b` crosses segment `c`–`d`, as a fraction of `a`–`b`; `None` when they
|
||||
/// are parallel or don't meet.
|
||||
fn intersect(a: Point, b: Point, c: Point, d: Point) -> Option<f64> {
|
||||
let (r, s) = (b - a, d - c);
|
||||
let den = r.x * s.y - r.y * s.x;
|
||||
if den.abs() <= f64::EPSILON * (r.hypot() * s.hypot()).max(f64::MIN_POSITIVE) {
|
||||
return None;
|
||||
}
|
||||
let ac = c - a;
|
||||
let t = (ac.x * s.y - ac.y * s.x) / den;
|
||||
let u = (ac.x * r.y - ac.y * r.x) / den;
|
||||
((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then_some(t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<Point> {
|
||||
vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)]
|
||||
}
|
||||
|
||||
/// `line` cut by `r` with no limit on the work.
|
||||
fn cut(r: &Region, line: &[Point]) -> Vec<Vec<Point>> {
|
||||
let mut unlimited = u64::MAX;
|
||||
r.cut(line, &mut unlimited).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_across_a_square_keeps_its_middle() {
|
||||
let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap();
|
||||
let pieces = cut(&r, &[Point::new(-5.0, 5.0), Point::new(15.0, 5.0)]);
|
||||
assert_eq!(pieces, vec![vec![Point::new(0.0, 5.0), Point::new(10.0, 5.0)]]);
|
||||
// Wholly outside, nothing; wholly inside, the line as it is.
|
||||
assert!(cut(&r, &[Point::new(20.0, 0.0), Point::new(30.0, 0.0)]).is_empty());
|
||||
let inside = vec![Point::new(1.0, 1.0), Point::new(9.0, 1.0), Point::new(9.0, 9.0)];
|
||||
assert_eq!(cut(&r, &inside), vec![inside]);
|
||||
}
|
||||
|
||||
/// Each piece between crossings costs a pass over the edges: a line through the teeth of a
|
||||
/// comb spends far more than its two points times the edges.
|
||||
#[test]
|
||||
fn every_piece_between_crossings_is_paid_for() {
|
||||
let mut ring = vec![];
|
||||
for i in 0..100 {
|
||||
let x = f64::from(i) * 4.0;
|
||||
ring.extend([Point::new(x, 0.0), Point::new(x + 2.0, 0.0), Point::new(x + 2.0, 10.0), Point::new(x + 4.0, 10.0)]);
|
||||
}
|
||||
ring.extend([Point::new(400.0, 20.0), Point::new(0.0, 20.0)]);
|
||||
let r = Region::new(vec![ring], FillRule::NonZero).unwrap();
|
||||
let line = [Point::new(-1.0, 5.0), Point::new(401.0, 5.0)];
|
||||
// 402 edges, 200 crossings, 201 pieces: 402 + 201 × 2 × 402 tests.
|
||||
let need = 402 + 201 * 2 * 402;
|
||||
let mut budget = need;
|
||||
assert_eq!(r.cut(&line, &mut budget).map(|p| p.len()), Some(100));
|
||||
assert_eq!(budget, 0);
|
||||
let mut short = need - 1;
|
||||
assert!(r.cut(&line, &mut short).is_none());
|
||||
// A segment off the region's box costs nothing.
|
||||
assert_eq!(r.cut(&[Point::new(0.0, 30.0), Point::new(9.0, 30.0)], &mut 0), Some(vec![]));
|
||||
}
|
||||
|
||||
/// A line along any of the region's edges is inside it.
|
||||
#[test]
|
||||
fn a_line_on_an_edge_is_kept() {
|
||||
let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap();
|
||||
for line in [
|
||||
[Point::new(0.0, 0.0), Point::new(10.0, 0.0)],
|
||||
[Point::new(10.0, 0.0), Point::new(10.0, 10.0)],
|
||||
[Point::new(10.0, 10.0), Point::new(0.0, 10.0)],
|
||||
[Point::new(0.0, 10.0), Point::new(0.0, 0.0)],
|
||||
] {
|
||||
assert_eq!(cut(&r, &line), vec![line.to_vec()], "{line:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_leaving_and_coming_back_is_two_pieces() {
|
||||
let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap();
|
||||
let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0)];
|
||||
assert_eq!(cut(&r, &line), vec![vec![Point::new(5.0, 5.0), Point::new(10.0, 5.0)], vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0)]]);
|
||||
}
|
||||
|
||||
/// A closed line that starts inside, leaves and comes back is one piece: the part after it
|
||||
/// comes back runs on into the part before it left.
|
||||
#[test]
|
||||
fn a_closed_line_cut_once_stays_one_piece() {
|
||||
let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap();
|
||||
let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0)];
|
||||
assert_eq!(cut(&r, &line), vec![vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0), Point::new(10.0, 5.0)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_rule_decides_a_hole() {
|
||||
let rings = vec![square(0.0, 0.0, 10.0, 10.0), square(3.0, 3.0, 7.0, 7.0)];
|
||||
let line = [Point::new(-1.0, 5.0), Point::new(11.0, 5.0)];
|
||||
// Both rings wind the same way: even-odd cuts a hole, non-zero doesn't.
|
||||
let even_odd = cut(&Region::new(rings.clone(), FillRule::EvenOdd).unwrap(), &line);
|
||||
assert_eq!(even_odd, vec![vec![Point::new(0.0, 5.0), Point::new(3.0, 5.0)], vec![Point::new(7.0, 5.0), Point::new(10.0, 5.0)]]);
|
||||
let non_zero = cut(&Region::new(rings, FillRule::NonZero).unwrap(), &line);
|
||||
assert_eq!(non_zero.len(), 1);
|
||||
assert!(Region::new(vec![vec![Point::ZERO, Point::new(1.0, 1.0)]], FillRule::NonZero).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
//! Which of a pen's paths lie inside which of its closed paths, in plotter units, for drawing the
|
||||
//! inner paths first.
|
||||
|
||||
/// The box of `p`: `[x0, y0, x1, y1]`.
|
||||
pub(super) fn bounds(p: &[(i64, i64)]) -> [i64; 4] {
|
||||
p.iter().fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |b, q| [b[0].min(q.0), b[1].min(q.1), b[2].max(q.0), b[3].max(q.1)])
|
||||
}
|
||||
|
||||
/// For each of `paths` (`boxes` are their [`bounds`]), the closed paths it lies inside: none of
|
||||
/// its segments crosses the closed path's line, each part of it between the points where it meets
|
||||
/// that line lies inside the closed path (by the even-odd rule) or on the line, and at least one
|
||||
/// part lies inside. A path touching the line of the one around it is inside it, a path crossing
|
||||
/// it is not, and copies of one outline are not inside each other. A path is tested only against
|
||||
/// closed paths larger than it (by the area of their box, then the area they enclose, then paint
|
||||
/// order), so no two paths are each inside the other, and only against the closed paths in the
|
||||
/// [`Grid`] cell of its box's first corner. `None` once `work` is spent: a grid cell filled and a
|
||||
/// box compared cost one each, and each segment tested costs the closed path's points for its
|
||||
/// crossings and again for each part of it.
|
||||
pub(super) fn outer(paths: &[Vec<(i64, i64)>], boxes: &[[i64; 4]], work: &mut u64) -> Option<Vec<Vec<usize>>> {
|
||||
let size: Vec<(i128, i128)> = paths
|
||||
.iter()
|
||||
.zip(boxes)
|
||||
.map(|(p, b)| {
|
||||
let box_area = (i128::from(b[2]) - i128::from(b[0])) * (i128::from(b[3]) - i128::from(b[1]));
|
||||
(box_area, if closed(p) { twice_area(p) } else { 0 })
|
||||
})
|
||||
.collect();
|
||||
let rings: Vec<usize> = (0..paths.len()).filter(|&i| paths.get(i).is_some_and(|p| closed(p))).collect();
|
||||
let mut out = vec![vec![]; paths.len()];
|
||||
if rings.is_empty() {
|
||||
return Some(out);
|
||||
}
|
||||
let grid = Grid::new(&rings, boxes, work)?;
|
||||
for (a, (p, ab)) in paths.iter().zip(boxes).enumerate() {
|
||||
for &r in grid.at(ab[0], ab[1]) {
|
||||
spend(work, 1)?;
|
||||
let (Some(rb), Some(ring)) = (boxes.get(r), paths.get(r)) else { continue };
|
||||
let smaller = (size.get(a), a) < (size.get(r), r);
|
||||
if !smaller || rb[0] > ab[0] || rb[1] > ab[1] || rb[2] < ab[2] || rb[3] < ab[3] {
|
||||
continue;
|
||||
}
|
||||
if inside(p, ring, work)?
|
||||
&& let Some(o) = out.get_mut(a)
|
||||
{
|
||||
o.push(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The most cells along each side of a [`Grid`].
|
||||
const MAX_GRID_SIDE: usize = 512;
|
||||
/// The most cells of a [`Grid`] a closed path is listed in; one whose box covers more is listed
|
||||
/// once, among the wide ones. A closed path has 4 points or more, so the grid lists no more
|
||||
/// entries than the pen has points.
|
||||
const MAX_CELLS_PER_PATH: usize = 4;
|
||||
|
||||
/// A grid over the boxes of a pen's closed paths, about one cell for each, up to
|
||||
/// [`MAX_GRID_SIDE`] a side: each cell lists, in paint order, the closed paths whose box covers
|
||||
/// it, and the closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells are listed
|
||||
/// apart. A closed path whose box holds a point is among the wide ones or in that point's cell.
|
||||
struct Grid {
|
||||
/// The first corner of the closed paths' boxes together.
|
||||
x0: i128,
|
||||
y0: i128,
|
||||
/// Their width and height, plus one.
|
||||
w: i128,
|
||||
h: i128,
|
||||
/// Cells along each side.
|
||||
side: usize,
|
||||
/// The cells row by row.
|
||||
cells: Vec<Vec<usize>>,
|
||||
/// The closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells.
|
||||
wide: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
/// The grid of the closed paths `rings` (indices into `boxes`). `None` once `work` is spent.
|
||||
fn new(rings: &[usize], boxes: &[[i64; 4]], work: &mut u64) -> Option<Self> {
|
||||
let all = rings
|
||||
.iter()
|
||||
.filter_map(|&r| boxes.get(r))
|
||||
.fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |e, b| [e[0].min(b[0]), e[1].min(b[1]), e[2].max(b[2]), e[3].max(b[3])]);
|
||||
let side = ((rings.len() as f64).sqrt().ceil() as usize).clamp(1, MAX_GRID_SIDE);
|
||||
let (x0, y0) = (i128::from(all[0]), i128::from(all[1]));
|
||||
let mut grid = Self {
|
||||
x0,
|
||||
y0,
|
||||
w: (i128::from(all[2]) - x0 + 1).max(1),
|
||||
h: (i128::from(all[3]) - y0 + 1).max(1),
|
||||
side,
|
||||
cells: vec![vec![]; side * side],
|
||||
wide: vec![],
|
||||
};
|
||||
for &r in rings {
|
||||
let Some(b) = boxes.get(r) else { continue };
|
||||
let (Some((cx0, cy0)), Some((cx1, cy1))) = (grid.cell(b[0], b[1]), grid.cell(b[2], b[3])) else { continue };
|
||||
let covered = (cx1 - cx0 + 1) * (cy1 - cy0 + 1);
|
||||
if covered > MAX_CELLS_PER_PATH {
|
||||
spend(work, 1)?;
|
||||
grid.wide.push(r);
|
||||
continue;
|
||||
}
|
||||
spend(work, covered as u64)?;
|
||||
for cy in cy0..=cy1 {
|
||||
for cell in grid.cells.get_mut(cy * side + cx0..=cy * side + cx1).into_iter().flatten() {
|
||||
cell.push(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(grid)
|
||||
}
|
||||
|
||||
/// The column and row of the cell holding `(x, y)`, `None` outside the grid.
|
||||
fn cell(&self, x: i64, y: i64) -> Option<(usize, usize)> {
|
||||
let (dx, dy) = (i128::from(x) - self.x0, i128::from(y) - self.y0);
|
||||
if dx < 0 || dy < 0 || dx >= self.w || dy >= self.h {
|
||||
return None;
|
||||
}
|
||||
let side = self.side as i128;
|
||||
Some(((dx * side / self.w) as usize, (dy * side / self.h) as usize))
|
||||
}
|
||||
|
||||
/// The wide closed paths, then those listed in the cell holding `(x, y)`.
|
||||
fn at(&self, x: i64, y: i64) -> impl Iterator<Item = &usize> {
|
||||
let cell = self.cell(x, y).and_then(|(cx, cy)| self.cells.get(cy * self.side + cx)).map_or(&[][..], Vec::as_slice);
|
||||
self.wide.iter().chain(cell)
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes `n` from `work`; `None`, with `work` at 0, when it has less.
|
||||
fn spend(work: &mut u64, n: u64) -> Option<()> {
|
||||
let left = work.checked_sub(n);
|
||||
*work = left.unwrap_or(0);
|
||||
left.map(|_| ())
|
||||
}
|
||||
|
||||
/// Does `p` start and end at one point, with three other points or more?
|
||||
fn closed(p: &[(i64, i64)]) -> bool {
|
||||
p.len() > 3 && p.first() == p.last()
|
||||
}
|
||||
|
||||
/// Twice the area the closed path `p` encloses.
|
||||
fn twice_area(p: &[(i64, i64)]) -> i128 {
|
||||
let sum: i128 = p
|
||||
.windows(2)
|
||||
.map(|w| match w {
|
||||
[a, b] => i128::from(a.0) * i128::from(b.1) - i128::from(b.0) * i128::from(a.1),
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
sum.abs()
|
||||
}
|
||||
|
||||
/// Does `p` lie inside the closed path `ring`, as [`outer`] decides? `None` once `work` is spent.
|
||||
fn inside(p: &[(i64, i64)], ring: &[(i64, i64)], work: &mut u64) -> Option<bool> {
|
||||
let mut any = false;
|
||||
for w in p.windows(2) {
|
||||
let [s, e] = w else { continue };
|
||||
spend(work, ring.len() as u64)?;
|
||||
// Where the segment meets the line without crossing it: its ends and the ring's points on
|
||||
// it. Between two of these the segment is all inside or all outside.
|
||||
let mut stops = vec![*s, *e];
|
||||
for edge in ring.windows(2) {
|
||||
let [a, b] = edge else { continue };
|
||||
if crosses((*s, *e), (*a, *b)) {
|
||||
return Some(false);
|
||||
}
|
||||
if a != s && a != e && on((*s, *e), *a) {
|
||||
stops.push(*a);
|
||||
}
|
||||
}
|
||||
let along = |q: &(i64, i64)| {
|
||||
(i128::from(q.0) - i128::from(s.0)) * (i128::from(e.0) - i128::from(s.0))
|
||||
+ (i128::from(q.1) - i128::from(s.1)) * (i128::from(e.1) - i128::from(s.1))
|
||||
};
|
||||
stops.sort_by_key(along);
|
||||
stops.dedup();
|
||||
for part in stops.windows(2) {
|
||||
let [m, n] = part else { continue };
|
||||
spend(work, ring.len() as u64)?;
|
||||
// The part's middle, doubled so it is whole.
|
||||
match locate((i128::from(m.0) + i128::from(n.0), i128::from(m.1) + i128::from(n.1)), ring) {
|
||||
Some(false) => return Some(false),
|
||||
Some(true) => any = true,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(any)
|
||||
}
|
||||
|
||||
/// Which side of the line through `a` and `b` `c` is on: 1 left, -1 right, 0 on it.
|
||||
fn side(a: (i64, i64), b: (i64, i64), c: (i64, i64)) -> i128 {
|
||||
let d = (i128::from(b.0) - i128::from(a.0)) * (i128::from(c.1) - i128::from(a.1))
|
||||
- (i128::from(b.1) - i128::from(a.1)) * (i128::from(c.0) - i128::from(a.0));
|
||||
d.signum()
|
||||
}
|
||||
|
||||
/// Do segments `u` and `v` cross at a point inside both, each passing from one side of the other
|
||||
/// to the other side?
|
||||
fn crosses(u: ((i64, i64), (i64, i64)), v: ((i64, i64), (i64, i64))) -> bool {
|
||||
side(u.0, u.1, v.0) * side(u.0, u.1, v.1) < 0 && side(v.0, v.1, u.0) * side(v.0, v.1, u.1) < 0
|
||||
}
|
||||
|
||||
/// Does `q` lie on segment `u`?
|
||||
fn on(u: ((i64, i64), (i64, i64)), q: (i64, i64)) -> bool {
|
||||
let ((x0, y0), (x1, y1)) = u;
|
||||
side(u.0, u.1, q) == 0 && q.0 >= x0.min(x1) && q.0 <= x0.max(x1) && q.1 >= y0.min(y1) && q.1 <= y0.max(y1)
|
||||
}
|
||||
|
||||
/// Where the doubled point `q` lies against the closed path `ring`: `Some(true)` inside by the
|
||||
/// even-odd rule, `Some(false)` outside, `None` on its line.
|
||||
fn locate(q: (i128, i128), ring: &[(i64, i64)]) -> Option<bool> {
|
||||
let mut inside = false;
|
||||
for w in ring.windows(2) {
|
||||
let [a, b] = w else { continue };
|
||||
let (a, b) = ((2 * i128::from(a.0), 2 * i128::from(a.1)), (2 * i128::from(b.0), 2 * i128::from(b.1)));
|
||||
// Which side of the segment's line `q` is on, 0 on it.
|
||||
let side = (b.0 - a.0) * (q.1 - a.1) - (b.1 - a.1) * (q.0 - a.0);
|
||||
if side == 0 && q.0 >= a.0.min(b.0) && q.0 <= a.0.max(b.0) && q.1 >= a.1.min(b.1) && q.1 <= a.1.max(b.1) {
|
||||
return None;
|
||||
}
|
||||
// A segment crossing the level of `q` to its right.
|
||||
if (a.1 > q.1) != (b.1 > q.1) && (side > 0) == (b.1 > a.1) {
|
||||
inside = !inside;
|
||||
}
|
||||
}
|
||||
Some(inside)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn square(x0: i64, y0: i64, x1: i64, y1: i64) -> Vec<(i64, i64)> {
|
||||
vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]
|
||||
}
|
||||
|
||||
fn nest(paths: &[Vec<(i64, i64)>]) -> Option<Vec<Vec<usize>>> {
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect();
|
||||
let mut work = u64::MAX;
|
||||
outer(paths, &boxes, &mut work)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn points_inside_outside_and_on_the_line() {
|
||||
let ring = square(0, 0, 10, 10);
|
||||
assert_eq!(locate((10, 10), &ring), Some(true));
|
||||
assert_eq!(locate((30, 10), &ring), Some(false));
|
||||
assert_eq!(locate((10, -2), &ring), Some(false));
|
||||
assert_eq!(locate((20, 10), &ring), None);
|
||||
assert_eq!(locate((0, 0), &ring), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_inside_another_lies_inside_it_and_not_the_other_way() {
|
||||
let paths = [square(0, 0, 100, 100), square(10, 10, 20, 20), vec![(30, 30), (40, 40)]];
|
||||
assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn touching_counts_as_inside_and_crossing_does_not() {
|
||||
// A square with a corner on the outline's left edge, a triangle whose corners lie on the
|
||||
// outline's edges, and a square that crosses the outline.
|
||||
let paths = [square(0, 0, 100, 100), square(0, 40, 20, 60), vec![(0, 50), (50, 0), (100, 50), (0, 50)], square(90, 90, 120, 95)];
|
||||
assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0], vec![]]));
|
||||
}
|
||||
|
||||
/// Every point of a copy lies on the other's line, and none inside it.
|
||||
#[test]
|
||||
fn copies_of_one_outline_do_not_lie_inside_each_other() {
|
||||
let paths = [square(0, 0, 10, 10), square(0, 0, 10, 10), vec![(10, 10), (10, 0), (0, 0), (0, 10), (10, 10)]];
|
||||
assert_eq!(nest(&paths), Some(vec![vec![], vec![], vec![]]));
|
||||
}
|
||||
|
||||
/// A line whose ends and middle lie inside an outline but which crosses a slot cut into it.
|
||||
#[test]
|
||||
fn a_line_across_a_slot_is_not_inside() {
|
||||
let slotted = vec![(0, 0), (100, 0), (100, 100), (14, 100), (14, 40), (12, 40), (12, 100), (0, 100), (0, 0)];
|
||||
assert_eq!(nest(&[slotted, vec![(10, 50), (40, 50)]]), Some(vec![vec![], vec![]]));
|
||||
}
|
||||
|
||||
/// A line that leaves an outline and comes back through two of its corners, crossing none of
|
||||
/// its sides, and one that runs along the bottom of a slot.
|
||||
#[test]
|
||||
fn a_line_through_corners_is_inside_only_where_it_stays_inside() {
|
||||
let v_slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (15, 40), (10, 50), (10, 100), (0, 100), (0, 0)];
|
||||
assert_eq!(nest(&[v_slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![]]));
|
||||
let slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (10, 50), (10, 100), (0, 100), (0, 0)];
|
||||
assert_eq!(nest(&[slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![0]]));
|
||||
}
|
||||
|
||||
/// An outline that crosses itself encloses no area by its signed sum, yet a line in one of its
|
||||
/// lobes lies inside it.
|
||||
#[test]
|
||||
fn a_line_inside_a_lobe_of_a_crossed_outline_lies_inside_it() {
|
||||
let bow = vec![(0, 0), (100, 100), (0, 100), (100, 0), (0, 0)];
|
||||
assert_eq!(twice_area(&bow), 0);
|
||||
assert_eq!(nest(&[bow, vec![(40, 80), (60, 80)]]), Some(vec![vec![], vec![0]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ring_inside_a_ring_inside_a_ring_lies_inside_both() {
|
||||
let paths = [square(20, 20, 80, 80), square(0, 0, 100, 100), square(40, 40, 60, 60)];
|
||||
assert_eq!(nest(&paths), Some(vec![vec![1], vec![], vec![0, 1]]));
|
||||
}
|
||||
|
||||
/// 10,000 parts in rows, each with a hole: each hole is tested against the few closed paths
|
||||
/// near it, not against every part.
|
||||
#[test]
|
||||
fn parts_in_rows_are_tested_only_against_the_closed_paths_near_them() {
|
||||
let mut paths = vec![];
|
||||
for row in 0..100 {
|
||||
for col in 0..100 {
|
||||
let (x, y) = (col * 30, row * 30);
|
||||
paths.push(square(x, y, x + 20, y + 20));
|
||||
paths.push(square(x + 5, y + 5, x + 15, y + 15));
|
||||
}
|
||||
}
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect();
|
||||
let mut work = 5_000_000;
|
||||
let found = outer(&paths, &boxes, &mut work);
|
||||
let want: Vec<Vec<usize>> = (0..paths.len()).map(|i| if i % 2 == 1 { vec![i - 1] } else { vec![] }).collect();
|
||||
assert_eq!(found, Some(want));
|
||||
}
|
||||
|
||||
/// 400 closed paths that each cover most of the grid are listed once each, not in every cell
|
||||
/// they cover.
|
||||
#[test]
|
||||
fn closed_paths_covering_many_cells_are_listed_once() {
|
||||
let mut paths: Vec<Vec<(i64, i64)>> = (0..400).map(|i| square(i, i, 1000 + i, 1000 + i)).collect();
|
||||
paths.extend((0..400).map(|i| {
|
||||
let (x, y) = ((i % 20) * 50, (i / 20) * 50);
|
||||
square(x, y, x + 10, y + 10)
|
||||
}));
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect();
|
||||
let rings: Vec<usize> = (0..paths.len()).collect();
|
||||
let mut work = u64::MAX;
|
||||
let Some(grid) = Grid::new(&rings, &boxes, &mut work) else { panic!("the budget ran out") };
|
||||
assert_eq!(grid.wide, (0..400).collect::<Vec<_>>());
|
||||
assert!(grid.cells.iter().map(Vec::len).sum::<usize>() <= 400 * MAX_CELLS_PER_PATH);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finding_what_lies_inside_stops_at_its_budget() {
|
||||
let paths: Vec<Vec<(i64, i64)>> = (0..50).map(|i| square(-i, -i, 100 + i, 100 + i)).collect();
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect();
|
||||
let mut work = 1_000;
|
||||
assert_eq!(outer(&paths, &boxes, &mut work), None);
|
||||
assert_eq!(work, 0);
|
||||
let mut work = u64::MAX;
|
||||
let found = outer(&paths, &boxes, &mut work);
|
||||
assert_eq!(found.map(|o| o.iter().map(Vec::len).sum::<usize>()), Some(50 * 49 / 2));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader, and an
|
||||
//! HP-GL/2 plot file reader.
|
||||
//! HP-GL/2 plot file reader and writer.
|
||||
//!
|
||||
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
|
||||
//! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths
|
||||
@@ -12,13 +12,13 @@
|
||||
//! clipping) is approximated or left out, and each such loss comes back as a warning.
|
||||
//!
|
||||
//! [`import()`] reads an ASCII DXF drawing (any version) into a document: see [`import`].
|
||||
//! [`hpgl::import`] reads an HP-GL plotter file: see [`hpgl`].
|
||||
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
|
||||
//!
|
||||
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
|
||||
//! - `writer`: group codes, handles and the file's sections, tables and objects.
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
|
||||
mod aci;
|
||||
pub mod hpgl;
|
||||
|
||||
@@ -8,6 +8,9 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::Color;
|
||||
use crate::freeform::Freeform;
|
||||
|
||||
mod spread;
|
||||
pub use spread::{MAX_SPREAD_LEVEL, MAX_SPREAD_RUNS, MAX_SPREAD_STOPS, Padded};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum GradientKind {
|
||||
#[default]
|
||||
@@ -94,6 +97,82 @@ impl GradientMethod {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the
|
||||
/// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times
|
||||
/// along the vector (around the circle, for a conic), and keep going past both of its ends.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
|
||||
pub enum GradientSpread {
|
||||
/// The first and last stops' colors carry on past the ends, as gradients always did.
|
||||
#[default]
|
||||
Pad,
|
||||
/// The stops start again at each end.
|
||||
Repeat,
|
||||
/// The stops run back the other way at each end, so every other run is mirrored.
|
||||
Reflect,
|
||||
}
|
||||
|
||||
impl GradientSpread {
|
||||
/// Every spread, in the order the Gradient panel lists them.
|
||||
pub const ALL: [GradientSpread; 3] = [GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect];
|
||||
/// Parse a spread name (`pad`, `repeat`, `reflect`; any case).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Pad => "Pad",
|
||||
Self::Repeat => "Repeat",
|
||||
Self::Reflect => "Reflect",
|
||||
}
|
||||
}
|
||||
pub fn is_pad(&self) -> bool {
|
||||
*self == Self::Pad
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for GradientSpread {
|
||||
/// A spread name; a file's unknown name or other value reads as Pad.
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Name(String),
|
||||
Other(serde::de::IgnoredAny),
|
||||
}
|
||||
Ok(match Raw::deserialize(d)? {
|
||||
Raw::Name(s) => Self::parse(&s).unwrap_or_default(),
|
||||
Raw::Other(_) => Self::Pad,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Most times a gradient's stops run along its vector ([`Gradient::repeats`]): VectorCraft's own
|
||||
/// limit.
|
||||
pub const MAX_REPEATS: u32 = 100;
|
||||
|
||||
fn one_repeat() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_one_repeat(n: &u32) -> bool {
|
||||
*n == 1
|
||||
}
|
||||
|
||||
/// A file's repeat count: a number, rounded and kept within 1 to [`MAX_REPEATS`]; anything else
|
||||
/// reads as 1.
|
||||
fn lenient_repeats<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Number(f64),
|
||||
Other(serde::de::IgnoredAny),
|
||||
}
|
||||
Ok(match Raw::deserialize(d)? {
|
||||
Raw::Number(n) if n.is_finite() => n.round().clamp(1.0, f64::from(MAX_REPEATS)) as u32,
|
||||
_ => 1,
|
||||
})
|
||||
}
|
||||
|
||||
/// How far (display RGB, 0..1) the straight line between a Perceptual gradient's neighbouring
|
||||
/// expanded stops may stray from the perceptual mix: under half a colour level.
|
||||
const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
|
||||
@@ -259,6 +338,15 @@ pub struct Gradient {
|
||||
/// How the colours between the stops are mixed (Classic unless set; written only when not).
|
||||
#[serde(default, skip_serializing_if = "GradientMethod::is_classic")]
|
||||
pub method: GradientMethod,
|
||||
/// What it paints past the ends of its stops (Pad unless set; written only when not). A
|
||||
/// freeform gradient has no ends and ignores it.
|
||||
#[serde(default, skip_serializing_if = "GradientSpread::is_pad")]
|
||||
pub spread: GradientSpread,
|
||||
/// How many times the stops run along the vector with Repeat and Reflect, 1 to
|
||||
/// [`MAX_REPEATS`] (use [`Self::repeat_count`]: a value set in code may be out of range); Pad
|
||||
/// ignores it. Written only when it is not 1.
|
||||
#[serde(default = "one_repeat", skip_serializing_if = "is_one_repeat", deserialize_with = "lenient_repeats")]
|
||||
pub repeats: u32,
|
||||
}
|
||||
|
||||
impl Default for Gradient {
|
||||
@@ -271,7 +359,55 @@ impl Default for Gradient {
|
||||
impl Gradient {
|
||||
/// A gradient of `kind` through `stops`, with the default options.
|
||||
pub fn new(kind: GradientKind, stops: Vec<GradientStop>) -> Self {
|
||||
Self { kind, stops, dither: false, method: GradientMethod::Classic }
|
||||
Self { kind, stops, dither: false, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1 }
|
||||
}
|
||||
/// [`Self::repeats`] kept within 1 to [`MAX_REPEATS`].
|
||||
pub fn repeat_count(&self) -> u32 {
|
||||
self.repeats.clamp(1, MAX_REPEATS)
|
||||
}
|
||||
/// Does it paint something other than its end colors past the ends of its stops, or run its
|
||||
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
|
||||
pub fn is_spread(&self) -> bool {
|
||||
!self.spread.is_pad() && self.kind != GradientKind::Freeform
|
||||
}
|
||||
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
|
||||
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
|
||||
/// for two gradients whose spreads paint alike.
|
||||
pub fn painted_spread(&self) -> (GradientSpread, u32) {
|
||||
if self.is_spread() { (self.spread, self.repeat_count()) } else { (GradientSpread::Pad, 1) }
|
||||
}
|
||||
/// The position (0..1) along the stops that gradient parameter `t` (0 at the start of the
|
||||
/// vector, 1 at its end; [`GradientGeom::param_at`]) samples: `t` itself with Pad (the stops
|
||||
/// clamp it), else `t` × [`Self::repeat_count`] wrapped back into 0..1, every other run
|
||||
/// mirrored with Reflect. A `t` that is not finite is returned as it is.
|
||||
pub fn spread_param(&self, t: f64) -> f64 {
|
||||
self.spreader()(t)
|
||||
}
|
||||
/// How many wedges a conic gradient is written as ([`GradientGeom::conic_wedges`]) where
|
||||
/// `per_turn` would do for stops that run once around: that many for each time the stops run
|
||||
/// around, at most [`MAX_CONIC_WEDGES`]. Sample each wedge at [`Self::spread_param`] of its
|
||||
/// turn.
|
||||
pub fn conic_wedge_count(&self, per_turn: usize) -> usize {
|
||||
let runs = if self.is_spread() { self.repeat_count() as usize } else { 1 };
|
||||
per_turn.saturating_mul(runs).clamp(1, MAX_CONIC_WEDGES)
|
||||
}
|
||||
/// [`Self::spread_param`] as a function that holds no borrow of the gradient.
|
||||
pub fn spreader(&self) -> impl Fn(f64) -> f64 + Copy + use<> {
|
||||
let spread = if self.is_spread() { self.spread } else { GradientSpread::Pad };
|
||||
let n = f64::from(self.repeat_count());
|
||||
move |t: f64| {
|
||||
if !t.is_finite() {
|
||||
return t;
|
||||
}
|
||||
match spread {
|
||||
GradientSpread::Pad => t,
|
||||
GradientSpread::Repeat => (t * n).rem_euclid(1.0),
|
||||
GradientSpread::Reflect => {
|
||||
let w = (t * n).rem_euclid(2.0);
|
||||
if w > 1.0 { 2.0 - w } else { w }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Colour and opacity at `t` (honours midpoints and the method).
|
||||
pub fn sample(&self, t: f32) -> (Color, f32) {
|
||||
@@ -544,10 +680,18 @@ impl Gradient {
|
||||
GradientStop { opacity, ..GradientStop::new(offset, color) }
|
||||
};
|
||||
let d = to - from;
|
||||
let mut stops = vec![stop(0.0, from)];
|
||||
let expanded = self.expanded_stops();
|
||||
// Where stops share the offset `from` (a sharp step, as where the runs of a repeating
|
||||
// gradient meet), the piece starts with the color after the step; sampling gives the one
|
||||
// before it.
|
||||
let first = match expanded.iter().rev().find(|(t, ..)| *t == from) {
|
||||
Some(&(_, color, opacity)) if d > 1e-6 => GradientStop { opacity, ..GradientStop::new(0.0, color) },
|
||||
_ => stop(0.0, from),
|
||||
};
|
||||
let mut stops = vec![first];
|
||||
if d > 1e-6 {
|
||||
stops.extend(
|
||||
self.expanded_stops()
|
||||
expanded
|
||||
.into_iter()
|
||||
.filter(|(t, ..)| *t > from && *t < to)
|
||||
.map(|(t, color, opacity)| GradientStop { opacity, ..GradientStop::new((t - from) / d, color) }),
|
||||
@@ -954,6 +1098,35 @@ impl GradientGeom {
|
||||
self.set_focal(Some(m * q));
|
||||
}
|
||||
}
|
||||
/// The placement whose level `t` is this one's level `k`·`t` (`k` > 0), for a linear, radial or
|
||||
/// diamond gradient: the vector `k` times as long from the same start, and for an off-center
|
||||
/// radial the extent ellipse scaled `k` times about the focal point, which stays. A conic keeps
|
||||
/// its placement (its level is a turn).
|
||||
pub fn levels_scaled(&self, kind: GradientKind, k: f64) -> GradientGeom {
|
||||
if kind == GradientKind::Conic || !(k.is_finite() && k > 0.0) {
|
||||
return *self;
|
||||
}
|
||||
let u = self.end - self.start;
|
||||
let mut out = *self;
|
||||
if kind == GradientKind::Radial
|
||||
&& let (Some(f), Some(frame)) = (self.focal, self.unit_frame())
|
||||
{
|
||||
// Level t of an off-center radial is the extent ellipse scaled by t about the line
|
||||
// from the focal point to the center: the new center sits on that line, `k` times as
|
||||
// far from the focal point.
|
||||
let f = (frame.inverse() * f).to_vec2();
|
||||
out.start = frame * (f * (1.0 - k)).to_point();
|
||||
}
|
||||
out.end = out.start + u * k;
|
||||
out
|
||||
}
|
||||
|
||||
/// The placement over which one run of the stops of a gradient that repeats `n` times along
|
||||
/// its vector lies ([`Self::levels_scaled`] by 1/`n`).
|
||||
pub fn period(&self, kind: GradientKind, n: u32) -> GradientGeom {
|
||||
self.levels_scaled(kind, 1.0 / f64::from(n.max(1)))
|
||||
}
|
||||
|
||||
pub fn angle_deg(&self) -> f64 {
|
||||
let v = self.end - self.start;
|
||||
(-v.y).atan2(v.x).to_degrees()
|
||||
@@ -1148,12 +1321,13 @@ impl GradientPaint {
|
||||
inks: bool,
|
||||
) -> impl Iterator<Item = [u8; N]> + use<N> {
|
||||
let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither);
|
||||
let spread = self.gradient.spreader();
|
||||
let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1)));
|
||||
let (x0, y0) = (area.x0, area.y0);
|
||||
let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end));
|
||||
down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| {
|
||||
let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch);
|
||||
let c = ramp.at(geom.param_at(kind, p) as f32);
|
||||
let c = ramp.at(spread(geom.param_at(kind, p)) as f32);
|
||||
std::array::from_fn(|k| {
|
||||
if k + 1 == N {
|
||||
return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//! A repeating or reflecting gradient as one that pads, for formats whose gradients only pad
|
||||
//! past their ends: the stops repeated (every other run mirrored, for Reflect) as many times as
|
||||
//! the painted area needs, and the vector stretched over those runs.
|
||||
|
||||
use kurbo::{Point, Rect, Vec2};
|
||||
|
||||
use super::{Gradient, GradientGeom, GradientKind, GradientSpread, GradientStop};
|
||||
|
||||
/// Most runs of the stops [`Gradient::padded_over`] writes.
|
||||
pub const MAX_SPREAD_RUNS: usize = 256;
|
||||
|
||||
/// Most stops [`Gradient::padded_over`] writes, all runs together.
|
||||
pub const MAX_SPREAD_STOPS: usize = 16384;
|
||||
|
||||
/// The farthest level from its center a radial or diamond gradient's runs are written out to by
|
||||
/// [`Gradient::padded_over`] (its stops' offsets, single-precision fractions of it, stay apart),
|
||||
/// nearer for stops closer together than a run ([`MIN_OFFSET_GAP`]).
|
||||
pub const MAX_SPREAD_LEVEL: f64 = 65536.0;
|
||||
|
||||
/// The least difference between two stops' offsets [`Gradient::padded_over`] writes as
|
||||
/// different: sixteen times single precision's step just below 1.
|
||||
const MIN_OFFSET_GAP: f64 = 1e-6;
|
||||
|
||||
/// A repeating or reflecting gradient written as one that pads ([`Gradient::padded_over`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Padded {
|
||||
/// The gradient with its stops repeated, padding past its ends.
|
||||
pub gradient: Gradient,
|
||||
/// Where those runs lie.
|
||||
pub geom: GradientGeom,
|
||||
/// Where along `geom` (0 to 1) the first run written starts: 0 for a linear gradient, the
|
||||
/// first run's level over the last one's outer level for a radial or diamond one.
|
||||
pub first: f64,
|
||||
/// How many runs are written, evenly spaced from [`Self::first`] to 1.
|
||||
pub runs: usize,
|
||||
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or than [`MAX_SPREAD_STOPS`] allows),
|
||||
/// or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
|
||||
pub capped: bool,
|
||||
}
|
||||
|
||||
impl Gradient {
|
||||
/// A linear, radial or diamond gradient that repeats or reflects, placed at `geom`, as a
|
||||
/// gradient that pads and paints `area` the same way: its stops repeated, each run's
|
||||
/// placement [`GradientGeom::period`] of `geom`, as many runs as the area reaches (a radial or
|
||||
/// diamond from its first level, 0, the first stop's color inside the area's innermost run).
|
||||
/// `None` for a gradient that pads, a conic or
|
||||
/// freeform one, one without stops, and a placement whose levels at the corners are not
|
||||
/// finite.
|
||||
pub fn padded_over(&self, geom: &GradientGeom, area: Rect) -> Option<Padded> {
|
||||
self.padded_within(geom, area, MAX_SPREAD_STOPS)
|
||||
}
|
||||
|
||||
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run).
|
||||
pub fn padded_within(&self, geom: &GradientGeom, area: Rect, max_stops: usize) -> Option<Padded> {
|
||||
let kind = self.kind;
|
||||
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let period = geom.period(kind, self.repeat_count());
|
||||
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)];
|
||||
let ts = corners.map(|p| period.param_at(kind, p));
|
||||
if ts.iter().any(|t| !t.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let centered = kind.is_centered();
|
||||
// The level's range over the area. A linear gradient's extremes lie at corners. Radial and
|
||||
// diamond levels are nested convex rings from level 0: the largest at a corner, the
|
||||
// smallest 0 when the area holds the rings' center, else on its edge.
|
||||
let lo = if centered { inner_level(&period, kind, area).floor() } else { ts.iter().copied().fold(f64::INFINITY, f64::min).floor() };
|
||||
let hi = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil().max(lo + 1.0);
|
||||
let one = whole_run(&self.stops);
|
||||
let most = MAX_SPREAD_RUNS.min(max_stops.min(MAX_SPREAD_STOPS) / one.len().max(1)).max(1);
|
||||
let capped = hi - lo > most as f64;
|
||||
// Capped, the runs kept are the area's innermost ones (radial and diamond), or (linear)
|
||||
// those around the vector's start where the area reaches it, else the area's runs nearest
|
||||
// to it.
|
||||
let lo = match capped {
|
||||
true if !centered => (-((most / 2) as f64)).clamp(lo, hi - most as f64),
|
||||
_ => lo,
|
||||
};
|
||||
let n = (hi - lo).min(most as f64).max(1.0);
|
||||
// A radial or diamond writes its runs among the levels from 0, which its stops' offsets
|
||||
// (single-precision fractions of the outermost level) tell apart only so far out, the
|
||||
// nearer the closer its stops lie: past that, the runs end there and the gradient pads.
|
||||
let gap = one.windows(2).map(|w| f64::from(w[1].offset - w[0].offset)).filter(|d| *d > 0.0).fold(1.0, f64::min);
|
||||
// A whole level, so the runs keep their places (and Reflect its mirrored ones).
|
||||
let farthest = MAX_SPREAD_LEVEL.min(gap / MIN_OFFSET_GAP).floor().max(n);
|
||||
let far = centered && lo + n > farthest;
|
||||
let (lo, capped) = if far { ((farthest - n).max(0.0), true) } else { (lo, capped) };
|
||||
// `lo` is a whole number, possibly past what an integer holds: its parity in floating point.
|
||||
let first_odd = lo.rem_euclid(2.0) >= 1.0;
|
||||
let (stops, geom) = if centered {
|
||||
// The levels from 0, the runs from level `lo` (the first stop's color inside it).
|
||||
(self.runs(&one, first_odd, lo, n as usize, lo + n), period.levels_scaled(kind, lo + n))
|
||||
} else {
|
||||
let u = period.end - period.start;
|
||||
(
|
||||
self.runs(&one, first_odd, 0.0, n as usize, n),
|
||||
GradientGeom { start: period.start + u * lo, end: period.start + u * (lo + n), ..period },
|
||||
)
|
||||
};
|
||||
let gradient = Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() };
|
||||
let first = if centered { lo / (lo + n) } else { 0.0 };
|
||||
Some(Padded { gradient, geom, first, runs: n as usize, capped })
|
||||
}
|
||||
|
||||
/// The gradient as it runs from the start of its vector (0) to its end (1), as one that
|
||||
/// pads: a gradient that repeats or reflects with its stops repeated [`Self::repeat_count`]
|
||||
/// times between 0 and 1 (every other run mirrored, for Reflect), for what only shows that
|
||||
/// stretch (a gradient along or across a stroke, a swatch's preview). Others as they are.
|
||||
pub fn unrolled(&self) -> std::borrow::Cow<'_, Gradient> {
|
||||
self.unrolled_within(MAX_SPREAD_STOPS)
|
||||
}
|
||||
|
||||
/// [`Self::unrolled`] with at most `max_stops` stops (and at least one run): past the runs
|
||||
/// that fit, the last one pads.
|
||||
pub fn unrolled_within(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
|
||||
use std::borrow::Cow;
|
||||
if !self.is_spread() {
|
||||
return Cow::Borrowed(self);
|
||||
}
|
||||
// Without stops there is nothing to repeat: it pads all the same.
|
||||
if self.stops.is_empty() {
|
||||
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
|
||||
}
|
||||
let one = whole_run(&self.stops);
|
||||
let n = self.repeat_count() as usize;
|
||||
let kept = n.min(max_stops.min(MAX_SPREAD_STOPS) / one.len().max(1)).max(1);
|
||||
let stops = self.runs(&one, false, 0.0, kept, n as f64);
|
||||
Cow::Owned(Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() })
|
||||
}
|
||||
|
||||
/// One cycle of a gradient that repeats or reflects, which repeated end to end paints it, as
|
||||
/// a gradient that pads: one run of the stops (Repeat), or a run and its mirror (Reflect),
|
||||
/// between 0 and 1, and how many runs that is (1 or 2). `None` for a gradient that pads and
|
||||
/// one without stops.
|
||||
pub fn cycle(&self) -> Option<(Gradient, u32)> {
|
||||
if !self.is_spread() || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let one = whole_run(&self.stops);
|
||||
let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 };
|
||||
let stops = self.runs(&one, false, 0.0, runs, runs as f64);
|
||||
Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32))
|
||||
}
|
||||
|
||||
/// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1,
|
||||
/// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with
|
||||
/// Reflect, the odd-numbered runs are mirrored).
|
||||
fn runs(&self, one: &[GradientStop], first_odd: bool, start: f64, n: usize, of: f64) -> Vec<GradientStop> {
|
||||
let mirrored_run = (self.spread == GradientSpread::Reflect).then(|| mirror(one));
|
||||
let mut stops = Vec::with_capacity(one.len() * n);
|
||||
for j in 0..n {
|
||||
let run = match &mirrored_run {
|
||||
Some(m) if (j % 2 == 1) != first_odd => m.as_slice(),
|
||||
_ => one,
|
||||
};
|
||||
stops.extend(run.iter().map(|s| GradientStop { offset: ((start + j as f64 + f64::from(s.offset)) / of) as f32, ..s.clone() }));
|
||||
}
|
||||
stops
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest level of radial or diamond gradient `geom` over `area`, less a run (for rounding):
|
||||
/// 0 when the area holds the rings' center (a radial's focal point, a diamond's center), else the
|
||||
/// smallest along its sides, worked out in the gradient's unit frame from the sides' ends rather
|
||||
/// than from samples along them, so a long side does not hide a run near it. 0 for a placement
|
||||
/// without a frame.
|
||||
fn inner_level(geom: &GradientGeom, kind: GradientKind, area: Rect) -> f64 {
|
||||
let center = if kind == GradientKind::Radial { geom.focal_point() } else { geom.start };
|
||||
if area.contains(center) {
|
||||
return 0.0;
|
||||
}
|
||||
let frame = if kind == GradientKind::Diamond { geom.diamond_frame() } else { geom.unit_frame() };
|
||||
let Some(to_unit) = frame.map(|m| m.inverse()) else { return 0.0 };
|
||||
let focal = geom.focal.filter(|_| kind == GradientKind::Radial).map(|f| (to_unit * f).to_vec2());
|
||||
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)]
|
||||
.map(|p| (to_unit * p).to_vec2());
|
||||
let mut least = f64::INFINITY;
|
||||
for (&a, &b) in corners.iter().zip(corners.iter().cycle().skip(1)) {
|
||||
let side = if kind == GradientKind::Diamond { diamond_least(a, b) } else { radial_least(a, b, focal) };
|
||||
least = least.min(side);
|
||||
}
|
||||
if least.is_finite() { (least - 1.0).max(0.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The smallest diamond level, |x| + |y| in its unit frame, on the segment from `a` to `b`: the
|
||||
/// level is linear between the points where the segment crosses an axis, so the smallest is at
|
||||
/// an end or at one of those crossings.
|
||||
fn diamond_least(a: Vec2, b: Vec2) -> f64 {
|
||||
let d = b - a;
|
||||
let crossings = [(d.x != 0.0).then(|| -a.x / d.x), (d.y != 0.0).then(|| -a.y / d.y)];
|
||||
[Some(0.0), Some(1.0), crossings[0], crossings[1]]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|u| (0.0..=1.0).contains(u))
|
||||
.map(|u| {
|
||||
let p = a + d * u;
|
||||
p.x.abs() + p.y.abs()
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Halvings at most in [`radial_least`]: enough to bring any finite span below a quarter level.
|
||||
const RADIAL_HALVINGS: usize = 1100;
|
||||
|
||||
/// The smallest radial level on the segment from `a` to `b` in the unit frame, at most a quarter
|
||||
/// level under it: the distance to the center for a centered radial. An off-center radial's level
|
||||
/// `t` is the circle of radius `t` about `f`(1 − `t`), `f` its focal point; the segment's distance
|
||||
/// from that center less `t` falls as `t` grows (the center moves |`f`| < 1 per level), and the
|
||||
/// smallest level is where it reaches 0, found by halving. 0 for a focal point not inside the
|
||||
/// extent ellipse.
|
||||
fn radial_least(a: Vec2, b: Vec2, focal: Option<Vec2>) -> f64 {
|
||||
let Some(f) = focal else { return distance_to_segment(a, b, Vec2::ZERO) };
|
||||
let reach = f.hypot();
|
||||
if reach.is_nan() || reach >= 1.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let past = |t: f64| distance_to_segment(a, b, f * (1.0 - t)) <= t;
|
||||
// At this level the circle reaches the segment's nearest point to the ellipse's center.
|
||||
let mut hi = (distance_to_segment(a, b, Vec2::ZERO) / (1.0 - reach)).max(1.0);
|
||||
let mut lo = 0.0;
|
||||
if !hi.is_finite() || past(lo) {
|
||||
return 0.0;
|
||||
}
|
||||
for _ in 0..RADIAL_HALVINGS {
|
||||
let mid = lo + (hi - lo) / 2.0;
|
||||
if hi - lo <= 0.25 || mid <= lo || mid >= hi {
|
||||
break;
|
||||
}
|
||||
if past(mid) { hi = mid } else { lo = mid }
|
||||
}
|
||||
lo
|
||||
}
|
||||
|
||||
/// How far `c` is from the segment from `a` to `b`.
|
||||
fn distance_to_segment(a: Vec2, b: Vec2, c: Vec2) -> f64 {
|
||||
let d = b - a;
|
||||
let along = (c - a).dot(d) / d.hypot2();
|
||||
let u = if along.is_finite() { along.clamp(0.0, 1.0) } else { 0.0 };
|
||||
(a + d * u - c).hypot()
|
||||
}
|
||||
|
||||
/// The stops of one run, from offset 0 to 1: the end colors held out to the ends.
|
||||
fn whole_run(stops: &[GradientStop]) -> Vec<GradientStop> {
|
||||
let mut out = stops.to_vec();
|
||||
if let Some(first) = out.first().filter(|s| s.offset > 0.0).cloned() {
|
||||
out.insert(0, GradientStop { offset: 0.0, ..first });
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
// The last stop's midpoint leads nowhere; the copy at 1 takes over.
|
||||
if last.offset < 1.0 {
|
||||
let end = GradientStop { offset: 1.0, ..last.clone() };
|
||||
out.push(end);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A run mirrored: the stops in reverse, each midpoint measured from the other side.
|
||||
fn mirror(run: &[GradientStop]) -> Vec<GradientStop> {
|
||||
let mut g = Gradient::new(GradientKind::Linear, run.to_vec());
|
||||
g.reverse();
|
||||
g.stops
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,368 @@
|
||||
use kurbo::Vec2;
|
||||
|
||||
use super::*;
|
||||
use crate::gradient::{GradientPaint, MAX_REPEATS};
|
||||
use crate::{Color, GradientMethod};
|
||||
|
||||
fn spread(kind: GradientKind, spread: GradientSpread, repeats: u32) -> Gradient {
|
||||
Gradient { spread, repeats, ..Gradient::new(kind, Gradient::default().stops) }
|
||||
}
|
||||
|
||||
fn black_white() -> Vec<GradientStop> {
|
||||
let mut a = GradientStop::new(0.0, Color::BLACK);
|
||||
a.midpoint = 0.3;
|
||||
vec![a, GradientStop::new(1.0, Color::WHITE)]
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
/// Repeat wraps the parameter, `repeats` times along the vector and on past both ends; Reflect
|
||||
/// runs every other run backwards; Pad leaves it to the stops to clamp; a freeform gradient has
|
||||
/// no ends to spread past.
|
||||
#[test]
|
||||
fn spread_maps_the_parameter_to_a_place_along_the_stops() {
|
||||
let repeat = spread(GradientKind::Linear, GradientSpread::Repeat, 3);
|
||||
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (0.5, 0.5), (1.0 / 3.0 + 0.1, 0.3), (1.1, 0.3), (-0.1, 0.7)] {
|
||||
assert!(close(repeat.spread_param(t), want), "repeat {t}: {}", repeat.spread_param(t));
|
||||
}
|
||||
let reflect = spread(GradientKind::Radial, GradientSpread::Reflect, 3);
|
||||
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (1.0 / 3.0 + 0.1, 0.7), (2.0 / 3.0 + 0.1, 0.3), (1.0, 1.0), (-0.1, 0.3)] {
|
||||
assert!(close(reflect.spread_param(t), want), "reflect {t}: {}", reflect.spread_param(t));
|
||||
}
|
||||
let pad = spread(GradientKind::Linear, GradientSpread::Pad, 3);
|
||||
assert_eq!((pad.spread_param(1.7), pad.spread_param(-0.2)), (1.7, -0.2));
|
||||
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
|
||||
assert_eq!(free.spread_param(0.7), 0.7);
|
||||
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
|
||||
assert!(repeat.spread_param(f64::NAN).is_nan());
|
||||
// A count out of range (set in code) counts as the nearest one in range.
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 5000).repeat_count(), MAX_REPEATS);
|
||||
}
|
||||
|
||||
/// The native format writes the spread and count only when they are not Pad and 1, reads a file
|
||||
/// without them as Pad and 1, and reads an unknown spread or a count out of range as the nearest
|
||||
/// one it can hold.
|
||||
#[test]
|
||||
fn the_file_keeps_the_spread_and_reads_bad_values_leniently() {
|
||||
let plain = serde_json::to_value(Gradient::default()).unwrap();
|
||||
assert!(plain.get("spread").is_none() && plain.get("repeats").is_none(), "{plain}");
|
||||
let g = spread(GradientKind::Conic, GradientSpread::Reflect, 4);
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
assert_eq!((v["spread"].as_str(), v["repeats"].as_u64()), (Some("Reflect"), Some(4)));
|
||||
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
|
||||
let read = |spread: serde_json::Value, repeats: serde_json::Value| {
|
||||
let mut v = serde_json::to_value(Gradient::default()).unwrap();
|
||||
v["spread"] = spread;
|
||||
v["repeats"] = repeats;
|
||||
let g: Gradient = serde_json::from_value(v).unwrap();
|
||||
(g.spread, g.repeats)
|
||||
};
|
||||
assert_eq!(read("Repeat".into(), 3.4.into()), (GradientSpread::Repeat, 3));
|
||||
assert_eq!(read("Spiral".into(), (-5).into()), (GradientSpread::Pad, 1));
|
||||
assert_eq!(read(7.into(), 1e12.into()), (GradientSpread::Pad, MAX_REPEATS));
|
||||
assert_eq!(read(serde_json::Value::Null, "many".into()), (GradientSpread::Pad, 1));
|
||||
let missing: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap();
|
||||
assert_eq!((missing.spread, missing.repeats), (GradientSpread::Pad, 1));
|
||||
}
|
||||
|
||||
/// One run's placement: a level of the period is the gradient's level times the count, for
|
||||
/// linear, diamond and off-center radial gradients; a conic keeps its placement.
|
||||
#[test]
|
||||
fn a_period_holds_one_run_of_the_stops() {
|
||||
let p = Point::new(72.0, 61.0);
|
||||
let linear = GradientGeom { start: Point::new(10.0, 20.0), end: Point::new(60.0, 40.0), aspect: 1.0, focal: None };
|
||||
let radial = GradientGeom { start: Point::new(50.0, 50.0), end: Point::new(60.0, 50.0), aspect: 0.6, focal: Some(Point::new(55.0, 52.0)) };
|
||||
let diamond = GradientGeom { end: Point::new(58.0, 56.0), focal: None, ..radial };
|
||||
for (kind, geom) in [(GradientKind::Linear, linear), (GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
|
||||
let period = geom.period(kind, 4);
|
||||
assert!(close(period.param_at(kind, p), 4.0 * geom.param_at(kind, p)), "{kind:?}");
|
||||
assert_eq!(period.focal, geom.focal, "{kind:?}");
|
||||
}
|
||||
assert_eq!(radial.period(GradientKind::Conic, 4), radial);
|
||||
assert_eq!(linear.period(GradientKind::Linear, 0), linear, "a count of 0 counts as 1");
|
||||
}
|
||||
|
||||
/// The stops repeated over the area: as many runs as its corners reach, each in place.
|
||||
#[test]
|
||||
fn a_linear_gradient_pads_with_its_stops_repeated_over_the_area() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(-5.0, 0.0, 25.0, 10.0)).unwrap();
|
||||
assert!(!p.capped);
|
||||
// Runs of 10 from -10 to 30: four of them.
|
||||
assert_eq!((p.geom.start, p.geom.end), (Point::new(-10.0, 0.0), Point::new(30.0, 0.0)));
|
||||
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0]);
|
||||
assert!(p.gradient.stops.iter().step_by(2).all(|s| s.color == Color::BLACK && (s.midpoint - 0.3).abs() < 1e-6));
|
||||
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
|
||||
// Every point gets the color the gradient gives it.
|
||||
for x in [-4.0, 1.0, 7.5, 13.0, 24.0] {
|
||||
let q = Point::new(x, 5.0);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0;
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0;
|
||||
assert!(want.to_rgb().iter().zip(got.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_mirrors_every_other_run_and_its_midpoints() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
let colors: Vec<Color> = p.gradient.stops.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK]);
|
||||
// Black → white with the midpoint at 0.3 mirrors to white → black with it at 0.7.
|
||||
assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_inside_a_run_hold_their_colors_to_its_ends() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let stops = vec![GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.75, Color::WHITE)];
|
||||
let g = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.125, 0.375, 0.5, 0.5, 0.625, 0.875, 1.0]);
|
||||
}
|
||||
|
||||
/// An off-center radial grows about its focal point, a diamond about its center; every point
|
||||
/// keeps its color.
|
||||
#[test]
|
||||
fn radial_and_diamond_gradients_pad_in_rings_from_their_first_level() {
|
||||
let c = Point::new(50.0, 50.0);
|
||||
let radial = GradientGeom { start: c, end: Point::new(60.0, 50.0), aspect: 1.0, focal: Some(Point::new(55.0, 50.0)) };
|
||||
let diamond = GradientGeom { focal: None, ..radial };
|
||||
for (kind, geom) in [(GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 100.0)).unwrap();
|
||||
assert!(p.gradient.stops.len() / 2 >= 10, "{kind:?}: {}", p.gradient.stops.len());
|
||||
assert_eq!(p.geom.focal, geom.focal);
|
||||
for q in [Point::new(72.0, 61.0), Point::new(10.0, 95.0), Point::new(52.0, 49.0)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-4), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of the stops far too short for the area, or a gradient of many stops, is written with at
|
||||
/// most so many runs and stops, and pads past them; a conic, a padding gradient and one without
|
||||
/// stops have nothing to pad.
|
||||
#[test]
|
||||
fn far_repeats_and_many_stops_are_capped() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.01, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
|
||||
assert!(p.capped);
|
||||
assert_eq!(p.gradient.stops.len(), 2 * MAX_SPREAD_RUNS);
|
||||
let many: Vec<GradientStop> = (0..=4000).map(|i| GradientStop::new(i as f32 / 4000.0, Color::gray(i as f32 / 4000.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 50, ..Gradient::new(GradientKind::Linear, many) };
|
||||
let wide = GradientGeom { end: Point::new(100.0, 0.0), ..geom };
|
||||
let p = g.padded_over(&wide, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
|
||||
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{}", p.gradient.stops.len());
|
||||
assert!(g.unrolled().stops.len() <= MAX_SPREAD_STOPS);
|
||||
assert!(p.gradient.padded_over(&p.geom, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none(), "it pads");
|
||||
assert!(spread(GradientKind::Conic, GradientSpread::Repeat, 3).padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
|
||||
let empty = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, vec![]) };
|
||||
assert!(empty.padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
|
||||
}
|
||||
|
||||
/// The runs written are the ones the area shows: a radial or diamond centered a thousand runs
|
||||
/// from the area writes the hundred it crosses, not the first 256 from the center; a linear
|
||||
/// gradient over an area of 1,100 runs far before its start, capped, keeps the runs nearest it.
|
||||
/// Every point checked gets the color the gradient gives it.
|
||||
#[test]
|
||||
fn the_runs_written_cover_a_distant_area() {
|
||||
let centered = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(1.0, 50.0), aspect: 1.0, focal: None };
|
||||
let before = GradientGeom { start: Point::new(5000.0, 0.0), end: Point::new(5001.0, 0.0), aspect: 1.0, focal: None };
|
||||
for (kind, geom, area) in [
|
||||
(GradientKind::Radial, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
|
||||
(GradientKind::Diamond, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
|
||||
(GradientKind::Linear, before, Rect::new(0.0, 0.0, 1100.0, 100.0)),
|
||||
] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, area).unwrap();
|
||||
assert_eq!(p.capped, kind == GradientKind::Linear, "{kind:?}");
|
||||
assert!(p.gradient.stops.len() <= MAX_SPREAD_STOPS);
|
||||
for q in [Point::new(1000.5, 0.5), Point::new(1050.25, 50.0), Point::new(1099.5, 99.5), Point::new(1010.75, 90.0)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tiny radial centered just outside the area, beside a side between any evenly spaced
|
||||
/// samples of it: the runs written start from the area's true innermost level.
|
||||
#[test]
|
||||
fn the_innermost_level_is_found_between_samples() {
|
||||
let c = Point::new(-0.0005, 7.8125);
|
||||
let geom = GradientGeom { start: c, end: c + Vec2::new(0.001, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 1000.0, 1000.0)).unwrap();
|
||||
for q in [Point::new(0.05, 7.8125), Point::new(0.1, 7.9)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Radial, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Radial, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An area four billion units wide whose long side passes 50 runs from a tiny radial or diamond's
|
||||
/// center: the runs written start from that side's true innermost level, so the runs beside it
|
||||
/// keep their colors.
|
||||
#[test]
|
||||
fn the_innermost_level_is_found_along_a_very_long_side() {
|
||||
let area = Rect::new(-1.3e9, 0.0, 2.9e9, 1.0);
|
||||
for x in [0.3, 12345.678, -7777.25, 98765.4321] {
|
||||
let c = Point::new(x, -0.00005);
|
||||
let run = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
|
||||
let off_center = GradientGeom { focal: Some(c + Vec2::new(0.5e-6, 0.0)), ..run };
|
||||
for (kind, geom) in [(GradientKind::Diamond, run), (GradientKind::Radial, run), (GradientKind::Radial, off_center)] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, area).unwrap();
|
||||
assert!(p.capped, "{kind:?}");
|
||||
for q in [Point::new(x, 1e-5), Point::new(x + 2e-5, 2e-5), Point::new(x - 1e-5, 0.0001)] {
|
||||
let level = geom.param_at(kind, q);
|
||||
assert!((40.0..200.0).contains(&level), "{kind:?} {q:?}: level {level}");
|
||||
let want = g.sample(g.spread_param(level) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a billion levels from a radial's center are past what the stops' offsets can tell apart:
|
||||
/// the gradient is written capped, its stops still apart and in order.
|
||||
#[test]
|
||||
fn runs_too_far_from_the_center_are_capped() {
|
||||
let c = Point::new(0.0, 0.0);
|
||||
let geom = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(1000.0, 0.0, 1000.0001, 0.0001)).unwrap();
|
||||
assert!(p.capped);
|
||||
assert!(p.gradient.stops.windows(2).all(|w| w[0].offset <= w[1].offset), "in order");
|
||||
let distinct = p.gradient.stops.windows(2).filter(|w| w[1].offset > w[0].offset).count();
|
||||
assert!(distinct * 2 + 2 >= p.gradient.stops.len(), "the runs stay apart: {distinct} of {}", p.gradient.stops.len());
|
||||
}
|
||||
|
||||
/// A run of 1,000 close stops is written only as far out as their offsets stay apart: around
|
||||
/// level 50,000 it is capped, every stop written apart from the next.
|
||||
#[test]
|
||||
fn close_stops_are_written_only_where_they_stay_apart() {
|
||||
let many: Vec<GradientStop> = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray(i as f32 / 1000.0))).collect();
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.001, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 1, ..Gradient::new(GradientKind::Diamond, many) };
|
||||
let p = g.padded_over(&geom, Rect::new(50.0, 0.0, 50.002, 0.002)).unwrap();
|
||||
assert!(p.capped);
|
||||
// Only where one run meets the next do two stops share an offset.
|
||||
let runs = p.gradient.stops.len() / 1001;
|
||||
let shared = p.gradient.stops.windows(2).filter(|w| w[1].offset <= w[0].offset).count();
|
||||
assert!(shared < runs, "{shared} stops share an offset in {runs} runs");
|
||||
// Stops 0.0001234 of a run apart are written out to level 123, on whole runs: an area within
|
||||
// it gets the gradient's colors, Reflect's mirrored runs included.
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.0001234, Color::gray(0.5)), GradientStop::new(1.0, Color::WHITE)];
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Diamond, stops) };
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0), aspect: 1.0, focal: None };
|
||||
let p = g.padded_over(&geom, Rect::new(121.0, 0.0, 123.9, 0.2)).unwrap();
|
||||
assert!(p.capped, "past level 123 it pads");
|
||||
for x in [121.3, 121.9, 122.5] {
|
||||
let q = Point::new(x, 0.1);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Diamond, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Diamond, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece of a gradient that starts where two runs meet (a gradient along a stroke, sliced at a
|
||||
/// corner there) starts with the new run's first color, not the old run's last.
|
||||
#[test]
|
||||
fn a_piece_starting_at_a_sharp_step_takes_the_color_after_it() {
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, Gradient::default().stops) };
|
||||
let piece = g.unrolled().span(0.5, 1.0);
|
||||
assert_eq!(piece.stops.first().map(|s| s.color), Some(Color::WHITE), "{:?}", piece.stops);
|
||||
assert_eq!(piece.stops.last().map(|s| s.color), Some(Color::BLACK));
|
||||
let before = g.unrolled().span(0.0, 0.5);
|
||||
assert_eq!((before.stops[0].color, before.stops.last().unwrap().color), (Color::WHITE, Color::BLACK));
|
||||
}
|
||||
|
||||
/// An area very far past a very short reflecting vector (a file's numbers) is padded without the
|
||||
/// run count overflowing.
|
||||
#[test]
|
||||
fn a_far_area_pads_without_overflowing() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1e-300, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(1e3, 0.0, 2e3, 1.0));
|
||||
assert!(p.is_none_or(|p| p.gradient.stops.len() <= MAX_SPREAD_STOPS));
|
||||
// Runs of 1e-8: the area's levels lie past 1e19, more than an integer holds.
|
||||
let geom = GradientGeom { end: Point::new(1e-6, 0.0), ..geom };
|
||||
let p = g.padded_over(&geom, Rect::new(1e11, 0.0, 1e11 + 1.0, 1.0)).unwrap();
|
||||
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {} {:?}", p.capped, p.gradient.stops.len(), p.geom);
|
||||
}
|
||||
|
||||
/// Unrolled, the stops run `repeats` times between 0 and 1 (every other run mirrored with
|
||||
/// Reflect); one cycle is a run, or a run and its mirror.
|
||||
#[test]
|
||||
fn unrolled_and_cycle_stops() {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let u = g.unrolled();
|
||||
let offsets: Vec<f32> = u.stops.iter().map(|s| (s.offset * 3.0).round()).collect();
|
||||
assert_eq!(offsets, [0.0, 1.0, 1.0, 2.0, 2.0, 3.0]);
|
||||
let colors: Vec<Color> = u.stops.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK, Color::BLACK, Color::WHITE]);
|
||||
for t in [0.05, 0.4, 0.71, 0.99] {
|
||||
let (a, b) = (g.sample(g.spread_param(t) as f32).0.to_rgb(), u.sample(t as f32).0.to_rgb());
|
||||
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), "{t}");
|
||||
}
|
||||
let (cycle, runs) = g.cycle().unwrap();
|
||||
assert_eq!((runs, cycle.stops.len()), (2, 4));
|
||||
let repeat = Gradient { spread: GradientSpread::Repeat, ..g.clone() };
|
||||
assert_eq!(repeat.cycle().unwrap().1, 1);
|
||||
assert!(Gradient::default().cycle().is_none());
|
||||
assert!(matches!(Gradient::default().unrolled(), std::borrow::Cow::Borrowed(_)));
|
||||
}
|
||||
|
||||
/// Pixels (what the canvas draws a diamond, dithered or Perceptual gradient as, and what SVG and
|
||||
/// PDF write as images) repeat with the stops, for each kind.
|
||||
#[test]
|
||||
fn pixels_repeat_and_reflect_for_every_kind() {
|
||||
let b = Rect::new(0.0, 0.0, 40.0, 40.0);
|
||||
let c = Point::new(20.0, 20.0);
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
|
||||
for sp in [GradientSpread::Repeat, GradientSpread::Reflect] {
|
||||
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
|
||||
let mut g = GradientPaint::new(Gradient { spread: sp, repeats: 3, method, ..Gradient::new(kind, Gradient::default().stops) });
|
||||
let geom = if kind == GradientKind::Linear {
|
||||
GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(40.0, 10.0), aspect: 1.0, focal: None }
|
||||
} else {
|
||||
GradientGeom { start: c, end: c + Vec2::new(18.0, 4.0), aspect: 0.8, focal: None }
|
||||
};
|
||||
g.geom = Some(geom);
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 40, 40, false, &Color::to_rgb).collect();
|
||||
for (i, got) in px.iter().enumerate().step_by(37) {
|
||||
let p = Point::new((i % 40) as f64 + 0.5, (i / 40) as f64 + 0.5);
|
||||
let t = g.gradient.spread_param(geom.param_at(kind, p));
|
||||
// Not where Repeat jumps from the last stop back to the first.
|
||||
if sp == GradientSpread::Repeat && !(0.03..0.97).contains(&t) {
|
||||
continue;
|
||||
}
|
||||
let want = g.gradient.sample(t as f32).0.to_rgba8(1.0);
|
||||
assert!(got[0].abs_diff(want[0]) <= 2, "{kind:?} {sp:?} {method:?} {p:?}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A conic gradient's wedges: as many for each time the stops run around as for one turn, at most
|
||||
/// so many.
|
||||
#[test]
|
||||
fn conic_wedges_count_each_run() {
|
||||
let g = spread(GradientKind::Conic, GradientSpread::Repeat, 4);
|
||||
assert_eq!(g.conic_wedge_count(360), 1440);
|
||||
assert_eq!(spread(GradientKind::Conic, GradientSpread::Pad, 4).conic_wedge_count(360), 360);
|
||||
assert_eq!(spread(GradientKind::Conic, GradientSpread::Reflect, MAX_REPEATS).conic_wedge_count(360), crate::gradient::MAX_CONIC_WEDGES);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ pub mod swatch;
|
||||
|
||||
pub use blend::BlendMode;
|
||||
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
|
||||
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop};
|
||||
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop};
|
||||
pub use libraries::SwatchLibrary;
|
||||
pub use swatch::{Swatch, SwatchGroup, default_swatches};
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ pub const GRADIENT_LIBRARIES: &[BuiltinLibrary] = &[
|
||||
lib!("sky-gradients", "Sky Gradients", sky_gradients),
|
||||
lib!("neutral-gradients", "Neutral Gradients", neutral_gradients),
|
||||
lib!("organic-fades", "Organic Fades", organic_fades),
|
||||
lib!("holographic", "Holographic", holographic),
|
||||
lib!("duotone-gradients", "Duotone Gradients", duotone_gradients),
|
||||
lib!("radial-glows", "Radial Glows", radial_glows),
|
||||
];
|
||||
@@ -531,6 +532,62 @@ fn organic_fades() -> (Vec<Swatch>, Vec<SwatchGroup>) {
|
||||
(s, vec![])
|
||||
}
|
||||
|
||||
/// The stops of a [`holographic`] look: offset, opacity and midpoint toward the next stop.
|
||||
type Bands = [(f32, f32, f32)];
|
||||
|
||||
/// Foil: six opaque linear bands, a narrow bright one among them, with off-center midpoints.
|
||||
const FOIL: &Bands = &[(0.0, 1.0, 0.37), (0.13, 1.0, 0.64), (0.34, 1.0, 0.28), (0.48, 1.0, 0.68), (0.71, 1.0, 0.42), (1.0, 1.0, 0.5)];
|
||||
|
||||
/// Glow: five radial rings from a bright center out to a clear edge.
|
||||
const GLOW: &Bands = &[(0.0, 0.95, 0.4), (0.12, 1.0, 0.58), (0.31, 0.72, 0.34), (0.58, 0.3, 0.62), (1.0, 0.0, 0.5)];
|
||||
|
||||
/// A [`holographic`] look: name, kind, stops and the OKLCH color of each stop in order.
|
||||
type Look = (&'static str, GradientKind, &'static Bands, Anchors);
|
||||
|
||||
/// Iridescent looks mixed perceptually: linear foils of narrow pastel and pearl bands, and radial
|
||||
/// glows that fade out to a clear edge. Each color is one stop of [`FOIL`] or [`GLOW`] in order.
|
||||
fn holographic() -> (Vec<Swatch>, Vec<SwatchGroup>) {
|
||||
use GradientKind::{Linear, Radial};
|
||||
// Pale pearl, pastel and deep-violet OKLCH `(l, c, h°)` anchors.
|
||||
const PEARL: (f64, f64, f64) = (0.97, 0.01, 90.0);
|
||||
const SILVER: (f64, f64, f64) = (0.86, 0.015, 255.0);
|
||||
const BLUSH: (f64, f64, f64) = (0.82, 0.055, 340.0);
|
||||
const VIOLET: (f64, f64, f64) = (0.72, 0.1, 310.0);
|
||||
const BLUE: (f64, f64, f64) = (0.73, 0.09, 255.0);
|
||||
const CYAN: (f64, f64, f64) = (0.79, 0.09, 210.0);
|
||||
const MINT: (f64, f64, f64) = (0.82, 0.08, 165.0);
|
||||
const LIME: (f64, f64, f64) = (0.86, 0.085, 125.0);
|
||||
const GOLD: (f64, f64, f64) = (0.89, 0.08, 85.0);
|
||||
const AMBER: (f64, f64, f64) = (0.82, 0.1, 55.0);
|
||||
const CORAL: (f64, f64, f64) = (0.78, 0.09, 25.0);
|
||||
const DEEP_VIOLET: (f64, f64, f64) = (0.42, 0.04, 275.0);
|
||||
let looks: [Look; 14] = [
|
||||
("Prism Veil", Linear, FOIL, &[SILVER, BLUSH, PEARL, CYAN, VIOLET, SILVER]),
|
||||
("Opal Ribbon", Linear, FOIL, &[PEARL, MINT, BLUSH, PEARL, BLUE, SILVER]),
|
||||
("Pearl Flash", Linear, FOIL, &[SILVER, VIOLET, PEARL, GOLD, CYAN, PEARL]),
|
||||
("Aurora Foil", Linear, FOIL, &[BLUE, MINT, PEARL, BLUSH, CYAN, SILVER]),
|
||||
("Iris Sheen", Linear, FOIL, &[BLUSH, VIOLET, PEARL, CYAN, MINT, SILVER]),
|
||||
("Frost Spectrum", Linear, FOIL, &[CYAN, BLUE, PEARL, MINT, BLUSH, SILVER]),
|
||||
("Silver Tide", Linear, FOIL, &[SILVER, CYAN, PEARL, VIOLET, BLUE, SILVER]),
|
||||
("Rose Quartz Gleam", Radial, GLOW, &[PEARL, BLUSH, CORAL, VIOLET, BLUSH]),
|
||||
("Moonstone Shift", Radial, GLOW, &[PEARL, CYAN, MINT, BLUE, SILVER]),
|
||||
("Violet Edge", Radial, GLOW, &[PEARL, VIOLET, BLUSH, BLUE, DEEP_VIOLET]),
|
||||
("Mint Halo", Radial, GLOW, &[PEARL, MINT, CYAN, LIME, MINT]),
|
||||
("Amber Corona", Radial, GLOW, &[PEARL, GOLD, AMBER, CORAL, AMBER]),
|
||||
("Polar Glint", Radial, GLOW, &[PEARL, CYAN, BLUE, VIOLET, BLUE]),
|
||||
("Pastel Orbit", Radial, GLOW, &[PEARL, BLUSH, MINT, CYAN, VIOLET]),
|
||||
];
|
||||
let s = looks
|
||||
.iter()
|
||||
.map(|&(name, kind, bands, colors)| {
|
||||
let stops: Vec<(f32, Color, f32, f32)> =
|
||||
bands.iter().zip(colors).map(|(&(at, opacity, mid), &(l, c, h))| (at, oklch(l, c, h), opacity, mid)).collect();
|
||||
gradient_with(name, kind, GradientMethod::Perceptual, &stops)
|
||||
})
|
||||
.collect();
|
||||
(s, vec![])
|
||||
}
|
||||
|
||||
/// The sequential scales of [`perceptual`]: name and anchors of rising lightness.
|
||||
const SEQUENTIAL: [(&str, Anchors); 5] = [
|
||||
("Ember", &[(0.22, 0.10, 300.0), (0.55, 0.18, 30.0), (0.93, 0.15, 100.0)]),
|
||||
@@ -708,9 +765,63 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holographic_holds_seven_opaque_foils_and_seven_glows_to_a_clear_edge() {
|
||||
let lib = builtin_library("holographic").unwrap();
|
||||
let order: Vec<&str> = GRADIENT_LIBRARIES.iter().map(|b| b.name).collect();
|
||||
assert_eq!(order.iter().position(|n| *n == "Holographic"), Some(4), "after Organic Fades: {order:?}");
|
||||
assert!(lib.groups.is_empty());
|
||||
assert_eq!(lib.len(), 14);
|
||||
// No name another built-in gradient has, in any case.
|
||||
let mut others = std::collections::HashSet::new();
|
||||
for other in builtins().filter(|b| b.id != "holographic").map(|b| builtin_library(b.id).unwrap()) {
|
||||
others.extend(other.iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| s.name.to_lowercase()));
|
||||
}
|
||||
assert!(lib.iter().all(|s| !others.contains(&s.name.to_lowercase())), "a name another library has");
|
||||
let (mut foils, mut glows) = (0, 0);
|
||||
for s in lib.iter() {
|
||||
let Paint::Gradient(g) = &s.paint else { panic!("{} is a gradient", s.name) };
|
||||
let (g, n) = (&g.gradient, &s.name);
|
||||
assert_eq!(g.method, GradientMethod::Perceptual, "{n}");
|
||||
let bands = match &g.kind {
|
||||
GradientKind::Linear => {
|
||||
foils += 1;
|
||||
FOIL
|
||||
}
|
||||
GradientKind::Radial => {
|
||||
glows += 1;
|
||||
GLOW
|
||||
}
|
||||
kind => panic!("{n}: {kind:?}"),
|
||||
};
|
||||
// Every stop takes its band's offset, opacity and midpoint, and none is dropped.
|
||||
let shape: Vec<(f32, f32, f32)> = g.stops.iter().map(|st| (st.offset, st.opacity, st.midpoint)).collect();
|
||||
assert_eq!(shape, bands, "{n}");
|
||||
assert!(g.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{n}");
|
||||
}
|
||||
assert_eq!((foils, glows), (7, 7));
|
||||
// Foils are opaque; a glow is clear at the edge.
|
||||
assert!(FOIL.iter().all(|&(_, opacity, _)| opacity == 1.0));
|
||||
assert_eq!(GLOW.last().map(|b| b.1), Some(0.0));
|
||||
// Every segment's midpoint is off center and within the Gradient panel's 13 to 87%.
|
||||
for bands in [FOIL, GLOW] {
|
||||
assert!(bands[..bands.len() - 1].iter().all(|&(_, _, m)| (m - 0.5).abs() > 0.02 && (0.13..=0.87).contains(&m)));
|
||||
assert!(bands.windows(2).all(|w| w[0].0 < w[1].0) && bands[0].0 == 0.0 && bands[bands.len() - 1].0 == 1.0);
|
||||
}
|
||||
// Sampled colors: Prism Veil's bright band is the pearl anchor, and Violet Edge ends in deep violet.
|
||||
let stop = |name: &str, i: usize| match &lib.swatch(name).unwrap().paint {
|
||||
Paint::Gradient(g) => g.gradient.stops[i].color,
|
||||
_ => panic!("{name} is a gradient"),
|
||||
};
|
||||
assert_eq!(stop("Prism Veil", 2), oklch(0.97, 0.01, 90.0));
|
||||
assert_eq!(stop("Violet Edge", 4), oklch(0.42, 0.04, 275.0));
|
||||
let [l, ..] = to_oklab(&stop("Violet Edge", 4));
|
||||
assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() {
|
||||
for b in builtins().filter(|b| b.id != "organic-fades") {
|
||||
for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) {
|
||||
for s in builtin_library(b.id).unwrap().iter() {
|
||||
if let Paint::Gradient(g) = &s.paint {
|
||||
assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name);
|
||||
|
||||
@@ -196,8 +196,10 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
};
|
||||
// Stops that repeat or reflect run that many times across the box.
|
||||
let unrolled = g.gradient.unrolled();
|
||||
let stops: Vec<String> =
|
||||
if mirrored { g.gradient.stops.iter().rev().map(stop).collect() } else { g.gradient.stops.iter().map(stop).collect() };
|
||||
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
|
||||
@@ -261,6 +261,29 @@ fn css_preserves_fractional_gradient_stop_positions() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient swatch that repeats or reflects has its stops written that many times across the
|
||||
/// box, every other run backwards for Reflect.
|
||||
#[test]
|
||||
fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
|
||||
for (spread, want) in [
|
||||
(crate::GradientSpread::Repeat, "#ffffff 0%, #000000 50%, #ffffff 50%, #000000 100%"),
|
||||
(crate::GradientSpread::Reflect, "#ffffff 0%, #000000 50%, #000000 50%, #ffffff 100%"),
|
||||
] {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch {
|
||||
name: "Bands".into(),
|
||||
paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::default() }))),
|
||||
global: false,
|
||||
spot: false,
|
||||
}],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert!(text.contains(&format!("--bands: linear-gradient(90deg, {want});")), "{spread:?}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
|
||||
+91
-8
@@ -152,6 +152,11 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<Gradien
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// Two gradients that repeat (or reflect) step their count from one to the other; a spread
|
||||
// that differs switches halfway, as the method does.
|
||||
if a.gradient.is_spread() && a.gradient.spread == b.gradient.spread {
|
||||
out.gradient.repeats = lerp_f32(a.gradient.repeat_count() as f32, b.gradient.repeat_count() as f32, t).round() as u32;
|
||||
}
|
||||
out.angle = a.angle + (b.angle - a.angle) * t as f64;
|
||||
out.swatch = None;
|
||||
if let (Some(ga), Some(gb)) = (a.geom, b.geom) {
|
||||
@@ -1051,7 +1056,8 @@ fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option<Vec<usize>> {
|
||||
/// - a pinned spine (`key_anchors`): the stored spine's first subpath with each key's anchor (and
|
||||
/// its handles) moved onto the key's centre, so moving a key moves its end of the spine;
|
||||
/// - a spine from Replace Spine: its first subpath, `None` for the anchors (the keys spread
|
||||
/// evenly along it by arc length).
|
||||
/// evenly along it by arc length) while the keys sit there; once one is moved off, pinned as
|
||||
/// above at the anchors where they were spread.
|
||||
///
|
||||
/// `None` for a blend made without a spine ([`BlendSpec::no_spine`]).
|
||||
pub fn blend_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Option<Vec<usize>>)> {
|
||||
@@ -1077,7 +1083,24 @@ fn layout_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Optio
|
||||
return Some((PathData::single(SubPath::polyline(¢ers, false)), Some((0..keys.len()).collect())));
|
||||
};
|
||||
let mut first = stored.subpaths.first()?.clone();
|
||||
let Some(ka) = pinned(spec, keys.len(), first.anchors.len()) else { return Some((PathData::single(first), None)) };
|
||||
let Some(ka) = pinned(spec, keys.len(), first.anchors.len()) else {
|
||||
let mut path = PathData::single(first);
|
||||
// A key moved off where Replace Spine spread it takes its point of the spine along, as
|
||||
// on a pinned spine; otherwise the steps would put it back on the spine (#6809).
|
||||
if Spine::new(&path).is_none_or(|sp| keys_spread_along(keys, &sp)) {
|
||||
return Some((path, None));
|
||||
}
|
||||
let Some(mut ka) = spread_anchors(&mut path, keys.len()) else { return Some((path, None)) };
|
||||
let mut first = path.subpaths.into_iter().next()?;
|
||||
open_at_start(&mut first, &mut ka);
|
||||
for (k, &ai) in keys.iter().zip(&ka) {
|
||||
if let Some(a) = first.anchors.get_mut(ai) {
|
||||
let d = center_of(k) - a.p;
|
||||
a.translate(d);
|
||||
}
|
||||
}
|
||||
return Some((PathData::single(first), Some(ka)));
|
||||
};
|
||||
for (k, &ai) in keys.iter().zip(&ka) {
|
||||
let c = center_of(k);
|
||||
if let Some(a) = first.anchors.get_mut(ai) {
|
||||
@@ -1091,21 +1114,62 @@ fn layout_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Optio
|
||||
/// [`blend_spine`] with every key on an anchor: a spine from Replace Spine gets anchors where its
|
||||
/// keys sit (by arc length), so editing it keeps them in place.
|
||||
pub fn pin_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Vec<usize>)> {
|
||||
let (mut path, anchors) = blend_spine(keys, spec)?;
|
||||
if let Some(a) = anchors {
|
||||
return Some((path, a));
|
||||
// A spine from Replace Spine is pinned as stored, even with a key moved off it (where
|
||||
// [`blend_spine`] moves that key's point along): the layout is the same.
|
||||
if keys.len() >= 2
|
||||
&& let Some(first) = stored_spine(spec).and_then(|s| s.subpaths.first())
|
||||
&& pinned(spec, keys.len(), first.anchors.len()).is_none()
|
||||
{
|
||||
let mut path = PathData::single(first.clone());
|
||||
let mut out = spread_anchors(&mut path, keys.len())?;
|
||||
// A closed spine's end keys get points of their own, so that once pinned each still
|
||||
// moves only its own end.
|
||||
let mut sp = path.subpaths.into_iter().next()?;
|
||||
open_at_start(&mut sp, &mut out);
|
||||
return Some((PathData::single(sp), out));
|
||||
}
|
||||
let (path, anchors) = blend_spine(keys, spec)?;
|
||||
Some((path, anchors?))
|
||||
}
|
||||
|
||||
/// Do `keys` sit where a spine from Replace Spine spreads them: evenly along `spine` by arc length
|
||||
/// (within a hundredth of a point, as [`anchor_at_length`] matches anchors)?
|
||||
fn keys_spread_along(keys: &[Arc<Node>], spine: &Spine) -> bool {
|
||||
let k = keys.len();
|
||||
let total = Spine::new(&path)?.length();
|
||||
keys.iter().enumerate().all(|(i, key)| {
|
||||
let f = if k > 1 { i as f64 / (k - 1) as f64 } else { 0.0 };
|
||||
center_of(key).distance(spine.at(f).0) < 0.01
|
||||
})
|
||||
}
|
||||
|
||||
/// Open closed spine `sp` at its first anchor when the last key sits there with the first (as
|
||||
/// [`spread_anchors`] puts them): a copy of that anchor at the end takes the closing segment and
|
||||
/// the last key, so the two end keys move their ends of the spine apart.
|
||||
fn open_at_start(sp: &mut SubPath, ka: &mut [usize]) {
|
||||
let Some(&start) = sp.anchors.first() else { return };
|
||||
if !sp.closed || ka.len() < 2 {
|
||||
return;
|
||||
}
|
||||
if let Some(last) = ka.last_mut().filter(|a| **a == 0) {
|
||||
*last = sp.anchors.len();
|
||||
sp.anchors.push(start);
|
||||
sp.closed = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors of `path`'s first subpath that `k` keys spread evenly along it by arc length sit
|
||||
/// on, splitting segments where none is.
|
||||
fn spread_anchors(path: &mut PathData, k: usize) -> Option<Vec<usize>> {
|
||||
let total = Spine::new(path)?.length();
|
||||
let closed = path.subpaths.first().is_some_and(|s| s.closed);
|
||||
let mut out = vec![0usize];
|
||||
for i in 1..k.saturating_sub(1) {
|
||||
let s = total * i as f64 / (k - 1) as f64;
|
||||
out.push(anchor_at_length(&mut path, s)?);
|
||||
out.push(anchor_at_length(path, s)?);
|
||||
}
|
||||
let last = path.subpaths.first().map_or(0, |sp| if closed { 0 } else { sp.anchors.len().saturating_sub(1) });
|
||||
out.push(last);
|
||||
Some((path, out))
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The anchor of the first subpath at arc length `s`: an existing one within a hundredth of a
|
||||
@@ -1597,6 +1661,25 @@ mod tests {
|
||||
assert!(pair.at(0.5).bounds().unwrap().height() < 1e-6, "the clicked anchors pair up");
|
||||
}
|
||||
|
||||
/// A blend between two gradients that repeat steps the count; one between a gradient that
|
||||
/// pads and one that repeats switches halfway, as the method does.
|
||||
#[test]
|
||||
fn blend_between_repeating_gradients_steps_the_count() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let spread = |spread, repeats| Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats, ..Gradient::default() })));
|
||||
let at = |a: &Paint, b: &Paint, t: f32| match lerp_paint(a, b, t) {
|
||||
Paint::Gradient(g) => (g.gradient.spread, g.gradient.repeat_count()),
|
||||
p => panic!("a gradient, not {p:?}"),
|
||||
};
|
||||
let (two, twenty) = (spread(GradientSpread::Repeat, 2), spread(GradientSpread::Repeat, 20));
|
||||
assert_eq!(at(&two, &twenty, 0.25), (GradientSpread::Repeat, 7));
|
||||
assert_eq!(at(&two, &twenty, 0.5), (GradientSpread::Repeat, 11));
|
||||
assert_eq!(at(&two, &twenty, 1.0), (GradientSpread::Repeat, 20));
|
||||
let pad = spread(GradientSpread::Pad, 1);
|
||||
assert_eq!(at(&pad, &twenty, 0.25), (GradientSpread::Pad, 1));
|
||||
assert_eq!(at(&pad, &twenty, 0.75), (GradientSpread::Repeat, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_between_tints_of_one_swatch_keeps_the_link() {
|
||||
let tinted = |tint: f32| Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint), swatch: Some("Spot".into()), tint };
|
||||
|
||||
+26
-4
@@ -133,6 +133,13 @@ pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Deco
|
||||
Some((d.colortype().ok()?, d))
|
||||
}
|
||||
|
||||
/// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images
|
||||
/// and TIFFs without one. Reads only its header.
|
||||
pub fn tiff_orientation(bytes: &[u8]) -> Option<u16> {
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::Orientation).ok().flatten()
|
||||
}
|
||||
|
||||
/// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)?
|
||||
fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1)
|
||||
@@ -309,10 +316,10 @@ fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
Inks::new(w, h, read_samples(&mut d, n, 4)?)
|
||||
}
|
||||
|
||||
/// CMYK TIFF `bytes` as Open and Place store them: as they are, or, when they store one plane per
|
||||
/// ink, which the image decoder doesn't read, their ink amounts written again by
|
||||
/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi`. `None` for other images and for CMYK
|
||||
/// TIFFs whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
/// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and
|
||||
/// Place store them: as they are, or, when they store one plane per ink, which the image decoder
|
||||
/// doesn't read, their ink amounts written again by [`ImageBlob::cmyk_tiff_at`] with the resolution
|
||||
/// `ppi`. `None` for other images and for CMYK TIFFs whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>> {
|
||||
let inks = tiff_inks(bytes)?;
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
@@ -322,6 +329,21 @@ pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>
|
||||
ImageBlob::cmyk_tiff_at(&inks, ppi).map(|b| Arc::unwrap_or_clone(b.bytes))
|
||||
}
|
||||
|
||||
/// CMYK JPEG or TIFF `bytes` that `orientation` turns or flips, as Open and Place store them: their
|
||||
/// ink amounts ([`ImageBlob::cmyk`], 8 bits each) turned and written again by
|
||||
/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi` of the turned pixels, with the turned
|
||||
/// width and height. `None` for other images and for CMYK images whose inks [`ImageBlob::cmyk`]
|
||||
/// doesn't read.
|
||||
pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec<u8>, (u32, u32))> {
|
||||
let inks = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_inks(bytes) } else { tiff_inks(bytes) }?;
|
||||
// Four 8-bit inks to a pixel, turned as four 8-bit channels are.
|
||||
let mut px = image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(inks.width, inks.height, inks.data)?);
|
||||
px.apply_orientation(orientation);
|
||||
let inks = Inks::new(px.width(), px.height(), px.into_bytes())?;
|
||||
let tiff = ImageBlob::cmyk_tiff_at(&inks, ppi)?;
|
||||
Some((Arc::unwrap_or_clone(tiff.bytes), (inks.width, inks.height)))
|
||||
}
|
||||
|
||||
/// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at
|
||||
/// all, as RGBA pixels: CMYK with an alpha channel (5 samples), each colour converted by `rgb` (ink
|
||||
/// amounts 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB),
|
||||
|
||||
@@ -450,7 +450,7 @@ fn a_marquee_meets_blends_and_envelopes_by_their_box() {
|
||||
envelope,
|
||||
NodeKind::Envelope {
|
||||
content,
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }),
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }),
|
||||
fidelity: 100.0,
|
||||
editing: false,
|
||||
options: Default::default(),
|
||||
@@ -1192,7 +1192,7 @@ fn objects_at_edit_contents_uses_general_order() {
|
||||
d.alloc_id(),
|
||||
NodeKind::Envelope {
|
||||
content: vec![inner(a), inner(b)],
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }),
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }),
|
||||
fidelity: 100.0,
|
||||
editing: true,
|
||||
options: Default::default(),
|
||||
|
||||
@@ -267,7 +267,7 @@ pub struct Document {
|
||||
/// they were copied from instead of the current layer.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub paste_remembers_layers: bool,
|
||||
/// File → File Info (the title is [`Document::title`]).
|
||||
/// File → File Info (its title is [`Document::info_title`]).
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub metadata: DocMetadata,
|
||||
/// Effect → Document Raster Effects Settings besides the resolution
|
||||
|
||||
+197
-3
@@ -60,12 +60,12 @@ pub use envelope::{
|
||||
pub(crate) use expand::max_outset;
|
||||
pub use expand::{
|
||||
Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with,
|
||||
expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, subtree_has_live,
|
||||
expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use mesh::grid_eval;
|
||||
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
|
||||
pub use warp::{WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, warp_point};
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -132,6 +132,200 @@ mod tests {
|
||||
let (r0, a) = (4.0 / PI, 0.5 / (4.0 / PI));
|
||||
assert!((nx - (r0 - 0.25) * a.sin()).abs() < 1e-12 && (ny - (r0 - (r0 - 0.25) * a.cos())).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// Each warp style's Bézier net, at points worked out by a separate implementation of the same
|
||||
/// nets: (style, bend %, horizontal and vertical distortion %, vertical, box w × h, (u, v)) →
|
||||
/// the point in the box (origin at its top left, y down).
|
||||
#[test]
|
||||
fn warp_nets_bend_each_style_as_its_own_patch() {
|
||||
#[rustfmt::skip]
|
||||
let samples = [
|
||||
("arc", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -31.1605665, 30.1243045),
|
||||
("arc", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 170.241998, 58.8743443),
|
||||
("arc", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 50.6087118, 47.6275948),
|
||||
("arcLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 18.8784581, 35.5028749),
|
||||
("arcLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.486168, 119.348666),
|
||||
("arcLower", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 38.1073767, 36.0911629),
|
||||
("arcUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 17.3830689, 17.1599587),
|
||||
("arcUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.498463, 86.7390371),
|
||||
("arcUpper", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 46.1081993, 36.0252855),
|
||||
("arch", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 16.261527, 11.6570838),
|
||||
("arch", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.984631, 57.3903712),
|
||||
("arch", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 49.2508226, 36.2064484),
|
||||
("bulge", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 16.261527, 22.6628335),
|
||||
("bulge", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.984631, 116.087703),
|
||||
("bulge", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.965576, 36.2064484),
|
||||
("shellLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 10.6489723, 25.9914004),
|
||||
("shellLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 208.565464, 99.4817585),
|
||||
("shellLower", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 41.043987, 36.1302767),
|
||||
("shellUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -21.8346746, 41.6042708),
|
||||
("shellUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.791499, 90.3680631),
|
||||
("shellUpper", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.9282896, 36.1475509),
|
||||
("flag", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 55.92),
|
||||
("flag", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 55.44),
|
||||
("flag", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 58.098, 35.91),
|
||||
("wave", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 40.8864),
|
||||
("wave", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 83.7792),
|
||||
("wave", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.33, 35.91),
|
||||
("fish", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 19.632),
|
||||
("fish", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 62.352),
|
||||
("fish", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 44.994, 35.91),
|
||||
("rise", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 146.64),
|
||||
("rise", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 102.48),
|
||||
("rise", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 118.686, 35.91),
|
||||
("fisheye", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 9.1136, 27.2784),
|
||||
("fisheye", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 166.2208, 94.1472),
|
||||
("fisheye", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 47.514, 35.7048),
|
||||
("inflate", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -0.16, 27.84),
|
||||
("inflate", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 166.48, 97.68),
|
||||
("inflate", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.75, 36.54),
|
||||
("squeeze", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 40.16, 27.84),
|
||||
("squeeze", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 153.52, 97.68),
|
||||
("squeeze", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.75, 36.0),
|
||||
("twist", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 32.2472, 27.9588),
|
||||
("twist", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 149.1136, 89.2224),
|
||||
("twist", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.56325, 33.8769),
|
||||
];
|
||||
for (style, bend, dh, dv, vertical, w, h, u, v, x, y) in samples {
|
||||
let Some(st) = WarpStyle::from_id(style) else { panic!("{style}") };
|
||||
let p = WarpNet::new(st, bend / 100.0, dh / 100.0, dv / 100.0, w, h, vertical).at(u, v);
|
||||
assert!(p.distance(Point::new(x, y)) < 1e-6, "{style} {bend} {dh} {dv} {vertical} ({u}, {v}): {p:?} vs ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Arc's edges are concentric circles: at 100 % on a 200 × 100 box the bottom edge is the half
|
||||
/// circle through the bottom corners about the bottom's middle, and the top edge the one 100
|
||||
/// further out. One cubic for a half circle strays up to 1.84 % of the radius from the circle.
|
||||
#[test]
|
||||
fn warp_net_arc_edges_are_concentric_circles() {
|
||||
let net = WarpNet::new(WarpStyle::Arc, 1.0, 0.0, 0.0, 200.0, 100.0, false);
|
||||
let center = Point::new(100.0, 100.0);
|
||||
for i in 0..=20 {
|
||||
let u = f64::from(i) / 20.0;
|
||||
for (v, r) in [(0.0, 200.0), (1.0, 100.0)] {
|
||||
let d = net.at(u, v).distance(center);
|
||||
assert!((d - r).abs() < 0.0184 * r, "u {u}, v {v}: {d} from the center, not {r}");
|
||||
// Its ends and middle lie on the circle.
|
||||
if i % 10 == 0 {
|
||||
assert!((d - r).abs() < 1e-9, "u {u}, v {v}: {d} from the center, not {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Bend 0 leaves the box as it is.
|
||||
for st in [WarpStyle::Arc, WarpStyle::ShellLower, WarpStyle::Bulge, WarpStyle::Twist] {
|
||||
let flat = WarpNet::new(st, 0.0, 0.0, 0.0, 200.0, 100.0, false);
|
||||
assert!(flat.at(0.3, 0.7).distance(Point::new(60.0, 70.0)) < 1e-9, "{st:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The horizontal distortion scales each column of the net about its middle (narrowing the left
|
||||
/// side for a positive value), then the vertical one each row (narrowing the top).
|
||||
#[test]
|
||||
fn warp_net_distortion_scales_the_columns_then_the_rows() {
|
||||
let corners = |dh: f64, dv: f64| {
|
||||
let net = WarpNet::new(WarpStyle::Arc, 0.0, dh, dv, 200.0, 100.0, false);
|
||||
[net.at(0.0, 0.0), net.at(1.0, 0.0), net.at(0.0, 1.0), net.at(1.0, 1.0)]
|
||||
};
|
||||
let near = |got: [Point; 4], want: [(f64, f64); 4]| got.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-9);
|
||||
assert!(near(corners(0.5, 0.0), [(0.0, 25.0), (200.0, -25.0), (0.0, 75.0), (200.0, 125.0)]), "{:?}", corners(0.5, 0.0));
|
||||
assert!(near(corners(0.0, 0.5), [(50.0, 0.0), (150.0, 0.0), (-50.0, 100.0), (250.0, 100.0)]), "{:?}", corners(0.0, 0.5));
|
||||
// Both coordinates scale: after the columns the top row runs from (0, 15) to (200, -15), and
|
||||
// it then scales by 1.4 about its middle, (100, 0).
|
||||
assert!(near(corners(0.3, -0.4), [(-40.0, 21.0), (240.0, -21.0), (40.0, 91.0), (160.0, 109.0)]), "{:?}", corners(0.3, -0.4));
|
||||
}
|
||||
|
||||
/// Numbers no warp can take still give a finite net: a bend or distortion that isn't a number
|
||||
/// counts as 0, and out of range as its limit; a size that isn't a number as 0.
|
||||
#[test]
|
||||
fn warp_net_takes_any_numbers() {
|
||||
for st in [WarpStyle::Arc, WarpStyle::ShellUpper, WarpStyle::Wave, WarpStyle::Inflate, WarpStyle::Twist] {
|
||||
for (b, dh, w, h) in
|
||||
[(f64::NAN, 0.2, 10.0, 10.0), (5.0, f64::INFINITY, 10.0, 0.0), (-1e300, -3.0, f64::NAN, 1e-300), (1e-300, 0.0, 0.0, 0.0)]
|
||||
{
|
||||
for vertical in [false, true] {
|
||||
let p = WarpNet::new(st, b, dh, dh, w, h, vertical).at(0.3, 0.6);
|
||||
assert!(p.x.is_finite() && p.y.is_finite(), "{st:?} {b} {dh} {w} {h}: {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let clamped = WarpNet::new(WarpStyle::Flag, 7.0, 0.0, 0.0, 200.0, 100.0, false);
|
||||
assert_eq!(clamped, WarpNet::new(WarpStyle::Flag, 1.0, 0.0, 0.0, 200.0, 100.0, false));
|
||||
}
|
||||
|
||||
/// A box near the largest finite size still warps: Flag on a 1e308 × 100 box moves points only
|
||||
/// up and down, as on a 1 × 1e-306 one scaled up, and on a 1e308 × 1e-300 box keeps the box's
|
||||
/// height. Fisheye at 100 % on a 1.7e308 square, whose net goes past the largest finite number,
|
||||
/// gives finite points inside the box and past it, and the unit square's points scaled up where
|
||||
/// those are finite. Fisheye moves y by the height alone, so on boxes of the largest finite
|
||||
/// width and a height of 1e-300 or 100 every y is the unit square's times the height, also
|
||||
/// where x goes past the largest finite number.
|
||||
#[test]
|
||||
fn warp_net_bends_a_huge_box_without_overflowing() {
|
||||
let w = 1e308;
|
||||
let flag = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, w, 100.0, false);
|
||||
let small = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, 1.0, 100.0 / w, false);
|
||||
for (u, v) in [(0.0, 0.0), (0.3, 0.6), (0.9, 1.0), (1.0, 0.5)] {
|
||||
let (p, q) = (flag.at(u, v), small.at(u, v));
|
||||
assert!(p.is_finite(), "({u}, {v}): {p:?}");
|
||||
assert!((p.x - u * w).abs() <= 1e-12 * w, "({u}, {v}): {p:?}");
|
||||
assert!((p.y - q.y * w).abs() <= 1e-9 * p.y.abs().max(1.0), "({u}, {v}): {p:?} against {q:?}");
|
||||
}
|
||||
let thin = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, w, 1e-300, false);
|
||||
assert_eq!(thin.at(0.0, 1.0), Point::new(0.0, 1e-300));
|
||||
let fisheye = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, 1.7e308, 1.7e308, false);
|
||||
for (u, v) in [(0.1, 0.1), (0.8, 0.3), (1.5, 0.5), (3.0, 3.0)] {
|
||||
let p = fisheye.at(u, v);
|
||||
assert!(p.is_finite(), "({u}, {v}): {p:?}");
|
||||
}
|
||||
let unit = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, 1.0, 1.0, false);
|
||||
let near = |a: f64, b: f64| (a - b).abs() <= 1e-12 * b.abs().max(f64::MIN_POSITIVE);
|
||||
let (p, q) = (fisheye.at(0.1, 0.1), unit.at(0.1, 0.1));
|
||||
assert!(near(p.x, q.x * 1.7e308) && near(p.y, q.y * 1.7e308), "{p:?} against {q:?}");
|
||||
// The bottom of a box with a subnormal height stays exactly at that height: the net is
|
||||
// built on the box halved, and the height's lowest bit but one is set.
|
||||
let low = f64::MIN_POSITIVE / 4.0 + f64::from_bits(2);
|
||||
let sub = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, f64::MAX, low, false).at(0.0, 1.0);
|
||||
assert_eq!(sub.y, low, "{sub:?}");
|
||||
for h in [1e-300, 100.0] {
|
||||
let tall = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, f64::MAX, h, false);
|
||||
for (u, v) in [(0.1, 0.1), (0.9, 0.4), (0.5, 0.8)] {
|
||||
let (p, q) = (tall.at(u, v), unit.at(u, v));
|
||||
assert!(p.is_finite() && near(p.y, q.y * h), "h {h}, ({u}, {v}): {p:?} against {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Content with no width or no height takes the middle of a warp envelope's patch along that
|
||||
/// side: under Arc a vertical line stays vertical, under Bulge a horizontal line stays straight.
|
||||
#[test]
|
||||
fn warp_envelopes_bend_flat_content_as_the_middle_of_the_patch() {
|
||||
let warp = |style: &str| EnvelopeKind::Warp { style: style.into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET };
|
||||
let arc = warp("arc");
|
||||
let map = envelope_mapper(&arc, Rect::new(100.0, 0.0, 100.0, 100.0));
|
||||
for y in [0.0, 30.0, 100.0] {
|
||||
let p = map(Point::new(100.0, y));
|
||||
assert!((p.x - 100.0).abs() <= 1e-9, "{y}: {p:?}");
|
||||
}
|
||||
let bulge = warp("bulge");
|
||||
let map = envelope_mapper(&bulge, Rect::new(0.0, 50.0, 200.0, 50.0));
|
||||
for x in [0.0, 70.0, 200.0] {
|
||||
let p = map(Point::new(x, 50.0));
|
||||
assert!((p.y - 50.0).abs() <= 1e-9, "{x}: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A warp envelope's map version: none in a file reads as 0 (the earlier map), 0 is written
|
||||
/// as none, so files keep their bytes, and the nets' version is written.
|
||||
#[test]
|
||||
fn warp_envelopes_write_their_map_version_only_when_it_has_one() {
|
||||
let old: EnvelopeKind = serde_json::from_str(r#"{"type":"warp","style":"arc","bend":20}"#).unwrap();
|
||||
assert!(matches!(old, EnvelopeKind::Warp { version: 0, .. }), "{old:?}");
|
||||
assert!(!serde_json::to_string(&old).unwrap().contains("version"));
|
||||
let new = EnvelopeKind::Warp { style: "arc".into(), bend: 20.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET };
|
||||
let text = serde_json::to_string(&new).unwrap();
|
||||
assert!(text.contains(r#""version":1"#), "{text}");
|
||||
assert_eq!(serde_json::from_str::<EnvelopeKind>(&text).unwrap(), new);
|
||||
}
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
fn rect_node(x: f64, y: f64, w: f64, h: f64, c: Color) -> Arc<Node> {
|
||||
@@ -537,7 +731,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_envelope_maps_from_its_box_with_its_margins() {
|
||||
let rect = Node::path(NodeId(2), vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)), crate::Appearance::default_art());
|
||||
let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true };
|
||||
let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 };
|
||||
let content = [Arc::new(rect)];
|
||||
let src = |content: &[Arc<Node>], frame: Affine, options: EnvelopeOptions| EnvelopeMap::new(content, &kind, frame, options).unwrap().src();
|
||||
// Top, bottom, left and right.
|
||||
|
||||
@@ -3,6 +3,10 @@ use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, surface_of};
|
||||
use super::{Affine, Arc, Color, Deserialize, Node, NodeId, NodeKind, PathData, Point, Rect, Serialize, Vec2, yes};
|
||||
use vectorcraft_geom::Homography;
|
||||
|
||||
fn is_zero(n: &u32) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// How an envelope distorts its content.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
@@ -19,6 +23,10 @@ pub enum EnvelopeKind {
|
||||
v: f64,
|
||||
#[serde(default = "yes")]
|
||||
horizontal: bool,
|
||||
/// The map the warp draws with: [`WARP_NET`](super::WARP_NET) for its style's Bézier net,
|
||||
/// 0 (as in files from before the version existed) for [`warp_point`](super::warp_point).
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
version: u32,
|
||||
},
|
||||
/// A `(rows+1)×(cols+1)` grid of points (row-major) the content's bounding box maps onto.
|
||||
Mesh {
|
||||
|
||||
@@ -119,7 +119,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
|
||||
{
|
||||
out.appearance.warp_linear_gradients(b, &|p| affine_near(w.f, p, w.eps));
|
||||
}
|
||||
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
// A linked opacity mask bends with the object it masks; an unlinked one stays where it is.
|
||||
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) {
|
||||
m.art = Arc::new(map_node(&m.art, w));
|
||||
}
|
||||
match &mut out.kind {
|
||||
@@ -178,29 +179,46 @@ fn affine_between(s: [Point; 3], d: [Point; 3]) -> Option<Affine> {
|
||||
a.is_finite().then_some(a)
|
||||
}
|
||||
|
||||
/// Image `n` (`im`) pushed through the warp as a raster mesh warp: its frame cut into
|
||||
/// `w.cells`² cells of two triangles, each a clip group showing the image under the affine map
|
||||
/// that takes the triangle where the warp takes its corners (with Preserve Shape Using
|
||||
/// Transparency, the image masked by the triangle; with Anti-Alias off, drawn without smoothing).
|
||||
/// Each piece reaches a little past its edges (at most half a point) so neighbours overlap and no
|
||||
/// seams show.
|
||||
/// Image `n` (`im`) pushed through the envelope's warp as a raster mesh warp ([`mesh_warp_image`]
|
||||
/// with `w.cells` cells, Preserve Shape Using Transparency and Anti-Alias as the envelope's
|
||||
/// options say).
|
||||
fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node {
|
||||
let k = w.cells.max(1);
|
||||
// Two triangles a cell, three objects each; an image an inner envelope already cut into
|
||||
// pieces is cut again here, so the pieces count against [`MAX_GENERATED`]. Past it, the image
|
||||
// is left out.
|
||||
if !Generating::charge(k.saturating_mul(k).saturating_mul(6)) {
|
||||
// An image an inner envelope already cut into pieces is cut again here, so the pieces count
|
||||
// against [`MAX_GENERATED`]. Past it, the image is left out.
|
||||
if !Generating::charge(mesh_warp_cost(k)) {
|
||||
let mut g = n.clone();
|
||||
g.kind = NodeKind::Group { children: vec![], clip: false };
|
||||
return g;
|
||||
}
|
||||
mesh_warp_image(n, im, w.f, k, !w.options.anti_alias, w.options.preserve_shape == PreserveShape::Transparency)
|
||||
}
|
||||
|
||||
/// How many objects [`mesh_warp_image`] makes of one image with `cells` rows and columns: two
|
||||
/// triangles a cell, three objects each.
|
||||
pub fn mesh_warp_cost(cells: usize) -> usize {
|
||||
let k = cells.max(1);
|
||||
k.saturating_mul(k).saturating_mul(6)
|
||||
}
|
||||
|
||||
/// Image `n` (`im`) pushed through point map `f` as a raster mesh warp: its frame cut into
|
||||
/// `cells`² cells of two triangles, each a clip group showing the image under the affine map
|
||||
/// that takes the triangle where `f` takes its corners (with `masked`, the image masked by the
|
||||
/// triangle instead; with `pixelated`, drawn without smoothing). Each piece reaches a little past
|
||||
/// its edges (at most half a point) so neighbors overlap and no seams show. Each piece keeps the
|
||||
/// color `n` colorizes a grayscale image with. The result is a group with `n`'s id, name,
|
||||
/// transparency, opacity mask and appearance.
|
||||
pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node {
|
||||
let k = cells.max(1);
|
||||
// A grayscale image's fill color colorizes each piece; the group of pieces takes none.
|
||||
let colorize = n.extras().colorize.clone();
|
||||
let (pw, ph) = (im.width as f64, im.height as f64);
|
||||
let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64);
|
||||
let mut pieces = Vec::with_capacity(2 * k * k);
|
||||
for j in 0..k {
|
||||
for i in 0..k {
|
||||
let s = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)];
|
||||
let d = s.map(|p| (w.f)(im.xf * p));
|
||||
let d = s.map(|p| f(im.xf * p));
|
||||
for t in [[0, 1, 2], [0, 2, 3]] {
|
||||
let (st, dt) = (t.map(|v| s[v]), t.map(|v| d[v]));
|
||||
let Some(xf) = affine_between(st, dt) else { continue };
|
||||
@@ -216,8 +234,9 @@ fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node {
|
||||
.collect();
|
||||
let shape = PathData::single(SubPath::polyline(&tri, true));
|
||||
let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
|
||||
image.extras_mut().pixelated = !w.options.anti_alias;
|
||||
if w.options.preserve_shape == PreserveShape::Transparency {
|
||||
image.extras_mut().pixelated = pixelated;
|
||||
image.extras_mut().colorize = colorize.clone();
|
||||
if masked {
|
||||
// Preserve Shape Using Transparency: the triangle is the piece's alpha (a
|
||||
// white opacity mask) instead of its clipping path.
|
||||
let white = Node::path(n.id, shape, Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0));
|
||||
@@ -234,6 +253,9 @@ fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node {
|
||||
}
|
||||
let mut g = n.clone();
|
||||
g.kind = NodeKind::Group { children: pieces, clip: false };
|
||||
if let Some(e) = g.extras_if_any() {
|
||||
e.colorize = None;
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::envelope::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP, envelope_grid, mesh_at};
|
||||
use super::warp::{WarpStyle, flatten_subpath, resample, warp_point};
|
||||
use super::warp::{WarpNet, WarpStyle, flatten_subpath, resample, uses_net, warp_point};
|
||||
use super::{
|
||||
Affine, Anchor, Arc, Color, CubicBez, Deserialize, Node, ParamCurve, PathData, Point, Rect, Serialize, Shape, SubPath, Vec2, fifty, lerp_color,
|
||||
one,
|
||||
@@ -1731,10 +1731,19 @@ pub(super) fn grid_eval(rows: usize, cols: usize, pts: &[Point], u: f64, v: f64)
|
||||
pub(super) fn surface_of<'a>(kind: &'a EnvelopeKind, src: Rect, frame: Affine) -> Box<dyn Fn(f64, f64) -> Point + 'a> {
|
||||
let flat = move |u: f64, v: f64| frame * Point::new(src.x0 + u * src.width(), src.y0 + v * src.height());
|
||||
match kind {
|
||||
EnvelopeKind::Warp { style, bend, h: dh, v: dv, horizontal } => {
|
||||
EnvelopeKind::Warp { style, bend, h: dh, v: dv, horizontal, version } => {
|
||||
let st = WarpStyle::from_id(style).unwrap_or(WarpStyle::Arc);
|
||||
let b = bend.clamp(-100.0, 100.0) / 100.0;
|
||||
let (dh, dv) = (dh.clamp(-100.0, 100.0) / 100.0, dv.clamp(-100.0, 100.0) / 100.0);
|
||||
if uses_net(*version) {
|
||||
let net = WarpNet::new(st, b, dh, dv, src.width(), src.height(), !*horizontal);
|
||||
// Content with no width or no height takes the middle of the patch along that side.
|
||||
let (flat_u, flat_v) = (src.width() <= 0.0, src.height() <= 0.0);
|
||||
return Box::new(move |u: f64, v: f64| {
|
||||
let (u, v) = (if flat_u { 0.5 } else { u }, if flat_v { 0.5 } else { v });
|
||||
frame * (src.origin() + net.at(u, v).to_vec2())
|
||||
});
|
||||
}
|
||||
let c = src.center();
|
||||
let (hw, hh) = (src.width() / 2.0, src.height() / 2.0);
|
||||
let horizontal = *horizontal;
|
||||
|
||||
@@ -109,6 +109,337 @@ pub fn warp_point(style: WarpStyle, b: f64, dh: f64, dv: f64, aspect: f64, x: f6
|
||||
(x2, y2)
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
// Warp nets: each style as one Bézier patch over its box
|
||||
// =====================================================================================
|
||||
|
||||
/// The `version` a Warp effect's params or a warp envelope carries for the [`WarpNet`] map. With
|
||||
/// none (or 0) a warp draws with [`warp_point`], as every warp did before, so saved documents keep
|
||||
/// their look; new and imported warps are given this one.
|
||||
pub const WARP_NET: u32 = 1;
|
||||
|
||||
/// Does a warp of map `version` draw with [`WarpNet`]? A version newer than this build knows draws
|
||||
/// with the newest map it has.
|
||||
pub fn uses_net(version: u32) -> bool {
|
||||
version >= WARP_NET
|
||||
}
|
||||
|
||||
/// The map version `v` names when it is one this build draws: a whole number from 0 to
|
||||
/// [`WARP_NET`], written as an integer or as a float (`1` or `1.0`).
|
||||
pub fn warp_version(v: &serde_json::Value) -> Option<u32> {
|
||||
let n = v.as_f64()?;
|
||||
(n.fract() == 0.0 && (0.0..=f64::from(WARP_NET)).contains(&n)).then_some(n as u32)
|
||||
}
|
||||
|
||||
/// A style's own control net: `rows` × `cols` points (2 to 4 each) of a Bézier patch, row by row
|
||||
/// from the top, in the box's coordinates (origin at its top left, y down).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Net {
|
||||
rows: usize,
|
||||
cols: usize,
|
||||
p: [[Point; 4]; 4],
|
||||
}
|
||||
|
||||
impl Net {
|
||||
/// The undistorted box `w` × `h` as a `rows` × `cols` net.
|
||||
fn flat(w: f64, h: f64, rows: usize, cols: usize) -> Self {
|
||||
let mut p = [[Point::ZERO; 4]; 4];
|
||||
for (r, row) in p.iter_mut().enumerate().take(rows) {
|
||||
for (c, q) in row.iter_mut().enumerate().take(cols) {
|
||||
*q = Point::new(w * (c as f64 / (cols - 1) as f64), h * (r as f64 / (rows - 1) as f64));
|
||||
}
|
||||
}
|
||||
Self { rows, cols, p }
|
||||
}
|
||||
|
||||
/// Upside down within a box `h` high: the rows in reverse order, each point mirrored.
|
||||
fn mirrored(self, h: f64) -> Self {
|
||||
let mut out = self;
|
||||
for (to, from) in out.p[..self.rows].iter_mut().zip(self.p[..self.rows].iter().rev()) {
|
||||
for (q, f) in to.iter_mut().zip(from).take(self.cols) {
|
||||
*q = Point::new(f.x, h - f.y);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows and columns exchanged, and x with y: a net made on the box turned on its side.
|
||||
fn transposed(self) -> Self {
|
||||
let mut out = Self { rows: self.cols, cols: self.rows, p: [[Point::ZERO; 4]; 4] };
|
||||
for (r, row) in self.p[..self.rows].iter().enumerate() {
|
||||
for (c, q) in row[..self.cols].iter().enumerate() {
|
||||
out.p[c][r] = Point::new(q.y, q.x);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Each column scaled about the midpoint of its end points by `1 + a (2t - 1)`, `t` running from
|
||||
/// 0 at the left column to 1 at the right: a horizontal distortion `a` (-1..1).
|
||||
fn distort_columns(&mut self, a: f64) {
|
||||
let (rows, cols) = (self.rows, self.cols);
|
||||
for c in 0..cols {
|
||||
let s = 1.0 + a * (2.0 * c as f64 / (cols - 1) as f64 - 1.0);
|
||||
let mid = half_way(self.p[0][c], self.p[rows - 1][c]);
|
||||
for row in &mut self.p[..rows] {
|
||||
row[c] = mid + (row[c] - mid) * s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each row scaled about the midpoint of its end points by `1 + a (2t - 1)`, `t` running from 0
|
||||
/// at the top row to 1 at the bottom: a vertical distortion `a` (-1..1).
|
||||
fn distort_rows(&mut self, a: f64) {
|
||||
let (rows, cols) = (self.rows, self.cols);
|
||||
for (r, row) in self.p[..rows].iter_mut().enumerate() {
|
||||
let s = 1.0 + a * (2.0 * r as f64 / (rows - 1) as f64 - 1.0);
|
||||
let mid = half_way(row[0], row[cols - 1]);
|
||||
for q in &mut row[..cols] {
|
||||
*q = mid + (*q - mid) * s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The same patch as a bicubic net (degree elevation, which leaves the surface as it is).
|
||||
fn bicubic(self) -> [[Point; 4]; 4] {
|
||||
let rows: Vec<[Point; 4]> = self.p[..self.rows].iter().map(|row| cubic_line(&row[..self.cols])).collect();
|
||||
let mut out = [[Point::ZERO; 4]; 4];
|
||||
for c in 0..4 {
|
||||
let col: Vec<Point> = rows.iter().map(|row| row[c]).collect();
|
||||
for (to, q) in out.iter_mut().zip(cubic_line(&col)) {
|
||||
to[c] = q;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The point half way from `a` to `b`, as halves added: two finite points always give a finite one.
|
||||
fn half_way(a: Point, b: Point) -> Point {
|
||||
Point::new(0.5 * a.x + 0.5 * b.x, 0.5 * a.y + 0.5 * b.y)
|
||||
}
|
||||
|
||||
/// A Bézier curve of 2 to 4 control points as the 4 of the same curve's cubic form.
|
||||
fn cubic_line(p: &[Point]) -> [Point; 4] {
|
||||
match *p {
|
||||
[a, b] => [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b],
|
||||
[a, b, c] => [a, a.lerp(b, 2.0 / 3.0), c.lerp(b, 2.0 / 3.0), c],
|
||||
[a, b, c, d] => [a, b, c, d],
|
||||
_ => [Point::ZERO; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle offsets (along the chord, across it) of a cubic circular arc over a chord `chord`
|
||||
/// long that turns through θ = |`b`| × 180°: each handle is 4/3 tan(θ/4) of the radius long, along
|
||||
/// the arc's end tangent. With the radius `chord / (2 sin(θ/2))` that length is
|
||||
/// `chord / (3 cos²(θ/4))`, which a bend near 0 leaves at a third of the chord.
|
||||
fn arc_handles(chord: f64, b: f64) -> (f64, f64) {
|
||||
let th = b.abs().min(1.0) * PI;
|
||||
let len = chord / (3.0 * (th / 4.0).cos().powi(2));
|
||||
(len * (th / 2.0).cos(), len * (th / 2.0).sin())
|
||||
}
|
||||
|
||||
/// A row from (0, `y`) to (`w`, `y`) bent into a circular arc of |`b`| × 180°: up for a positive
|
||||
/// `b` when `up`, down when not, the other way for a negative one.
|
||||
fn arc_row(w: f64, y: f64, b: f64, up: bool) -> [Point; 4] {
|
||||
let (ax, ay) = arc_handles(w, b);
|
||||
let dy = if (b > 0.0) == up { -ay } else { ay };
|
||||
[Point::new(0.0, y), Point::new(ax, y + dy), Point::new(w - ax, y + dy), Point::new(w, y)]
|
||||
}
|
||||
|
||||
/// Arc at bend |`b`| as four rows: the bottom edge bends up through the bottom corners, the top
|
||||
/// edge is the arc around the same center `h` further out, and the rows between are spaced evenly
|
||||
/// along the radii. The top corners lie `h` out from the bottom ones along the radii, which lean
|
||||
/// out by θ/2.
|
||||
fn arc_rows(w: f64, h: f64, b: f64) -> [[Point; 4]; 4] {
|
||||
let th = b.abs().min(1.0) * PI;
|
||||
let (s, c) = (th / 2.0).sin_cos();
|
||||
let (tl, tr) = (Point::new(-h * s, h * (1.0 - c)), Point::new(w + h * s, h * (1.0 - c)));
|
||||
let (ax, ay) = arc_handles(tr.x - tl.x, b);
|
||||
let top = [tl, Point::new(tl.x + ax, tl.y - ay), Point::new(tr.x - ax, tr.y - ay), tr];
|
||||
let bottom = arc_row(w, h, b.abs(), true);
|
||||
let mut out = [[Point::ZERO; 4]; 4];
|
||||
for (r, row) in out.iter_mut().enumerate() {
|
||||
for (q, (t, u)) in row.iter_mut().zip(top.iter().zip(bottom)) {
|
||||
*q = t.lerp(u, r as f64 / 3.0);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Warp style `style`'s own net at bend `b` (-1..1) over the box `w` × `h`, before distortion.
|
||||
/// `vertical`: the net of the box turned on its side, where Rise moves the other half.
|
||||
fn style_net(style: WarpStyle, b: f64, w: f64, h: f64, vertical: bool) -> Net {
|
||||
use WarpStyle::*;
|
||||
let two = |top: [Point; 4], bottom: [Point; 4]| {
|
||||
let mut p = [[Point::ZERO; 4]; 4];
|
||||
(p[0], p[1]) = (top, bottom);
|
||||
Net { rows: 2, cols: 4, p }
|
||||
};
|
||||
let flat_row = |y: f64| [0.0, 1.0, 2.0, 3.0].map(|c| Point::new(w * c / 3.0, y));
|
||||
match style {
|
||||
Arc => {
|
||||
let rows = arc_rows(w, h, b);
|
||||
let net = two(rows[0], rows[3]);
|
||||
if b < 0.0 { net.mirrored(h) } else { net }
|
||||
}
|
||||
ArcUpper => two(arc_row(w, 0.0, b, true), flat_row(h)),
|
||||
ArcLower => two(flat_row(0.0), arc_row(w, h, b, false)),
|
||||
Arch => {
|
||||
let top = arc_row(w, 0.0, b, true);
|
||||
two(top, top.map(|q| Point::new(q.x, q.y + h)))
|
||||
}
|
||||
Bulge => two(arc_row(w, 0.0, b, true), arc_row(w, h, b, false)),
|
||||
ShellLower | ShellUpper => {
|
||||
let a = arc_rows(w, h, b);
|
||||
let mut net = Net::flat(w, h, 4, 4);
|
||||
if b >= 0.0 {
|
||||
// The outer arc and the ends of the row inside it, upside down for Shell Lower.
|
||||
net.p[0] = a[0];
|
||||
(net.p[1][0], net.p[1][3]) = (a[1][0], a[1][3]);
|
||||
if style == ShellLower { net.mirrored(h) } else { net }
|
||||
} else {
|
||||
// The inner arc and the ends of the row outside it, upside down for Shell Upper.
|
||||
net.p[3] = a[3];
|
||||
(net.p[2][0], net.p[2][3]) = (a[2][0], a[2][3]);
|
||||
if style == ShellUpper { net.mirrored(h) } else { net }
|
||||
}
|
||||
}
|
||||
Flag | Fish | Rise => {
|
||||
let mut net = Net::flat(w, h, 2, 4);
|
||||
let d = 2.0 * b * h;
|
||||
match style {
|
||||
Flag => {
|
||||
for row in &mut net.p[..2] {
|
||||
(row[1].y, row[2].y) = (row[1].y + d, row[2].y - d);
|
||||
}
|
||||
}
|
||||
Fish => {
|
||||
(net.p[0][1].y, net.p[0][2].y) = (net.p[0][1].y - d, net.p[0][2].y + d);
|
||||
(net.p[1][1].y, net.p[1][2].y) = (net.p[1][1].y + d, net.p[1][2].y - d);
|
||||
}
|
||||
_ => {
|
||||
for row in &mut net.p[..2] {
|
||||
if vertical {
|
||||
(row[2].y, row[3].y) = (row[2].y - d, row[3].y - d);
|
||||
} else {
|
||||
(row[0].y, row[1].y) = (row[0].y + d, row[1].y + d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
net
|
||||
}
|
||||
Wave => {
|
||||
let mut net = Net::flat(w, h, 3, 4);
|
||||
let d = 2.0 * b * h;
|
||||
(net.p[1][1].y, net.p[1][2].y) = (net.p[1][1].y + d, net.p[1][2].y - d);
|
||||
net
|
||||
}
|
||||
Fisheye => {
|
||||
let mut net = Net::flat(w, h, 4, 4);
|
||||
let c = Point::new(w / 2.0, h / 2.0);
|
||||
for row in &mut net.p[1..3] {
|
||||
for q in &mut row[1..3] {
|
||||
*q = c + (*q - c) * (1.0 + 4.0 * b);
|
||||
}
|
||||
}
|
||||
net
|
||||
}
|
||||
Inflate | Squeeze => {
|
||||
let mut net = Net::flat(w, h, 3, 3);
|
||||
let side = if style == Inflate { b * w / 2.0 } else { -b * w / 2.0 };
|
||||
net.p[0][1].y -= b * h / 2.0;
|
||||
net.p[2][1].y += b * h / 2.0;
|
||||
net.p[1][0].x -= side;
|
||||
net.p[1][2].x += side;
|
||||
net
|
||||
}
|
||||
Twist => {
|
||||
// The four inner points move round: clockwise for a positive bend.
|
||||
let mut net = Net::flat(w, h, 4, 4);
|
||||
let (dx, dy) = (b.abs() * w, b.abs() * h);
|
||||
if b >= 0.0 {
|
||||
net.p[1][1].x += dx;
|
||||
net.p[1][2].y += dy;
|
||||
net.p[2][2].x -= dx;
|
||||
net.p[2][1].y -= dy;
|
||||
} else {
|
||||
net.p[1][1].y += dy;
|
||||
net.p[1][2].x -= dx;
|
||||
net.p[2][2].y -= dy;
|
||||
net.p[2][1].x += dx;
|
||||
}
|
||||
net
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A warp as one bicubic Bézier patch over its box: the style's own net at the bend, its columns
|
||||
/// scaled by the horizontal distortion and then its rows by the vertical one. Points are in the
|
||||
/// box's coordinates (origin at its top left, y down).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct WarpNet {
|
||||
/// The control points over the box divided by `scale`.
|
||||
net: [[Point; 4]; 4],
|
||||
/// 1, or a power of two when the net over the box itself does not fit in finite numbers.
|
||||
scale: f64,
|
||||
w: f64,
|
||||
h: f64,
|
||||
}
|
||||
|
||||
impl WarpNet {
|
||||
/// The net of `style` over a box `w` × `h` at bend `b` and distortions `dh` and `dv` (each
|
||||
/// -1..1, clamped); `vertical` bends along the box's height.
|
||||
pub fn new(style: WarpStyle, b: f64, dh: f64, dv: f64, w: f64, h: f64, vertical: bool) -> Self {
|
||||
let unit = |x: f64| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 };
|
||||
let size = |x: f64| if x.is_finite() { x.max(0.0) } else { 0.0 };
|
||||
let (b, dh, dv, w, h) = (unit(b), unit(dh), unit(dv), size(w), size(h));
|
||||
let build = |w: f64, h: f64| {
|
||||
let mut net = if vertical { style_net(style, b, h, w, true).transposed() } else { style_net(style, b, w, h, false) };
|
||||
net.distort_columns(dh);
|
||||
net.distort_rows(dv);
|
||||
net.bicubic()
|
||||
};
|
||||
// A box near the largest finite size can overflow the net. The net is then built on the box
|
||||
// divided by the smallest power of two that fits (2 to 4096), an exact division for every
|
||||
// side above the subnormal range, and points are multiplied back as they are read.
|
||||
let mut out = Self { net: build(w, h), scale: 1.0, w, h };
|
||||
while out.scale < 4096.0 && !out.net.iter().flatten().all(|q| q.is_finite()) {
|
||||
let scale = out.scale * 2.0;
|
||||
out = Self { net: build(w / scale, h / scale), scale, w, h };
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The point at `(u, v)` of the box (0..1 across and down; outside, the patch goes on). A
|
||||
/// coordinate the patch would send past the largest finite number is the box's own, held to
|
||||
/// the finite range.
|
||||
pub fn at(&self, u: f64, v: f64) -> Point {
|
||||
let p = self.at_scaled(u, v);
|
||||
let held = |x: f64| if x.is_nan() { 0.0 } else { x.clamp(-f64::MAX, f64::MAX) };
|
||||
let coord = |x: f64, flat: f64| if (x * self.scale).is_finite() { x * self.scale } else { held(flat) };
|
||||
Point::new(coord(p.x, u * self.w), coord(p.y, v * self.h))
|
||||
}
|
||||
|
||||
/// [`Self::at`] divided by the net's scale.
|
||||
fn at_scaled(&self, u: f64, v: f64) -> Point {
|
||||
let bern = |t: f64| {
|
||||
let s = 1.0 - t;
|
||||
[s * s * s, 3.0 * t * s * s, 3.0 * t * t * s, t * t * t]
|
||||
};
|
||||
let (bu, bv) = (bern(u), bern(v));
|
||||
let (mut x, mut y) = (0.0, 0.0);
|
||||
for (row, wv) in self.net.iter().zip(bv) {
|
||||
for (q, wu) in row.iter().zip(bu) {
|
||||
x += wv * wu * q.x;
|
||||
y += wv * wu * q.y;
|
||||
}
|
||||
}
|
||||
Point::new(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
/// Segment as a cubic; straight lines get handles at 1/3 and 2/3 so a non-linear map bends them.
|
||||
fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
|
||||
let c = sp.segment(i);
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
//! File → File Info: the document's descriptive metadata (author, description, keywords, rating,
|
||||
//! copyright) and its created and modified dates, which the SVG, PDF and PNG writers carry. The
|
||||
//! document title is [`crate::Document::title`]. Every field is defaulted, so documents saved
|
||||
//! before File Info existed load unchanged.
|
||||
//! document title is [`Document::title`], the name it shows in its tab and offers Save As when it
|
||||
//! has no file; a title the file it was opened from gave itself is [`DocMetadata::title`], and
|
||||
//! [`Document::info_title`] is the title File Info shows and exports write. Every field is
|
||||
//! defaulted, so documents saved before File Info existed load unchanged.
|
||||
|
||||
use chrono::{Datelike, Timelike};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Document;
|
||||
|
||||
/// File Info → Copyright Status.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -44,6 +48,13 @@ pub const MAX_RATING: u8 = 5;
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DocMetadata {
|
||||
/// The title the file this document was opened from gives itself (an SVG's root `<title>`, a
|
||||
/// PDF's XMP `dc:title` or Info `Title`), which File Info shows and exports write in place of
|
||||
/// [`Document::title`], the document's display name. `None`: the file gave none, so the
|
||||
/// display name is the title. Left out of a saved document when unset, so other documents
|
||||
/// save as they did.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub title: Option<String>,
|
||||
pub author: String,
|
||||
/// The author's position or job title.
|
||||
pub author_title: String,
|
||||
@@ -83,6 +94,16 @@ impl DocMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// The title File Info shows and the files an export writes carry (PDF `Title` and XMP
|
||||
/// `dc:title`, SVG `<title>`, PNG `Title`): the title the file this document was opened from
|
||||
/// gave itself ([`DocMetadata::title`]), else [`Document::title`]. The display name (the tab, the
|
||||
/// default file name) is always [`Document::title`].
|
||||
pub fn info_title(&self) -> &str {
|
||||
self.metadata.title.as_deref().filter(|t| !t.trim().is_empty()).unwrap_or(&self.title)
|
||||
}
|
||||
}
|
||||
|
||||
/// The time exported files record: PDF `CreationDate` and `ModDate`, the PNG `Creation Time`
|
||||
/// entry, a zip entry's date, and a saved document's `created` and `modified`. It is the clock,
|
||||
/// unless `SOURCE_DATE_EPOCH` is set, which replaces it so that the same commands produce the same
|
||||
@@ -191,6 +212,24 @@ mod tests {
|
||||
assert!(DocMetadata::default().png_text("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_info_title_is_the_files_own_title_else_the_display_name() {
|
||||
let mut d = Document::new(10.0, 10.0);
|
||||
d.title = "box.svg".into();
|
||||
assert_eq!(d.info_title(), "box.svg");
|
||||
d.metadata.title = Some("Access paths".into());
|
||||
assert_eq!((d.title.as_str(), d.info_title()), ("box.svg", "Access paths"));
|
||||
d.metadata.title = Some(" ".into());
|
||||
assert_eq!(d.info_title(), "box.svg");
|
||||
// Saved only when set: other documents' metadata is as before, and the field comes back.
|
||||
d.metadata.title = None;
|
||||
assert!(!serde_json::to_string(&d.metadata).unwrap().contains("title"));
|
||||
d.metadata.title = Some("Access paths".into());
|
||||
let json = serde_json::to_string(&d.metadata).unwrap();
|
||||
assert_eq!(serde_json::from_str::<DocMetadata>(&json).unwrap().title.as_deref(), Some("Access paths"));
|
||||
assert_eq!(serde_json::from_str::<DocMetadata>("{}").unwrap().title, None);
|
||||
}
|
||||
|
||||
/// `SOURCE_DATE_EPOCH` replaces the clock in exported output only when it is a non-negative
|
||||
/// decimal integer; anything else leaves the clock to decide, so an export is never refused.
|
||||
#[test]
|
||||
|
||||
@@ -180,6 +180,24 @@ impl ObjectsOnPath {
|
||||
});
|
||||
Some((spacing, start))
|
||||
}
|
||||
/// Move the object `member` to the place on the path of the object `target`: the objects
|
||||
/// between them each move one place toward where `member` was, except the objects for which
|
||||
/// `fixed` is true, which keep their places and are passed over. Only the order changes, not the
|
||||
/// Space or the start. Returns `member`'s new index, or `None` when either one is not an object
|
||||
/// of the group.
|
||||
pub fn move_member(&mut self, member: NodeId, target: NodeId, fixed: impl Fn(NodeId) -> bool) -> Option<usize> {
|
||||
let moves = |id: NodeId| id == member || id == target || !fixed(id);
|
||||
let slots: Vec<usize> = (0..self.members.len()).filter(|&i| moves(self.members[i].id)).collect();
|
||||
let from = slots.iter().position(|&i| self.members[i].id == member)?;
|
||||
let to = slots.iter().position(|&i| self.members[i].id == target)?;
|
||||
let mut moving: Vec<_> = slots.iter().map(|&i| self.members[i]).collect();
|
||||
let m = moving.remove(from);
|
||||
moving.insert(to, m);
|
||||
for (&i, m) in slots.iter().zip(moving) {
|
||||
self.members[i] = m;
|
||||
}
|
||||
Some(slots[to])
|
||||
}
|
||||
/// The children given new ids (a copy of the group): the path and the objects by their new ids.
|
||||
pub fn rename(&mut self, ids: &HashMap<NodeId, NodeId>) {
|
||||
let to = |id: NodeId| ids.get(&id).copied().unwrap_or(id);
|
||||
@@ -487,6 +505,36 @@ mod tests {
|
||||
assert_eq!(layout(400.0, true, 4, Some(300.0), 400.0), (0.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_object_shifts_the_ones_between_it_and_its_new_place() {
|
||||
let (a, b, c) =
|
||||
(rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)), rect(4, Rect::new(40.0, 0.0, 50.0, 10.0)));
|
||||
let rec = ObjectsOnPath { spacing: Some(30.0), start: 5.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b, &c], CENTER, 15.0) };
|
||||
let order = |r: &ObjectsOnPath| r.members.iter().map(|m| m.id.0).collect::<Vec<_>>();
|
||||
let free = |_: NodeId| false;
|
||||
let mut fwd = rec.clone();
|
||||
assert_eq!(fwd.move_member(NodeId(2), NodeId(4), free), Some(2));
|
||||
assert_eq!(order(&fwd), [3, 4, 2], "the first to the last place");
|
||||
assert_eq!((fwd.spacing, fwd.start, fwd.pivot, fwd.rotate), (rec.spacing, rec.start, rec.pivot, rec.rotate));
|
||||
let mut back = rec.clone();
|
||||
assert_eq!(back.move_member(NodeId(4), NodeId(2), free), Some(0));
|
||||
assert_eq!(order(&back), [4, 2, 3], "the last to the first place");
|
||||
let mut same = rec.clone();
|
||||
assert_eq!(same.move_member(NodeId(3), NodeId(3), free), Some(1));
|
||||
assert_eq!(same, rec, "onto its own place");
|
||||
let mut other = rec.clone();
|
||||
assert_eq!(other.move_member(NodeId(1), NodeId(3), free), None, "the path is not one of the objects");
|
||||
assert_eq!(other.move_member(NodeId(3), NodeId(9), free), None);
|
||||
assert_eq!(other, rec);
|
||||
// A fixed object between them keeps its place; the others pass over it.
|
||||
let mut over = rec.clone();
|
||||
assert_eq!(over.move_member(NodeId(2), NodeId(4), |id| id == NodeId(3)), Some(2));
|
||||
assert_eq!(order(&over), [4, 3, 2], "the first and last trade places round the fixed one");
|
||||
let mut back_over = rec.clone();
|
||||
assert_eq!(back_over.move_member(NodeId(4), NodeId(2), |id| id == NodeId(3)), Some(0));
|
||||
assert_eq!(order(&back_over), [4, 3, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_saved_without_space_reads_as_auto() {
|
||||
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
|
||||
@@ -59,6 +59,11 @@ pub struct Selection {
|
||||
/// that object ([`crate::symbol_overrides`]). Any other selection change clears it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub symbol_part: Option<SymbolPart>,
|
||||
/// An object of an Objects on Path group, chosen with its Select/Move widget: the group is the
|
||||
/// one selected object, and the object is one of its objects on the path
|
||||
/// ([`crate::objects_on_path::ObjectsOnPath::members`]). Any other selection change clears it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub on_path_member: Option<NodeId>,
|
||||
}
|
||||
|
||||
/// See [`Selection::symbol_part`].
|
||||
@@ -94,6 +99,13 @@ impl Selection {
|
||||
self.guides.clear();
|
||||
self.key_guide = None;
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
}
|
||||
/// Select only the Objects on Path group `group`, with its object `member` (see
|
||||
/// [`Selection::on_path_member`]).
|
||||
pub fn set_on_path_member(&mut self, group: NodeId, member: NodeId) {
|
||||
self.set([group]);
|
||||
self.on_path_member = Some(member);
|
||||
}
|
||||
/// Select only instance `instance`, with the object at `path` of its symbol's art (see
|
||||
/// [`Selection::symbol_part`]).
|
||||
@@ -115,6 +127,7 @@ impl Selection {
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
if !self.objects.contains(&id) {
|
||||
self.objects.push(id);
|
||||
}
|
||||
@@ -123,6 +136,7 @@ impl Selection {
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
self.objects.retain(|x| *x != id);
|
||||
self.anchors.remove(&id);
|
||||
self.segments.remove(&id);
|
||||
@@ -152,6 +166,7 @@ impl Selection {
|
||||
/// Shift-click on a guide).
|
||||
pub fn toggle_guide(&mut self, i: NodeId) {
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
if let Some(k) = self.guides.iter().position(|g| *g == i) {
|
||||
self.guides.remove(k);
|
||||
if self.key_guide == Some(i) {
|
||||
@@ -258,6 +273,22 @@ impl Selection {
|
||||
if !part_kept {
|
||||
self.symbol_part = None;
|
||||
}
|
||||
// A chosen object on a path needs its Objects on Path group selected alone, with no anchors
|
||||
// or guides, and still one of the group's objects, neither hidden nor locked.
|
||||
let member_kept = self.on_path_member.is_some_and(|m| {
|
||||
let [g] = self.objects.as_slice() else { return false };
|
||||
self.anchors.is_empty()
|
||||
&& self.guides.is_empty()
|
||||
&& doc.is_editable(m)
|
||||
&& found
|
||||
.get(g)
|
||||
.and_then(|p| doc.node_at(p))
|
||||
.and_then(|n| n.extras().objects_on_path.as_deref().filter(|_| crate::objects_on_path::is_objects_on_path(n)))
|
||||
.is_some_and(|rec| rec.members.iter().any(|x| x.id == m))
|
||||
});
|
||||
if !member_kept {
|
||||
self.on_path_member = None;
|
||||
}
|
||||
}
|
||||
/// Deselect the objects that are hidden or locked, themselves or through a group or layer
|
||||
/// around them (and so the key object when it is one): hidden or locked art can't stay
|
||||
|
||||
@@ -179,6 +179,49 @@ fn selection_changes_clear_the_target() {
|
||||
assert_eq!(s.target, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_object_on_a_path_needs_its_group_selected_alone() {
|
||||
use vectorcraft_geom::{Point, Rect, shapes};
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (line, a, b, g, other) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let line = Node::path(line, shapes::line(Point::new(0.0, 100.0), Point::new(200.0, 100.0)), Default::default());
|
||||
let a = Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default());
|
||||
let b = Node::path(b, shapes::rectangle(Rect::new(20.0, 0.0, 30.0, 10.0)), Default::default());
|
||||
let rec = crate::objects_on_path::ObjectsOnPath::new(line.id, &[&a, &b], crate::objects_on_path::CENTER, 0.0);
|
||||
let (line_id, a_id) = (line.id, a.id);
|
||||
let mut group = Node::new(g, NodeKind::Group { children: vec![Arc::new(line), Arc::new(a), Arc::new(b)], clip: false });
|
||||
group.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
d.insert(Some(l), 0, group).unwrap();
|
||||
d.insert(Some(l), 1, Node::path(other, shapes::rectangle(Rect::new(150.0, 0.0, 160.0, 10.0)), Default::default())).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.set_on_path_member(g, a_id);
|
||||
s.prune(&d);
|
||||
assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], Some(a_id)));
|
||||
s.add(other);
|
||||
assert_eq!(s.on_path_member, None, "another object joins the selection");
|
||||
s.set_on_path_member(g, a_id);
|
||||
s.set([g]);
|
||||
assert_eq!(s.on_path_member, None, "a new selection");
|
||||
// The path is not one of the objects, nor is an object outside the group.
|
||||
for m in [line_id, other] {
|
||||
s.set_on_path_member(g, m);
|
||||
s.prune(&d);
|
||||
assert_eq!(s.on_path_member, None, "{m:?}");
|
||||
}
|
||||
// A locked object is not chosen.
|
||||
s.set_on_path_member(g, a_id);
|
||||
d.node_mut(a_id).unwrap().locked = true;
|
||||
s.prune(&d);
|
||||
assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], None), "locked");
|
||||
d.node_mut(a_id).unwrap().locked = false;
|
||||
// Once the group is a plain group, no object of it is chosen.
|
||||
s.set_on_path_member(g, a_id);
|
||||
d.node_mut(g).unwrap().extras_mut().objects_on_path = None;
|
||||
s.prune(&d);
|
||||
assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_object_needs_two_or_more_selected_objects() {
|
||||
let mut s = Selection::default();
|
||||
|
||||
@@ -156,6 +156,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
|
||||
BuiltinStyleLibrary { id: "outlines-rules", name: "Outlines and Rules", make: outlines_rules },
|
||||
BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn },
|
||||
BuiltinStyleLibrary { id: "textures", name: "Textures", make: textures },
|
||||
BuiltinStyleLibrary { id: "painted-sketched", name: "Painted and Sketched", make: painted_sketched },
|
||||
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
|
||||
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
|
||||
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
|
||||
@@ -193,8 +194,14 @@ fn round(h: &str, width: f64) -> StrokeLayer {
|
||||
StrokeLayer { cap: LineCap::Round, join: LineJoin::Round, ..stroke(h, width) }
|
||||
}
|
||||
|
||||
/// Live effect `id` with `params` (the others keep the effect's defaults).
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
/// Live effect `id` with `params` (the others keep the effect's defaults). A Warp draws with its
|
||||
/// style's Bézier net, as a new Warp does.
|
||||
fn fx(id: &str, mut params: Value) -> Effect {
|
||||
if id.starts_with("warp.")
|
||||
&& let Value::Object(m) = &mut params
|
||||
{
|
||||
m.entry("version").or_insert(json!(crate::live::WARP_NET));
|
||||
}
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
}
|
||||
|
||||
@@ -323,6 +330,59 @@ fn hand_drawn() -> Vec<GraphicStyle> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Painted and Sketched: one catalog paint or sketch effect over the whole appearance, so it
|
||||
/// repaints the fill and the stroke together (watercolor, dry brush, pastels, charcoal and ink).
|
||||
fn painted_sketched() -> Vec<GraphicStyle> {
|
||||
vec![
|
||||
style(
|
||||
"Washed Blue",
|
||||
vec![F(fill("#8ab9c9"))],
|
||||
vec![fx("artistic.watercolor", json!({"brushDetail": 8.0, "shadowIntensity": 2.0, "texture": 2.0}))],
|
||||
),
|
||||
style(
|
||||
"Bristle Ochre",
|
||||
vec![F(fill("#c4975a")), S(stroke("#76533d", 1.0))],
|
||||
vec![fx("artistic.dryBrush", json!({"brushSize": 4.0, "brushDetail": 7.0, "texture": 2.0}))],
|
||||
),
|
||||
style(
|
||||
"Pastel Heather",
|
||||
vec![F(fill("#a78ca5"))],
|
||||
vec![fx(
|
||||
"artistic.roughPastels",
|
||||
json!({
|
||||
"strokeLength": 8.0,
|
||||
"strokeDetail": 9.0,
|
||||
"texture": "canvas",
|
||||
"scaling": 100.0,
|
||||
"relief": 5.0,
|
||||
"lightDirection": "topLeft",
|
||||
"invert": false
|
||||
}),
|
||||
)],
|
||||
),
|
||||
style(
|
||||
"Charcoal Shade",
|
||||
vec![F(fill("#666666"))],
|
||||
vec![fx("sketch.charcoal", json!({"thickness": 3.0, "detail": 3.0, "lightDarkBalance": 55.0}))],
|
||||
),
|
||||
style(
|
||||
"Ink Contour",
|
||||
vec![F(fill("#d9e2df")), S(stroke("#26323b", 1.0))],
|
||||
vec![fx("brushStrokes.inkOutlines", json!({"strokeLength": 6.0, "darkIntensity": 24.0, "lightIntensity": 8.0}))],
|
||||
),
|
||||
style(
|
||||
"Wet Ink",
|
||||
vec![F(fill("#637b85"))],
|
||||
vec![fx("brushStrokes.sumiE", json!({"strokeWidth": 7.0, "strokePressure": 5.0, "contrast": 20.0}))],
|
||||
),
|
||||
style(
|
||||
"Fine Pen",
|
||||
vec![F(fill("#d8d4c6"))],
|
||||
vec![fx("sketch.graphicPen", json!({"strokeLength": 6.0, "lightDarkBalance": 55.0, "strokeDirection": "rightDiagonal"}))],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Textures: fills and strokes painted with the catalog's texture effects (grain, canvas and
|
||||
/// burlap surfaces, craquelure, tiles, patchwork, stained glass and water paper).
|
||||
fn textures() -> Vec<GraphicStyle> {
|
||||
@@ -603,6 +663,54 @@ mod tests {
|
||||
assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn");
|
||||
}
|
||||
|
||||
/// The built-in styles' Warps draw with the map a new Warp takes.
|
||||
#[test]
|
||||
fn builtin_warp_styles_take_the_nets_map() {
|
||||
let mut warps = 0;
|
||||
for b in STYLE_LIBRARIES {
|
||||
let lib = builtin_style_library(b.id).unwrap();
|
||||
for g in &lib.styles {
|
||||
let mut effects: Vec<&Effect> = g.appearance.effects.iter().collect();
|
||||
effects.extend(g.appearance.items.iter().flat_map(|i| i.effects()));
|
||||
for e in effects.into_iter().filter(|e| e.id.starts_with("warp.")) {
|
||||
assert_eq!(e.params["version"], json!(crate::live::WARP_NET), "{} › {}: {}", b.id, g.name, e.id);
|
||||
warps += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(warps >= 3, "{warps}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painted_and_sketched_follows_textures_with_one_effect_per_style() {
|
||||
let ids: Vec<&str> = STYLE_LIBRARIES.iter().map(|b| b.id).collect();
|
||||
let at = ids.iter().position(|&id| id == "painted-sketched").expect("listed");
|
||||
assert_eq!(ids[at - 1], "textures");
|
||||
let lib = builtin_style_library("painted-sketched").unwrap();
|
||||
assert_eq!(lib.name, "Painted and Sketched");
|
||||
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(names, ["Washed Blue", "Bristle Ochre", "Pastel Heather", "Charcoal Shade", "Ink Contour", "Wet Ink", "Fine Pen"]);
|
||||
let effects: Vec<&str> = lib.styles.iter().flat_map(|g| g.appearance.effects.iter().map(|e| e.id.as_str())).collect();
|
||||
assert_eq!(
|
||||
effects,
|
||||
[
|
||||
"artistic.watercolor",
|
||||
"artistic.dryBrush",
|
||||
"artistic.roughPastels",
|
||||
"sketch.charcoal",
|
||||
"brushStrokes.inkOutlines",
|
||||
"brushStrokes.sumiE",
|
||||
"sketch.graphicPen"
|
||||
]
|
||||
);
|
||||
assert!(lib.styles.iter().all(|g| g.appearance.items.iter().all(|i| i.effects().is_empty())), "no effects on a fill or stroke");
|
||||
// No other built-in library holds a style of the same name.
|
||||
for b in STYLE_LIBRARIES.iter().filter(|b| b.id != "painted-sketched") {
|
||||
let other = builtin_style_library(b.id).unwrap();
|
||||
assert!(other.styles.iter().all(|g| !names.contains(&g.name.as_str())), "{}", b.id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vcstyles_round_trip() {
|
||||
let mut lib = (*builtin_style_library("gradient-finishes").unwrap()).clone();
|
||||
|
||||
@@ -52,7 +52,7 @@ pub struct TextObject {
|
||||
/// the object, so the runs (and their styles) stay the text itself.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub ruby: Vec<RubySpan>,
|
||||
#[serde(default)]
|
||||
#[serde(default = "ParaStyle::omitted")]
|
||||
pub para: ParaStyle,
|
||||
/// Per-paragraph attributes (see the type's docs); empty = every paragraph uses `para`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
|
||||
@@ -28,6 +28,12 @@ pub struct CharStyle {
|
||||
/// Manual pair spacing in 1/1000 em, as [`Self::tracking`]; None uses the automatic mode.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub kerning: Option<f64>,
|
||||
/// Space before the character in 1/1000 em, as [`Self::kerning`], when it starts a line by
|
||||
/// itself: the first character of the text, of a paragraph, or after a forced line break. The
|
||||
/// Type tool's caret before such a character kerns with it (#5111), since there is no character
|
||||
/// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect.
|
||||
#[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub kerning_before: f64,
|
||||
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
|
||||
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub optical_kerning: bool,
|
||||
@@ -51,7 +57,9 @@ pub struct CharStyle {
|
||||
#[serde(default)]
|
||||
pub all_caps: bool,
|
||||
/// OpenType features that differ from the defaults (OpenType panel), as tags: `"dlig"` turns
|
||||
/// a feature on, `"-liga"` off.
|
||||
/// a feature on, `"-liga"` off, and `"salt=2"` turns a feature with alternates on at the font's
|
||||
/// alternate number 2 (the value the shaper gets; a plain `"salt"` is value 1). Runs that
|
||||
/// differ only in this list are shaped together, each with its own features.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub features: Vec<String>,
|
||||
/// Character style (Character Styles panel) these attributes come from; None = Normal.
|
||||
@@ -411,6 +419,7 @@ impl Default for CharStyle {
|
||||
leading: None,
|
||||
tracking: 0.0,
|
||||
kerning: None,
|
||||
kerning_before: 0.0,
|
||||
optical_kerning: false,
|
||||
baseline_shift: 0.0,
|
||||
h_scale: 100.0,
|
||||
|
||||
@@ -244,9 +244,21 @@ pub struct ParaStyle {
|
||||
/// Insert Kashidas (Paragraph panel): justified lines lengthen their Arabic words with
|
||||
/// kashidas before they widen their word spaces.
|
||||
pub kashida: Kashida,
|
||||
/// Korean Line Break Anywhere (Paragraph panel menu): a line may break between any two Hangul
|
||||
/// syllables. Off, a Korean word (the characters between spaces, when any of them is Hangul)
|
||||
/// breaks only at its spaces and punctuation, or where it is wider than the line. New type and
|
||||
/// imported text have it off; paragraphs saved before it existed open with it on, the line
|
||||
/// breaks they were laid out with.
|
||||
pub korean_line_break_anywhere: bool,
|
||||
}
|
||||
|
||||
impl ParaStyle {
|
||||
/// The attributes a text object saved without `para` reads with: the defaults, with Korean
|
||||
/// Line Break Anywhere on, as a saved paragraph without that field reads.
|
||||
pub(crate) fn omitted() -> Self {
|
||||
Self { korean_line_break_anywhere: true, ..Self::default() }
|
||||
}
|
||||
|
||||
/// Keeps the indents and the space before and after to -[`crate::MAX_COORD`] to
|
||||
/// [`crate::MAX_COORD`], and the tab stop positions to 0 to 100,000 pt, the range
|
||||
/// `text.tabs.set` takes. A value outside its range becomes the nearer end, and one that is
|
||||
@@ -330,6 +342,10 @@ struct ParaStyleFile {
|
||||
roman_hanging: bool,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kashida: Kashida,
|
||||
/// Written only when off: a paragraph saved without it was laid out breaking between Hangul
|
||||
/// syllables.
|
||||
#[serde(default = "crate::yes", skip_serializing_if = "crate::skip::is_true")]
|
||||
korean_line_break_anywhere: bool,
|
||||
}
|
||||
|
||||
impl From<ParaStyle> for ParaStyleFile {
|
||||
@@ -361,6 +377,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
..
|
||||
} = p;
|
||||
Self {
|
||||
@@ -386,6 +403,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -415,6 +433,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
..
|
||||
} = f;
|
||||
Self {
|
||||
@@ -439,6 +458,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,15 @@ pub struct TabStop {
|
||||
pub align_on: char,
|
||||
}
|
||||
|
||||
impl TabStop {
|
||||
/// The largest stop position `text.tabs.set` and a paragraph style take, in points.
|
||||
pub const MAX_POSITION: f64 = 100_000.0;
|
||||
/// The most leader characters a stop repeats.
|
||||
pub const MAX_LEADER: usize = 8;
|
||||
/// The most stops `text.tabs.set` and a paragraph style take in one list.
|
||||
pub const MAX_STOPS: usize = 256;
|
||||
}
|
||||
|
||||
fn default_align_on() -> char {
|
||||
'.'
|
||||
}
|
||||
@@ -356,6 +365,7 @@ impl ParaList {
|
||||
position: CharPosition::Normal,
|
||||
tracking: 0.0,
|
||||
kerning: None,
|
||||
kerning_before: 0.0,
|
||||
optical_kerning: first.optical_kerning,
|
||||
tate_chu_yoko: false,
|
||||
underline: false,
|
||||
|
||||
@@ -184,6 +184,29 @@ fn justification_options_read_from_a_file_stay_in_range() {
|
||||
assert_eq!(same, d);
|
||||
}
|
||||
|
||||
/// Korean Line Break Anywhere is off for a new paragraph and saved only when off; a paragraph
|
||||
/// saved before it existed, or a text object saved without paragraph attributes, reads with it on,
|
||||
/// and both values read back as saved.
|
||||
#[test]
|
||||
fn korean_line_break_anywhere_is_saved_only_when_off() {
|
||||
let off = ParaStyle::default();
|
||||
assert!(!off.korean_line_break_anywhere);
|
||||
let saved = serde_json::to_value(&off).unwrap();
|
||||
assert_eq!(saved["korean_line_break_anywhere"], false);
|
||||
assert_eq!(serde_json::from_value::<ParaStyle>(saved).unwrap(), off);
|
||||
let on = ParaStyle { korean_line_break_anywhere: true, ..ParaStyle::default() };
|
||||
let saved = serde_json::to_value(&on).unwrap();
|
||||
assert!(saved.get("korean_line_break_anywhere").is_none());
|
||||
assert_eq!(serde_json::from_value::<ParaStyle>(saved).unwrap(), on);
|
||||
let old: ParaStyle = serde_json::from_str(r#"{"justify":"Left"}"#).unwrap();
|
||||
assert!(old.korean_line_break_anywhere);
|
||||
let mut saved = serde_json::to_value(TextObject::point(Point::ZERO, "가나", CharStyle::default())).unwrap();
|
||||
assert_eq!(saved["para"]["korean_line_break_anywhere"], false);
|
||||
saved.as_object_mut().unwrap().remove("para");
|
||||
let old: TextObject = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(old.para, ParaStyle { korean_line_break_anywhere: true, ..ParaStyle::default() });
|
||||
}
|
||||
|
||||
/// Numbered lists: each number style writes its numbers and rolls over (letters after Z,
|
||||
/// roman numerals in subtractive forms, zero-padded numbers past their digits), the marker adds
|
||||
/// a period, and the count runs through list paragraphs, skips empty and bulleted ones and
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use super::{CLASSIC_EXTRUDE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap};
|
||||
use super::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value,
|
||||
json, trap,
|
||||
};
|
||||
|
||||
/// Catalogue entry for one effect.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -81,6 +84,7 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"threeD.revolve" => always(&["offset"]),
|
||||
"threeD.extrude" => always(&["depth", "bevelWidth", "bevelHeight"]),
|
||||
"threeD.classicExtrude" => always(&["depth", "bevelHeight"]),
|
||||
"threeD.classicRevolve" => always(&["offset"]),
|
||||
"threeD.inflate" => always(&["depth"]),
|
||||
"path.outlineStroke" => always(&["width"]),
|
||||
"stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]),
|
||||
@@ -112,7 +116,7 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
}
|
||||
}
|
||||
|
||||
const WARP_DOC: &str = "{bend: % (-100..100, 50; with a bend or a distortion, placed gradients move and scale from the object's bounds to its warped bounds), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}";
|
||||
const WARP_DOC: &str = "{bend: % (-100..100, 50; with a bend or a distortion, placed gradients move and scale from the object's bounds to its warped bounds, and images bend as 10 × 10 cells of two triangles unless the pieces would make the art pass 2,000,000 objects or the image's frame keeps its shape past the anchor budget), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\", version: 0|1 (the map: 1 bends each style as one Bézier patch over the bounds, which new and imported warps get; 0, or none, is VectorCraft's earlier map, which warps saved without a version keep)}";
|
||||
|
||||
const DT: &[&str] = &["Effect", "Distort & Transform"];
|
||||
|
||||
@@ -207,6 +211,20 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","drawHiddenFaces":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_REVOLVE,
|
||||
"Revolve (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_ROTATE,
|
||||
"Rotate (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}),
|
||||
),
|
||||
g(
|
||||
"convertToShape.rectangle",
|
||||
"Rectangle…",
|
||||
|
||||
@@ -690,6 +690,525 @@ fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A white 10 pt square with id `id` at the origin.
|
||||
fn white_square(id: u64) -> Node {
|
||||
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// `n` masked by `art`, linked or not.
|
||||
fn masked_by(mut n: Node, art: Node, linked: bool) -> Node {
|
||||
let mut mask = vectorcraft_doc::OpacityMask::new(art, true);
|
||||
mask.linked = linked;
|
||||
n.extras_mut().mask = Some(Box::new(mask));
|
||||
n
|
||||
}
|
||||
|
||||
/// The geometry effects that reshape a group's members, one at a time.
|
||||
fn reshaping_effects() -> Vec<Effect> {
|
||||
let fx = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true };
|
||||
let corners = serde_json::json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
|
||||
vec![
|
||||
fx("distort.transform", serde_json::json!({"moveH": 30})),
|
||||
fx("distort.transform", serde_json::json!({"rotate": 90})),
|
||||
fx("distort.twist", serde_json::json!({"angle": 90})),
|
||||
fx("distort.freeDistort", corners),
|
||||
fx("warp.arc", serde_json::json!({})),
|
||||
fx("distort.roughen", serde_json::json!({"size": 5, "seed": 3})),
|
||||
fx("distort.zigZag", serde_json::json!({})),
|
||||
fx("distort.puckerBloat", serde_json::json!({"amount": 50})),
|
||||
fx("distort.tweak", serde_json::json!({})),
|
||||
fx("path.offsetPath", serde_json::json!({"offset": 3})),
|
||||
fx("stylize.roundCorners", serde_json::json!({"radius": 3})),
|
||||
]
|
||||
}
|
||||
|
||||
/// A group's geometry effect reshapes the art of a member's linked opacity mask as it reshapes the
|
||||
/// member: a mask drawn over the member still covers it. An unlinked mask stays where it is.
|
||||
#[test]
|
||||
fn a_groups_geometry_effects_reshape_a_members_linked_mask_with_it() {
|
||||
let square = white_square(1);
|
||||
let original = square.path_data().cloned();
|
||||
for e in reshaping_effects() {
|
||||
for linked in [true, false] {
|
||||
let member = masked_by(square.clone(), white_square(4), linked);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = member.extras().mask.as_deref().unwrap();
|
||||
assert!(member.path_data().cloned() != original, "{}: the member is reshaped", e.id);
|
||||
let want = if linked { member.path_data().cloned() } else { original.clone() };
|
||||
assert_eq!(mask.art.path_data().cloned(), want, "{} (linked: {linked})", e.id);
|
||||
assert_eq!(mask.linked, linked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mask of a group inside the group, the mask of a path in it, a mask inside that mask's art and
|
||||
/// an inverted mask all take the outer group's effect with the paths they mask.
|
||||
#[test]
|
||||
fn a_groups_geometry_effects_reshape_nested_and_inverted_masks() {
|
||||
for e in reshaping_effects() {
|
||||
let innermost = masked_by(white_square(7), white_square(8), true);
|
||||
let path = masked_by(white_square(1), masked_by(white_square(6), innermost, true), true);
|
||||
let mut inner = masked_by(Node::group(NodeId(5), vec![Arc::new(path)]), white_square(4), true);
|
||||
if let Some(m) = inner.extras_if_any().and_then(|x| x.mask.as_mut()) {
|
||||
m.invert = true;
|
||||
}
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let path = &inner.children().unwrap()[0];
|
||||
let want = path.path_data().cloned();
|
||||
let mask_of = |n: &Node| n.extras().mask.as_deref().map(|m| (*m.art).clone()).unwrap();
|
||||
let (outer_mask, path_mask) = (mask_of(inner), mask_of(path));
|
||||
assert!(inner.extras().mask.as_deref().is_some_and(|m| m.invert));
|
||||
assert_eq!(outer_mask.path_data().cloned(), want, "{}: the inner group's inverted mask", e.id);
|
||||
assert_eq!(path_mask.path_data().cloned(), want, "{}: the path's mask", e.id);
|
||||
assert_eq!(mask_of(&path_mask).path_data().cloned(), want, "{}: the mask inside the mask's art", e.id);
|
||||
assert_eq!(mask_of(&mask_of(&path_mask)).path_data().cloned(), want, "{}: one level deeper", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect's copies of a path with a linked mask are objects of their own, each with the
|
||||
/// mask moved with it; the original keeps its mask where it was.
|
||||
#[test]
|
||||
fn each_transform_copy_of_a_masked_member_carries_its_mask() {
|
||||
let member = masked_by(white_square(1), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let copies = art.children().unwrap()[0].children().expect("the object and its copies are objects of their own");
|
||||
assert_eq!(copies.len(), 3);
|
||||
for c in copies {
|
||||
let mask = c.extras().mask.as_deref().unwrap();
|
||||
assert_eq!(mask.art.geometric_bounds(), c.geometric_bounds());
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect's copies of the paths of a member group give the group's linked mask the same
|
||||
/// copies: the mask covers each copy.
|
||||
#[test]
|
||||
fn a_member_groups_mask_takes_the_transform_copies_of_its_paths() {
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let want = inner.geometric_bounds();
|
||||
assert_eq!(want, Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "the path and its copy");
|
||||
assert_eq!(inner.extras().mask.as_deref().unwrap().art.geometric_bounds(), want);
|
||||
}
|
||||
|
||||
/// A mask's art of several objects takes Transform copies whole, as the art it masks does: each copy
|
||||
/// of the mask's art is a group of its objects, so the copies do not interleave object by object.
|
||||
#[test]
|
||||
fn a_masks_art_of_several_objects_is_copied_whole() {
|
||||
let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
let copies = mask.children().unwrap();
|
||||
assert_eq!(copies.len(), 2, "the mask's art and its copy");
|
||||
for c in copies {
|
||||
let ids: Vec<NodeId> = c.children().into_iter().flatten().map(|m| m.id).collect();
|
||||
assert_eq!(ids, [NodeId(4), NodeId(5)], "each copy holds the mask's objects");
|
||||
}
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)));
|
||||
}
|
||||
|
||||
/// The linked mask of a mask's art that is copied whole takes the same Transform copies.
|
||||
#[test]
|
||||
fn the_mask_of_a_masks_art_copied_whole_takes_its_copies() {
|
||||
let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let mask_art = masked_by(parts, white_square(6), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)), "the mask's art and its copy");
|
||||
let own = &mask.extras().mask.as_deref().expect("the mask's art keeps its own mask").art;
|
||||
assert_eq!(own.geometric_bounds(), Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "its mask covers the copy too");
|
||||
}
|
||||
|
||||
/// The mask of a mask's art copied whole stays in the budget while that art is copied: when the
|
||||
/// budget has no room for that mask's copy, the art keeps its shape with its masks.
|
||||
#[test]
|
||||
fn the_mask_of_a_masks_art_copied_whole_counts_against_the_budget() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true };
|
||||
let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let mask_art = masked_by(parts, white_square(6), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the four squares and the copies of three of them, not for the copy of the fourth.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 7 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
assert_eq!(inner.geometric_bounds(), square, "the path keeps its shape");
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 15.0, 10.0)), "and so does its mask");
|
||||
}
|
||||
|
||||
/// When a member group's linked mask can't take all the Transform copies its paths take (past the
|
||||
/// budget), the art keeps its shape under the effect, so the mask still covers the paths.
|
||||
#[test]
|
||||
fn art_whose_mask_would_take_fewer_copies_keeps_its_shape() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true };
|
||||
let member = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the path, its mask and a copy of the path, not for a copy of the mask.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 3 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let member = &art.children().unwrap()[0];
|
||||
let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
assert_eq!(member.geometric_bounds(), square, "the path keeps its shape");
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), square, "and so does its mask");
|
||||
}
|
||||
|
||||
/// The copies of a path with a linked mask count the art of the mask each copy carries against the
|
||||
/// budget: they stop where the masks would pass it.
|
||||
#[test]
|
||||
fn transform_copies_count_the_art_of_their_masks() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 2}), visible: true };
|
||||
let member = masked_by(white_square(1), white_square(4), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the path, its mask and one copy of both, not for a second copy.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 4 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let copies = art.children().unwrap()[0].children().expect("the object and its copy are objects of their own");
|
||||
assert_eq!(copies.len(), 2);
|
||||
for c in copies {
|
||||
assert_eq!(c.extras().mask.as_deref().unwrap().art.geometric_bounds(), c.geometric_bounds());
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect that scales strokes moves a group's paths as objects, their masks with them.
|
||||
/// The mask of a member group, whose art holds a path with a mask of its own, moves with the group's
|
||||
/// paths too.
|
||||
#[test]
|
||||
fn a_transform_that_moves_paths_as_objects_moves_a_member_groups_nested_mask() {
|
||||
let mask_art = masked_by(white_square(4), white_square(5), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(3, 20.0, Color::BLACK)]);
|
||||
let params = serde_json::json!({"moveH": 30, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let want = inner.children().unwrap()[0].geometric_bounds();
|
||||
assert_eq!(want, Some(Rect::new(30.0, 0.0, 40.0, 10.0)));
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), want, "the group's mask");
|
||||
assert_eq!(mask.extras().mask.as_deref().unwrap().art.geometric_bounds(), want, "the mask inside its art");
|
||||
}
|
||||
|
||||
/// A group's Transform effect moves an image member's linked opacity mask with the image, and its
|
||||
/// copies' masks with the copies; an unlinked mask stays.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_an_image_members_linked_mask() {
|
||||
for linked in [true, false] {
|
||||
for copies in [0, 2] {
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), white_square(4), linked);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": copies});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let first = &art.children().unwrap()[0];
|
||||
let images: Vec<&Node> = match first.children() {
|
||||
Some(ch) => ch.iter().map(|c| &**c).collect(),
|
||||
None => vec![first],
|
||||
};
|
||||
assert_eq!(images.len(), copies + 1);
|
||||
for im in images {
|
||||
let mask = im.extras().mask.as_deref().unwrap();
|
||||
let want = if linked { im.geometric_bounds() } else { Some(Rect::new(0.0, 0.0, 10.0, 10.0)) };
|
||||
assert_eq!(mask.art.geometric_bounds(), want, "linked {linked}, copies {copies}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When a path in a member's mask art would pass the effects' budget, the whole mask stays as it
|
||||
/// was, rather than part of its art moving with the member, and the member keeps its shape with it.
|
||||
#[test]
|
||||
fn a_mask_whose_art_passes_the_budget_stays_whole() {
|
||||
// Bloat bends a path's sides into curves drawn with more lines the larger they are: many more
|
||||
// on the mask's large square.
|
||||
let bloat = Effect { id: "distort.puckerBloat".into(), params: serde_json::json!({"amount": 50}), visible: true };
|
||||
let large = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0)), Appearance::default());
|
||||
let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), Arc::new(large.clone())]);
|
||||
let member = masked_by(white_square(1), mask_art.clone(), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
// Room for the member and the mask's small square to take the effect, not for the large one.
|
||||
let bounds = art.geometric_bounds().unwrap();
|
||||
let ctx = crate::GeomContext { seed: 10, ..crate::GeomContext::of(&art) };
|
||||
let square = white_square(1).path_data().cloned().unwrap();
|
||||
let made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), &square, bounds, &ctx)).lines;
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 2 * made + crate::Budget::of(large.path_data().unwrap()).lines };
|
||||
let large_made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), large.path_data().unwrap(), bounds, &ctx)).lines;
|
||||
assert!(large_made > crate::Budget::of(large.path_data().unwrap()).lines, "the large square's curves cost more lines");
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&bloat], budget, None);
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.path_data(), Some(&square), "the member keeps its shape with its mask");
|
||||
assert_eq!(*member.extras().mask.as_deref().unwrap().art, mask_art, "the mask stays whole");
|
||||
}
|
||||
|
||||
/// Live objects in a member's linked mask are evaluated before the group's geometry effects run
|
||||
/// over the mask's art, so the mask still covers the member: a Repeat in it moves and bends with
|
||||
/// the member.
|
||||
#[test]
|
||||
fn a_groups_effects_reshape_a_live_object_in_a_members_mask() {
|
||||
let mut grid = vectorcraft_doc::RepeatSpec::grid(vec![Arc::new(white_square(5))], 0.0, 0.0);
|
||||
if let vectorcraft_doc::RepeatKind::Grid { rows, cols, .. } = &mut grid.kind {
|
||||
(*rows, *cols) = (1, 1);
|
||||
}
|
||||
let repeat = Node::new(NodeId(4), NodeKind::Repeat(grid));
|
||||
let drawn: Vec<Node> = crate::expand_live(None, &repeat);
|
||||
let leaf = |n: &Node| {
|
||||
let mut found = None;
|
||||
n.walk(&mut |c| found = found.take().or_else(|| c.path_data().cloned()));
|
||||
found
|
||||
};
|
||||
assert_eq!(drawn.iter().find_map(leaf), white_square(1).path_data().cloned(), "the Repeat draws one square over the member");
|
||||
for e in [reshaping_effects()[0].clone(), reshaping_effects()[4].clone()] {
|
||||
let member = masked_by(white_square(1), repeat.clone(), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = &member.extras().mask.as_deref().unwrap().art;
|
||||
assert!(member.path_data() != white_square(1).path_data(), "{}: the member is reshaped", e.id);
|
||||
assert_eq!(leaf(mask), member.path_data().cloned(), "{}: the mask's square takes the effect with it", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Type in a member's linked mask is outlined before the group's Transform effect moves the mask's
|
||||
/// art with the member.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_type_in_a_members_mask() {
|
||||
if skip_without_craft_fonts() {
|
||||
return;
|
||||
}
|
||||
let member = masked_by(white_square(1), type_h(), true);
|
||||
let before = crate::reshape::outline_text(&type_h()).unwrap().geometric_bounds().unwrap();
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
let mut text = false;
|
||||
mask.walk(&mut |c| text |= matches!(c.kind, NodeKind::Text(_)));
|
||||
assert!(!text, "the type is outlined");
|
||||
let after = mask.geometric_bounds().unwrap();
|
||||
assert!((after.x0 - before.x0 - 30.0).abs() < 0.5 && (after.y0 - before.y0).abs() < 0.5, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
/// The linked mask of a compound path in a group, and of a path in a layer, takes the geometry
|
||||
/// effects with the art it masks.
|
||||
#[test]
|
||||
fn a_compound_paths_and_a_layers_members_masks_take_the_effects() {
|
||||
let geometry = |n: &Node| crate::reshape::leaf_geometry(n).map(|(p, _)| p);
|
||||
for e in reshaping_effects() {
|
||||
let square = white_square(1);
|
||||
let compound = Node::new(NodeId(1), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: FillRule::NonZero });
|
||||
let compound = masked_by(compound, white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(compound), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert!(geometry(member) != square.path_data().cloned(), "{}: the compound path is reshaped", e.id);
|
||||
assert_eq!(geometry(&member.extras().mask.as_deref().unwrap().art), geometry(member), "{}: compound path", e.id);
|
||||
|
||||
let mut layer = Node::layer(NodeId(10), "Layer", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
ch.extend([Arc::new(masked_by(square.clone(), white_square(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
}
|
||||
layer.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &layer).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert!(member.path_data() != square.path_data(), "{}: the layer's path is reshaped", e.id);
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.path_data(), member.path_data(), "{}: layer", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect moves a symbol instance member's linked mask with the instance.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_a_symbol_instance_members_linked_mask() {
|
||||
let instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(instance, white_square(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let instance = &art.children().unwrap()[0];
|
||||
let NodeKind::SymbolInstance { xf, .. } = &instance.kind else { panic!("an instance: {instance:?}") };
|
||||
assert!((xf.translation().x - 30.0).abs() < 1e-9, "the instance moves: {xf:?}");
|
||||
let mask = instance.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
|
||||
assert!((mask.x0 - 30.0).abs() < 1e-9 && (mask.x1 - 40.0).abs() < 1e-9, "its mask moves with it: {mask:?}");
|
||||
}
|
||||
|
||||
/// With Scale Strokes & Effects on, a group's Transform effect scales the stroke of an image
|
||||
/// member's linked mask as it scales that of a path member's mask.
|
||||
#[test]
|
||||
fn a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike() {
|
||||
let stroked =
|
||||
Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0));
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), stroked.clone(), true);
|
||||
let path = masked_by(white_square(2), stroked, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image), Arc::new(path)]);
|
||||
let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let width = |n: &Node| n.extras().mask.as_deref().unwrap().art.appearance.stroke().map(|s| s.width);
|
||||
let ch = art.children().unwrap();
|
||||
assert_eq!(width(&ch[1]), Some(4.0), "the path's mask");
|
||||
assert_eq!(width(&ch[0]), width(&ch[1]), "the image's mask");
|
||||
}
|
||||
|
||||
/// With Transform Objects off and Scale Strokes & Effects on, a group's Transform effect scales the
|
||||
/// strokes of a member's linked mask as it scales the member's, and moves neither.
|
||||
#[test]
|
||||
fn a_transform_of_strokes_only_scales_a_members_mask_strokes() {
|
||||
let stroked = |id: u64| {
|
||||
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0))
|
||||
};
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(stroked(1), stroked(4), true))]);
|
||||
let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = &member.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(member.appearance.stroke().map(|s| s.width), Some(4.0), "the member's stroke");
|
||||
assert_eq!(mask.appearance.stroke().map(|s| s.width), Some(4.0), "the mask's stroke");
|
||||
assert_eq!(mask.geometric_bounds(), member.geometric_bounds());
|
||||
}
|
||||
|
||||
/// The art of a member group's mask is copied as it was before the first effect: a mask of one
|
||||
/// path takes a second Transform effect's copies path by path, as the path it masks does, though
|
||||
/// the first effect (with Scale Strokes & Effects) made it a group of copies.
|
||||
#[test]
|
||||
fn a_masks_art_is_copied_as_it_was_before_the_first_effect() {
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
for strokes in [true, false] {
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2, "strokes": strokes});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), inner.geometric_bounds());
|
||||
let kinds = |n: &Node| n.children().unwrap().iter().map(|c| std::mem::discriminant(&c.kind)).collect::<Vec<_>>();
|
||||
let paths = &inner.children().unwrap()[0];
|
||||
assert_eq!(kinds(paths).len(), 3, "the first effect's three paths");
|
||||
assert!(paths.children().unwrap().iter().all(|c| matches!(c.kind, NodeKind::Compound { .. })), "each with its copies");
|
||||
assert_eq!(kinds(mask), kinds(paths), "the mask's art takes the copies as the paths do");
|
||||
}
|
||||
|
||||
/// A 10 × 10 image with id `id` at the origin.
|
||||
fn image_node(id: u64) -> Node {
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
Node::new(NodeId(id), NodeKind::Image(Box::new(im)))
|
||||
}
|
||||
|
||||
/// A linked mask whose art is an image moves with the path it masks under a group's Transform
|
||||
/// effect, and a member group's image mask takes the copies its paths take.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_a_linked_mask_whose_art_is_an_image() {
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(white_square(1), image_node(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.geometric_bounds(), Some(Rect::new(30.0, 0.0, 40.0, 10.0)));
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), member.geometric_bounds());
|
||||
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), image_node(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
assert_eq!(inner.geometric_bounds(), Some(Rect::new(0.0, 0.0, 70.0, 10.0)));
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), inner.geometric_bounds(), "the image and its copies");
|
||||
}
|
||||
|
||||
/// An image in a linked mask's art takes no geometry effect but Transform, so under a Warp effect
|
||||
/// the art keeps its shape with its mask.
|
||||
#[test]
|
||||
fn art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp() {
|
||||
let member = masked_by(white_square(1), Node::group(NodeId(3), vec![Arc::new(image_node(4))]), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[4].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.path_data(), white_square(1).path_data(), "the path keeps its shape");
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), Some(Rect::new(0.0, 0.0, 10.0, 10.0)));
|
||||
}
|
||||
|
||||
/// A Warp effect bends an image's pixels but not the art of its linked mask, so art with such an
|
||||
/// image keeps its shape under the warp, with the image and its mask.
|
||||
#[test]
|
||||
fn art_with_a_masked_image_keeps_its_shape_under_a_warp() {
|
||||
let image = masked_by(image_node(1), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image.clone()), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[4].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert_eq!(*ch[0], image, "the image and its mask");
|
||||
assert_eq!(ch[1].path_data(), sq(2, 20.0, Color::BLACK).path_data(), "the path keeps its shape");
|
||||
}
|
||||
|
||||
/// A symbol instance in perspective projects the linked masks of the objects in its art with them.
|
||||
#[test]
|
||||
fn perspective_projects_the_masks_in_a_symbols_art() {
|
||||
let art = Node::group(NodeId(20), vec![Arc::new(masked_by(white_square(21), white_square(22), true))]);
|
||||
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let mut at = vectorcraft_doc::PerspectiveAttachment::new("left", 0.0);
|
||||
at.projection = Some([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.01, 0.0, 1.0]);
|
||||
instance.extras_mut().perspective = Some(Box::new(at));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap();
|
||||
let mut masked = vec![];
|
||||
out.walk(&mut |c| masked.extend(c.extras().mask.as_deref().map(|m| (c.path_data().cloned(), m.art.path_data().cloned()))));
|
||||
let [(path, mask)] = masked.as_slice() else { panic!("one masked path: {masked:?}") };
|
||||
assert!(path != &white_square(21).path_data().cloned(), "the path is projected");
|
||||
assert_eq!(mask, path, "and so is its mask");
|
||||
}
|
||||
|
||||
/// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit
|
||||
/// pitch, each crossing every bar of the other direction: n² crossings.
|
||||
fn crossing_bars(n: usize, effect: &str) -> Node {
|
||||
|
||||
@@ -83,18 +83,20 @@ pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
|
||||
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
|
||||
};
|
||||
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in};
|
||||
pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
};
|
||||
pub use solids::{
|
||||
CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options,
|
||||
classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, solid_art_in, three_d_meshes, three_d_meshes_in,
|
||||
three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at,
|
||||
validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES,
|
||||
classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_classic_three_d, is_three_d, solid_art, solid_art_in,
|
||||
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in,
|
||||
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
pub use trap::TRAP;
|
||||
pub use vectorcraft_three_d::Mesh;
|
||||
pub use warp::{WarpStyle, warp_point};
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version};
|
||||
|
||||
mod catalog;
|
||||
mod geometry;
|
||||
|
||||
@@ -31,7 +31,8 @@ pub fn merged_params(id: &str, params: &Value) -> Value {
|
||||
/// (`lightRotation`, `lightHeight`, `lightBehind`). Scribble took one `variation` before its
|
||||
/// separate `overlapVariation` and `spacingVariation`. Earlier values (from a file or a script of
|
||||
/// then) become the current ones that show exactly the same, unless those are given too, which win.
|
||||
/// Scribble's angle is also stored above -180° and up to 180° (270° becomes -90°).
|
||||
/// Scribble's angle is also stored above -180° and up to 180° (270° becomes -90°), and a Warp's
|
||||
/// map `version` given as a whole float is stored as an integer.
|
||||
pub fn upgrade_params(id: &str, params: &Value) -> Value {
|
||||
match params {
|
||||
Value::Object(m) => {
|
||||
@@ -39,6 +40,7 @@ pub fn upgrade_params(id: &str, params: &Value) -> Value {
|
||||
upgrade_perspective(id, &mut m);
|
||||
upgrade_light(id, &mut m);
|
||||
upgrade_scribble(id, &mut m);
|
||||
upgrade_warp_version(id, &mut m);
|
||||
Value::Object(m)
|
||||
}
|
||||
other => other.clone(),
|
||||
@@ -71,6 +73,19 @@ fn upgrade_perspective(id: &str, m: &mut Map<String, Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Warp's map `version` given as a whole float (`1.0`) is stored as the integer.
|
||||
fn upgrade_warp_version(id: &str, m: &mut Map<String, Value>) {
|
||||
if !id.starts_with("warp.") {
|
||||
return;
|
||||
}
|
||||
if let Some(v) = m.get_mut("version")
|
||||
&& !v.is_u64()
|
||||
&& let Some(n) = crate::warp::warp_version(v)
|
||||
{
|
||||
*v = json!(n);
|
||||
}
|
||||
}
|
||||
|
||||
fn upgrade_scribble(id: &str, m: &mut Map<String, Value>) {
|
||||
if id != "stylize.scribble" {
|
||||
return;
|
||||
@@ -91,7 +106,15 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
|
||||
if !catalog_index().contains_key(id) {
|
||||
vectorcraft_plugins::effect::installed(id)?;
|
||||
}
|
||||
Some(Effect { id: id.to_string(), params: merged_params(id, params), visible: true })
|
||||
let mut params = merged_params(id, params);
|
||||
// A new Warp takes its style's Bézier net unless a map is given; the catalog's defaults carry
|
||||
// no version, so warps saved without one keep the earlier map.
|
||||
if id.starts_with("warp.")
|
||||
&& let Value::Object(m) = &mut params
|
||||
{
|
||||
m.entry("version").or_insert(json!(crate::warp::WARP_NET));
|
||||
}
|
||||
Some(Effect { id: id.to_string(), params, visible: true })
|
||||
}
|
||||
|
||||
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
|
||||
|
||||
+698
-66
@@ -4,19 +4,22 @@
|
||||
//! Geometry effects reach them through outlines: [`outline_art`] turns the object into plain paths
|
||||
//! (glyph outlines, the evaluated live object, the symbol's art) and [`reshape`] runs each effect
|
||||
//! over all of them as one piece, with the whole art's bounds as the effect's reference box, so a
|
||||
//! warp bends a line of type as a whole. An image is clipped by its reshaped frame. Raster effects
|
||||
//! (shadows, glows, blur, feather) stay on the result for the renderer and exporters. Type without
|
||||
//! warp bends a line of type as a whole. An image is clipped by its reshaped frame, and a Warp
|
||||
//! effect bends its pixels with the frame ([`cut_warped_images`]). Raster effects (shadows, glows, blur,
|
||||
//! feather) stay on the result for the renderer and exporters. Type without
|
||||
//! inline graphics whose own fills or strokes have geometry effects is outlined too: each of those
|
||||
//! effects reshapes the whole outline that its fill or stroke paints. An image's own fills and
|
||||
//! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives
|
||||
//! them ([`image_rows`]).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use vectorcraft_doc::live::Hooks;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, shapes};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes};
|
||||
|
||||
use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params};
|
||||
|
||||
@@ -548,7 +551,14 @@ fn as_art_opts(
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Image(im) => {
|
||||
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
|
||||
let image = Node::new(n.id, n.kind.clone());
|
||||
let mut image = Node::new(n.id, n.kind.clone());
|
||||
// Its pixels draw as the image's do: colorized by a grayscale image's fill color, and
|
||||
// smoothed or not.
|
||||
{
|
||||
let mut e = image.extras_mut();
|
||||
e.colorize = n.extras().colorize.clone();
|
||||
e.pixelated = n.extras().pixelated;
|
||||
}
|
||||
let clipped = || {
|
||||
let mut clip = Node::path(n.id, frame.clone(), Appearance::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
@@ -580,7 +590,7 @@ fn as_art_opts(
|
||||
transform_items(&mut art, paint_doc);
|
||||
// Type and symbols in perspective: the art projected onto their plane.
|
||||
if let Some(h) = n.projection() {
|
||||
project_leaves(&mut art, &h);
|
||||
project_leaves(&mut art, &h, paint_doc);
|
||||
}
|
||||
// The art is a group with `n`'s id (for an image without fills or strokes that paint, a clip
|
||||
// group).
|
||||
@@ -598,9 +608,29 @@ fn as_art_opts(
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Map every path under `art` (and its gradients) through the projective map `h`, curves split
|
||||
/// finely enough to follow it.
|
||||
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
/// Map every path under `art` (and its gradients), and every path in the art of the linked opacity
|
||||
/// masks of the objects under it, through the projective map `h`, curves split finely enough to
|
||||
/// follow it. The type and live objects in the art of those masks are outlined and evaluated
|
||||
/// first ([`outlined_members`], with the symbols of `doc`).
|
||||
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
|
||||
project_paths(art, h);
|
||||
each_linked_mask_mut(art, false, 0, &mut |m| {
|
||||
*m = outlined_mask_art(doc, m);
|
||||
project_paths(m, h);
|
||||
});
|
||||
}
|
||||
|
||||
/// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated
|
||||
/// ([`outlined_members`]), and as art that keeps its look ([`as_art`]) when it is type itself.
|
||||
fn outlined_mask_art(doc: Option<&Document>, art: &Node) -> Node {
|
||||
match art.kind {
|
||||
NodeKind::Text(_) => as_art(doc, art, None).unwrap_or_else(|| art.clone()),
|
||||
_ => outlined_members(doc, art),
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths of [`project_leaves`] outside the art of masks.
|
||||
fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
let f = |p: vectorcraft_geom::Point| h.apply(p).unwrap_or(p);
|
||||
let piece = art.geometric_bounds().map_or(1.0, |b| (b.width().max(b.height()) / 64.0).max(0.25));
|
||||
let project = |path: &mut PathData| *path = vectorcraft_doc::live::map_nonlinear(path, piece, f);
|
||||
@@ -632,9 +662,9 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
|
||||
|
||||
/// Apply `fx` to every path under `art` as one piece: each effect takes the whole art's bounds as
|
||||
/// its reference box and the art's seed (a random Transform moves the pieces together). Images and
|
||||
/// symbol instances follow a Transform effect the same way ([`transform_placed`]); other geometry
|
||||
/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The
|
||||
/// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path
|
||||
/// symbol instances follow a Transform effect the same way ([`transform_placed`]), and images
|
||||
/// follow a Warp effect as a raster mesh warp ([`cut_warped_images`]); other geometry effects leave them
|
||||
/// as they are. The paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path
|
||||
/// whose effect would pass what the others leave of it keeps its shape. The swatches and patterns
|
||||
/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one
|
||||
/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]).
|
||||
@@ -677,57 +707,151 @@ fn hoist_copies(art: &mut Node) {
|
||||
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
|
||||
/// Returns how gradients that paint the art as a whole follow the effects. A deferred live-effect
|
||||
/// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when
|
||||
/// `owner` does not hold it.
|
||||
/// `owner` does not hold it. The art of the linked opacity masks of the objects in `art` (not of
|
||||
/// `art` itself) takes each effect as the paths it masks do ([`Step::reshape_masks`]), with the
|
||||
/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask
|
||||
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
|
||||
/// masks keeps its shape under that effect.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
|
||||
let mut whole = crate::Carry::default();
|
||||
if fx.is_empty() {
|
||||
return whole;
|
||||
}
|
||||
let mut leaves_safe = true;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
if !leaves_safe {
|
||||
return;
|
||||
}
|
||||
if let Some((_, rule)) = leaf_geometry(leaf) {
|
||||
let has_stroke = leaf.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
if rule != FillRule::NonZero || has_stroke {
|
||||
leaves_safe = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
let masked = has_linked_mask(art, false);
|
||||
if masked {
|
||||
each_linked_mask_mut(art, false, 0, &mut |m| *m = outlined_mask_art(doc, m));
|
||||
}
|
||||
let mut masks_safe = true;
|
||||
each_linked_mask(art, false, 0, &mut |_, m| masks_safe &= leaves_safe(m));
|
||||
let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
let style_safe = leaves_safe && !art_stroke;
|
||||
let style_safe = leaves_safe(art) && masks_safe && !art_stroke;
|
||||
let listed = fx;
|
||||
let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe);
|
||||
let fx = opt_fx.as_slice();
|
||||
let seed = art.id.0;
|
||||
let mut used = art_cost(art);
|
||||
each_linked_mask(art, false, 0, &mut |_, m| used = used.plus(art_cost(m)));
|
||||
let max = budget.at_least(used);
|
||||
// Read before the effects run: a path's own copies don't make it art of several objects.
|
||||
// Read before the effects run: a path's own copies don't make it art of several objects. The
|
||||
// same holds for the art of each mask, listed by the object it masks.
|
||||
let copy_whole = copies_whole(art);
|
||||
let mut wholes = HashMap::new();
|
||||
each_linked_mask(art, false, 0, &mut |id, m| {
|
||||
wholes.entry(id).or_insert_with(|| copies_whole(m));
|
||||
});
|
||||
let mut warped = WarpedImages::new();
|
||||
for e in fx {
|
||||
let Some(bounds) = art.geometric_bounds() else { break };
|
||||
let Some(bounds) = warped.bounds(art) else { break };
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
|
||||
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes };
|
||||
// Art with linked masks keeps its shape under an effect that a mask in it could not take
|
||||
// as the art it masks did, so no mask is left apart from its art.
|
||||
let before = masked.then(|| (art.clone(), used));
|
||||
let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0);
|
||||
if (ran.masks || ran.short)
|
||||
&& let Some((was, cost)) = before
|
||||
{
|
||||
*art = was;
|
||||
used = cost;
|
||||
continue;
|
||||
}
|
||||
if let Some(carry) = ran.whole {
|
||||
whole.push(carry);
|
||||
}
|
||||
}
|
||||
cut_warped_images(art, &warped);
|
||||
whole
|
||||
}
|
||||
|
||||
/// One geometry effect of an object run over its art ([`reshape_leaves_apart`]): the effect, its
|
||||
/// merged params, the reference box and seed of the object's art, where a deferred live-effect
|
||||
/// plug-in is listed, whether each Transform copy becomes an object, the document that the
|
||||
/// swatches and patterns of painted pieces are looked up in, and [`copies_whole`] of the art of
|
||||
/// each linked mask before the first effect, by the id of the object it masks.
|
||||
struct Step<'a> {
|
||||
e: &'a Effect,
|
||||
params: &'a serde_json::Value,
|
||||
bounds: Rect,
|
||||
seed: u64,
|
||||
effect: Option<usize>,
|
||||
apart: bool,
|
||||
doc: Option<&'a Document>,
|
||||
wholes: &'a HashMap<NodeId, bool>,
|
||||
}
|
||||
|
||||
/// What [`Step::run`] did to a piece of art.
|
||||
struct Ran {
|
||||
/// A path in the art kept its shape (past the budget).
|
||||
kept: bool,
|
||||
/// The linked opacity mask of an object in the art stayed as it was while the paths it masks
|
||||
/// took the effect, or could have ([`Step::reshape_masks`]).
|
||||
masks: bool,
|
||||
/// A Transform effect made fewer copies of a path, image or symbol instance than it asks for
|
||||
/// (past the budget or out of reach), where a linked mask could take a different number.
|
||||
short: bool,
|
||||
/// How what paints the art as a whole follows the effect, when it does.
|
||||
whole: Option<crate::Carry>,
|
||||
}
|
||||
|
||||
impl Ran {
|
||||
/// Nothing in the art kept its shape or made fewer copies, and every linked mask in it moved.
|
||||
fn complete(&self) -> bool {
|
||||
!self.kept && !self.masks && !self.short
|
||||
}
|
||||
}
|
||||
|
||||
impl Step<'_> {
|
||||
/// Run the effect over `art`, whose paths and those of the linked opacity masks in it keep to
|
||||
/// `max` together with what they cost so far (`used`). `copy_whole` is [`copies_whole`] of the
|
||||
/// art, or of a mask's art, before the first effect. `warped` lists the images Warp effects
|
||||
/// bend in the art ([`WarpedImages`]); a mask's art has none. With `own`, `art` is the art of a
|
||||
/// mask, and its own linked mask takes the effect too. `depth` counts the masks `art` is in. A
|
||||
/// live-effect plug-in that paints its pieces leaves a mask's art, and art that holds objects
|
||||
/// with linked masks, as they are and reports the masks as stayed: a mask can't take the
|
||||
/// pieces as the art it masks does. So does a Warp effect that bends an image with a linked
|
||||
/// mask.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn run(
|
||||
&self,
|
||||
art: &mut Node,
|
||||
max: Budget,
|
||||
used: &mut Budget,
|
||||
copy_whole: bool,
|
||||
mut warped: Option<&mut WarpedImages>,
|
||||
own: bool,
|
||||
depth: usize,
|
||||
) -> Ran {
|
||||
let (e, params, bounds, seed) = (self.e, self.params, self.bounds, self.seed);
|
||||
let stayed = Ran { kept: false, masks: true, short: false, whole: None };
|
||||
if let Some(plugin) = painted_plugin(e) {
|
||||
let at = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
|
||||
if own || has_linked_mask(art, false) {
|
||||
return stayed;
|
||||
}
|
||||
let at = self.effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
let Some((path, _)) = leaf_geometry(leaf) else { return };
|
||||
let before = Budget::of(&path);
|
||||
let room = max.minus(used.minus(before));
|
||||
if let Some(made) = paint_leaf(leaf, plugin, ¶ms, bounds, room, doc, at) {
|
||||
used = used.minus(before).plus(made);
|
||||
if let Some(made) = paint_leaf(leaf, plugin, params, bounds, room, self.doc, at) {
|
||||
*used = used.minus(before).plus(made);
|
||||
}
|
||||
});
|
||||
continue;
|
||||
return Ran { kept: false, masks: false, short: false, whole: None };
|
||||
}
|
||||
// A Warp effect that bends images ([`mark_warped_images`]) bends an image's pixels, not the
|
||||
// art of its linked mask.
|
||||
let warp = e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).filter(|_| crate::warp::bends(&e.id, params));
|
||||
if warp.is_some() && has_masked_image(art) {
|
||||
return stayed;
|
||||
}
|
||||
// Placed gradients follow a Transform effect, Free Distort and the Warp effects
|
||||
// ([`crate::Carry`]): under Free Distort and Warp (`boxes`) each path's move and scale from
|
||||
// its bounds before the effect to its bounds after it. Under those and the other effects,
|
||||
// the placed gradients of type's outlines in `art` (`outline_text`) move and scale with
|
||||
// the outlines' bounds.
|
||||
let follows = crate::Carry::follows(&e.id, ¶ms, bounds, seed);
|
||||
let follows = crate::Carry::follows(&e.id, params, bounds, seed);
|
||||
let boxes = follows && crate::Carry::by_bounds(&e.id);
|
||||
let mut outlines = vec![];
|
||||
if !follows || boxes {
|
||||
@@ -739,24 +863,68 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
}
|
||||
let mut groups = vec![];
|
||||
if follows {
|
||||
group_marks(art, &mut vec![], &HashSet::new(), &mut groups);
|
||||
group_marks(art, &mut vec![], &HashSet::new(), None, &mut groups);
|
||||
// The images earlier Warps bend are measured by their pieces only when a group's
|
||||
// gradient needs the bounds.
|
||||
if !groups.is_empty()
|
||||
&& let Some(images) = warped.as_deref().and_then(|w| w.when_cut(art))
|
||||
{
|
||||
groups.clear();
|
||||
group_marks(art, &mut vec![], &HashSet::new(), Some(images), &mut groups);
|
||||
}
|
||||
}
|
||||
// The ids of the paths that kept their shape (past the budget).
|
||||
// The ids of the paths that kept their shape (past the budget), and their places in the
|
||||
// order [`for_each_leaf`] visits the paths; and the ids of the paths whose linked masks
|
||||
// moved with them as they were transformed as objects.
|
||||
let mut kept_ids = HashSet::new();
|
||||
let mut kept_leaves = HashSet::new();
|
||||
let mut leaf_at = 0usize;
|
||||
let mut moved_ids = HashSet::new();
|
||||
let transform = (e.id == "distort.transform").then(|| {
|
||||
let (m, copies) = crate::distort::transform_map(bounds, ¶ms, seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
(m, copies, options, crate::distort::transform_affine(bounds, ¶ms, seed))
|
||||
let (m, copies) = crate::distort::transform_map(bounds, params, seed);
|
||||
let options = crate::distort::TransformOptions::of(params);
|
||||
(m, copies, options, crate::distort::transform_affine(bounds, params, seed))
|
||||
});
|
||||
// In a mask's art, images and symbol instances take only a Transform effect
|
||||
// ([`transform_placed`]): a mask's art that holds one can't take another effect as the art
|
||||
// it masks does.
|
||||
if own && transform.is_none() && (is_placed(art) || placed_count(art) > 0) {
|
||||
return Ran { kept: false, masks: true, short: false, whole: None };
|
||||
}
|
||||
// Art of several objects is copied whole, so the copies don't interleave member by member.
|
||||
// The copies of its members carry their linked masks, moved with them.
|
||||
if let Some((m, copies, options, _)) = transform
|
||||
&& copies > 0
|
||||
&& copy_whole
|
||||
{
|
||||
used = copy_art(art, m, copies, copy_scaling(options), max);
|
||||
continue;
|
||||
if !own {
|
||||
*used = copy_art(art, m, copies, copy_scaling(options), max);
|
||||
return Ran { kept: false, masks: false, short: false, whole: None };
|
||||
}
|
||||
// A mask's art: its copies keep to what the rest of the art leaves of `max`, and the
|
||||
// linked mask of the art itself takes them too. That mask's art stays in `used`, as
|
||||
// [`copy_art`] counts only the members.
|
||||
let before = copy_cost(art);
|
||||
let rest = used.minus(before).plus(art.extras().mask.as_deref().map_or(Budget { anchors: 0, lines: 0 }, |k| copy_cost(&k.art)));
|
||||
let made = copy_art(art, m, copies, copy_scaling(options), max.minus(rest));
|
||||
*used = rest.plus(made);
|
||||
let short = art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies);
|
||||
let none = HashSet::new();
|
||||
let masks = self.reshape_own_mask(art, &Skip { moved: &none, kept: &none }, max, used, depth);
|
||||
return Ran { kept: false, masks, short, whole: None };
|
||||
}
|
||||
// A shortfall in the copies matters for the objects a linked mask above them covers, which
|
||||
// the mask would take a different number of copies than, and anywhere in a mask's art.
|
||||
let watch = transform.is_some_and(|(_, copies, options, _)| copies > 0 && options.objects) && (own || has_linked_mask(art, false));
|
||||
let mut covered = HashSet::new();
|
||||
if watch && !own {
|
||||
masked_ids(art, false, &mut covered);
|
||||
}
|
||||
let counts = |id: NodeId| watch && (own || covered.contains(&id));
|
||||
let mut short = false;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
let at = leaf_at;
|
||||
leaf_at += 1;
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
// What the other paths leave of the budget.
|
||||
let before = Budget::of(&path);
|
||||
@@ -766,15 +934,26 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
// strokes; a gradient paints each copy by itself, not the one piece the copies
|
||||
// make together; and Expand Appearance (`apart`) makes each copy an object.
|
||||
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
|
||||
// Each copy of a path with a linked mask carries the mask, moved with it.
|
||||
let separate = copies > 0
|
||||
&& (apart
|
||||
&& (self.apart
|
||||
|| leaf.appearance.has_unplaced_gradient()
|
||||
|| leaf.appearance.has_placed_gradient()
|
||||
|| paints_copies_apart(&leaf.appearance, rule));
|
||||
|| paints_copies_apart(&leaf.appearance, rule)
|
||||
|| leaf.extras().mask.as_ref().is_some_and(|m| m.linked));
|
||||
// The copies of a path replace it by a group of them, the path included.
|
||||
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
|
||||
if options.reach_appearance() {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
used = used.minus(before).plus(made);
|
||||
if !moved {
|
||||
*used = used.minus(before).plus(made);
|
||||
if moved {
|
||||
// With Transform Objects off the path stays, and its mask takes the
|
||||
// effect's stroke and pattern changes as its own art.
|
||||
if options.objects {
|
||||
moved_ids.insert(leaf.id);
|
||||
}
|
||||
short |= counts(leaf.id) && copied(leaf) <= copies;
|
||||
} else {
|
||||
kept_ids.insert(leaf.id);
|
||||
}
|
||||
return;
|
||||
@@ -782,19 +961,28 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
if separate {
|
||||
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
|
||||
let made = copy_leaf(leaf, &path, m, copies, scaling, room);
|
||||
used = used.minus(before).plus(made);
|
||||
*used = used.minus(before).plus(made);
|
||||
moved_ids.insert(leaf.id);
|
||||
short |= counts(leaf.id) && copied(leaf) <= copies;
|
||||
return;
|
||||
}
|
||||
}
|
||||
let stage = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
|
||||
let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else {
|
||||
let stage = self.effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
|
||||
let Some(out) = apply_one(&e.id, params, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else {
|
||||
kept_ids.insert(leaf.id);
|
||||
kept_leaves.insert(at);
|
||||
return;
|
||||
};
|
||||
used = used.minus(before).plus(Budget::of(&out));
|
||||
// A Transform effect's copies of a path are subpaths of it, each with the path's anchors.
|
||||
if counts(leaf.id)
|
||||
&& let Some((_, copies, _, _)) = transform
|
||||
{
|
||||
short |= out.anchor_count() < path.anchor_count().saturating_mul(copies.saturating_add(1));
|
||||
}
|
||||
*used = used.minus(before).plus(Budget::of(&out));
|
||||
if follows && !boxes {
|
||||
// A gradient fitted to the path fits the path's own bounds.
|
||||
let carry = crate::Carry::of(&e.id, ¶ms, bounds, path.bounds(), None, seed);
|
||||
let carry = crate::Carry::of(&e.id, params, bounds, path.bounds(), None, seed);
|
||||
if carry.moves(&leaf.appearance) {
|
||||
carry.apply(&mut leaf.appearance);
|
||||
}
|
||||
@@ -804,27 +992,233 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
if boxes {
|
||||
rebase_leaves(art, &mut leaves.into_iter());
|
||||
}
|
||||
// Warp bends images too: each one's pixels follow the warp's map over the same box. The
|
||||
// images are cut into pieces once, after the last effect ([`cut_warped_images`]). An image
|
||||
// whose clipping frame kept its shape (past the budget) keeps its pixels as they are.
|
||||
if let Some(style) = warp
|
||||
&& let Some(warped) = warped.as_deref_mut()
|
||||
{
|
||||
let f: WarpMap = Rc::from(crate::warp::warp_map(bounds, style, params));
|
||||
warped.reserve(art);
|
||||
mark_warped_images(art, &f, &kept_leaves, false, &mut 0, warped);
|
||||
}
|
||||
if let Some((m, copies, options, _)) = transform
|
||||
&& options.objects
|
||||
{
|
||||
transform_placed(art, m, copies);
|
||||
// A mask's art that is one image or symbol instance is placed as the only member of a
|
||||
// group of it.
|
||||
let root = is_placed(art);
|
||||
if root {
|
||||
let id = art.id;
|
||||
let one = std::mem::replace(art, Node::group(id, vec![]));
|
||||
*art = Node::group(id, vec![Arc::new(one)]);
|
||||
}
|
||||
let placed = if watch { masked_placed(art, own) } else { 0 };
|
||||
transform_placed(art, m, copies, copy_scaling(options));
|
||||
short |= watch && masked_placed(art, own) < placed.saturating_mul(copies.saturating_add(1));
|
||||
if root && let Some([one]) = art.children().map(Vec::as_slice) {
|
||||
*art = (**one).clone();
|
||||
}
|
||||
}
|
||||
if outlines.iter().any(Option::is_some) {
|
||||
rebase_type_outlines(art, &mut outlines.into_iter());
|
||||
}
|
||||
// Under Transform copies, a mask takes the copies as the paths it masks do; the copies of a
|
||||
// path with a mask of its own each carry it ([`copy_leaf`]).
|
||||
let masks = self.reshape_masks(art, own, &Skip { moved: &moved_ids, kept: &kept_ids }, max, used, depth);
|
||||
// What paints the art as a whole, and the own fills and strokes of the groups inside it,
|
||||
// follow their bounds under Free Distort and Warp (they stay when no path changed them).
|
||||
// Each stays when a path under it that its bounds measure kept its shape (past the budget).
|
||||
let mut after = vec![];
|
||||
let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, &mut after).1;
|
||||
let images = if groups.is_empty() { None } else { warped.as_deref().and_then(|w| w.when_cut(art)) };
|
||||
let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, images, &mut after).1;
|
||||
if !groups.is_empty() {
|
||||
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, ¶ms, bounds, from, to, seed));
|
||||
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed));
|
||||
}
|
||||
if follows && !held {
|
||||
whole.push(crate::Carry::of(&e.id, ¶ms, bounds, Some(bounds), art.geometric_bounds(), seed));
|
||||
let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art));
|
||||
let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed));
|
||||
Ran { kept: !kept_ids.is_empty(), masks, short, whole }
|
||||
}
|
||||
|
||||
/// Run the effect over the art of the linked opacity mask of `n` (with `own`) and of each path,
|
||||
/// compound path, group and layer under it, with the art's reference box, as the paths the mask
|
||||
/// covers take it: the mask moves and bends with what it masks. The mask of an object
|
||||
/// transformed as an object moved with it already and is left as it is. A mask stays as it was
|
||||
/// past [`vectorcraft_doc::depth::MAX_DEPTH`] masks inside masks, and for the reasons
|
||||
/// [`Step::reshape_own_mask`] gives. Returns whether a mask stayed for one of those reasons.
|
||||
fn reshape_masks(&self, n: &mut Node, own: bool, skip: &Skip, max: Budget, used: &mut Budget, depth: usize) -> bool {
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_linked_mask(n, own) {
|
||||
return false;
|
||||
}
|
||||
let mut stayed = own && self.reshape_own_mask(n, skip, max, used, depth);
|
||||
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind {
|
||||
for c in children.iter_mut() {
|
||||
if has_linked_mask(c, true) {
|
||||
stayed |= self.reshape_masks(Arc::make_mut(c), true, skip, max, used, depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
stayed
|
||||
}
|
||||
|
||||
/// Run the effect over the art of the linked opacity mask of `n` itself, when `n` is a path,
|
||||
/// compound path, group or layer that `skip` does not list as moved. The mask stays as it was
|
||||
/// when a path it masks kept its shape, and when its own art could not take the effect whole: a
|
||||
/// path in it would keep its shape, its copies would stop short, or a mask inside it would stay
|
||||
/// (no mask is left half moved). Returns whether the mask stayed for one of those reasons.
|
||||
fn reshape_own_mask(&self, n: &mut Node, skip: &Skip, max: Budget, used: &mut Budget, depth: usize) -> bool {
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !reshapes_mask_of(n) || skip.moved.contains(&n.id) {
|
||||
return false;
|
||||
}
|
||||
let stays = holds_any(n, skip.kept);
|
||||
let id = n.id;
|
||||
let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) else { return false };
|
||||
let before = *used;
|
||||
let mut art = (*m.art).clone();
|
||||
let whole = self.wholes.get(&id).copied().unwrap_or_else(|| copies_whole(&art));
|
||||
let ran = (!stays).then(|| self.run(&mut art, max, used, whole, None, true, depth + 1));
|
||||
match ran {
|
||||
Some(ran) if ran.complete() => {
|
||||
// What paints the mask's art as a whole follows the effect as the art does.
|
||||
if let Some(carry) = ran.whole
|
||||
&& carry.moves(&art.appearance)
|
||||
{
|
||||
carry.apply(&mut art.appearance);
|
||||
}
|
||||
m.art = Arc::new(art);
|
||||
false
|
||||
}
|
||||
_ => {
|
||||
*used = before;
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
whole
|
||||
}
|
||||
|
||||
/// The objects whose linked masks [`Step::reshape_masks`] leaves as they are: those transformed
|
||||
/// as objects (`moved`), and those holding a path that kept its shape (`kept`).
|
||||
struct Skip<'a> {
|
||||
moved: &'a HashSet<NodeId>,
|
||||
kept: &'a HashSet<NodeId>,
|
||||
}
|
||||
|
||||
/// Is `n` an object whose linked opacity mask a geometry effect on the art it is in reshapes with
|
||||
/// it: a path, compound path, group or layer? An image or symbol instance moves its mask only
|
||||
/// with the map a Transform effect places it by ([`transform_placed`]).
|
||||
fn reshapes_mask_of(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// Does `n` (with `own`) or a path, compound path, group or layer under it carry a linked opacity
|
||||
/// mask that [`Step::reshape_masks`] reshapes?
|
||||
fn has_linked_mask(n: &Node, own: bool) -> bool {
|
||||
let mine = own && reshapes_mask_of(n) && n.extras().mask.as_ref().is_some_and(|m| m.linked);
|
||||
mine || match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().any(|c| has_linked_mask(c, true)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` on the id of `n` (with `own`) and of each path, compound path, group and layer under it
|
||||
/// that carries a linked opacity mask, with the art of that mask, and on the masks inside that
|
||||
/// art, as [`Step::reshape_masks`] reaches them: `depth` masks deep already, up to
|
||||
/// [`vectorcraft_doc::depth::MAX_DEPTH`].
|
||||
fn each_linked_mask(n: &Node, own: bool, depth: usize, f: &mut dyn FnMut(NodeId, &Node)) {
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
if own
|
||||
&& reshapes_mask_of(n)
|
||||
&& let Some(m) = n.extras().mask.as_deref().filter(|m| m.linked)
|
||||
{
|
||||
f(n.id, &m.art);
|
||||
each_linked_mask(&m.art, true, depth + 1, f);
|
||||
}
|
||||
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &n.kind {
|
||||
for c in children {
|
||||
each_linked_mask(c, true, depth, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`each_linked_mask`] that changes the art of each mask: `f` runs on a mask's art before the
|
||||
/// masks inside it are reached.
|
||||
fn each_linked_mask_mut(n: &mut Node, own: bool, depth: usize, f: &mut dyn FnMut(&mut Node)) {
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_linked_mask(n, own) {
|
||||
return;
|
||||
}
|
||||
if own
|
||||
&& reshapes_mask_of(n)
|
||||
&& let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked)
|
||||
{
|
||||
let art = Arc::make_mut(&mut m.art);
|
||||
f(art);
|
||||
each_linked_mask_mut(art, true, depth + 1, f);
|
||||
}
|
||||
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind {
|
||||
for c in children.iter_mut() {
|
||||
if has_linked_mask(c, true) {
|
||||
each_linked_mask_mut(Arc::make_mut(c), true, depth, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does [`Step::reshape_masks`] reshape the linked opacity mask of `n` itself?
|
||||
fn has_own_linked_mask(n: &Node) -> bool {
|
||||
reshapes_mask_of(n) && n.extras().mask.as_ref().is_some_and(|m| m.linked)
|
||||
}
|
||||
|
||||
/// Add to `out` the ids of the objects under `n` that the linked opacity mask of an object above
|
||||
/// them covers (every one of them with `under`).
|
||||
fn masked_ids(n: &Node, under: bool, out: &mut HashSet<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if under {
|
||||
out.insert(c.id);
|
||||
}
|
||||
masked_ids(c, under || has_own_linked_mask(c), out);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many images and symbol instances under `n` the linked opacity mask of an object above them
|
||||
/// covers (every one of them with `under`).
|
||||
fn masked_placed(n: &Node, under: bool) -> usize {
|
||||
n.children().into_iter().flatten().map(|c| usize::from(under && is_placed(c)) + masked_placed(c, under || has_own_linked_mask(c))).sum()
|
||||
}
|
||||
|
||||
/// Is `n`, or anything under it, one of `ids`?
|
||||
fn holds_any(n: &Node, ids: &HashSet<NodeId>) -> bool {
|
||||
if ids.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut any = false;
|
||||
n.walk(&mut |c| any |= ids.contains(&c.id));
|
||||
any
|
||||
}
|
||||
|
||||
/// Do the paths under `n` that [`for_each_leaf`] visits all fill by the non-zero rule without a
|
||||
/// stroke that paints? Effects then reshape their outlines alike in any order that the
|
||||
/// optimization of [`crate::geometry::optimize_geometry_effects`] takes.
|
||||
fn leaves_safe(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => {
|
||||
let has_stroke = n.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
leaf_geometry(n).is_none_or(|(_, rule)| rule == FillRule::NonZero && !has_stroke)
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().all(|c| leaves_safe(c)),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is there an image with a linked opacity mask among the members of `n`, or among its groups'
|
||||
/// and layers' members, which [`mark_warped_images`] walks?
|
||||
fn has_masked_image(n: &Node) -> bool {
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return false };
|
||||
children.iter().any(|c| match c.kind {
|
||||
NodeKind::Image(_) => c.extras().mask.as_ref().is_some_and(|m| m.linked),
|
||||
_ => has_masked_image(c),
|
||||
})
|
||||
}
|
||||
|
||||
/// Largest factor a Transform effect's Scale Strokes & Effects scales one object's strokes by
|
||||
@@ -1045,7 +1439,9 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
|
||||
let mut copy = leaf.clone();
|
||||
copy.transform(xf, scaling);
|
||||
// Each copy's own geometry effects make a different amount, as the copy and its effects scale.
|
||||
let cost = Budget::of(&moved).plus(effects_cost(©, &moved));
|
||||
let mut cost = Budget::of(&moved).plus(effects_cost(©, &moved));
|
||||
// Each copy carries the art of its linked masks, moved with it.
|
||||
each_linked_mask(©, true, 0, &mut |_, m| cost = cost.plus(art_cost(m)));
|
||||
if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
|
||||
break;
|
||||
}
|
||||
@@ -1445,17 +1841,25 @@ type GroupMark = (Vec<usize>, Option<Rect>, bool);
|
||||
|
||||
/// The geometric bounds of `n` (as [`Node::geometric_bounds`] gives them) and whether a path or
|
||||
/// compound path below it that those bounds measure is in `kept`, measured in one walk. Each group below `n` that
|
||||
/// [`GroupMark`] describes goes into `out`, reached from `n` through `at`.
|
||||
fn group_marks(n: &Node, at: &mut Vec<usize>, kept: &HashSet<NodeId>, out: &mut Vec<GroupMark>) -> (Option<Rect>, bool) {
|
||||
/// [`GroupMark`] describes goes into `out`, reached from `n` through `at`. An image that `images`
|
||||
/// lists is measured by the pieces it will be cut into ([`WarpedImages::image_bounds`]).
|
||||
fn group_marks(
|
||||
n: &Node,
|
||||
at: &mut Vec<usize>,
|
||||
kept: &HashSet<NodeId>,
|
||||
images: Option<&WarpedImages>,
|
||||
out: &mut Vec<GroupMark>,
|
||||
) -> (Option<Rect>, bool) {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => (n.geometric_bounds(), kept.contains(&n.id)),
|
||||
NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false),
|
||||
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
let skip = children.len().saturating_sub(n.editing_children().len());
|
||||
let (mut bounds, mut held) = (None, false);
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
at.push(i);
|
||||
let (b, h) = group_marks(c, at, kept, out);
|
||||
let (b, h) = group_marks(c, at, kept, images, out);
|
||||
if is_member_group(c) && (c.appearance.has_positioned_gradient() || c.appearance.has_unplaced_gradient()) {
|
||||
out.push((at.clone(), b, h));
|
||||
}
|
||||
@@ -1577,17 +1981,239 @@ fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
|
||||
/// Apply the Transform effect's map `m` to every image and symbol instance under `n`, as
|
||||
/// [`for_each_leaf`] does to paths: the map goes into the object's placement, and `copies` more
|
||||
/// follow, each mapped once more than the last. Without copies the object itself takes the map,
|
||||
/// as a path does.
|
||||
fn transform_placed(n: &mut Node, m: Affine, copies: usize) {
|
||||
transform_placed_within(n, m, copies, crate::distort::MAX_COPY_OBJECTS)
|
||||
/// as a path does. The art of each one's linked opacity mask takes the map with `scaling`, as a
|
||||
/// path's mask does.
|
||||
fn transform_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling) {
|
||||
let mut room = crate::distort::MAX_COPY_OBJECTS.saturating_sub(placed_count(n));
|
||||
copy_placed(n, m, copies, scaling, &mut room);
|
||||
}
|
||||
|
||||
/// [`transform_placed`] whose copies make at most `max` image and symbol instance nodes of the art,
|
||||
/// the originals included: each copy adds the object once more, and a Transform after this one
|
||||
/// copies the lot again, so copies stop where the result would pass `max` (#2042).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn transform_placed_within(n: &mut Node, m: Affine, copies: usize, max: usize) {
|
||||
let mut room = max.saturating_sub(placed_count(n));
|
||||
copy_placed(n, m, copies, &mut room);
|
||||
copy_placed(n, m, copies, vectorcraft_doc::Scaling::default(), &mut room);
|
||||
}
|
||||
|
||||
/// Rows and columns of the pieces a Warp effect cuts an image into (VectorCraft's own number).
|
||||
pub(crate) const WARP_IMAGE_CELLS: usize = 10;
|
||||
|
||||
/// A Warp effect's point map, shared by the images it bends.
|
||||
pub(crate) type WarpMap = Rc<dyn Fn(Point) -> Point>;
|
||||
|
||||
/// One image a Warp effect bent: the image's own key, and each warp it took with the placement
|
||||
/// the image had when it took it, in order.
|
||||
type WarpedImage = (String, Vec<(WarpMap, Affine)>);
|
||||
|
||||
/// The images Warp effects bend while [`reshape_leaves_apart`] runs the effects. Each such image's
|
||||
/// key is replaced by a key of this table ([`WarpedImages::add`]), which a copy a later Transform
|
||||
/// effect makes keeps. The images are cut into pieces once, after the last effect
|
||||
/// ([`cut_warped_images`]): the effects after a Warp reshape the image's frame, not each piece,
|
||||
/// and a later Warp or Transform moves the one set of pieces.
|
||||
pub(crate) struct WarpedImages {
|
||||
/// What this table's keys start with: no image key in the art starts with it
|
||||
/// ([`WarpedImages::reserve`]).
|
||||
prefix: String,
|
||||
/// The prefix was checked against the art's image keys.
|
||||
reserved: bool,
|
||||
images: Vec<WarpedImage>,
|
||||
}
|
||||
|
||||
impl WarpedImages {
|
||||
pub(crate) fn new() -> Self {
|
||||
static TABLES: AtomicUsize = AtomicUsize::new(0);
|
||||
Self { prefix: format!("\0warp{}:", TABLES.fetch_add(1, Ordering::Relaxed)), reserved: false, images: vec![] }
|
||||
}
|
||||
|
||||
/// Before the first image of `art` is marked: lengthen the prefix until no image key in `art`
|
||||
/// starts with it, so no key from the document is read as one of this table's.
|
||||
pub(crate) fn reserve(&mut self, art: &Node) {
|
||||
if self.reserved {
|
||||
return;
|
||||
}
|
||||
self.reserved = true;
|
||||
let mut keys = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
});
|
||||
while keys.iter().any(|k| k.starts_with(self.prefix.as_str())) {
|
||||
self.prefix.push(':');
|
||||
}
|
||||
}
|
||||
|
||||
/// What this table's keys start with.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn prefix(&self) -> &str {
|
||||
&self.prefix
|
||||
}
|
||||
|
||||
/// The image that `key`, a key of this table, stands for.
|
||||
fn get(&self, key: &str) -> Option<&WarpedImage> {
|
||||
self.images.get(key.strip_prefix(self.prefix.as_str())?.parse::<usize>().ok()?)
|
||||
}
|
||||
|
||||
/// Record that the image with key `key`, placed by `xf`, takes warp `f`; returns the image's
|
||||
/// new key.
|
||||
fn add(&mut self, key: &str, xf: Affine, f: &WarpMap) -> String {
|
||||
let (own, mut warps) = self.get(key).cloned().unwrap_or_else(|| (key.to_string(), vec![]));
|
||||
warps.push((f.clone(), xf));
|
||||
self.images.push((own, warps));
|
||||
format!("{}{}", self.prefix, self.images.len() - 1)
|
||||
}
|
||||
|
||||
/// Does the art `n` have room, within `max` nodes, for the pieces of every image under it that
|
||||
/// this table lists?
|
||||
fn fits(&self, n: &Node, max: usize) -> bool {
|
||||
let mut count = 0usize;
|
||||
n.walk(&mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind
|
||||
&& self.get(&im.key).is_some()
|
||||
{
|
||||
count += 1;
|
||||
}
|
||||
});
|
||||
vectorcraft_doc::live::mesh_warp_cost(WARP_IMAGE_CELLS).saturating_mul(count) <= max.saturating_sub(n.count())
|
||||
}
|
||||
|
||||
/// The geometric bounds of `art` as it draws after the effects so far: each image this table
|
||||
/// lists measured by the pieces the warps and moves it took would cut it into, when the art
|
||||
/// has room for them ([`cut_warped_images`]).
|
||||
pub(crate) fn bounds(&self, art: &Node) -> Option<Rect> {
|
||||
if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) {
|
||||
return art.geometric_bounds();
|
||||
}
|
||||
// The pieces the images would be cut into now: each group of pieces is shown or hidden as
|
||||
// its image is, and hidden objects are left out of a layer's bounds.
|
||||
let mut probe = art.clone();
|
||||
restore_warped_images(&mut probe, self, true);
|
||||
probe.geometric_bounds()
|
||||
}
|
||||
|
||||
/// The geometric bounds of image `n`: when this table lists it, measured by the pieces the
|
||||
/// warps and moves it took would cut it into.
|
||||
fn image_bounds(&self, n: &Node) -> Option<Rect> {
|
||||
let NodeKind::Image(im) = &n.kind else { return n.geometric_bounds() };
|
||||
if self.get(&im.key).is_none() {
|
||||
return n.geometric_bounds();
|
||||
}
|
||||
let mut probe = Node::group(n.id, vec![Arc::new(n.clone())]);
|
||||
restore_warped_images(&mut probe, self, true);
|
||||
probe.geometric_bounds()
|
||||
}
|
||||
|
||||
/// This table when the art `art` has room for the pieces of the images it lists, so that a
|
||||
/// measure of the art takes them bent ([`WarpedImages::bounds`]); `None` otherwise.
|
||||
fn when_cut(&self, art: &Node) -> Option<&Self> {
|
||||
(!self.images.is_empty() && self.fits(art, crate::distort::MAX_COPY_OBJECTS)).then_some(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Record in `warped` that each image under `n` takes warp `f`, walking the groups and layers
|
||||
/// [`for_each_leaf`] walks and counting the paths it passes in `at`. `kept` holds the places of
|
||||
/// the paths that kept their shape (past the budget), in the order [`for_each_leaf`] visits the
|
||||
/// paths of the art: an image in a clip group whose clipping art holds one (`held`) does not take
|
||||
/// the warp.
|
||||
pub(crate) fn mark_warped_images(n: &mut Node, f: &WarpMap, kept: &HashSet<usize>, held: bool, at: &mut usize, warped: &mut WarpedImages) {
|
||||
let (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }) = &mut n.kind else { return };
|
||||
let mut held = held;
|
||||
// A clip group's first member is its clipping art: when a path in it kept its shape, it and
|
||||
// the members it clips keep theirs.
|
||||
if *clip && let Some(first) = children.first() {
|
||||
let start = *at;
|
||||
held |= (start..start + leaf_count(first)).any(|p| kept.contains(&p));
|
||||
}
|
||||
for c in children.iter_mut() {
|
||||
match &c.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => *at += 1,
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => mark_warped_images(Arc::make_mut(c), f, kept, held, at, warped),
|
||||
NodeKind::Image(_) if !held => {
|
||||
if let NodeKind::Image(im) = &mut Arc::make_mut(c).kind {
|
||||
im.key = warped.add(&im.key, im.xf, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Give each image under `n` that `warped` lists its own key back, and cut it into the pieces of
|
||||
/// a raster mesh warp ([`vectorcraft_doc::live::mesh_warp_image`], each piece drawn as the image
|
||||
/// is, smoothed or not) through the warps it took and the moves between and after them
|
||||
/// ([`warped_map`]). The art keeps to [`crate::distort::MAX_COPY_OBJECTS`] nodes: when the pieces
|
||||
/// would pass it, no image is cut. An image whose placement has no inverse is not cut either.
|
||||
fn cut_warped_images(n: &mut Node, warped: &WarpedImages) {
|
||||
cut_warped_images_within(n, warped, crate::distort::MAX_COPY_OBJECTS);
|
||||
}
|
||||
|
||||
/// [`cut_warped_images`] with the art keeping to `max` nodes.
|
||||
pub(crate) fn cut_warped_images_within(n: &mut Node, warped: &WarpedImages, max: usize) {
|
||||
if warped.images.is_empty() {
|
||||
return;
|
||||
}
|
||||
let cut = warped.fits(n, max);
|
||||
restore_warped_images(n, warped, cut);
|
||||
}
|
||||
|
||||
/// The walk of [`cut_warped_images`]: each listed image gets its key back, and with `cut` is cut
|
||||
/// into pieces.
|
||||
fn restore_warped_images(n: &mut Node, warped: &WarpedImages, cut: bool) {
|
||||
let Some(children) = n.children_mut() else { return };
|
||||
for c in children.iter_mut() {
|
||||
let NodeKind::Image(im) = &c.kind else {
|
||||
if c.children().is_some() {
|
||||
restore_warped_images(Arc::make_mut(c), warped, cut);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let Some((key, warps)) = warped.get(&im.key) else { continue };
|
||||
let mut image = (**c).clone();
|
||||
let NodeKind::Image(own) = &mut image.kind else { continue };
|
||||
own.key = key.clone();
|
||||
// The pieces start from the image as it was placed when it took its first warp.
|
||||
let first = warps.first().map(|(_, at)| ImageObject { xf: *at, ..(**own).clone() });
|
||||
let map = warped_map(warps, own.xf);
|
||||
*c = Arc::new(match (first, map) {
|
||||
(Some(first), Some(map)) if cut => {
|
||||
let pixelated = image.extras().pixelated;
|
||||
vectorcraft_doc::live::mesh_warp_image(&image, &first, &*map, WARP_IMAGE_CELLS, pixelated, false)
|
||||
}
|
||||
_ => image,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The map that takes a point of an image placed by the first of `warps`' placements to where the
|
||||
/// warps and the moves between them take it, for an image now placed by `placed`: each warp in
|
||||
/// turn, then the move from the placement the image had when it took that warp to the one it had
|
||||
/// at the next, or to `placed` after the last. `None` when a placement has no inverse.
|
||||
fn warped_map(warps: &[(WarpMap, Affine)], placed: Affine) -> Option<Box<dyn Fn(Point) -> Point>> {
|
||||
let mut steps: Vec<(WarpMap, Affine)> = Vec::with_capacity(warps.len());
|
||||
for (i, (f, at)) in warps.iter().enumerate() {
|
||||
let det = at.determinant();
|
||||
if !det.is_finite() || det == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let next = warps.get(i + 1).map_or(placed, |(_, at)| *at);
|
||||
let m = next * at.inverse();
|
||||
if !m.is_finite() {
|
||||
return None;
|
||||
}
|
||||
steps.push((f.clone(), m));
|
||||
}
|
||||
Some(Box::new(move |p| steps.iter().fold(p, |q, (f, m)| *m * f(q))))
|
||||
}
|
||||
|
||||
/// How many paths [`for_each_leaf`] visits in `n`.
|
||||
fn leaf_count(n: &Node) -> usize {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => 1,
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().map(|c| leaf_count(c)).sum(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// An object that a Transform effect places through its transform rather than reshapes: an image
|
||||
@@ -1600,11 +2226,11 @@ fn is_placed(n: &Node) -> bool {
|
||||
/// document order, each copy taking one from `room` (what the art can still grow by), until the
|
||||
/// budget is full. As with a path, the copies stop before one reaches past
|
||||
/// [`crate::distort::within_reach`].
|
||||
fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
|
||||
fn copy_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, room: &mut usize) {
|
||||
let Some(children) = n.children_mut() else { return };
|
||||
for c in children.iter_mut() {
|
||||
if !is_placed(c) {
|
||||
copy_placed(Arc::make_mut(c), m, copies, room);
|
||||
copy_placed(Arc::make_mut(c), m, copies, scaling, room);
|
||||
continue;
|
||||
}
|
||||
let src = (**c).clone();
|
||||
@@ -1623,6 +2249,12 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
|
||||
if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() {
|
||||
one.appearance.transform_gradients(xf);
|
||||
}
|
||||
// So does the art of its linked opacity mask.
|
||||
if xf != Affine::IDENTITY
|
||||
&& let Some(m) = one.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked)
|
||||
{
|
||||
Arc::make_mut(&mut m.art).transform(xf, scaling);
|
||||
}
|
||||
one
|
||||
};
|
||||
if copies == 0 {
|
||||
|
||||
+102
-42
@@ -1,4 +1,5 @@
|
||||
//! Revolve as live, shaded vector art, shared by the canvas and every exporter.
|
||||
//! Revolve and Revolve (Classic) as live, shaded vector art, shared by the canvas and every
|
||||
//! exporter.
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
@@ -13,6 +14,14 @@ use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
|
||||
|
||||
pub const REVOLVE: &str = "threeD.revolve";
|
||||
|
||||
mod classic;
|
||||
pub use classic::CLASSIC_REVOLVE;
|
||||
|
||||
/// Is `id` Revolve or Revolve (Classic), the effects this module draws?
|
||||
pub fn is_revolve(id: &str) -> bool {
|
||||
id == REVOLVE || id == CLASSIC_REVOLVE
|
||||
}
|
||||
|
||||
/// Most bytes the copies of the object's paint in the faces may take together. Each face and the
|
||||
/// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of
|
||||
/// thousands of faces took gigabytes; past this the source path is drawn.
|
||||
@@ -20,7 +29,7 @@ const MAX_PAINT_COPIES: usize = 256 << 20;
|
||||
|
||||
/// The most face and box tests a group's transparent members' faces take together to rejoin their
|
||||
/// members' last runs; past them each starts a run of its own.
|
||||
const MAX_OVERLAP_TESTS: usize = 1 << 22;
|
||||
pub(crate) const MAX_OVERLAP_TESTS: usize = 1 << 22;
|
||||
|
||||
/// The width of the stroke around each face that covers the seams between faces.
|
||||
const SEAM_WIDTH: f64 = 0.75;
|
||||
@@ -55,7 +64,7 @@ pub(crate) fn paint_copies_add(used: &mut usize, copies: usize, paint: &Paint) -
|
||||
}
|
||||
|
||||
fn visible(fx: &[Effect]) -> bool {
|
||||
fx.iter().any(|e| e.visible && e.id == REVOLVE)
|
||||
fx.iter().any(|e| e.visible && is_revolve(&e.id))
|
||||
}
|
||||
|
||||
pub fn has_revolve(n: &Node) -> bool {
|
||||
@@ -88,6 +97,17 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
}
|
||||
}
|
||||
|
||||
/// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with
|
||||
/// parameters `p` sweeps its surface with.
|
||||
fn options_of(id: &str, p: &Value) -> Revolve {
|
||||
if id == CLASSIC_REVOLVE { classic::options(p) } else { revolve_options(p) }
|
||||
}
|
||||
|
||||
/// The options effect `fx`, a Revolve or a Revolve (Classic), sweeps its surface with.
|
||||
fn fx_options(fx: &Effect) -> Revolve {
|
||||
options_of(&fx.id, &merged_params(&fx.id, &fx.params))
|
||||
}
|
||||
|
||||
/// Validate before a command mutates the document. Loading external files is still bounded
|
||||
/// by the evaluator; unsupported source kinds remain unchanged when rendered.
|
||||
pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> {
|
||||
@@ -97,11 +117,16 @@ pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> {
|
||||
/// [`validate_revolve`] with the symbols of `doc`: a symbol instance, a blend and a clipping group
|
||||
/// revolve the art they show ([`resolve_for`]), cut for Revolve whatever 3D effect `n` carries now.
|
||||
pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Result<(), String> {
|
||||
validate_revolve_params(p)?;
|
||||
validate_in(doc, n, REVOLVE, p)
|
||||
}
|
||||
|
||||
/// [`validate_revolve_in`] for Revolve or Revolve (Classic), `id`.
|
||||
pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
validate_params_of(id, p)?;
|
||||
let n = &*resolve_for(doc, n, "Revolve", false)?;
|
||||
let effects = &n.appearance.effects;
|
||||
// The profile is measured before the object's one Revolve, hidden or shown.
|
||||
let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects);
|
||||
let before = effects.iter().position(|e| is_revolve(&e.id)).and_then(|i| effects.get(..i)).unwrap_or(effects);
|
||||
if is_container(n) {
|
||||
const EMPTY: &str = "Revolve requires a group holding a shape with at least two anchors";
|
||||
let mut shapes = members(n, "Revolve")?;
|
||||
@@ -110,7 +135,7 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul
|
||||
}
|
||||
reshape_members(n, before, &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or(EMPTY)?;
|
||||
let options = shared_options(&shapes, revolve_options(p))?;
|
||||
let options = shared_options(&shapes, options_of(id, p))?;
|
||||
let mut copies = 0;
|
||||
shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?;
|
||||
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0));
|
||||
@@ -123,8 +148,8 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul
|
||||
let path = geometry(&path, before, &GeomContext::of(n));
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let paints = solid_paints(n);
|
||||
check_surface(&path, b, revolve_options(p), surface_item(&paints), &mut 0)?;
|
||||
check_shadow(p, [&path], b, revolve_options(p))
|
||||
check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?;
|
||||
check_shadow(p, [&path], b, options_of(id, p))
|
||||
}
|
||||
|
||||
/// With the shadow of Revolve parameters `p` on, an error when the surfaces of `paths` it is cast
|
||||
@@ -138,14 +163,21 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
|
||||
}
|
||||
|
||||
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
|
||||
/// appearance item `target` of `n`. The surfaces of every fill and stroke that carries a Revolve,
|
||||
/// `target`'s included, share one budget of paint copies, as in [`art`]. A visible object-level
|
||||
/// Revolve draws in place of those surfaces.
|
||||
/// appearance item `target` of `n` ([`validate_item_of`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> {
|
||||
validate_item_of(n, REVOLVE, p, target, index)
|
||||
}
|
||||
|
||||
/// [`validate_revolve`] for a Revolve or Revolve (Classic), `id`, with parameters `p` at index
|
||||
/// `index` of the effects of appearance item `target` of `n`. The surfaces of every fill and stroke
|
||||
/// that carries one, `target`'s included, share one budget of paint copies, as in [`art`]. A visible
|
||||
/// object-level Revolve draws in place of those surfaces.
|
||||
pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> {
|
||||
if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() {
|
||||
return validate_revolve(n, p);
|
||||
return validate_in(None, n, id, p);
|
||||
}
|
||||
validate_revolve_params(p)?;
|
||||
validate_params_of(id, p)?;
|
||||
const EMPTY: &str = "Revolve requires a shape with at least two anchors";
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
if !has_two_anchors(&path) {
|
||||
@@ -156,13 +188,13 @@ pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: u
|
||||
let mut copies = 0;
|
||||
for (i, item) in n.appearance.items.iter().enumerate() {
|
||||
let effects = item.effects();
|
||||
let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && e.id == REVOLVE) };
|
||||
let params = match at.and_then(|at| effects.get(at)) {
|
||||
_ if i == target => p.clone(),
|
||||
Some(fx) if crate::paints(item) => merged_params(REVOLVE, &fx.params),
|
||||
let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && is_revolve(&e.id)) };
|
||||
let (kind, params) = match at.and_then(|at| effects.get(at)) {
|
||||
_ if i == target => (id, p.clone()),
|
||||
Some(fx) if crate::paints(item) => (fx.id.as_str(), merged_params(&fx.id, &fx.params)),
|
||||
_ => continue,
|
||||
};
|
||||
let options = revolve_options(¶ms);
|
||||
let options = options_of(kind, ¶ms);
|
||||
let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item));
|
||||
let b = path.bounds().ok_or(EMPTY)?;
|
||||
check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?;
|
||||
@@ -217,6 +249,16 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`validate_revolve_params`] for Revolve or Revolve (Classic), `id`; Revolve (Classic) also takes
|
||||
/// only its own parameters, each in its range.
|
||||
pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> {
|
||||
validate_revolve_params(p)?;
|
||||
if id == CLASSIC_REVOLVE {
|
||||
classic::validate(p)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
apply_geometry_with(fx, path, path.bounds().unwrap_or(Rect::ZERO), ctx)
|
||||
}
|
||||
@@ -226,7 +268,7 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
|
||||
/// the surface it is cast from is past the limits.
|
||||
fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result<Option<Node>, String> {
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(REVOLVE, &fx.params)) else { return Ok(None) };
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
|
||||
let (_, opacity, blend) = paint_of(item);
|
||||
if opacity <= 0.0 {
|
||||
return Ok(None);
|
||||
@@ -242,7 +284,7 @@ fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b:
|
||||
/// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the
|
||||
/// limits.
|
||||
fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result<Vec<Arc<Node>>, String> {
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(REVOLVE, &fx.params)) else { return Ok(vec![]) };
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) };
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast = vec![];
|
||||
for s in shapes {
|
||||
@@ -259,7 +301,8 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R
|
||||
}
|
||||
|
||||
/// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts
|
||||
/// the bytes of the paint copies of every surface of the object.
|
||||
/// the bytes of the paint copies of every surface of the object. Revolve (Classic) draws every face
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn surface(
|
||||
n: &Node,
|
||||
@@ -275,6 +318,16 @@ fn surface(
|
||||
) -> Option<(Vec<f64>, Node)> {
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
// of crashing the frame. Commands validate the same evaluator and report its errors.
|
||||
if fx.id == CLASSIC_REVOLVE {
|
||||
let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?;
|
||||
*copies = copies.saturating_add(paint_copies(facets.len(), &paint));
|
||||
if *copies > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
}
|
||||
let depths = facets.iter().map(|f| f.depth).collect();
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
return Some((depths, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p)));
|
||||
}
|
||||
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
|
||||
*copies = copies.saturating_add(paint_copies(faces.len(), &paint));
|
||||
@@ -371,8 +424,7 @@ fn surface(
|
||||
fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option<Node> {
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let options = revolve_options(&merged_params(REVOLVE, &fx.params));
|
||||
surface(n, path, b, options, fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
|
||||
surface(n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
|
||||
}
|
||||
|
||||
fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint {
|
||||
@@ -429,10 +481,10 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> {
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?;
|
||||
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
|
||||
};
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) {
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let before = n.appearance.effects.get(..index).unwrap_or_default();
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
|
||||
let path = geometry(&path, before, &ctx);
|
||||
@@ -445,7 +497,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE)
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id))
|
||||
&& let Some(fx) = item.effects().get(index)
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
@@ -461,13 +513,13 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
|
||||
.appearance
|
||||
.effects
|
||||
.iter()
|
||||
.position(|e| e.visible && e.id == REVOLVE)
|
||||
.position(|e| e.visible && is_revolve(&e.id))
|
||||
.ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?;
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
|
||||
let mut shapes = members(n, "Revolve")?;
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
|
||||
let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
|
||||
let options = shared_options(&shapes, fx_options(fx))?;
|
||||
let mut out = vec![];
|
||||
for s in &shapes {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
@@ -491,7 +543,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let mut children = vec![];
|
||||
let mut copies = 0;
|
||||
let mut remaining = n.appearance.effects.clone();
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) {
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let fx = n.appearance.effects.get(index)?;
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
// An object's surface uses its top visible fill, falling back to its stroke.
|
||||
@@ -500,7 +552,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let surface = object_surface(n, &path, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, revolve_options(&merged_params(REVOLVE, &fx.params))).ok()?
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
}
|
||||
@@ -511,7 +563,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
.effects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, e)| e.id != REVOLVE && (!is_geometry(&e.id) || *i > index))
|
||||
.filter(|(i, e)| !is_revolve(&e.id) && (!is_geometry(&e.id) || *i > index))
|
||||
.map(|(_, e)| e.clone())
|
||||
.collect();
|
||||
} else {
|
||||
@@ -520,14 +572,14 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
// Every item's shadow goes behind every item's art.
|
||||
let mut shadows = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let fx = item.effects().get(index)?;
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| e.id != REVOLVE).cloned().collect();
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
if let Some(b) = p.bounds()
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, revolve_options(&merged_params(REVOLVE, &fx.params))).ok()?
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()?
|
||||
{
|
||||
shadow.appearance.effects = art.appearance.effects.clone();
|
||||
shadows.push(Arc::new(shadow));
|
||||
@@ -576,14 +628,14 @@ pub(crate) fn scoped<'a>(id: NodeId, surfaces: Vec<(&'a [Scope], Arc<Node>)>, le
|
||||
/// What a face can paint, to tell whether two faces overlap: the convex hull of the points and
|
||||
/// control points of its outline, which holds the outline, and the hull's box grown by half the
|
||||
/// seam stroke.
|
||||
struct Coverage {
|
||||
bounds: Rect,
|
||||
pub(crate) struct Coverage {
|
||||
pub(crate) bounds: Rect,
|
||||
hull: Vec<Point>,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
/// `None` for a face with no outline and no box.
|
||||
fn of(face: &Node) -> Option<Coverage> {
|
||||
pub(crate) fn of(face: &Node) -> Option<Coverage> {
|
||||
let points: Vec<Point> = match face.path_data() {
|
||||
Some(path) => path
|
||||
.to_bezpath()
|
||||
@@ -611,7 +663,7 @@ impl Coverage {
|
||||
/// Do the two faces' hulls, each grown by half the seam stroke, overlap? A test of the
|
||||
/// separating axes of their edges and of the page's axes: `true` whenever they overlap, and
|
||||
/// sometimes near a corner when they don't.
|
||||
fn meets(&self, other: &Coverage) -> bool {
|
||||
pub(crate) fn meets(&self, other: &Coverage) -> bool {
|
||||
fn normals(hull: &[Point]) -> impl Iterator<Item = Vec2> + '_ {
|
||||
(0..hull.len()).filter_map(|i| {
|
||||
let (a, b) = (hull.get(i)?, hull.get((i + 1) % hull.len())?);
|
||||
@@ -658,7 +710,7 @@ fn convex_hull(mut points: Vec<Point>) -> Vec<Point> {
|
||||
}
|
||||
|
||||
/// Do boxes `a` and `b` overlap with some area?
|
||||
fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
|
||||
}
|
||||
|
||||
@@ -666,12 +718,12 @@ fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
|
||||
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
|
||||
fn group_art(n: &Node, expand: bool) -> Option<Node> {
|
||||
let index = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE)?;
|
||||
let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?;
|
||||
let fx = n.appearance.effects.get(index)?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let b = union_bounds(&shapes)?;
|
||||
let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params))).ok()?;
|
||||
let options = shared_options(&shapes, fx_options(fx)).ok()?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut copies = 0;
|
||||
let mut surfaces = vec![];
|
||||
@@ -690,6 +742,10 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> {
|
||||
return None;
|
||||
}
|
||||
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
|
||||
// A classic surface whose gradient has transparent stops carries an opacity mask: its faces go
|
||||
// in runs, as a transparent member's do, and each run carries the mask.
|
||||
let masks: Vec<Option<Box<vectorcraft_doc::OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect();
|
||||
let opaque = opaque && masks.iter().all(Option::is_none);
|
||||
let children = if !plain {
|
||||
scoped(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect(), 0)
|
||||
} else {
|
||||
@@ -731,7 +787,8 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> {
|
||||
runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
|
||||
continue;
|
||||
};
|
||||
if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() {
|
||||
let masked = masks.get(member).is_some_and(Option::is_some);
|
||||
if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() && !masked {
|
||||
runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
continue;
|
||||
}
|
||||
@@ -767,6 +824,9 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> {
|
||||
let mut group = Node::group(n.id, r.faces);
|
||||
group.opacity = r.opacity;
|
||||
group.blend = r.blend;
|
||||
if let Some(mask) = r.member.and_then(|m| masks.get(m)).cloned().flatten() {
|
||||
group.extras_mut().mask = Some(mask);
|
||||
}
|
||||
Some((r.scopes, Arc::new(group)))
|
||||
});
|
||||
scoped(n.id, runs.collect(), 0)
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
//! Revolve (Classic): the surface Revolve sweeps from a path, drawn with the classic surfaces of
|
||||
//! Extrude & Bevel (Classic) (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend
|
||||
//! steps and shading color.
|
||||
use serde_json::Value;
|
||||
use vectorcraft_three_d::Revolve;
|
||||
|
||||
pub const CLASSIC_REVOLVE: &str = "threeD.classicRevolve";
|
||||
|
||||
/// The numeric parameters: (key, lowest, highest, whole numbers only).
|
||||
const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("angle", 0.0, 360.0, false),
|
||||
("offset", 0.0, 1000.0, false),
|
||||
("rotationX", -180.0, 180.0, false),
|
||||
("rotationY", -180.0, 180.0, false),
|
||||
("rotationZ", -180.0, 180.0, false),
|
||||
("perspectiveAngle", 0.0, 160.0, false),
|
||||
("lightRotation", -180.0, 180.0, false),
|
||||
("lightHeight", 0.0, 90.0, false),
|
||||
("lightIntensity", 0.0, 100.0, false),
|
||||
("ambient", 0.0, 100.0, false),
|
||||
("highlightIntensity", 0.0, 100.0, false),
|
||||
("highlightSize", 0.0, 100.0, false),
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 2] = ["cap", "lightBehind"];
|
||||
|
||||
/// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge,
|
||||
/// rotation and perspective, built unshaded, since the classic surfaces light its faces.
|
||||
pub(crate) fn options(p: &Value) -> Revolve {
|
||||
Revolve { shade: false, smooth_shading: false, lights: None, light_color: [1.0; 3], ..super::revolve_options(p) }
|
||||
}
|
||||
|
||||
/// Check Revolve (Classic)'s parameters `p` (its defaults filled in) beyond the checks it shares
|
||||
/// with Revolve: every key is one of its parameters, numbers are in range, flags are true or false,
|
||||
/// and the surface and shading color are named.
|
||||
pub(crate) fn validate(p: &Value) -> Result<(), String> {
|
||||
crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeId};
|
||||
use vectorcraft_geom::{BezPath, PathData};
|
||||
|
||||
use super::*;
|
||||
|
||||
const BLUE: Color = Color::Rgb { r: 0.2, g: 0.4, b: 0.8 };
|
||||
|
||||
/// Half a vase's profile, open, filled blue.
|
||||
fn profile() -> Node {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((100.0, 40.0));
|
||||
b.line_to((130.0, 60.0));
|
||||
b.line_to((130.0, 140.0));
|
||||
b.line_to((100.0, 160.0));
|
||||
Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
fn revolved(params: Value) -> Node {
|
||||
let mut n = profile();
|
||||
n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, ¶ms).unwrap());
|
||||
crate::revolve_art(&n).unwrap()
|
||||
}
|
||||
|
||||
/// The faces of the surface of `art`, back to front.
|
||||
fn faces(art: &Node) -> Vec<&Node> {
|
||||
art.children().unwrap().iter().flat_map(|s| s.children().unwrap().iter().map(|f| &**f)).collect()
|
||||
}
|
||||
|
||||
fn fill(face: &Node) -> Option<Color> {
|
||||
face.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.color(),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn facets(params: &Value) -> usize {
|
||||
let n = profile();
|
||||
let path = n.path_data().unwrap();
|
||||
let p = crate::merged_params(CLASSIC_REVOLVE, params);
|
||||
vectorcraft_three_d::revolve_facets(path, path.bounds().unwrap(), options(&p)).unwrap().len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plastic_shades_every_face_of_the_swept_surface_in_the_fill() {
|
||||
let art = revolved(json!({}));
|
||||
let drawn = faces(&art);
|
||||
assert_eq!(drawn.len(), facets(&json!({})), "one face for each facet of the surface");
|
||||
let colors: Vec<[f32; 3]> = drawn.iter().map(|f| fill(f).unwrap().to_rgb()).collect();
|
||||
// Lit from one side, the faces take more than one tone, and none is another hue: a face is
|
||||
// the blue darkened toward black, lightened toward white, or both.
|
||||
let distinct = colors.iter().filter(|c| colors.iter().any(|d| (c[0] - d[0]).abs() > 0.02)).count();
|
||||
assert!(distinct > 0, "{colors:?}");
|
||||
// Diffuse has no highlight, so every face is the blue darkened toward black.
|
||||
let art = revolved(json!({"surface": "diffuse"}));
|
||||
for face in faces(&art) {
|
||||
let [r, g, b] = fill(face).unwrap().to_rgb();
|
||||
assert!(b <= 0.8 + 1e-6 && (g * 2.0 - b).abs() < 1e-4 && (r * 4.0 - b).abs() < 1e-4, "{r} {g} {b}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wireframe_strokes_the_edges_of_every_face_and_no_shading_keeps_the_paint() {
|
||||
let art = revolved(json!({"surface": "wireframe"}));
|
||||
let faces_drawn = faces(&art);
|
||||
assert_eq!(faces_drawn.len(), facets(&json!({"surface": "wireframe"})));
|
||||
for face in faces_drawn {
|
||||
match face.appearance.items.as_slice() {
|
||||
[AppearanceItem::Stroke(s)] => assert_eq!((s.paint.color(), s.width), (Some(BLUE), 0.5)),
|
||||
items => panic!("a wireframe face is one stroke: {items:?}"),
|
||||
}
|
||||
}
|
||||
for face in faces(&revolved(json!({"surface": "none"}))) {
|
||||
assert_eq!(fill(face), Some(BLUE));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angle_offset_edge_and_cap_shape_the_surface() {
|
||||
let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap();
|
||||
// Seen from the front, the full turn is twice the profile's width across, about its left edge.
|
||||
assert!((full.width() - 60.0).abs() < 2.0, "{full:?}");
|
||||
let ring = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "offset": 20})).visual_bounds().unwrap();
|
||||
assert!((ring.width() - 100.0).abs() < 2.0, "{ring:?}");
|
||||
// About its right edge the axis is at x 130, so the surface reaches x 160.
|
||||
let right = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "edge": "right"})).visual_bounds().unwrap();
|
||||
assert!((right.x1 - 160.0).abs() < 2.0, "{right:?}");
|
||||
assert!(facets(&json!({"angle": 90})) < facets(&json!({})));
|
||||
// The profile's ends lie on the axis, so they close nothing until an offset moves them off it.
|
||||
assert!(facets(&json!({"cap": false, "offset": 10})) < facets(&json!({"offset": 10})), "hollow leaves out the end caps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_revolves_its_members_about_one_shared_axis() {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((150.0, 60.0));
|
||||
b.line_to((170.0, 60.0));
|
||||
b.line_to((170.0, 140.0));
|
||||
let outer = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let mut g = Node::group(NodeId(3), vec![std::sync::Arc::new(profile()), std::sync::Arc::new(outer)]);
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).unwrap());
|
||||
let art = crate::revolve_art(&g).unwrap();
|
||||
// The axis is at the left edge of both members together, x 100, so the outer one reaches 70
|
||||
// out on either side of it.
|
||||
let bounds = art.visual_bounds().unwrap();
|
||||
assert!((bounds.x0 - 30.0).abs() < 2.0 && (bounds.x1 - 170.0).abs() < 2.0, "{bounds:?}");
|
||||
let mut colors = vec![];
|
||||
art.walk(&mut |n| colors.extend(fill(n).map(|c| c.to_rgb())));
|
||||
assert!(colors.iter().any(|c| c[2] > c[0]) && colors.iter().any(|c| c[0] == c[2]), "both members' paints are drawn");
|
||||
}
|
||||
|
||||
/// A group member in a gradient with transparent stops keeps the shared back-to-front order of
|
||||
/// every member's faces: its faces go in runs that carry its opacity mask, and the other
|
||||
/// member's faces are drawn between them where they are in front of some and behind others.
|
||||
#[test]
|
||||
fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let art = |end_opacity: f32| {
|
||||
let mut end = GradientStop::new(1.0, Color::BLACK);
|
||||
end.opacity = end_opacity;
|
||||
let gradient =
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, BLUE), end]))));
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((150.0, 60.0));
|
||||
b.line_to((170.0, 60.0));
|
||||
b.line_to((170.0, 140.0));
|
||||
let outer = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(gradient, Paint::None, 0.0));
|
||||
let mut g = Node::group(NodeId(3), vec![std::sync::Arc::new(outer), std::sync::Arc::new(profile())]);
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({})).unwrap());
|
||||
crate::revolve_art(&g).unwrap()
|
||||
};
|
||||
// The drawing order: `M` for a group with an opacity mask, `F` for a face outside one.
|
||||
fn visit(n: &Node, order: &mut String) {
|
||||
if n.extras().mask.is_some() {
|
||||
order.push('M');
|
||||
return;
|
||||
}
|
||||
if n.path_data().is_some() {
|
||||
order.push('F');
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, order);
|
||||
}
|
||||
}
|
||||
let order = |art: &Node| {
|
||||
let mut order = String::new();
|
||||
visit(art, &mut order);
|
||||
order
|
||||
};
|
||||
assert!(!order(&art(1.0)).contains('M'), "an opaque gradient needs no mask");
|
||||
let masked = order(&art(0.5));
|
||||
let (first, last) = (masked.find('M').unwrap(), masked.rfind('M').unwrap());
|
||||
assert!(masked.get(first..last).is_some_and(|between| between.contains('F')), "faces between the member's runs: {masked}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_parameters_are_refused() {
|
||||
let check = |p: Value| crate::validate_three_d(&profile(), CLASSIC_REVOLVE, &crate::merged_params(CLASSIC_REVOLVE, &p));
|
||||
assert_eq!(check(json!({})), Ok(()));
|
||||
for (p, error) in [
|
||||
(json!({"segments": 32}), "unknown parameter `segments`"),
|
||||
(json!({"angle": 400}), "`angle` must be between 0 and 360"),
|
||||
(json!({"offset": 1001}), "`offset` must be between 0 and 1000"),
|
||||
(json!({"rotationY": -181}), "`rotationY` must be between -180 and 180"),
|
||||
(json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number"),
|
||||
(json!({"lightBehind": 1}), "`lightBehind` must be true or false"),
|
||||
(json!({"surface": "glossy"}), "`surface` must be one of"),
|
||||
(json!({"shadingColor": "white"}), "`shadingColor` must be one of"),
|
||||
(json!({"shadingCustom": "red"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"edge": "middle"}), "Revolve edge must be left or right"),
|
||||
(json!({"cap": "yes"}), "Revolve cap must be a boolean"),
|
||||
] {
|
||||
let e = check(p.clone()).unwrap_err();
|
||||
assert!(e.contains(error), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+108
-28
@@ -1,4 +1,4 @@
|
||||
//! Extrude & Bevel, Inflate, Rotate and Extrude & Bevel (Classic) as live, shaded vector art,
|
||||
//! Extrude & Bevel, Inflate, Rotate, Extrude & Bevel (Classic) and Rotate (Classic) as live, shaded vector art,
|
||||
//! shared by the canvas and every exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces.
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -14,8 +14,8 @@ use vectorcraft_doc::color::Color;
|
||||
use crate::util::{flag, num, text};
|
||||
use crate::{GeomContext, apply_geometry_with, is_geometry};
|
||||
|
||||
mod classic;
|
||||
pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading};
|
||||
pub(crate) mod classic;
|
||||
pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLORS, classic_extrude_options, classic_shading};
|
||||
|
||||
mod source;
|
||||
pub(crate) use source::{resolve, resolve_for};
|
||||
@@ -26,11 +26,22 @@ pub const EXTRUDE: &str = "threeD.extrude";
|
||||
pub const INFLATE: &str = "threeD.inflate";
|
||||
pub const ROTATE: &str = "threeD.rotate";
|
||||
/// The 3D effects this module draws (Revolve has its own).
|
||||
pub const SOLIDS: [&str; 4] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE];
|
||||
pub const SOLIDS: [&str; 5] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE, CLASSIC_ROTATE];
|
||||
|
||||
/// Is `id` one of the 3D and Materials effects (Revolve included)?
|
||||
/// Is `id` one of the 3D and Materials effects (Revolve and Revolve (Classic) included)?
|
||||
pub fn is_three_d(id: &str) -> bool {
|
||||
id == crate::REVOLVE || SOLIDS.contains(&id)
|
||||
crate::revolve::is_revolve(id) || SOLIDS.contains(&id)
|
||||
}
|
||||
|
||||
/// Is `id` one of the 3D (Classic) effects: Extrude & Bevel (Classic), Revolve (Classic) or Rotate
|
||||
/// (Classic)?
|
||||
pub fn is_classic_three_d(id: &str) -> bool {
|
||||
id == CLASSIC_EXTRUDE || id == crate::CLASSIC_REVOLVE || id == CLASSIC_ROTATE
|
||||
}
|
||||
|
||||
/// Does 3D effect `id` turn the art as a flat plane: Rotate or Rotate (Classic)?
|
||||
fn is_plane(id: &str) -> bool {
|
||||
id == ROTATE || id == CLASSIC_ROTATE
|
||||
}
|
||||
|
||||
/// The 3D and Materials panel's object types and the effect that draws each: (type, effect id).
|
||||
@@ -193,6 +204,9 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
if id == CLASSIC_EXTRUDE {
|
||||
classic::validate(p)?;
|
||||
}
|
||||
if id == CLASSIC_ROTATE {
|
||||
classic::validate_rotate(p)?;
|
||||
}
|
||||
crate::lighting::validate(p)?;
|
||||
shadow::validate(p)?;
|
||||
if let Some(v) = p.get("bevel")
|
||||
@@ -225,7 +239,7 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, item: Option<usize>) -> Result<(), String> {
|
||||
validate_solid_params(id, p)?;
|
||||
let label = label_of(id);
|
||||
let n = &*source::resolve_for(doc, n, label, id == ROTATE)?;
|
||||
let n = &*source::resolve_for(doc, n, label, is_plane(id))?;
|
||||
if is_container(n) {
|
||||
let shapes = members(n, label)?;
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
@@ -417,7 +431,7 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
|
||||
/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]).
|
||||
pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
if id == crate::REVOLVE { crate::revolve::validate_revolve_in(doc, n, p) } else { validate_solid_in(doc, n, id, p) }
|
||||
if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) }
|
||||
}
|
||||
|
||||
/// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of
|
||||
@@ -436,7 +450,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va
|
||||
Some(_) if is_container(n) || source::resolves(n) => {
|
||||
Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into())
|
||||
}
|
||||
Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index),
|
||||
Some((item, index)) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(n, id, p, item, index),
|
||||
Some((item, _)) => validate_solid_for(doc, n, id, p, Some(item)),
|
||||
None => validate_three_d_in(doc, n, id, p),
|
||||
}
|
||||
@@ -446,7 +460,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va
|
||||
/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does
|
||||
/// not need to fit.
|
||||
pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
if id == crate::REVOLVE { crate::revolve::validate_revolve_params(p) } else { validate_solid_params(id, p) }
|
||||
if crate::revolve::is_revolve(id) { crate::revolve::validate_params_of(id, p) } else { validate_solid_params(id, p) }
|
||||
}
|
||||
|
||||
/// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and
|
||||
@@ -686,10 +700,11 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a
|
||||
/// solid from the path for the top visible fill and one from the outline of each visible stroke,
|
||||
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
|
||||
/// a surface one composite or masks it, their faces are drawn in one back-to-front order (where
|
||||
/// depths tie, as for the caps turned toward the viewer, in the order of the appearance, and with
|
||||
/// caps, a shape's fill walls before the faces of its covering strokes that overlap them:
|
||||
/// [`draw_order`]);
|
||||
/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as
|
||||
/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's
|
||||
/// fill walls before the faces of its covering strokes that overlap them: [`draw_order`]), the
|
||||
/// faces of a solid in a gradient with transparent stops in runs that carry its opacity mask
|
||||
/// ([`in_runs`]);
|
||||
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
|
||||
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
|
||||
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
|
||||
@@ -708,12 +723,12 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurface
|
||||
/// What the shadow of the solids [`surfaces_for`] builds for effect `id` with parameters `p` on
|
||||
/// `shapes` is cast from, on one plane: the faces of every solid, the shadow's settings and the
|
||||
/// faces of each solid of visible art with its member's scopes and ink. `None` with the shadow
|
||||
/// off, for Extrude & Bevel (Classic) or with no shapes. A stroke's solid that is not built (past
|
||||
/// off, for Extrude & Bevel (Classic) and Rotate (Classic) or with no shapes. A stroke's solid that is not built (past
|
||||
/// the limits) casts nothing, as it draws nothing; any other solid that is not built is an error.
|
||||
/// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to
|
||||
/// the part of the shadow they cast too ([`shadow::scoped_art`]).
|
||||
fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<Cast<'a>>, String> {
|
||||
if id == CLASSIC_EXTRUDE {
|
||||
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
|
||||
@@ -775,12 +790,12 @@ type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow,
|
||||
fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
let b = union_bounds(shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let classic = fx.id == CLASSIC_EXTRUDE;
|
||||
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
|
||||
let colored = !classic && view_options(&p).has_colored_lights();
|
||||
let masks = has_masks(shapes);
|
||||
// The paint copies of every solid together: past the allowance the source path is drawn.
|
||||
let mut paint_bytes = 0usize;
|
||||
if fx.id == ROTATE {
|
||||
if is_plane(&fx.id) {
|
||||
// Every part turns about the centre of the object's own bounds (a group's members about
|
||||
// the centre of theirs), so they stay together.
|
||||
let mut out = vec![];
|
||||
@@ -792,7 +807,8 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
|
||||
return None;
|
||||
}
|
||||
out.push((s.scopes.as_slice(), Arc::new(surface(n, f, &paint, opacity, blend, colored))));
|
||||
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
|
||||
out.push((s.scopes.as_slice(), Arc::new(art)));
|
||||
}
|
||||
}
|
||||
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
|
||||
@@ -841,19 +857,21 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect()));
|
||||
}
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. With
|
||||
// colored lights a surface can instead be one clipped composite of all its facets, or carry an
|
||||
// opacity mask, and then it stays whole.
|
||||
let plain = surfaces.iter().all(|(depths, s, _)| {
|
||||
s.extras().mask.is_none() && matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())
|
||||
});
|
||||
// colored lights a surface can instead be one clipped composite of all its facets. A composite
|
||||
// has no faces to order, so when any surface is one, every surface of the solid, masked ones
|
||||
// included, draws whole in member order.
|
||||
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
|
||||
if !opaque || !plain {
|
||||
return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect());
|
||||
}
|
||||
// A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs
|
||||
// ([`in_runs`]), and each run carries the mask.
|
||||
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect();
|
||||
let (mut placed, mut faces) = (vec![], vec![]);
|
||||
for (depths, s, _) in surfaces {
|
||||
for (surface, (depths, s, _)) in surfaces.into_iter().enumerate() {
|
||||
if let NodeKind::Group { children, .. } = s.kind {
|
||||
placed.extend(depths);
|
||||
faces.extend(children.into_iter().map(Some));
|
||||
faces.extend(children.into_iter().map(|face| Some((surface, face))));
|
||||
}
|
||||
}
|
||||
let sealed = match fx.id.as_str() {
|
||||
@@ -862,7 +880,69 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
_ => extrude_options(&p).cap,
|
||||
};
|
||||
let order = draw_order(&placed, sealed);
|
||||
Some(vec![Arc::new(Node::group(n.id, order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect()))])
|
||||
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
|
||||
let children = if masks.iter().all(Option::is_none) { faces.into_iter().map(|(_, face)| face).collect() } else { in_runs(n.id, faces, &masks) };
|
||||
Some(vec![Arc::new(Node::group(n.id, children))])
|
||||
}
|
||||
|
||||
/// `faces` in their back-to-front order, each with the index of its surface, where some surfaces
|
||||
/// carry an opacity mask (`masks`, by surface). A face of a surface without one goes in the order
|
||||
/// on its own. The faces of a masked surface share a run, one group with the surface's mask. Such a
|
||||
/// face joins its surface's last run unless a face drawn after that run overlaps it: only then does
|
||||
/// the surface split, where one group can't be both behind and in front of another face.
|
||||
fn in_runs(id: NodeId, faces: Vec<(usize, Arc<Node>)>, masks: &[Option<Box<OpacityMask>>]) -> Vec<Arc<Node>> {
|
||||
use crate::revolve::{Coverage, overlaps};
|
||||
struct Run {
|
||||
surface: Option<usize>,
|
||||
bounds: Rect,
|
||||
faces: Vec<Arc<Node>>,
|
||||
cover: Vec<Coverage>,
|
||||
}
|
||||
let mut runs: Vec<Run> = vec![];
|
||||
let mut last_run = vec![None; masks.len()];
|
||||
// Past this many tests a face starts a run of its own, which never draws out of order.
|
||||
let mut budget = crate::revolve::MAX_OVERLAP_TESTS;
|
||||
for (surface, face) in faces {
|
||||
let Some(cover) = Coverage::of(&face) else {
|
||||
// A face with no outline and no box overlaps nothing.
|
||||
runs.push(Run { surface: None, bounds: Rect::ZERO, faces: vec![face], cover: vec![] });
|
||||
continue;
|
||||
};
|
||||
if masks.get(surface).is_none_or(Option::is_none) {
|
||||
runs.push(Run { surface: None, bounds: cover.bounds, faces: vec![face], cover: vec![cover] });
|
||||
continue;
|
||||
}
|
||||
let mut clear = |r: &Run| {
|
||||
budget = budget.saturating_sub(1);
|
||||
if !overlaps(r.bounds, cover.bounds) {
|
||||
return budget > 0;
|
||||
}
|
||||
budget = budget.saturating_sub(r.cover.len());
|
||||
budget > 0 && r.cover.iter().all(|c| !overlaps(c.bounds, cover.bounds) || !c.meets(&cover))
|
||||
};
|
||||
let joins = last_run.get(surface).copied().flatten().filter(|&i: &usize| runs.get(i + 1..).is_some_and(|later| later.iter().all(&mut clear)));
|
||||
match joins.and_then(|i| runs.get_mut(i)) {
|
||||
Some(run) => {
|
||||
run.bounds = run.bounds.union(cover.bounds);
|
||||
run.faces.push(face);
|
||||
run.cover.push(cover);
|
||||
}
|
||||
None => {
|
||||
if let Some(last) = last_run.get_mut(surface) {
|
||||
*last = Some(runs.len());
|
||||
}
|
||||
runs.push(Run { surface: Some(surface), bounds: cover.bounds, faces: vec![face], cover: vec![cover] });
|
||||
}
|
||||
}
|
||||
}
|
||||
runs.into_iter()
|
||||
.filter_map(|mut r| {
|
||||
let Some(mask) = r.surface.and_then(|s| masks.get(s)).cloned().flatten() else { return r.faces.pop() };
|
||||
let mut group = Node::group(id, r.faces);
|
||||
group.extras_mut().mask = Some(mask);
|
||||
Some(Arc::new(group))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
@@ -1001,7 +1081,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
let view = view_options(&p);
|
||||
let mut out = vec![];
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit);
|
||||
if fx.id == ROTATE {
|
||||
if is_plane(&fx.id) {
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, _) = paint_of(item, s.opacity);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Extrude & Bevel (Classic): the solid Extrude & Bevel builds from a path, drawn with the classic
|
||||
//! surfaces (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend steps and shading
|
||||
//! color.
|
||||
//! color. Rotate (Classic): the plane Rotate turns, drawn with the No Shading and Diffuse surfaces.
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
@@ -12,6 +12,10 @@ use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Ext
|
||||
use crate::util::{flag, num, text};
|
||||
|
||||
pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude";
|
||||
pub const CLASSIC_ROTATE: &str = "threeD.classicRotate";
|
||||
|
||||
/// The surfaces Rotate (Classic) takes: No Shading and Diffuse.
|
||||
pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"];
|
||||
|
||||
/// The width of a Wireframe edge, in points.
|
||||
const WIRE: f64 = 0.5;
|
||||
@@ -104,8 +108,39 @@ const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"
|
||||
/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and
|
||||
/// `shadingCustom` name a surface, a shading color and a #rrggbb color.
|
||||
pub fn validate(p: &Value) -> Result<(), String> {
|
||||
validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)
|
||||
}
|
||||
|
||||
/// Rotate (Classic)'s numeric parameters: (key, lowest, highest, whole numbers only).
|
||||
const ROTATE_RANGES: [(&str, f64, f64, bool); 9] = [
|
||||
("rotationX", -180.0, 180.0, false),
|
||||
("rotationY", -180.0, 180.0, false),
|
||||
("rotationZ", -180.0, 180.0, false),
|
||||
("perspectiveAngle", 0.0, 160.0, false),
|
||||
("lightRotation", -180.0, 180.0, false),
|
||||
("lightHeight", 0.0, 90.0, false),
|
||||
("lightIntensity", 0.0, 100.0, false),
|
||||
("ambient", 0.0, 100.0, false),
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
/// Check Rotate (Classic)'s parameters `p` (its defaults filled in) as [`validate`] checks Extrude &
|
||||
/// Bevel (Classic)'s, with `surface` No Shading or Diffuse only.
|
||||
pub fn validate_rotate(p: &Value) -> Result<(), String> {
|
||||
validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind"])?;
|
||||
if p.get("surface").is_some_and(|v| !v.as_str().is_some_and(|s| ROTATE_SURFACES.contains(&s))) {
|
||||
return Err(format!("`surface` must be one of {}", ROTATE_SURFACES.join(", ")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check the parameters `p` of classic 3D effect `id` (its defaults filled in): every key is one of
|
||||
/// its parameters, the numbers `ranges` lists, as (key, lowest, highest, whole numbers only), are in
|
||||
/// range, the `flags` are true or false, and `surface`, `shadingColor` and `shadingCustom` name a
|
||||
/// surface, a shading color and a #rrggbb color.
|
||||
pub(crate) fn validate_classic(id: &str, p: &Value, ranges: &[(&str, f64, f64, bool)], flags: &[&str]) -> Result<(), String> {
|
||||
let Some(map) = p.as_object() else { return Ok(()) };
|
||||
let defaults = crate::default_params(CLASSIC_EXTRUDE).unwrap_or(Value::Null);
|
||||
let defaults = crate::default_params(id).unwrap_or(Value::Null);
|
||||
let known: Vec<&str> = defaults.as_object().map(|m| m.keys().map(String::as_str).collect()).unwrap_or_default();
|
||||
for key in map.keys() {
|
||||
if !known.contains(&key.as_str()) {
|
||||
@@ -113,7 +148,7 @@ pub fn validate(p: &Value) -> Result<(), String> {
|
||||
return Err(format!("unknown parameter `{key}`; the command takes: {keys}"));
|
||||
}
|
||||
}
|
||||
for (key, min, max, whole) in RANGES {
|
||||
for &(key, min, max, whole) in ranges {
|
||||
let Some(v) = map.get(key) else { continue };
|
||||
let Some(x) = v.as_f64() else { return Err(format!("`{key}` must be a number")) };
|
||||
if whole && (x.fract() != 0.0 || !(min..=max).contains(&x)) {
|
||||
@@ -123,7 +158,7 @@ pub fn validate(p: &Value) -> Result<(), String> {
|
||||
return Err(format!("`{key}` must be between {min} and {max} (got {x})"));
|
||||
}
|
||||
}
|
||||
for key in FLAGS {
|
||||
for &key in flags {
|
||||
if map.get(key).is_some_and(|v| !v.is_boolean()) {
|
||||
return Err(format!("`{key}` must be true or false"));
|
||||
}
|
||||
@@ -161,7 +196,7 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color {
|
||||
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
|
||||
/// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its own transparency, so the shading follows the gradient's coverage.
|
||||
pub(super) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
let shade = shading_color(p);
|
||||
|
||||
@@ -55,7 +55,7 @@ fn needs(n: &Node) -> bool {
|
||||
/// a clipping path too complex to cut the art with. `label` is the effect's name. The art is cut
|
||||
/// for the solid effect `n` carries ([`resolve_for`]).
|
||||
pub(crate) fn resolve<'a>(doc: Option<&Document>, n: &'a Node, label: &str) -> Result<Cow<'a, Node>, String> {
|
||||
let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| fx.id == super::ROTATE);
|
||||
let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| super::is_plane(&fx.id));
|
||||
resolve_for(doc, n, label, every_fill)
|
||||
}
|
||||
|
||||
|
||||
@@ -415,15 +415,16 @@ fn a_translucent_stroke_is_a_surface_of_its_own() {
|
||||
}
|
||||
|
||||
/// With a light that is not white, a fill in a gradient with transparent stops is drawn with an
|
||||
/// opacity mask over its whole surface: the fill's solid and the stroke's stay surfaces of their
|
||||
/// own, and the mask stays on the fill's. Under a white light the same object is one surface.
|
||||
/// opacity mask: its faces still take their places in the one order of the fill's and the
|
||||
/// stroke's faces, in runs that each carry the mask. Under a white light the faces carry the
|
||||
/// gradient itself and no mask.
|
||||
#[test]
|
||||
fn a_masked_surface_under_a_colored_light_stays_whole() {
|
||||
fn a_masked_surface_under_a_colored_light_keeps_the_shared_face_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let mut half = GradientStop::new(1.0, RED);
|
||||
half.opacity = 0.5;
|
||||
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), half]));
|
||||
for (lights, surfaces) in [(json!({"lights": [{"color": "#ff8080"}]}), 2), (json!({}), 1)] {
|
||||
for (lights, masked) in [(json!({"lights": [{"color": "#ff8080"}]}), true), (json!({}), false)] {
|
||||
let mut n = stroked_rect(100.0);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
|
||||
f.paint = Paint::Gradient(Box::new(gradient.clone()));
|
||||
@@ -431,8 +432,10 @@ fn a_masked_surface_under_a_colored_light_stays_whole() {
|
||||
n.appearance.effects.push(fx(EXTRUDE, lights.clone()));
|
||||
let art = solid_art(&n).unwrap();
|
||||
let drawn = art.children().unwrap();
|
||||
assert_eq!(drawn.len(), surfaces, "{lights}");
|
||||
assert_eq!(drawn[0].extras().mask.is_some(), surfaces == 2, "{lights}");
|
||||
assert_eq!(drawn.len(), 1, "{lights}: one order of faces");
|
||||
let runs: Vec<&Arc<Node>> = drawn[0].children().unwrap().iter().filter(|c| c.extras().mask.is_some()).collect();
|
||||
assert_eq!(!runs.is_empty(), masked, "{lights}");
|
||||
assert!(runs.iter().all(|r| r.children().unwrap().iter().all(|f| !blue(f))), "{lights}: the mask stays on the fill's faces");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -847,7 +850,9 @@ fn classic_shading_keeps_a_gradients_transparency() {
|
||||
}
|
||||
let art = solid_art(&n).unwrap();
|
||||
let surface = &art.children().unwrap()[0];
|
||||
assert_eq!(surface.extras().mask.is_some(), masked, "{end}");
|
||||
let mut has_mask = false;
|
||||
surface.walk(&mut |c| has_mask |= c.extras().mask.is_some());
|
||||
assert_eq!(has_mask, masked, "{end}");
|
||||
let mut opaque = true;
|
||||
surface.walk(&mut |c| {
|
||||
for item in &c.appearance.items {
|
||||
@@ -862,6 +867,67 @@ fn classic_shading_keeps_a_gradients_transparency() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A group member in a gradient with transparent stops keeps the shared back-to-front order of
|
||||
/// every member's faces: its faces go in runs that carry its opacity mask, and the other member's
|
||||
/// faces are drawn between them where they are in front of some and behind others. Here a square
|
||||
/// frame in the gradient holds a square in its hole: the frame's inner walls are behind the square
|
||||
/// and its front cap is in front of the square's walls.
|
||||
#[test]
|
||||
fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let square = |b: &mut BezPath, x0: f64, x1: f64, clockwise: bool| {
|
||||
let corners = [(x0, x0), (x1, x0), (x1, x1), (x0, x1)];
|
||||
let mut points = corners.to_vec();
|
||||
if !clockwise {
|
||||
points.reverse();
|
||||
}
|
||||
b.move_to(points[0]);
|
||||
for p in &points[1..] {
|
||||
b.line_to(*p);
|
||||
}
|
||||
b.close_path();
|
||||
};
|
||||
let art = |id: &str, params: &Value, end_opacity: f32| {
|
||||
let mut end = GradientStop::new(1.0, Color::BLACK);
|
||||
end.opacity = end_opacity;
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), end]))));
|
||||
let mut b = BezPath::new();
|
||||
square(&mut b, 100.0, 300.0, true);
|
||||
square(&mut b, 150.0, 250.0, false);
|
||||
let frame = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(gradient, Paint::None, 0.0));
|
||||
let mut b = BezPath::new();
|
||||
square(&mut b, 185.0, 215.0, true);
|
||||
let inner = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0));
|
||||
let mut g = Node::group(NodeId(3), vec![Arc::new(frame), Arc::new(inner)]);
|
||||
g.appearance.effects.push(fx(id, params.clone()));
|
||||
solid_art(&g).unwrap_or_else(|| panic!("{id}"))
|
||||
};
|
||||
// The drawing order: `M` for a group with an opacity mask, `F` for a face outside one.
|
||||
fn visit(n: &Node, order: &mut String) {
|
||||
if n.extras().mask.is_some() {
|
||||
order.push('M');
|
||||
return;
|
||||
}
|
||||
if n.path_data().is_some() {
|
||||
order.push('F');
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, order);
|
||||
}
|
||||
}
|
||||
let order = |art: &Node| {
|
||||
let mut order = String::new();
|
||||
visit(art, &mut order);
|
||||
order
|
||||
};
|
||||
for (id, params) in [(CLASSIC_EXTRUDE, json!({})), (EXTRUDE, json!({"lights": [{"color": "#ff8080"}]}))] {
|
||||
assert!(!order(&art(id, ¶ms, 1.0)).contains('M'), "{id}: an opaque gradient needs no mask");
|
||||
let masked = order(&art(id, ¶ms, 0.5));
|
||||
let (first, last) = (masked.find('M').unwrap(), masked.rfind('M').unwrap());
|
||||
assert!(masked.get(first..last).is_some_and(|between| between.contains('F')), "{id}: faces between the member's runs: {masked}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_parameters_are_checked() {
|
||||
let n = classic(json!({}));
|
||||
@@ -889,3 +955,80 @@ fn classic_parameters_are_checked() {
|
||||
assert!(err.starts_with(says), "{p}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The red square, stroked black, with Rotate (Classic) and `params`: its surfaces, the fill's
|
||||
/// plane first, then the stroke's outline.
|
||||
fn classic_rotate(params: Value) -> Vec<Node> {
|
||||
let mut n = square_node();
|
||||
n.appearance.effects.push(fx(CLASSIC_ROTATE, params));
|
||||
solid_art(&n).unwrap().children().unwrap().iter().map(|s| (**s).clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_rotate_turns_every_fill_and_stroke_as_one_plane() {
|
||||
let front = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0});
|
||||
let surfaces = classic_rotate(front.clone());
|
||||
assert_eq!(surfaces.len(), 2, "the fill's plane and the stroke's outline");
|
||||
assert!(surfaces.iter().all(|s| s.children().unwrap().len() == 1), "each is one flat face");
|
||||
let fill = surfaces[0].visual_bounds().unwrap();
|
||||
assert!((fill.width() - 100.0).abs() < 1.0 && (fill.height() - 100.0).abs() < 1.0, "{fill:?}");
|
||||
// Turned 60° about the vertical axis, the square shows half its width and all its height,
|
||||
// about the center of its bounds.
|
||||
let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 60, "rotationZ": 0}))[0].visual_bounds().unwrap();
|
||||
assert!((turned.width() - 50.0).abs() < 1.0 && (turned.height() - 100.0).abs() < 1.0, "{turned:?}");
|
||||
assert!((turned.center().x - 150.0).abs() < 1.0, "{turned:?}");
|
||||
// Turned past 90°, the back of the plane is drawn.
|
||||
let back = classic_rotate(json!({"rotationX": 0, "rotationY": 150, "rotationZ": 0}));
|
||||
assert!(back[0].visual_bounds().is_some_and(|b| (b.width() - 100.0 * 30f64.to_radians().cos()).abs() < 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_rotate_shades_with_no_shading_or_diffuse() {
|
||||
let rgb = |p: Value| fill_rgb(&classic_rotate(p)[0].children().unwrap()[0]);
|
||||
// No Shading keeps the paint, the color itself kept.
|
||||
let mut n = square_node();
|
||||
n.appearance.effects.push(fx(CLASSIC_ROTATE, json!({"surface": "none"})));
|
||||
let art = solid_art(&n).unwrap();
|
||||
let AppearanceItem::Fill(f) = &faces(&art)[0].appearance.items[0] else { panic!("a fill first") };
|
||||
assert_eq!(f.paint, Paint::solid(RED));
|
||||
// Diffuse: straight on with the light in front, the face is fully lit; turned away from the
|
||||
// light, it is the red darkened toward black.
|
||||
let lit = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90});
|
||||
assert!(close3(rgb(lit), RED.to_rgb()));
|
||||
let [r, g, b] = rgb(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90}));
|
||||
assert!(r < 0.8 - 0.05 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4, "{r} {g} {b}");
|
||||
// No light: the ambient share of the red. A custom shading color darkens toward that color;
|
||||
// None keeps the paint.
|
||||
let dark = rgb(json!({"lightIntensity": 0, "ambient": 20, "blendSteps": 256}));
|
||||
assert!((dark[0] - 0.8 * 0.2).abs() < 0.01, "{dark:?}");
|
||||
let blue = rgb(json!({"lightIntensity": 0, "ambient": 20, "shadingColor": "custom", "shadingCustom": "#0000ff"}));
|
||||
assert!(blue[2] > blue[0] / 8.0 + 0.01, "{blue:?}");
|
||||
assert!(close3(rgb(json!({"lightIntensity": 0, "shadingColor": "none"})), RED.to_rgb()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_rotate_parameters_are_checked() {
|
||||
let n = square_node();
|
||||
let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p));
|
||||
assert!(check(json!({})).is_ok());
|
||||
assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok());
|
||||
for (p, says) in [
|
||||
(json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"),
|
||||
(json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"),
|
||||
(json!({"surface": 2}), "`surface` must be one of"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"),
|
||||
(json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"),
|
||||
(json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"),
|
||||
(json!({"lightIntensity": 101}), "`lightIntensity` must be between 0 and 100 (got 101)"),
|
||||
(json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"),
|
||||
(json!({"lightBehind": 1}), "`lightBehind` must be true or false"),
|
||||
(json!({"highlightSize": 50}), "unknown parameter `highlightSize`"),
|
||||
(json!({"drawHiddenFaces": true}), "unknown parameter `drawHiddenFaces`"),
|
||||
(json!({"shadow": true}), "unknown parameter `shadow`"),
|
||||
(json!({"lights": []}), "lights must contain one to ten lights"),
|
||||
] {
|
||||
let err = check(p.clone()).unwrap_err();
|
||||
assert!(err.starts_with(says), "{p}: {err}");
|
||||
}
|
||||
}
|
||||
@@ -367,9 +367,12 @@ pub struct Slice {
|
||||
}
|
||||
|
||||
impl Slice {
|
||||
/// The slice's paint: its piece of `g` as a linear gradient placed from `from` to `to`.
|
||||
pub fn paint(&self, g: &Gradient) -> Paint {
|
||||
let gradient = g.span(self.span.0 as f32, self.span.1 as f32);
|
||||
/// The slice's paint: its piece of `unrolled` as a linear gradient placed from `from` to `to`.
|
||||
/// `unrolled` is the stroke's gradient as [`Gradient::unrolled`] gives it (unrolled once for
|
||||
/// all the slices), so one that repeats or reflects runs its stops that many times along (or
|
||||
/// across) the stroke.
|
||||
pub fn paint(&self, unrolled: &Gradient) -> Paint {
|
||||
let gradient = unrolled.span(self.span.0 as f32, self.span.1 as f32);
|
||||
let end = if self.from.distance(self.to) > 1e-9 { self.to } else { self.from + Vec2::new(1.0, 0.0) };
|
||||
let geom = GradientGeom { start: self.from, end, aspect: 1.0, focal: None };
|
||||
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle: geom.angle_deg(), ..GradientPaint::new(gradient) }))
|
||||
@@ -471,35 +474,60 @@ pub fn written_slices(bp: &BezPath, rule: FillRule, st: &StrokeLayer, outlines:
|
||||
_ => vectorcraft_pathops::stroke_region(outlines).to_bezpath(),
|
||||
};
|
||||
let grow = if g.stops.iter().all(|s| s.opacity >= 1.0) { SLICE_GROW } else { 0.0 };
|
||||
let unrolled = g.unrolled();
|
||||
let slices = gradient_slices(bp, rule, st, SLICE_TOL, SLICE_MARGIN, grow)
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
let paint = s.paint(g);
|
||||
let paint = s.paint(&unrolled);
|
||||
(s.shape, paint)
|
||||
})
|
||||
.collect();
|
||||
Some(WrittenSlices { clip, slices })
|
||||
}
|
||||
|
||||
/// How far before and after a sharp step between two colors (two stops at one offset, as a
|
||||
/// gradient that repeats has where one run meets the next) [`mesh_marks`] puts a mesh row or
|
||||
/// column, as a fraction of the gradient's length.
|
||||
const STEP_GAP: f64 = 1e-4;
|
||||
|
||||
/// Where along gradient `g` (0 to 1) Outline Stroke's mesh puts a row or column for its stops
|
||||
/// ([`Gradient::expanded_stops`]): at each stop, and for two stops at one offset (a sharp step,
|
||||
/// or where a reflecting gradient turns back) also [`STEP_GAP`] before and after it, so the mesh
|
||||
/// takes the color on each side.
|
||||
fn mesh_marks(g: &Gradient) -> Vec<f64> {
|
||||
let offsets: Vec<f64> = g.expanded_stops().iter().map(|s| f64::from(s.0)).collect();
|
||||
let shared = |i: usize| {
|
||||
let t = offsets.get(i).copied().unwrap_or(0.0);
|
||||
let near = |j: Option<usize>| j.and_then(|j| offsets.get(j)).is_some_and(|&u| (u - t).abs() < 1e-6);
|
||||
near(i.checked_sub(1)) || near(i.checked_add(1))
|
||||
};
|
||||
let mut out = Vec::with_capacity(offsets.len() + 2);
|
||||
for (i, &t) in offsets.iter().enumerate() {
|
||||
out.push(t);
|
||||
if shared(i) {
|
||||
out.extend([(t - STEP_GAP).max(0.0), (t + STEP_GAP).min(1.0)]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Outline Stroke of stroke `st` of `bp` (filled with `rule`) whose gradient `g` runs along or
|
||||
/// across it: a gradient mesh per subpath over all the stroke can paint there (clip it to the
|
||||
/// stroke's outline), coloured as [`gradient_slices`] paint it.
|
||||
pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec<GradientMesh> {
|
||||
let g = &*g.unrolled();
|
||||
let across = st.gradient_mode == StrokeGradientMode::Across;
|
||||
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
|
||||
let at_stops = mesh_marks(g);
|
||||
// Along: a column at each stop (colours are linear between columns), close enough to look smooth.
|
||||
let marks: Vec<f64> = if across { vec![] } else { g.expanded_stops().iter().map(|s| s.0 as f64).collect() };
|
||||
let marks: Vec<f64> = if across { vec![] } else { at_stops.clone() };
|
||||
let max_dt = match (across, st.profile.is_some()) {
|
||||
(false, _) => MESH_STEP,
|
||||
(true, true) => PROFILE_STEP,
|
||||
(true, false) => 1.0,
|
||||
};
|
||||
// Rows across: the strip's edges, then (across) the band's left edge to its right edge with a row at each stop.
|
||||
let mut us: Vec<f64> = if across {
|
||||
(0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(g.expanded_stops().iter().map(|s| s.0 as f64)).collect()
|
||||
} else {
|
||||
vec![0.5]
|
||||
};
|
||||
let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(at_stops).collect() } else { vec![0.5] };
|
||||
us.sort_by(f64::total_cmp);
|
||||
us.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
|
||||
strips(bp, rule, st, SLICE_TOL, SLICE_MARGIN, &marks, max_dt)
|
||||
|
||||
@@ -286,6 +286,65 @@ fn a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone() {
|
||||
assert_covered(&hairpin, &st);
|
||||
}
|
||||
|
||||
/// A gradient along or across a stroke that repeats or reflects runs its stops that many times
|
||||
/// along (or across) it: a slice's paint, and Outline Stroke's meshes, give each point the color
|
||||
/// the spread gives its place.
|
||||
#[test]
|
||||
fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false);
|
||||
for (mode, spread) in [StrokeGradientMode::Along, StrokeGradientMode::Across]
|
||||
.into_iter()
|
||||
.flat_map(|m| [GradientSpread::Reflect, GradientSpread::Repeat].map(|s| (m, s)))
|
||||
{
|
||||
let mut st = stroke(10.0, mode);
|
||||
let g = Gradient { spread, repeats: 3, ..Gradient::default() };
|
||||
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
|
||||
for s in slices(&bp, &st) {
|
||||
let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") };
|
||||
let geom = p.geom.unwrap();
|
||||
for u in [0.1, 0.5, 0.9] {
|
||||
let at = s.from + (s.to - s.from) * u;
|
||||
let t = s.span.0 + (s.span.1 - s.span.0) * u;
|
||||
// Where two runs meet, Repeat's color is the next run's start or the last one's end.
|
||||
if (t * 3.0 - (t * 3.0).round()).abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(geom.param_at(vectorcraft_color::GradientKind::Linear, at) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-3), "{mode:?} at {t}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
// Outline Stroke: the mesh comes back to white where each run starts again, and reaches
|
||||
// black where each run ends, on both sides of a sharp step between runs.
|
||||
let count = |g: &Gradient, hex: &str| {
|
||||
gradient_meshes(&bp, FillRule::NonZero, &st, g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == hex).count()
|
||||
};
|
||||
for hex in ["#ffffff", "#000000"] {
|
||||
let (spread, pad) = (count(&g, hex), count(&Gradient::default(), hex));
|
||||
assert!(spread > pad, "{mode:?} {:?} {hex}: {spread} vs {pad}", g.spread);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a reflecting gradient turns back past a narrow last stop, Outline Stroke's mesh keeps that
|
||||
/// stop's color.
|
||||
#[test]
|
||||
fn a_narrow_peak_where_a_reflecting_gradient_turns_back_stays_in_the_mesh() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false);
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.995, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
|
||||
let mut st = stroke(10.0, mode);
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops.clone()) };
|
||||
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
|
||||
let whites =
|
||||
gradient_meshes(&bp, FillRule::NonZero, &st, &g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == "#ffffff").count();
|
||||
// The gradient turns back at white 50 times.
|
||||
assert!(whites >= 50, "{mode:?}: {whites}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5960: with dashes, the ribs reach as far as the stroke gets wide within a cap's length along
|
||||
/// the path, however many points lie that far: not as far as it is wide anywhere when more than
|
||||
/// 256 do.
|
||||
|
||||
@@ -209,6 +209,57 @@ fn warp_arc_bends_the_top_edge() {
|
||||
assert!(b.x0 < -1.0 || b.x1 > 101.0, "{b:?}");
|
||||
}
|
||||
|
||||
/// A Warp of `version` 1 bends its bounds as its style's Bézier net; one without a version, as
|
||||
/// saved before the version existed, draws as it always did. Flag at 60 % on a 200 × 100 box: the
|
||||
/// net moves the top edge up to 6 × 0.6 × 100 × max u(1 - u)(1 - 2u) = 34.64 out, the earlier map
|
||||
/// moves it 0.6 × 25 = 15.
|
||||
#[test]
|
||||
fn a_warp_draws_with_the_map_its_version_names() {
|
||||
let rect = shapes::rectangle(Rect::new(10.0, 20.0, 210.0, 120.0));
|
||||
// u(1 - u)(1 - 2u) peaks at √3 / 18.
|
||||
let peak = 360.0 * 3f64.sqrt() / 18.0;
|
||||
for (version, out) in [(json!(1), peak), (json!(null), 15.0), (json!(0), 15.0)] {
|
||||
let b = run("warp.flag", json!({"bend": 60, "version": version}), &rect).bounds().unwrap();
|
||||
assert!(close(b.y0, 20.0 - out, 0.1) && close(b.y1, 120.0 + out, 0.1), "version {version}: {b:?}");
|
||||
assert!(close(b.x0, 10.0, 1e-9) && close(b.x1, 210.0, 1e-9), "version {version}: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A straight line has a box with no width or no height, and the net bends it as the middle of
|
||||
/// the patch along that side: under Arc a vertical line stays vertical, and under Bulge, Fisheye,
|
||||
/// Inflate and Squeeze a horizontal line stays straight.
|
||||
#[test]
|
||||
fn a_warp_bends_a_flat_box_as_the_middle_of_its_patch() {
|
||||
let anchors = |p: &PathData| p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect::<Vec<_>>();
|
||||
let vertical = shapes::line(Point::new(100.0, 0.0), Point::new(100.0, 100.0));
|
||||
let out = run("warp.arc", json!({"bend": 50, "version": 1}), &vertical);
|
||||
assert!(anchors(&out).iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}");
|
||||
let horizontal = shapes::line(Point::new(0.0, 50.0), Point::new(200.0, 50.0));
|
||||
for style in ["bulge", "fisheye", "inflate", "squeeze"] {
|
||||
let out = run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal);
|
||||
assert!(
|
||||
anchors(&out).iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)),
|
||||
"{style}: {out:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new Warp takes the nets' version unless one is given, and the catalog's defaults carry none,
|
||||
/// so a saved warp's params don't gain one.
|
||||
#[test]
|
||||
fn new_warps_take_the_nets_version() {
|
||||
for (s, _) in WARP_STYLES {
|
||||
let id = format!("warp.{s}");
|
||||
let Some(e) = crate::new_effect(&id, &json!({"bend": 20})) else { panic!("{id}") };
|
||||
assert_eq!(e.params["version"], json!(crate::WARP_NET), "{id}");
|
||||
let Some(e) = crate::new_effect(&id, &json!({"version": 0})) else { panic!("{id}") };
|
||||
assert_eq!(e.params["version"], json!(0), "{id}");
|
||||
assert!(crate::merged_params(&id, &json!({"bend": 20})).get("version").is_none(), "{id}");
|
||||
}
|
||||
let Some(e) = crate::new_effect("distort.twist", &json!({})) else { panic!("twist") };
|
||||
assert!(e.params.get("version").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_copies_and_move() {
|
||||
let out = run("distort.transform", json!({"moveH": 20, "copies": 3}), &square());
|
||||
@@ -318,6 +369,317 @@ fn stacked_transform_copies_stay_within_the_image_budget() {
|
||||
assert_eq!(count(&evaluate_container(None, &g).unwrap()), 1001);
|
||||
}
|
||||
|
||||
/// A 40 × 40 px image placed at (0, 0) at one point a pixel, with id `id`.
|
||||
fn warp_test_image(id: u64) -> std::sync::Arc<Node> {
|
||||
use vectorcraft_doc::{ImageObject, NodeId};
|
||||
let im = ImageObject { key: "k".into(), width: 40, height: 40, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
|
||||
std::sync::Arc::new(Node::new(NodeId(id), NodeKind::Image(Box::new(im))))
|
||||
}
|
||||
|
||||
/// How many images `art` holds, and the keys they have.
|
||||
fn warp_test_images(art: &Node) -> (usize, std::collections::BTreeSet<String>) {
|
||||
let (mut n, mut keys) = (0, std::collections::BTreeSet::new());
|
||||
art.walk(&mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
n += 1;
|
||||
keys.insert(im.key.clone());
|
||||
}
|
||||
});
|
||||
(n, keys)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warped_images_stay_within_the_object_budget() {
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::NodeId;
|
||||
let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1));
|
||||
let cost = vectorcraft_doc::live::mesh_warp_cost(crate::reshape::WARP_IMAGE_CELLS);
|
||||
let none = std::collections::HashSet::new();
|
||||
let k = || std::collections::BTreeSet::from(["k".to_string()]);
|
||||
let warp = |art: &mut Node, warps: usize| {
|
||||
let mut warped = crate::reshape::WarpedImages::new();
|
||||
for _ in 0..warps {
|
||||
crate::reshape::mark_warped_images(art, &lift, &none, false, &mut 0, &mut warped);
|
||||
}
|
||||
warped
|
||||
};
|
||||
// The art has room for one image's pieces only: neither image is cut, and each gets its own
|
||||
// key back.
|
||||
let mut art = Node::group(NodeId(1), vec![warp_test_image(2), warp_test_image(3)]);
|
||||
let warped = warp(&mut art, 1);
|
||||
let max = art.count() + cost;
|
||||
crate::reshape::cut_warped_images_within(&mut art, &warped, max);
|
||||
assert_eq!(warp_test_images(&art), (2, k()));
|
||||
// With room for both, each is cut into 200 pieces once, however many warps it took.
|
||||
let mut art = Node::group(NodeId(1), vec![warp_test_image(2), warp_test_image(3)]);
|
||||
let warped = warp(&mut art, 3);
|
||||
let max = art.count() + 2 * cost;
|
||||
crate::reshape::cut_warped_images_within(&mut art, &warped, max);
|
||||
assert_eq!(warp_test_images(&art), (400, k()));
|
||||
// Images clipped by their frames: the second frame (the second path) kept its shape, so its
|
||||
// image stays whole, and the first is cut. The third's frame is a group of two paths, the
|
||||
// second of them kept, with an image after them, and its image sits in a group of its own:
|
||||
// both stay whole too.
|
||||
let frame = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Default::default()));
|
||||
let clip_group = |id: u64, children: Vec<Arc<Node>>| Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: true }));
|
||||
let nested = clip_group(
|
||||
4,
|
||||
vec![
|
||||
Arc::new(Node::group(NodeId(4), vec![frame(4), frame(4), warp_test_image(5)])),
|
||||
Arc::new(Node::group(NodeId(4), vec![warp_test_image(4)])),
|
||||
],
|
||||
);
|
||||
let mut art =
|
||||
Node::group(NodeId(1), vec![clip_group(2, vec![frame(2), warp_test_image(2)]), clip_group(3, vec![frame(3), warp_test_image(3)]), nested]);
|
||||
let (mut at, mut warped) = (0, crate::reshape::WarpedImages::new());
|
||||
crate::reshape::mark_warped_images(&mut art, &lift, &std::collections::HashSet::from([1, 3]), false, &mut at, &mut warped);
|
||||
assert_eq!(at, 4);
|
||||
crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX);
|
||||
assert_eq!(warp_test_images(&art), (203, k()));
|
||||
}
|
||||
|
||||
/// An image key from the document that looks like a key of the table is not read as one, and a
|
||||
/// hidden image stays out of the bounds the later effects take, as it does before it is warped.
|
||||
#[test]
|
||||
fn warped_images_keep_document_keys_and_hidden_images_apart() {
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::NodeId;
|
||||
let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1));
|
||||
let none = std::collections::HashSet::new();
|
||||
let mut warped = crate::reshape::WarpedImages::new();
|
||||
let lookalike = format!("{}0", warped.prefix());
|
||||
let mut b = (*warp_test_image(3)).clone();
|
||||
if let NodeKind::Image(im) = &mut b.kind {
|
||||
im.key = lookalike.clone();
|
||||
}
|
||||
let mut art = Node::group(NodeId(1), vec![warp_test_image(2), Arc::new(b)]);
|
||||
warped.reserve(&art);
|
||||
crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped);
|
||||
crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX);
|
||||
assert_eq!(warp_test_images(&art), (400, std::collections::BTreeSet::from(["k".to_string(), lookalike])));
|
||||
// A layer of a 10 × 10 square and a hidden 40 × 40 image: the warped image is not measured.
|
||||
let square = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()));
|
||||
let mut hidden = (*warp_test_image(5)).clone();
|
||||
hidden.visible = false;
|
||||
let mut layer = Node::layer(NodeId(6), "Layer 1", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(children) = layer.children_mut() {
|
||||
*children = vec![square, Arc::new(hidden)];
|
||||
}
|
||||
let before = layer.geometric_bounds();
|
||||
let mut warped = crate::reshape::WarpedImages::new();
|
||||
warped.reserve(&layer);
|
||||
crate::reshape::mark_warped_images(&mut layer, &lift, &none, false, &mut 0, &mut warped);
|
||||
assert_eq!(warped.bounds(&layer), before);
|
||||
// A shown image is measured by the pieces it is cut into.
|
||||
let mut art = Node::group(NodeId(1), vec![warp_test_image(2)]);
|
||||
let mut warped = crate::reshape::WarpedImages::new();
|
||||
warped.reserve(&art);
|
||||
crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped);
|
||||
let measured = warped.bounds(&art);
|
||||
crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX);
|
||||
assert_eq!(measured, art.geometric_bounds());
|
||||
assert!(measured.is_some_and(|b| b.y0 < -3.9), "{measured:?}");
|
||||
// An image placed at a tiny scale (a placement with a tiny determinant) is cut too; one placed
|
||||
// with no area is not.
|
||||
for (scale, pieces) in [(1e-7, 200), (0.0, 1)] {
|
||||
let mut image = (*warp_test_image(2)).clone();
|
||||
if let NodeKind::Image(im) = &mut image.kind {
|
||||
im.xf = Affine::scale(scale);
|
||||
}
|
||||
let mut art = Node::group(NodeId(1), vec![Arc::new(image)]);
|
||||
let mut warped = crate::reshape::WarpedImages::new();
|
||||
crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped);
|
||||
crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX);
|
||||
assert_eq!(warp_test_images(&art).0, pieces, "{scale}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An image whose frame keeps its shape because the warp would pass the anchor budget keeps its
|
||||
/// pixels as they are; within the budget, both bend.
|
||||
#[test]
|
||||
fn an_image_whose_frame_passes_the_budget_stays_whole() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::NodeId;
|
||||
let clipped = || {
|
||||
let mut frame = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Appearance::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut frame.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
Node::new(NodeId(1), NodeKind::Group { children: vec![Arc::new(frame), warp_test_image(1)], clip: true })
|
||||
};
|
||||
let arc = fx("warp.arc", json!({"bend": 50, "version": 1}));
|
||||
let k = || std::collections::BTreeSet::from(["k".to_string()]);
|
||||
let mut art = clipped();
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&arc], Budget { anchors: 0, lines: 0 }, None);
|
||||
assert_eq!(art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).map(|p| p.anchor_count()), Some(4));
|
||||
assert_eq!(warp_test_images(&art), (1, k()));
|
||||
let mut art = clipped();
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&arc], Budget::EFFECTS, None);
|
||||
assert!(art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).is_some_and(|p| p.anchor_count() > 4));
|
||||
assert_eq!(warp_test_images(&art), (200, k()));
|
||||
}
|
||||
|
||||
/// The first image under `n` (the first piece of a cut image).
|
||||
fn first_image(n: &Node) -> Option<vectorcraft_doc::ImageObject> {
|
||||
let mut first = None;
|
||||
n.walk(&mut |c| {
|
||||
if first.is_none()
|
||||
&& let NodeKind::Image(im) = &c.kind
|
||||
{
|
||||
first = Some((**im).clone());
|
||||
}
|
||||
});
|
||||
first
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_after_a_warp_reshape_an_images_frame_and_not_its_pieces() {
|
||||
let image = |effects: Vec<Effect>| {
|
||||
let mut n = (*warp_test_image(1)).clone();
|
||||
n.appearance.effects = effects;
|
||||
n
|
||||
};
|
||||
// Each piece's clipping path, and the image's frame (the outer clip group's clipping path).
|
||||
let clips = |art: &Node| {
|
||||
let (mut pieces, mut frame) = (vec![], None);
|
||||
art.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind
|
||||
&& let Some(path) = children.first().and_then(|p| p.path_data())
|
||||
{
|
||||
if matches!(children.get(1).map(|i| &i.kind), Some(NodeKind::Image(_))) && path.anchor_count() == 3 {
|
||||
pieces.push(path.anchor_count());
|
||||
} else if frame.is_none() {
|
||||
frame = Some(path.anchor_count());
|
||||
}
|
||||
}
|
||||
});
|
||||
(pieces, frame)
|
||||
};
|
||||
let arc = fx("warp.arc", json!({"bend": 50, "version": 1}));
|
||||
for after in [
|
||||
fx("distort.roughen", json!({"size": 5, "detail": 10})),
|
||||
fx("stylize.roundCorners", json!({"radius": 5})),
|
||||
fx("path.offsetPath", json!({"offset": -2})),
|
||||
] {
|
||||
let art = crate::reshape::reshape(None, &image(vec![arc.clone(), after.clone()]), None).unwrap();
|
||||
let (pieces, frame) = clips(&art);
|
||||
assert_eq!(pieces.len(), 200, "{}", after.id);
|
||||
assert!(frame.is_some_and(|n| n > 4), "{}: {frame:?}", after.id);
|
||||
assert_eq!(warp_test_images(&art), (200, std::collections::BTreeSet::from(["k".to_string()])), "{}", after.id);
|
||||
}
|
||||
// Two warps cut the image once, through both maps; a Transform after them moves the pieces.
|
||||
let flag = fx("warp.flag", json!({"bend": 30, "version": 1}));
|
||||
let mv = fx("distort.transform", json!({"moveH": 100, "moveV": 0}));
|
||||
let art = crate::reshape::reshape(None, &image(vec![arc.clone(), flag.clone()]), None).unwrap();
|
||||
assert_eq!(warp_test_images(&art).0, 200);
|
||||
let moved = crate::reshape::reshape(None, &image(vec![arc.clone(), flag.clone(), mv]), None).unwrap();
|
||||
assert_eq!(warp_test_images(&moved).0, 200);
|
||||
let box1 = Rect::new(0.0, 0.0, 40.0, 40.0);
|
||||
let f1 = crate::warp::warp_map(box1, crate::warp::WarpStyle::Arc, &merged_params("warp.arc", &arc.params));
|
||||
// The flag bends the box the arc leaves, which the arc's frame measures.
|
||||
let box2 = crate::reshape::reshape(None, &image(vec![arc.clone()]), None).unwrap().geometric_bounds().unwrap();
|
||||
let f2 = crate::warp::warp_map(box2, crate::warp::WarpStyle::Flag, &merged_params("warp.flag", &flag.params));
|
||||
// The first piece's corners: the pixels (0, 0), (4, 0) and (4, 4).
|
||||
for (art, by) in [(&art, 0.0), (&moved, 100.0)] {
|
||||
let piece = first_image(art).unwrap();
|
||||
for p in [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0)] {
|
||||
let want = f2(f1(p)) + vectorcraft_geom::Vec2::new(by, 0.0);
|
||||
assert!((piece.xf * p).distance(want) < 1e-6, "{p:?}: {:?} {want:?}", piece.xf * p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A warp with no version (VectorCraft's earlier map) bends an image's pixels with that map, as it
|
||||
/// bends the frame.
|
||||
#[test]
|
||||
fn an_images_pixels_take_the_map_their_warps_version_names() {
|
||||
for version in [json!(null), json!(0), json!(1)] {
|
||||
let mut params = json!({"bend": 50});
|
||||
if !version.is_null() {
|
||||
params["version"] = version.clone();
|
||||
}
|
||||
let mut n = (*warp_test_image(1)).clone();
|
||||
n.appearance.effects = vec![fx("warp.arc", params.clone())];
|
||||
let art = crate::reshape::reshape(None, &n, None).unwrap();
|
||||
let f = crate::warp::warp_map(Rect::new(0.0, 0.0, 40.0, 40.0), crate::warp::WarpStyle::Arc, &merged_params("warp.arc", ¶ms));
|
||||
let piece = first_image(&art).unwrap();
|
||||
for p in [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0)] {
|
||||
assert!((piece.xf * p).distance(f(p)) < 1e-6, "{version}: {p:?}");
|
||||
}
|
||||
// The frame has an anchor where the map takes each corner.
|
||||
let frame = art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).unwrap();
|
||||
for corner in [Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(40.0, 40.0), Point::new(0.0, 40.0)] {
|
||||
let near = frame.subpaths.iter().flat_map(|s| &s.anchors).any(|a| a.p.distance(f(corner)) < 1e-6);
|
||||
assert!(near, "{version}: {corner:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Under a group's Warp effect, a nested group's own placed gradient follows the nested group's
|
||||
/// bounds to where its image's pieces draw them.
|
||||
#[test]
|
||||
fn a_nested_groups_gradient_follows_its_warped_image() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, NodeId};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let geom = GradientGeom { start: (5.0, 20.0).into(), end: (35.0, 20.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
|
||||
let mut inner = Node::group(NodeId(5), vec![warp_test_image(1)]);
|
||||
inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed)));
|
||||
let square = Node::path(NodeId(2), shapes::rectangle(Rect::new(60.0, 0.0, 100.0, 40.0)), Appearance::default());
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), Arc::new(square)]);
|
||||
g.appearance.effects.push(fx("warp.arc", json!({"bend": 50, "version": 1})));
|
||||
let art = crate::group::evaluate_container(None, &g).unwrap();
|
||||
assert_eq!(warp_test_images(&art).0, 200);
|
||||
let (from, mut to) = (Rect::new(0.0, 0.0, 40.0, 40.0), None);
|
||||
art.walk(&mut |c| {
|
||||
if c.id == NodeId(5) && to.is_none() {
|
||||
to = c.geometric_bounds();
|
||||
}
|
||||
});
|
||||
let to = to.unwrap();
|
||||
assert!(to.y0 < from.y0 - 1.0, "the pieces draw the image bent: {to:?}");
|
||||
let follow = |p: Point| Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height());
|
||||
let mut checked = 0;
|
||||
art.walk(&mut |c| {
|
||||
if c.id != NodeId(5) {
|
||||
return;
|
||||
}
|
||||
for item in &c.appearance.items {
|
||||
let Paint::Gradient(gp) = item.paint() else { continue };
|
||||
let got = gp.geom.unwrap();
|
||||
assert!(got.start.distance(follow(geom.start)) < 1e-6 && got.end.distance(follow(geom.end)) < 1e-6, "{got:?} in {to:?}");
|
||||
checked += 1;
|
||||
}
|
||||
});
|
||||
assert!(checked > 0);
|
||||
}
|
||||
|
||||
/// An image under a geometry effect other than a Warp draws as the image does: colorized by
|
||||
/// a grayscale image's fill color, and smoothed or not.
|
||||
#[test]
|
||||
fn an_image_under_a_geometry_effect_keeps_its_color_and_smoothing() {
|
||||
let mut n = (*warp_test_image(1)).clone();
|
||||
n.appearance.effects = vec![fx("distort.roughen", json!({"size": 5, "detail": 10}))];
|
||||
n.extras_mut().colorize = Some(Box::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))));
|
||||
n.extras_mut().pixelated = true;
|
||||
let art = crate::reshape::reshape(None, &n, None).unwrap();
|
||||
let mut seen = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Image(_)) {
|
||||
seen.push((c.extras().colorize.clone(), c.extras().pixelated));
|
||||
}
|
||||
});
|
||||
assert_eq!(seen, vec![(n.extras().colorize.clone(), true)]);
|
||||
}
|
||||
|
||||
/// What `effects` make of `path` within `budget`.
|
||||
fn within(effects: &[Effect], path: &PathData, budget: Budget) -> PathData {
|
||||
apply_geometry_within(effects, path, path.bounds().unwrap(), &GeomContext::default(), budget)
|
||||
|
||||
+34
-11
@@ -1,25 +1,49 @@
|
||||
//! Warp effects: 15 envelope styles plus horizontal/vertical perspective distortion.
|
||||
//!
|
||||
//! Each style is a map on normalised box coordinates (x, y) ∈ [-1, 1]² (y down). The path is
|
||||
//! split into short pieces whose control points are mapped (see `map_nonlinear`).
|
||||
//! A warp with `version` [`WARP_NET`] is its style's Bézier patch over the box ([`WarpNet`]);
|
||||
//! one without (saved before the version existed) is a map on normalized box coordinates
|
||||
//! (x, y) ∈ [-1, 1]² (y down), [`warp_point`]. The path is split into short pieces whose control
|
||||
//! points are mapped (see `map_nonlinear`).
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{PathData, Point, Rect};
|
||||
|
||||
use crate::util::{map_nonlinear_within, num, text};
|
||||
|
||||
pub use vectorcraft_doc::live::{WarpStyle, warp_point};
|
||||
pub use vectorcraft_doc::live::{WARP_NET, WarpNet, WarpStyle, uses_net, warp_point, warp_version};
|
||||
|
||||
/// The map version warp params `p` ask for: their `version`, 0 (the first map) when absent.
|
||||
pub fn map_version(p: &Value) -> u32 {
|
||||
let v = num(p, "version", 0.0);
|
||||
if v.is_finite() && v >= 0.0 { v.min(f64::from(u32::MAX)) as u32 } else { 0 }
|
||||
}
|
||||
|
||||
/// Apply a warp to `path` using box `b`, making at most `max` anchors ([`map_nonlinear_within`]).
|
||||
pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) -> PathData {
|
||||
let piece = b.width().hypot(b.height()) / 24.0;
|
||||
map_nonlinear_within(path, piece, max, warp_map(b, style, p))
|
||||
}
|
||||
|
||||
/// The point map a warp of `style` with params `p` applies to box `b`: what [`warp`] moves each
|
||||
/// point of a path to.
|
||||
pub(crate) fn warp_map(b: Rect, style: WarpStyle, p: &Value) -> Box<dyn Fn(Point) -> Point> {
|
||||
let bend = num(p, "bend", 50.0).clamp(-100.0, 100.0) / 100.0;
|
||||
let dh = num(p, "horizontal", 0.0).clamp(-100.0, 100.0) / 100.0;
|
||||
let dv = num(p, "vertical", 0.0).clamp(-100.0, 100.0) / 100.0;
|
||||
let vertical = text(p, "orientation", "horizontal").eq_ignore_ascii_case("vertical");
|
||||
if uses_net(map_version(p)) {
|
||||
let net = WarpNet::new(style, bend, dh, dv, b.width(), b.height(), vertical);
|
||||
let (w, h) = (b.width(), b.height());
|
||||
// A box with no width or no height takes the middle of the patch along that side.
|
||||
return Box::new(move |q: Point| {
|
||||
let (u, v) = (if w > 0.0 { (q.x - b.x0) / w } else { 0.5 }, if h > 0.0 { (q.y - b.y0) / h } else { 0.5 });
|
||||
b.origin() + net.at(u, v).to_vec2()
|
||||
});
|
||||
}
|
||||
let c = b.center();
|
||||
let hw = (b.width() / 2.0).max(1e-9);
|
||||
let hh = (b.height() / 2.0).max(1e-9);
|
||||
let f = |q: Point| {
|
||||
Box::new(move |q: Point| {
|
||||
let (x, y) = ((q.x - c.x) / hw, (q.y - c.y) / hh);
|
||||
let (x2, y2) = if vertical {
|
||||
let (a, b2) = warp_point(style, bend, dh, dv, hw / hh, y, x);
|
||||
@@ -28,18 +52,17 @@ pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) -
|
||||
warp_point(style, bend, dh, dv, hh / hw, x, y)
|
||||
};
|
||||
Point::new(c.x + x2 * hw, c.y + y2 * hh)
|
||||
};
|
||||
let piece = b.width().hypot(b.height()) / 24.0;
|
||||
map_nonlinear_within(path, piece, max, f)
|
||||
})
|
||||
}
|
||||
|
||||
/// Does warp effect `id` with params `p` move any point? Every style leaves the box as it is with
|
||||
/// no bend and no distortion, and Arc (`warp.arc`) takes a bend under 0.0001 % as none: the
|
||||
/// threshold must match the one in [`warp_point`]'s Arc case (`warp_bends_when_the_warp_moves_the_outline`
|
||||
/// tests both sides of it).
|
||||
/// no bend and no distortion. With the first map, Arc (`warp.arc`) takes a bend under 0.0001 % as
|
||||
/// none: the threshold must match the one in [`warp_point`]'s Arc case
|
||||
/// (`warp_bends_when_the_warp_moves_the_outline` tests both sides of it). With [`WarpNet`] any
|
||||
/// bend moves the outline.
|
||||
pub(crate) fn bends(id: &str, p: &Value) -> bool {
|
||||
let share = |key: &str, default: f64| num(p, key, default).clamp(-100.0, 100.0) / 100.0;
|
||||
let bend = share("bend", 50.0);
|
||||
let bent = if id == "warp.arc" { bend.abs() >= 1e-6 } else { bend != 0.0 };
|
||||
let bent = if id == "warp.arc" && !uses_net(map_version(p)) { bend.abs() >= 1e-6 } else { bend != 0.0 };
|
||||
bent || share("horizontal", 0.0) != 0.0 || share("vertical", 0.0) != 0.0
|
||||
}
|
||||
@@ -507,6 +507,23 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt
|
||||
Some(v) => Ok(Some(vec![checked_id(s, v, command)?])),
|
||||
}
|
||||
}
|
||||
/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form:
|
||||
/// for a command that looks its objects up itself, outside the document's layers too.
|
||||
pub(crate) fn given_object_ids(p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> {
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
return ids_param(p, "ids", command);
|
||||
}
|
||||
match p.get("id").filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(Value::String(r)) if r.starts_with('$') => {
|
||||
Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
|
||||
}
|
||||
Some(v) => {
|
||||
let id = v.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {v}: expected a non-negative integer")))?;
|
||||
Ok(Some(vec![id]))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `v` as an index, a count or a byte offset: past `usize::MAX` reads as `usize::MAX`, past the end of any list.
|
||||
pub(crate) fn index(v: u64) -> usize {
|
||||
usize::try_from(v).unwrap_or(usize::MAX)
|
||||
@@ -754,6 +771,7 @@ pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub use plugin_call::{Location, key_location, location_in, location_keys};
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
|
||||
@@ -5,6 +5,7 @@ mod arrange;
|
||||
mod cleanup;
|
||||
mod color;
|
||||
mod contour;
|
||||
mod cutting;
|
||||
mod document;
|
||||
mod image;
|
||||
mod pathtools;
|
||||
@@ -23,6 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(cleanup::specs());
|
||||
v.extend(color::specs());
|
||||
v.extend(contour::specs());
|
||||
v.extend(cutting::specs());
|
||||
v.extend(document::specs());
|
||||
v.extend(image::specs());
|
||||
v.extend(pathtools::specs());
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Cutting Tools (`addon.cutting.*`), a built-in add-on that prepares art for cutting. Stencil
|
||||
//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together
|
||||
//! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art
|
||||
//! for vinyl cutting ([`weed`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are
|
||||
//! the UI's.
|
||||
|
||||
mod stencil;
|
||||
mod weed;
|
||||
|
||||
use super::super::CommandSpec;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = stencil::specs();
|
||||
v.extend(weed::specs());
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Stencil Bridges (`addon.cutting.bridges`), a command of the built-in Cutting Tools add-on: it
|
||||
//! cuts bridges out of the selected art so that a stencil cut from it holds together. Each island
|
||||
//! of the stencil sheet (the inside of an O, a hole in a shape) stays joined to the sheet by strips
|
||||
//! of a set width across the art (<https://en.wikipedia.org/wiki/Stencil> describes islands and
|
||||
//! bridges). The art becomes one compound path with the gaps cut, and type is measured by its
|
||||
//! glyph outlines. The original goes to a new hidden layer or is replaced. The geometry is
|
||||
//! `vectorcraft_pathops::addons::stencil`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
use vectorcraft_pathops::addons::stencil::{BRIDGE_WIDTH_RANGE, BridgeDirection, BridgeSpec, MAX_BRIDGES_PER_ISLAND, stencil_bridges};
|
||||
|
||||
use super::super::super::edit::selected_roots;
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::pathops::{length_given, node_path, pf_leaves, shape_node, style_of};
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// Stencil Bridges' command (the id in [`specs`]).
|
||||
pub const BRIDGES: &str = "addon.cutting.bridges";
|
||||
/// The ways bridges run, as `direction` takes them.
|
||||
pub const DIRECTIONS: [&str; 3] = ["vertical", "horizontal", "shortest"];
|
||||
/// A bridge's width when none is given, in points.
|
||||
pub const DEFAULT_WIDTH: f64 = 2.0;
|
||||
/// The name of the hidden layer the original art goes to (numbered when it is taken).
|
||||
const ORIGINAL_LAYER: &str = "Stencil Original";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.cutting.bridges",
|
||||
"Stencil Bridges…",
|
||||
["Object", "Plug-ins", "Cutting Tools"],
|
||||
None,
|
||||
"{width?: pt 0.01..1000 (2), count?: whole number 1..16 of bridges each island gets (1; fewer where it has no room and more where other islands are joined to the sheet through it), direction?: \"vertical\" | \"horizontal\" | \"shortest\" (the shortest crossing among 12 directions 15° apart) (\"vertical\"), keepOriginal?: true (the selected objects that make up the art go to a new hidden layer named \"Stencil Original\"; false: they are replaced)} cut bridges out of the selected art so that a stencil cut from it holds together: every island (an area the art encloses, such as the inside of an O or a hole in a shape) is joined to the area around the art by strips `width` wide across the art, the shortest crossings first, then spread around the island. The art is measured by the area its outlines enclose, whatever their paint (open paths closed as a fill closes them; type by its glyph outlines; groups by their members; hidden objects left out) and becomes one compound path with the gaps cut, painted as the topmost selected shape, in the place of the topmost selected object that has outlines. Selected objects with no outlines in the art stay where they are. Art with no islands, or none a bridge of the width fits, is left as it is, with a warning and no undo step; islands the cut result still encloses are counted in `unbridged`, with a warning. Art that reaches more than 10000000 pt from the origin, has more than 200000 anchors, whose combined area has more than 4000 outlines, whose outlines need more than 200000 straight segments, or that takes more work to measure than a fixed budget allows is refused. One undo step; the new path is selected → {id, islands, bridges, unbridged, original (the hidden layer's id, or null), warning?}",
|
||||
has_selection,
|
||||
bridges
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridges(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = BRIDGES;
|
||||
let width = length_given(p, "width", C)?.unwrap_or(DEFAULT_WIDTH);
|
||||
let (lo, hi) = BRIDGE_WIDTH_RANGE;
|
||||
if !(lo..=hi).contains(&width) {
|
||||
return Err(bad(C, format!("`width` must be from {lo} to {hi} pt")));
|
||||
}
|
||||
let count = number_or(p, "count", 1.0, C)?;
|
||||
if count.fract() != 0.0 || !(1.0..=MAX_BRIDGES_PER_ISLAND as f64).contains(&count) {
|
||||
return Err(bad(C, format!("`count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND}")));
|
||||
}
|
||||
let direction = match choice(p, C, "direction", &DIRECTIONS)?.unwrap_or("vertical") {
|
||||
"horizontal" => BridgeDirection::Horizontal,
|
||||
"shortest" => BridgeDirection::Shortest,
|
||||
_ => BridgeDirection::Vertical,
|
||||
};
|
||||
let keep = switch_or(p, "keepOriginal", true, C)?;
|
||||
let selected = selected_roots(s)?;
|
||||
let (bridged, style, roots) = {
|
||||
let d = &s.doc()?.doc;
|
||||
// The art's outlines, the selected objects they come from, and the topmost object that
|
||||
// has some, whose paint the result takes.
|
||||
let mut parts: Vec<(PathData, FillRule)> = vec![];
|
||||
let mut roots = vec![];
|
||||
let mut top = None;
|
||||
for id in selected {
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut leaves = vec![];
|
||||
shown_leaves(d, n, &mut leaves);
|
||||
let before = parts.len();
|
||||
for leaf in leaves {
|
||||
if let Some(part) = node_path(&leaf).filter(|(p, _)| !p.is_empty()) {
|
||||
parts.push(part);
|
||||
top = Some(leaf);
|
||||
}
|
||||
}
|
||||
if parts.len() > before {
|
||||
roots.push(id);
|
||||
}
|
||||
}
|
||||
let Some(top) = top else {
|
||||
let label = "Stencil Bridges";
|
||||
return Err(EngineError::Other(format!("{label}: select paths, compound paths, groups or text")));
|
||||
};
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
|
||||
let spec = BridgeSpec { width, count: count as usize, direction };
|
||||
let bridged = stencil_bridges(&refs, spec).map_err(|e| match e {
|
||||
vectorcraft_pathops::PathOpsError::TooComplex => {
|
||||
EngineError::Other("Stencil Bridges: the selected art is too large or too detailed to bridge".into())
|
||||
}
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
(bridged, style_of(&top), roots)
|
||||
};
|
||||
let summary = |id: Option<NodeId>, original: Option<NodeId>| {
|
||||
json!({
|
||||
"id": id.map(|i| i.0), "islands": bridged.islands, "bridges": bridged.bridges, "unbridged": bridged.unbridged,
|
||||
"original": original.map(|i| i.0),
|
||||
})
|
||||
};
|
||||
if bridged.islands == 0 {
|
||||
let mut r = summary(None, None);
|
||||
// The warnings are written as `EngineError::Other` so that the i18n message scan
|
||||
// (`untranslated_report`) finds them.
|
||||
r["warning"] = json!(EngineError::Other("The selected art has no islands to bridge".into()).to_string());
|
||||
return Ok(r);
|
||||
}
|
||||
if bridged.bridges == 0 {
|
||||
let mut r = summary(None, None);
|
||||
r["warning"] = json!(EngineError::Other("No bridge of this width fits across the selected art".into()).to_string());
|
||||
return Ok(r);
|
||||
}
|
||||
let path = bridged.path.clone();
|
||||
let (id, original) = s.edit("Stencil Bridges", |d, sel| {
|
||||
let mut made = shape_node(d, path, None);
|
||||
style.apply(&mut made);
|
||||
let mut taken = vec![];
|
||||
let id = d.wrap(&roots, |nodes| {
|
||||
taken = nodes;
|
||||
made
|
||||
})?;
|
||||
let original = if keep { Some(hide_originals(d, taken)?) } else { None };
|
||||
sel.set([id]);
|
||||
Ok((id, original))
|
||||
})?;
|
||||
let mut r = summary(Some(id), original);
|
||||
if bridged.unbridged > 0 {
|
||||
r["warning"] = json!(EngineError::Other("Some islands could not be joined to the area around the art".into()).to_string());
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The leaf shapes of `n` as [`pf_leaves`] gives them, leaving out hidden objects and the members
|
||||
/// of hidden groups.
|
||||
fn shown_leaves(d: &Document, n: &Node, out: &mut Vec<Node>) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } if !n.is_compound_shape() => {
|
||||
for c in children {
|
||||
shown_leaves(d, c, out);
|
||||
}
|
||||
}
|
||||
_ => pf_leaves(d, n, out),
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `nodes` in a new hidden layer above the others, in their order, and return its id.
|
||||
fn hide_originals(d: &mut Document, nodes: Vec<Arc<Node>>) -> Result<NodeId> {
|
||||
let mut taken = std::collections::HashSet::new();
|
||||
d.walk(|n| {
|
||||
if n.is_layer() {
|
||||
taken.extend(n.name.clone());
|
||||
}
|
||||
});
|
||||
let name = std::iter::once(ORIGINAL_LAYER.to_string())
|
||||
.chain((2..).map(|i| format!("{ORIGINAL_LAYER} {i}")))
|
||||
.find(|name| !taken.contains(name))
|
||||
.unwrap_or_else(|| ORIGINAL_LAYER.to_string());
|
||||
let layer = d.add_layer(Some(&name));
|
||||
for (i, n) in nodes.into_iter().enumerate() {
|
||||
d.insert(Some(layer), i, Arc::unwrap_or_clone(n))?;
|
||||
}
|
||||
d.node_mut(layer).ok_or(EngineError::NoNode(layer))?.visible = false;
|
||||
Ok(layer)
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
//! Tests for `addon.cutting.bridges`: bridges cut out of the selected art keep a stencil's islands
|
||||
//! attached.
|
||||
|
||||
use kurbo::Shape;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
|
||||
use super::super::super::super::pathops::node_path;
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
/// `outer` less each of `holes` (x, y, width, height), as one compound path, selected.
|
||||
fn shape_with_holes(s: &mut Session, outer: (f64, f64, f64, f64), holes: &[(f64, f64, f64, f64)]) -> NodeId {
|
||||
let mut ids = vec![rect(s, outer.0, outer.1, outer.2, outer.3)];
|
||||
for h in holes {
|
||||
ids.push(rect(s, h.0, h.1, h.2, h.3));
|
||||
}
|
||||
select(s, &ids);
|
||||
let r = s.execute("object.pathfinder.minusFront", &json!({})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
select(s, &[id]);
|
||||
id
|
||||
}
|
||||
|
||||
/// A square O: 100 pt across at (100, 100), with bars 20 pt thick.
|
||||
fn letter_o(s: &mut Session) -> NodeId {
|
||||
shape_with_holes(s, (100.0, 100.0, 100.0, 100.0), &[(120.0, 120.0, 60.0, 60.0)])
|
||||
}
|
||||
|
||||
fn id_of(r: &Value) -> NodeId {
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
/// Is `(x, y)` inside the area object `id` fills?
|
||||
fn fills(s: &Session, id: NodeId, x: f64, y: f64) -> bool {
|
||||
let (path, rule) = node_path(&node(s, id)).unwrap();
|
||||
let w = path.to_bezpath().winding(kurbo::Point::new(x, y));
|
||||
match rule {
|
||||
vectorcraft_geom::FillRule::EvenOdd => w % 2 != 0,
|
||||
vectorcraft_geom::FillRule::NonZero => w != 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_o_gets_a_bridge_and_the_original_goes_to_a_hidden_layer() {
|
||||
let mut s = session();
|
||||
let o = letter_o(&mut s);
|
||||
let fill = node(&s, o).appearance.fill_paint();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap();
|
||||
assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(1), json!(0)));
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
let made = id_of(&r);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![made]);
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
|
||||
// The bridge crosses the top bar in the middle; the rest of the O stays, painted as it was.
|
||||
assert!(!fills(&s, made, 150.0, 110.0));
|
||||
assert!(fills(&s, made, 130.0, 110.0) && fills(&s, made, 150.0, 190.0) && fills(&s, made, 110.0, 150.0));
|
||||
assert_eq!(node(&s, made).appearance.fill_paint(), fill);
|
||||
// The original, unchanged, is on a new hidden layer.
|
||||
let layer = NodeId(r["original"].as_u64().unwrap());
|
||||
let l = node(&s, layer);
|
||||
assert_eq!((l.name.as_deref(), l.visible), (Some("Stencil Original"), false));
|
||||
let held = s.doc().unwrap().doc.children(Some(layer)).map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>());
|
||||
assert_eq!(held, Some(vec![o]));
|
||||
// The island is joined to the sheet: the result has none left.
|
||||
let again = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap();
|
||||
assert_eq!(again["islands"], json!(0));
|
||||
assert!(again["warning"].as_str().is_some_and(|w| w.contains("no islands")), "{again}");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "no islands: no undo step");
|
||||
// Undo puts the O back where it was and takes the layer away.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(layer).is_none() && d.node(made).is_none() && d.node(o).is_some_and(|n| n.visible));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_original_off_replaces_the_art() {
|
||||
let mut s = session();
|
||||
let o = letter_o(&mut s);
|
||||
let layers = s.doc().unwrap().doc.layers.len();
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": false})).unwrap();
|
||||
assert_eq!(r["original"], Value::Null);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(o).is_none() && d.node(id_of(&r)).is_some());
|
||||
assert_eq!(d.layers.len(), layers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bridge_is_as_wide_as_asked() {
|
||||
for width in [2.0, 8.0] {
|
||||
let mut s = session();
|
||||
letter_o(&mut s);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": width})).unwrap();
|
||||
let made = id_of(&r);
|
||||
let half = width / 2.0;
|
||||
assert!(!fills(&s, made, 150.0 - half * 0.9, 110.0) && !fills(&s, made, 150.0 + half * 0.9, 110.0), "{width}");
|
||||
assert!(fills(&s, made, 150.0 - half * 1.2, 110.0) && fills(&s, made, 150.0 + half * 1.2, 110.0), "{width}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_width_takes_units() {
|
||||
let mut s = session();
|
||||
letter_o(&mut s);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": "2 mm"})).unwrap();
|
||||
let made = id_of(&r);
|
||||
// 2 mm is about 5.67 pt.
|
||||
assert!(!fills(&s, made, 152.5, 110.0) && fills(&s, made, 154.0, 110.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shortest_crossing_takes_the_thinnest_bar() {
|
||||
let mut s = session();
|
||||
// The left bar is 5 pt thick, the others 20.
|
||||
shape_with_holes(&mut s, (100.0, 100.0, 100.0, 100.0), &[(105.0, 120.0, 75.0, 60.0)]);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "direction": "shortest"})).unwrap();
|
||||
let made = id_of(&r);
|
||||
assert!(!fills(&s, made, 102.5, 150.0), "the bridge crosses the thin bar");
|
||||
assert!(fills(&s, made, 150.0, 110.0) && fills(&s, made, 190.0, 150.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_bridges_cross_the_sides() {
|
||||
let mut s = session();
|
||||
letter_o(&mut s);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "direction": "horizontal"})).unwrap();
|
||||
let made = id_of(&r);
|
||||
assert!(!fills(&s, made, 110.0, 150.0) || !fills(&s, made, 190.0, 150.0));
|
||||
assert!(fills(&s, made, 150.0, 110.0) && fills(&s, made, 150.0, 190.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_with_two_holes_gets_a_bridge_for_each() {
|
||||
let mut s = session();
|
||||
shape_with_holes(&mut s, (100.0, 100.0, 100.0, 50.0), &[(110.0, 110.0, 30.0, 30.0), (160.0, 110.0, 30.0, 30.0)]);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 3, "count": 2})).unwrap();
|
||||
assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(2), json!(4), json!(0)));
|
||||
let made = id_of(&r);
|
||||
for x in [125.0, 175.0] {
|
||||
assert!(!fills(&s, made, x, 105.0) && !fills(&s, made, x, 145.0), "{x}: a bridge above and below each hole");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_is_bridged_by_its_glyph_outlines_and_stays_type() {
|
||||
let mut s = session();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": "O", "size": 144})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[t]);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 3})).unwrap();
|
||||
assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(1), json!(0)), "{r}");
|
||||
assert!(matches!(node(&s, id_of(&r)).kind, NodeKind::Path { .. } | NodeKind::Compound { .. }));
|
||||
// The type itself is not converted: it is on the hidden layer, still type.
|
||||
assert!(matches!(node(&s, t).kind, NodeKind::Text(_)));
|
||||
assert!(!node(&s, NodeId(r["original"].as_u64().unwrap())).visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_result_is_painted_as_the_topmost_object_with_outlines() {
|
||||
let mut s = session();
|
||||
let o = letter_o(&mut s);
|
||||
// Type holding only a space draws no outlines, so it does not set the paint, though it is on top.
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": " ", "size": 24})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[o]);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let red = node(&s, o).appearance.fill_paint();
|
||||
select(&mut s, &[o, t]);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap();
|
||||
assert_eq!(node(&s, id_of(&r)).appearance.fill_paint(), red);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_members_of_a_group_are_left_out() {
|
||||
let mut s = session();
|
||||
let o = letter_o(&mut s);
|
||||
// A hidden square that would fill the O's hole, grouped with it.
|
||||
let cover = rect(&mut s, 120.0, 120.0, 60.0, 60.0);
|
||||
select(&mut s, &[o, cover]);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[cover]);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
select(&mut s, &[g]);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap();
|
||||
assert_eq!((r["islands"].clone(), r["bridges"].clone()), (json!(1), json!(1)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_without_islands_changes_nothing() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
|
||||
select(&mut s, &[a]);
|
||||
let (steps, count) = (undo_steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute("addon.cutting.bridges", &json!({})).unwrap();
|
||||
assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["id"].clone()), (json!(0), json!(0), Value::Null));
|
||||
assert!(r["warning"].as_str().is_some(), "{r}");
|
||||
assert_eq!((undo_steps(&s), s.doc().unwrap().doc.node_count()), (steps, count));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_island_too_narrow_for_the_width_is_reported() {
|
||||
let mut s = session();
|
||||
shape_with_holes(&mut s, (100.0, 100.0, 100.0, 100.0), &[(149.0, 120.0, 2.0, 60.0)]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap();
|
||||
assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(0), json!(1)));
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("No bridge")), "{r}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn islands_left_without_a_bridge_are_reported_beside_the_ones_bridged() {
|
||||
let mut s = session();
|
||||
// A wide hole on the left and a 2 pt slot on the right.
|
||||
shape_with_holes(&mut s, (100.0, 100.0, 200.0, 100.0), &[(120.0, 120.0, 60.0, 60.0), (249.0, 120.0, 2.0, 60.0)]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap();
|
||||
assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(2), json!(1), json!(1)));
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("could not be joined")), "{r}");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!(!fills(&s, id_of(&r), 150.0, 110.0), "the wide hole is bridged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_run_keeps_its_original_on_a_layer_of_its_own() {
|
||||
let mut s = session();
|
||||
letter_o(&mut s);
|
||||
let first = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap();
|
||||
shape_with_holes(&mut s, (300.0, 100.0, 100.0, 100.0), &[(320.0, 120.0, 60.0, 60.0)]);
|
||||
let second = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap();
|
||||
let name = |r: &Value| node(&s, NodeId(r["original"].as_u64().unwrap())).name;
|
||||
assert_eq!((name(&first).as_deref(), name(&second).as_deref()), (Some("Stencil Original"), Some("Stencil Original 2")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
letter_o(&mut s);
|
||||
let steps = undo_steps(&s);
|
||||
for (key, p) in [
|
||||
("width", json!({"width": 0})),
|
||||
("width", json!({"width": 5000})),
|
||||
("width", json!({"width": "wide"})),
|
||||
("count", json!({"count": 0})),
|
||||
("count", json!({"count": 1.5})),
|
||||
("count", json!({"count": 17})),
|
||||
("count", json!({"count": "two"})),
|
||||
("direction", json!({"direction": "diagonal"})),
|
||||
("direction", json!({"direction": 90})),
|
||||
("keepOriginal", json!({"keepOriginal": "yes"})),
|
||||
] {
|
||||
let e = s.execute("addon.cutting.bridges", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(key), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert!(s.execute("addon.cutting.bridges", &json!({"width": 4})).is_ok(), "good params run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_too_detailed_to_bridge_is_refused_with_a_message_that_says_so() {
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let id = s
|
||||
.edit("dense", |d, sel| {
|
||||
// More anchors than Stencil Bridges measures.
|
||||
let mut zigzag = kurbo::BezPath::new();
|
||||
zigzag.move_to((100.0, 100.0));
|
||||
for i in 1..=vectorcraft_pathops::addons::stencil::MAX_STENCIL_SEGMENTS {
|
||||
zigzag.line_to((100.0 + i as f64 * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 }));
|
||||
}
|
||||
zigzag.close_path();
|
||||
let huge = vectorcraft_geom::PathData::from_bezpath(&zigzag);
|
||||
let n = vectorcraft_doc::Node::path(d.alloc_id(), huge, vectorcraft_doc::Appearance::default());
|
||||
let id = n.id;
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let steps = undo_steps(&s);
|
||||
let e = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap_err().to_string();
|
||||
assert!(e.contains("Stencil Bridges: the selected art is too large or too detailed to bridge"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_objects_without_outlines_stay_where_they_are() {
|
||||
for keep in [true, false] {
|
||||
let mut s = session();
|
||||
let o = letter_o(&mut s);
|
||||
// Type holding only a space has no outlines.
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": " ", "size": 24})).unwrap()["id"].as_u64().unwrap());
|
||||
let layer = |s: &Session, id: NodeId| s.doc().unwrap().doc.layer_of(id);
|
||||
let before = layer(&s, t);
|
||||
select(&mut s, &[o, t]);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": keep})).unwrap();
|
||||
assert_eq!(r["bridges"], json!(1), "{r}");
|
||||
assert!(node(&s, t).visible && layer(&s, t) == before, "keep {keep}: the type stays where it was");
|
||||
if keep {
|
||||
let held =
|
||||
s.doc().unwrap().doc.children(Some(NodeId(r["original"].as_u64().unwrap()))).map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>());
|
||||
assert_eq!(held, Some(vec![o]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_result_takes_the_place_of_the_topmost_selected_object() {
|
||||
let mut s = session();
|
||||
let o = letter_o(&mut s);
|
||||
let between = rect(&mut s, 400.0, 100.0, 50.0, 50.0);
|
||||
let o2 = shape_with_holes(&mut s, (500.0, 100.0, 100.0, 100.0), &[(520.0, 120.0, 60.0, 60.0)]);
|
||||
let above = rect(&mut s, 400.0, 300.0, 50.0, 50.0);
|
||||
select(&mut s, &[o, o2]);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": false})).unwrap();
|
||||
let made = id_of(&r);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let order: Vec<NodeId> = d.children(d.layer_of(made)).unwrap().iter().map(|n| n.id).collect();
|
||||
let at = |id: NodeId| order.iter().position(|i| *i == id).unwrap();
|
||||
assert!(at(between) < at(made) && at(made) < at(above), "{order:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_result_is_one_path_when_one_outline_is_left() {
|
||||
for (count, plain) in [(1, true), (2, false)] {
|
||||
let mut s = session();
|
||||
letter_o(&mut s);
|
||||
let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "count": count})).unwrap();
|
||||
let kind = node(&s, id_of(&r)).kind;
|
||||
// One bridge leaves a C, one outline; two leave two pieces.
|
||||
assert_eq!(matches!(kind, NodeKind::Path { .. }), plain, "count {count}");
|
||||
assert_eq!(matches!(kind, NodeKind::Compound { .. }), !plain, "count {count}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Weed Box and Lines (`addon.cutting.weed`), a command of the built-in Cutting Tools add-on for
|
||||
//! vinyl cutting: around the selected art it adds a weed box (a rectangle at a margin around the
|
||||
//! art) and weeding lines across it that stop at the art, so the waste vinyl around the art lifts
|
||||
//! off in pieces (<https://help.arlon.com/what-is-a-weeding-border>). The art is measured by the
|
||||
//! outlines a cutter cuts ([`geometry`]).
|
||||
|
||||
mod geometry;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::super::super::edit::selected_roots;
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::paint::swatch_solid;
|
||||
use super::super::super::pathops::{length_given, number_given};
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_selection, switch_or, text_param};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// Weed Box and Lines' command.
|
||||
pub const WEED: &str = "addon.cutting.weed";
|
||||
/// Which way the weeding lines run.
|
||||
pub const DIRECTIONS: [&str; 3] = ["horizontal", "vertical", "both"];
|
||||
/// The largest margin, gap or spacing, in points.
|
||||
const MAX_DISTANCE: f64 = 100_000.0;
|
||||
/// The most weeding lines each way.
|
||||
const MAX_COUNT: usize = 1000;
|
||||
/// The most pieces of weeding line one run adds.
|
||||
const MAX_PIECES: usize = 100_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.cutting.weed",
|
||||
"Weed Box and Lines…",
|
||||
["Object", "Plug-ins", "Cutting Tools"],
|
||||
None,
|
||||
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt (instead of count: as few lines as keep them at most this far apart), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
|
||||
has_selection,
|
||||
weed
|
||||
)]
|
||||
}
|
||||
|
||||
/// The distance `p` gives for `key` (0..[`MAX_DISTANCE`]), or `default`.
|
||||
fn distance(p: &Value, key: &str, default: f64) -> Result<f64> {
|
||||
match length_given(p, key, WEED)? {
|
||||
None => Ok(default),
|
||||
Some(v) if (0.0..=MAX_DISTANCE).contains(&v) => Ok(v),
|
||||
Some(_) => Err(bad(WEED, format!("`{key}` must be from 0 to {MAX_DISTANCE} pt"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many lines divide a side `length` long: `count`, or as few as keep them at most `spacing`
|
||||
/// apart.
|
||||
fn lines_across(length: f64, count: Option<usize>, spacing: Option<f64>) -> Result<usize> {
|
||||
let n = match spacing {
|
||||
// `length / spacing` strips, rounded up, need one line fewer.
|
||||
Some(s) => ((length / s - 1e-9).ceil() - 1.0).max(0.0),
|
||||
None => return Ok(count.unwrap_or(1)),
|
||||
};
|
||||
if n > MAX_COUNT as f64 {
|
||||
return Err(bad(WEED, format!("`spacing` makes more than {MAX_COUNT} lines across the box")));
|
||||
}
|
||||
Ok(n as usize)
|
||||
}
|
||||
|
||||
/// Where the Weeding group goes: `parent`, or, when `parent` is inside a clip group or clipping
|
||||
/// sublayer (a group edited in isolation), the container around the outermost of them. A clipping
|
||||
/// path would hide the lines and the box, which lie outside the art.
|
||||
fn outside_clips(d: &Document, parent: Option<NodeId>) -> Option<NodeId> {
|
||||
let clips = |id: NodeId| d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }));
|
||||
let (mut at, mut out) = (parent, parent);
|
||||
while let Some(p) = at {
|
||||
let up = d.parent_of(p);
|
||||
if clips(p) {
|
||||
match up {
|
||||
Some(up) if d.is_editable(up) => out = Some(up),
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
at = up;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn weed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let margin = distance(p, "margin", 9.0)?;
|
||||
let gap = distance(p, "gap", 0.0)?;
|
||||
let with_box = switch_or(p, "box", true, WEED)?;
|
||||
let direction = choice(p, WEED, "direction", &DIRECTIONS)?.unwrap_or("both");
|
||||
let count = match number_given(p, "count", WEED)? {
|
||||
None => None,
|
||||
Some(n) if n.fract() == 0.0 && (0.0..=MAX_COUNT as f64).contains(&n) => Some(n as usize),
|
||||
Some(_) => return Err(bad(WEED, format!("`count` must be a whole number from 0 to {MAX_COUNT}"))),
|
||||
};
|
||||
let spacing = match length_given(p, "spacing", WEED)? {
|
||||
None => None,
|
||||
Some(v) if v > 0.0 && v <= MAX_DISTANCE => Some(v),
|
||||
Some(_) => return Err(bad(WEED, format!("`spacing` must be more than 0 and at most {MAX_DISTANCE} pt"))),
|
||||
};
|
||||
if count.is_some() && spacing.is_some() {
|
||||
return Err(bad(WEED, "give `count` or `spacing`, not both"));
|
||||
}
|
||||
let weight = match length_given(p, "weight", WEED)? {
|
||||
None => 0.3,
|
||||
Some(v) if (0.01..=1000.0).contains(&v) => v,
|
||||
Some(_) => return Err(bad(WEED, "`weight` must be from 0.01 to 1000 pt")),
|
||||
};
|
||||
let swatch = text_param(p, "swatch", WEED)?.unwrap_or(REGISTRATION);
|
||||
let stroke = swatch_solid(&s.doc()?.doc, swatch, None).map_err(|e| bad(WEED, e))?;
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.is_empty() {
|
||||
return Err(bad(WEED, "select the art to weed"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let parent = outside_clips(d, s.doc()?.target_parent()?);
|
||||
// Placed files' art uses their resources (symbols) under names of their own.
|
||||
let placed = d.with_placed_art();
|
||||
let region = geometry::Reader::new(&placed).read_ids(&roots).map_err(|e| bad(WEED, e))?;
|
||||
let region = region.ok_or_else(|| bad(WEED, "the selection has no outlines to weed around"))?;
|
||||
let outline = region.outline().map_err(|e| bad(WEED, e))?;
|
||||
let art = outline.iter().fold(None, |r: Option<Rect>, &(a, b)| Some(r.map_or(Rect::from_points(a, b), |r| r.union_pt(a).union_pt(b))));
|
||||
let frame = art.ok_or_else(|| bad(WEED, "the selection has no outlines to weed around"))?.inflate(margin, margin);
|
||||
if !(frame.width().is_finite() && frame.height().is_finite()) {
|
||||
return Err(bad(WEED, "the selected art is too large to measure"));
|
||||
}
|
||||
let each = |on: bool, length: f64| if on { lines_across(length, count, spacing) } else { Ok(0) };
|
||||
let counts =
|
||||
geometry::Counts { horizontal: each(direction != "vertical", frame.height())?, vertical: each(direction != "horizontal", frame.width())? };
|
||||
let pieces = geometry::lines(®ion, &outline, frame, counts, gap, MAX_PIECES).map_err(|e| bad(WEED, e))?;
|
||||
if pieces.is_empty() && !with_box {
|
||||
return Err(EngineError::Other("Weed Box and Lines: no weeding line fits outside the art, and the weed box is off".into()));
|
||||
}
|
||||
let ap = Appearance::basic(Paint::None, stroke, weight);
|
||||
let (group, weed_box, lines) = s.edit("Weed Box and Lines", |d, sel| {
|
||||
let mut children = vec![];
|
||||
let mut weed_box = None;
|
||||
if with_box {
|
||||
let mut b = Node::path(d.alloc_id(), shapes::rectangle(frame), ap.clone());
|
||||
b.name = Some("Weed Box".into());
|
||||
weed_box = Some(b.id);
|
||||
children.push(Arc::new(b));
|
||||
}
|
||||
for (a, b) in &pieces {
|
||||
children.push(Arc::new(Node::path(d.alloc_id(), shapes::line(*a, *b), ap.clone())));
|
||||
}
|
||||
let mut g = Node::group(d.alloc_id(), children);
|
||||
g.name = Some("Weeding".into());
|
||||
let id = g.id;
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([id]);
|
||||
Ok((id, weed_box, pieces.len()))
|
||||
})?;
|
||||
Ok(json!({ "id": group.0, "box": weed_box.map(|b| b.0), "lines": lines }))
|
||||
}
|
||||
@@ -0,0 +1,769 @@
|
||||
//! The geometry of Weed Box and Lines: the selected art as the outlines a cutter cuts ([`Region`]),
|
||||
//! and the weeding lines across a box that stop at those outlines or at a gap from them
|
||||
//! ([`lines`]).
|
||||
//!
|
||||
//! A region is measured along one straight line at a time. A closed outline encloses its area by
|
||||
//! its fill rule, an open one is a line with no area, a group is the union of its members and a
|
||||
//! clip group is what its members draw inside its clipping path. Along a weeding line the region
|
||||
//! gives the stretches inside its area ([`Region::spans`]), and its outline pieces
|
||||
//! ([`Region::outline`]) give the stretches within the gap of an outline.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{BezPath, FillRule, PathEl, Point, Rect};
|
||||
|
||||
use super::super::super::super::pathops::node_path;
|
||||
|
||||
/// How closely curves are followed, in points.
|
||||
const TOLERANCE: f64 = 0.02;
|
||||
/// The most points the outlines of one selection are measured by, once curves are followed in
|
||||
/// straight segments (each subpath's points, its first one included).
|
||||
pub(super) const MAX_POINTS: usize = 200_000;
|
||||
/// The most tests of a segment against another one measuring a clip group's outlines takes.
|
||||
const MAX_PAIRS: usize = 40_000_000;
|
||||
/// The deepest groups, symbol instances and live objects are opened inside one another: as deep
|
||||
/// as any object is drawn.
|
||||
pub(super) const MAX_DEPTH: usize = vectorcraft_doc::depth::MAX_DRAWN_DEPTH;
|
||||
/// The most pairs of an outline segment and a weeding line it comes near that one run measures.
|
||||
const MAX_NEAR: usize = 10_000_000;
|
||||
/// Pieces of weeding line shorter than this, in points, are left out.
|
||||
const MIN_PIECE: f64 = 0.01;
|
||||
|
||||
/// A straight segment.
|
||||
pub(super) type Segment = (Point, Point);
|
||||
|
||||
/// One subpath followed in straight segments.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Poly {
|
||||
points: Vec<Point>,
|
||||
closed: bool,
|
||||
/// The box around `points`.
|
||||
bounds: Rect,
|
||||
}
|
||||
|
||||
impl Poly {
|
||||
/// The segments, with the closing one of a closed subpath.
|
||||
fn segments(&self) -> impl Iterator<Item = Segment> + '_ {
|
||||
let closing = self.closed.then(|| (self.points.last().copied(), self.points.first().copied()));
|
||||
self.points.windows(2).map(|w| (w[0], w[1])).chain(closing.and_then(|(a, b)| Some((a?, b?))))
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected art as the outlines a cutter cuts.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) enum Region {
|
||||
/// A path, compound path or type: its subpaths with the rule its closed ones fill by.
|
||||
Shape { polys: Vec<Poly>, rule: FillRule },
|
||||
/// Everything its members draw.
|
||||
Union(Vec<Region>),
|
||||
/// What `content` draws inside `clip`.
|
||||
Clip { clip: Box<Region>, content: Box<Region> },
|
||||
}
|
||||
|
||||
/// Reads the selected objects into a [`Region`], keeping count of the outline points.
|
||||
pub(super) struct Reader<'a> {
|
||||
doc: &'a Document,
|
||||
points: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub(super) fn new(doc: &'a Document) -> Self {
|
||||
Self { doc, points: 0 }
|
||||
}
|
||||
|
||||
/// The region of `nodes` together, `None` when they hold no outlines.
|
||||
pub(super) fn read(&mut self, nodes: &[&Node]) -> Result<Option<Region>, String> {
|
||||
let mut parts = vec![];
|
||||
for n in nodes {
|
||||
parts.extend(self.node(n, 0)?);
|
||||
}
|
||||
Ok(union(parts))
|
||||
}
|
||||
|
||||
fn node(&mut self, n: &Node, depth: usize) -> Result<Option<Region>, String> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(format!("the selected art is nested more than {MAX_DEPTH} levels deep"));
|
||||
}
|
||||
if !n.visible {
|
||||
return Ok(None);
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => Ok(None),
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) => self.shape(n),
|
||||
NodeKind::Group { clip, .. } | NodeKind::Layer { clip, .. } => {
|
||||
let members = n.editing_children();
|
||||
if *clip {
|
||||
let Some((first, rest)) = members.split_first() else { return Ok(None) };
|
||||
let Some(clip) = self.clip_region(first)? else { return Ok(None) };
|
||||
let mut parts = vec![];
|
||||
for c in rest {
|
||||
parts.extend(self.node(c, depth + 1)?);
|
||||
}
|
||||
Ok(union(parts).map(|content| Region::Clip { clip: Box::new(clip), content: Box::new(content) }))
|
||||
} else {
|
||||
let mut parts = vec![];
|
||||
for c in members {
|
||||
parts.extend(self.node(c, depth + 1)?);
|
||||
}
|
||||
Ok(union(parts))
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let (w, h) = (f64::from(im.width), f64::from(im.height));
|
||||
let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| im.xf * p);
|
||||
self.polygon(&corners)
|
||||
}
|
||||
// An instance of a symbol the document doesn't have draws nothing.
|
||||
NodeKind::SymbolInstance { .. } => match vectorcraft_render::effects::outline_object(Some(self.doc), n) {
|
||||
Some(art) => self.node(&art, depth + 1),
|
||||
None => Ok(None),
|
||||
},
|
||||
NodeKind::PlacedDocument(p) => {
|
||||
// The art of the file it shows; a file that can't be read shows its preview in its
|
||||
// box, which may be rotated.
|
||||
if vectorcraft_doc::placed_document::read_cached(p).is_none() {
|
||||
return self.polygon(&p.corners());
|
||||
}
|
||||
let art = vectorcraft_render::effects::expand_live_deep(Some(self.doc), n);
|
||||
if std::mem::discriminant(&art.kind) == std::mem::discriminant(&n.kind) {
|
||||
self.polygon(&p.corners())
|
||||
} else {
|
||||
self.node(&art, depth + 1)
|
||||
}
|
||||
}
|
||||
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {
|
||||
// The art a live object draws, as the exporters write it; an object that stays
|
||||
// as it is is measured by its box.
|
||||
let art = vectorcraft_render::effects::expand_live_deep(Some(self.doc), n);
|
||||
if std::mem::discriminant(&art.kind) == std::mem::discriminant(&n.kind) { self.frame(n) } else { self.node(&art, depth + 1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The region a clipping path `first` clips to, whatever its own visibility: the region the
|
||||
/// renderer clips to (a path, a compound path, type by its glyphs, a group's visible members,
|
||||
/// an image's frame). `None` when it clips to nothing, and the clipped art is hidden.
|
||||
fn clip_region(&mut self, first: &Node) -> Result<Option<Region>, String> {
|
||||
let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(first) else { return Ok(None) };
|
||||
let mut polys = self.polys(outline)?;
|
||||
// A region is filled: an open subpath clips as if closed.
|
||||
polys.iter_mut().for_each(|p| p.closed = true);
|
||||
Ok((!polys.is_empty()).then_some(Region::Shape { polys, rule }))
|
||||
}
|
||||
|
||||
/// The region of the objects `ids` together, each within the clipping paths of the clip groups
|
||||
/// and layers around it (an object selected inside a clip group shows only within its clipping
|
||||
/// path, and not at all inside a hidden group or layer; a clipping path is measured as its clip
|
||||
/// group), `None` when they show no outlines.
|
||||
pub(super) fn read_ids(&mut self, ids: &[NodeId]) -> Result<Option<Region>, String> {
|
||||
let doc = self.doc;
|
||||
let clips = |n: &Node| matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
// Every object's place in the tree, found in one walk.
|
||||
let places = doc.index_paths(ids.iter().copied());
|
||||
let mut paths = vec![];
|
||||
for id in ids {
|
||||
let Some(mut path) = places.get(id).cloned() else { continue };
|
||||
// A clipping path selected on its own stands for the art it shows: its clip group.
|
||||
while let (Some(n), Some(up)) = (doc.node_at(&path), path.split_last().map(|(_, up)| up).and_then(|up| doc.node_at(up))) {
|
||||
if !(clips(up) && up.editing_children().first().is_some_and(|f| f.id == n.id)) {
|
||||
break;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
paths.push(path);
|
||||
}
|
||||
// An object selected twice, or inside another selected object, is measured once, with it.
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
let mut kept: Vec<Vec<usize>> = vec![];
|
||||
for path in paths {
|
||||
if !kept.last().is_some_and(|k| path.starts_with(k)) {
|
||||
kept.push(path);
|
||||
}
|
||||
}
|
||||
let mut parts = vec![];
|
||||
'ids: for path in &kept {
|
||||
let Some(n) = doc.node_at(path) else { continue };
|
||||
// Art in a hidden group or layer isn't shown, and isn't measured.
|
||||
if (1..path.len()).any(|depth| path.get(..depth).and_then(|p| doc.node_at(p)).is_some_and(|c| !c.visible)) {
|
||||
continue;
|
||||
}
|
||||
let Some(mut region) = self.read(&[n])? else { continue };
|
||||
// The containers around the object, innermost first.
|
||||
let mut child = n.id;
|
||||
for depth in (1..path.len()).rev() {
|
||||
let Some(container) = path.get(..depth).and_then(|p| doc.node_at(p)) else { break };
|
||||
if clips(container)
|
||||
&& let Some(first) = container.editing_children().first().filter(|f| f.id != child)
|
||||
{
|
||||
let Some(clip) = self.clip_region(first)? else { continue 'ids };
|
||||
region = Region::Clip { clip: Box::new(clip), content: Box::new(region) };
|
||||
}
|
||||
child = container.id;
|
||||
}
|
||||
parts.push(region);
|
||||
}
|
||||
Ok(union(parts))
|
||||
}
|
||||
|
||||
/// A path, compound path or type as its outlines.
|
||||
fn shape(&mut self, n: &Node) -> Result<Option<Region>, String> {
|
||||
// Each anchor is at least one point, so a path past the budget errs before it is copied.
|
||||
if anchors(n) > MAX_POINTS.saturating_sub(self.points) {
|
||||
return Err(too_many());
|
||||
}
|
||||
let Some((path, rule)) = node_path(n) else { return Ok(None) };
|
||||
let polys = self.polys(path.to_bezpath())?;
|
||||
Ok((!polys.is_empty()).then_some(Region::Shape { polys, rule }))
|
||||
}
|
||||
|
||||
/// The box of an object whose outlines can't be read.
|
||||
fn frame(&mut self, n: &Node) -> Result<Option<Region>, String> {
|
||||
match n.geometric_bounds_with(&self.doc.symbol_boxes()) {
|
||||
Some(r) => self.polygon(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed polygon through `points`.
|
||||
fn polygon(&mut self, points: &[Point]) -> Result<Option<Region>, String> {
|
||||
let poly = poly(points.to_vec(), true);
|
||||
self.count(poly.iter().map(|p| p.points.len()).sum())?;
|
||||
Ok(poly.map(|p| Region::Shape { polys: vec![p], rule: FillRule::NonZero }))
|
||||
}
|
||||
|
||||
fn count(&mut self, n: usize) -> Result<(), String> {
|
||||
self.points = self.points.saturating_add(n);
|
||||
if self.points > MAX_POINTS { Err(too_many()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The subpaths of `path` followed in straight segments.
|
||||
fn polys(&mut self, path: BezPath) -> Result<Vec<Poly>, String> {
|
||||
let (mut out, mut current, points) = (vec![], vec![], Cell::new(0usize));
|
||||
let left = MAX_POINTS.saturating_sub(self.points);
|
||||
// Past the budget no further curve is followed (one curve gives at most
|
||||
// `MAX_FLATTEN_PER_CURVE` points), and the read fails below.
|
||||
let elements = path.into_iter().take_while(|_| points.get() <= left);
|
||||
vectorcraft_geom::flatten(elements, TOLERANCE, |el| {
|
||||
points.set(points.get() + 1);
|
||||
if points.get() > left {
|
||||
return;
|
||||
}
|
||||
match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
out.extend(poly(std::mem::take(&mut current), false));
|
||||
current.push(p);
|
||||
}
|
||||
PathEl::LineTo(p) => current.push(p),
|
||||
PathEl::ClosePath => out.extend(poly(std::mem::take(&mut current), true)),
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => {}
|
||||
}
|
||||
});
|
||||
if points.get() > left {
|
||||
return Err(too_many());
|
||||
}
|
||||
out.extend(poly(current, false));
|
||||
self.count(out.iter().map(|p: &Poly| p.points.len()).sum())?;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn too_many() -> String {
|
||||
format!("the selected art has too many outline points to measure (more than {MAX_POINTS})")
|
||||
}
|
||||
|
||||
/// The anchors of a path or compound path node, read without copying its path; 0 for type.
|
||||
fn anchors(n: &Node) -> usize {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.anchor_count(),
|
||||
NodeKind::Compound { children, .. } => children.iter().fold(0, |sum, c| sum.saturating_add(anchors(c))),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A subpath through `points`, `None` for fewer than two points or one that isn't finite.
|
||||
fn poly(points: Vec<Point>, closed: bool) -> Option<Poly> {
|
||||
if points.len() < 2 || points.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let first = *points.first()?;
|
||||
let bounds = points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p));
|
||||
Some(Poly { points, closed, bounds })
|
||||
}
|
||||
|
||||
/// One region of `parts`, `None` when there are none.
|
||||
fn union(mut parts: Vec<Region>) -> Option<Region> {
|
||||
match parts.len() {
|
||||
0 => None,
|
||||
1 => parts.pop(),
|
||||
_ => Some(Region::Union(parts)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` as (along, across) a weeding line: horizontal lines run along x, vertical ones along y.
|
||||
fn uv(p: Point, vertical: bool) -> (f64, f64) {
|
||||
if vertical { (p.y, p.x) } else { (p.x, p.y) }
|
||||
}
|
||||
|
||||
/// Sorts `spans` and joins those that overlap or touch.
|
||||
fn merged(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> {
|
||||
spans.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut out: Vec<(f64, f64)> = Vec::with_capacity(spans.len());
|
||||
for (a, b) in spans {
|
||||
match out.last_mut() {
|
||||
Some(last) if a <= last.1 => last.1 = last.1.max(b),
|
||||
_ => out.push((a, b)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where sorted, joined spans `a` and `b` overlap.
|
||||
fn intersected(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> {
|
||||
let (mut i, mut j, mut out) = (0, 0, vec![]);
|
||||
while let (Some(&(a0, a1)), Some(&(b0, b1))) = (a.get(i), b.get(j)) {
|
||||
let (lo, hi) = (a0.max(b0), a1.min(b1));
|
||||
if lo <= hi {
|
||||
out.push((lo, hi));
|
||||
}
|
||||
if a1 < b1 {
|
||||
i += 1;
|
||||
} else {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where segment a→b crosses the line `across` = `c`, along it, and which way (1 when `across`
|
||||
/// grows from a to b), `None` when it doesn't. Each crossing counts once: an end exactly on the
|
||||
/// line counts as past it.
|
||||
fn crosses(a: Point, b: Point, vertical: bool, c: f64) -> Option<(f64, i32)> {
|
||||
let ((u0, v0), (u1, v1)) = (uv(a, vertical), uv(b, vertical));
|
||||
((v0 <= c && v1 > c) || (v1 <= c && v0 > c)).then(|| (u0 + (c - v0) * (u1 - u0) / (v1 - v0), if v1 > v0 { 1 } else { -1 }))
|
||||
}
|
||||
|
||||
/// The stretches inside an area filled by `rule`, from where its outlines cross a line, sorted
|
||||
/// along it.
|
||||
fn filled(crossings: impl IntoIterator<Item = (f64, i32)>, rule: FillRule) -> Vec<(f64, f64)> {
|
||||
let (mut winding, mut start, mut out) = (0, 0.0, vec![]);
|
||||
let inside = |w: i32| match rule {
|
||||
FillRule::NonZero => w != 0,
|
||||
FillRule::EvenOdd => w % 2 != 0,
|
||||
};
|
||||
for (u, dir) in crossings {
|
||||
let was = inside(winding);
|
||||
winding += dir;
|
||||
match (was, inside(winding)) {
|
||||
(false, true) => start = u,
|
||||
(true, false) => out.push((start, u)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
merged(out)
|
||||
}
|
||||
|
||||
/// Where the closed outlines of a region's shapes cross a set of weeding lines: for each line, the
|
||||
/// crossings as (shape, place along the line, direction), sorted by shape and then by place. Shapes
|
||||
/// are numbered in the order [`Region::shapes`] lists them.
|
||||
pub(super) type Crossings = Vec<Vec<(usize, f64, i32)>>;
|
||||
|
||||
/// Where the shapes of each part of a region are numbered among its [`Crossings`].
|
||||
#[derive(Debug)]
|
||||
pub(super) enum Layout {
|
||||
Shape,
|
||||
/// The number of each part's first shape, from the union's first, and the parts' layouts.
|
||||
Union {
|
||||
starts: Vec<usize>,
|
||||
parts: Vec<Layout>,
|
||||
},
|
||||
/// The clipping path's shapes come first.
|
||||
Clip {
|
||||
clip_shapes: usize,
|
||||
clip: Box<Layout>,
|
||||
content: Box<Layout>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// The layout of `region` and how many shapes it has.
|
||||
pub(super) fn of(region: &Region) -> (Layout, usize) {
|
||||
match region {
|
||||
Region::Shape { .. } => (Layout::Shape, 1),
|
||||
Region::Union(parts) => {
|
||||
let (mut starts, mut layouts, mut n) = (vec![], vec![], 0);
|
||||
for r in parts {
|
||||
let (l, k) = Layout::of(r);
|
||||
starts.push(n);
|
||||
layouts.push(l);
|
||||
n += k;
|
||||
}
|
||||
(Layout::Union { starts, parts: layouts }, n)
|
||||
}
|
||||
Region::Clip { clip, content } => {
|
||||
let ((lc, a), (lt, b)) = (Layout::of(clip), Layout::of(content));
|
||||
(Layout::Clip { clip_shapes: a, clip: Box::new(lc), content: Box::new(lt) }, a + b)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`Crossings`] of `region` with the lines `across` = v0 + (k + 1)·step, k < `count`. Errs
|
||||
/// past [`MAX_NEAR`] crossings in all.
|
||||
pub(super) fn crossings(region: &Region, vertical: bool, v0: f64, step: f64, count: usize) -> Result<Crossings, String> {
|
||||
let mut shapes = vec![];
|
||||
region.shapes(&mut shapes);
|
||||
let at = |k: usize| v0 + step * (k as f64 + 1.0);
|
||||
// The lines a segment may cross: those from just below its lower end to its higher end.
|
||||
let candidates = |(a, b): Segment| {
|
||||
let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1);
|
||||
if step <= 0.0 || va == vb {
|
||||
return 0..0;
|
||||
}
|
||||
let first = (((va.min(vb) - v0) / step).floor() - 1.0).clamp(0.0, count as f64);
|
||||
let end = ((va.max(vb) - v0) / step).ceil().clamp(0.0, count as f64);
|
||||
(first as usize)..(end as usize)
|
||||
};
|
||||
let closed = |polys: &[Poly]| polys.iter().filter(|p| p.closed).flat_map(Poly::segments).collect::<Vec<_>>();
|
||||
let total = shapes.iter().flat_map(|(polys, _)| closed(polys)).fold(0usize, |n, s| n.saturating_add(candidates(s).len()));
|
||||
if total > MAX_NEAR {
|
||||
return Err("the weeding lines cross the art's outlines too many times to measure; use fewer lines".into());
|
||||
}
|
||||
let mut out: Crossings = vec![vec![]; count];
|
||||
for (i, (polys, _)) in shapes.iter().enumerate() {
|
||||
for (a, b) in closed(polys) {
|
||||
for k in candidates((a, b)) {
|
||||
if let (Some((u, dir)), Some(line)) = (crosses(a, b, vertical, at(k)), out.get_mut(k)) {
|
||||
line.push((i, u, dir));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for line in &mut out {
|
||||
line.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Region {
|
||||
/// The stretches of the line `across` = `c` (horizontal: y = c, along x; vertical: x = c,
|
||||
/// along y) inside the region's area, sorted and joined.
|
||||
pub(super) fn spans(&self, vertical: bool, c: f64) -> Vec<(f64, f64)> {
|
||||
match self {
|
||||
Region::Shape { polys, rule } => {
|
||||
let mut crossings: Vec<(f64, i32)> = vec![];
|
||||
for p in polys.iter().filter(|p| p.closed) {
|
||||
let (lo, hi) = if vertical { (p.bounds.x0, p.bounds.x1) } else { (p.bounds.y0, p.bounds.y1) };
|
||||
if c >= lo && c <= hi {
|
||||
crossings.extend(p.segments().filter_map(|(a, b)| crosses(a, b, vertical, c)));
|
||||
}
|
||||
}
|
||||
crossings.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
filled(crossings, *rule)
|
||||
}
|
||||
Region::Union(parts) => merged(parts.iter().flat_map(|r| r.spans(vertical, c)).collect()),
|
||||
Region::Clip { clip, content } => intersected(&clip.spans(vertical, c), &content.spans(vertical, c)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The region's shapes with their fill rules, in a fixed order.
|
||||
fn shapes<'a>(&'a self, out: &mut Vec<(&'a [Poly], FillRule)>) {
|
||||
match self {
|
||||
Region::Shape { polys, rule } => out.push((polys, *rule)),
|
||||
Region::Union(parts) => parts.iter().for_each(|r| r.shapes(out)),
|
||||
Region::Clip { clip, content } => {
|
||||
clip.shapes(out);
|
||||
content.shapes(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Region::spans`] on a weeding line, from `line`, the line's [`Crossings`] with the
|
||||
/// region's shapes, numbered from `base` (`layout` is the region's [`Layout`]). Only the parts
|
||||
/// the line crosses are visited: a part it doesn't cross has no stretch inside its area.
|
||||
pub(super) fn spans_on(&self, layout: &Layout, line: &[(usize, f64, i32)], base: usize) -> Vec<(f64, f64)> {
|
||||
if line.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
match (self, layout) {
|
||||
(Region::Shape { rule, .. }, Layout::Shape) => filled(line.iter().map(|&(_, u, dir)| (u, dir)), *rule),
|
||||
(Region::Union(parts), Layout::Union { starts, parts: layouts }) => {
|
||||
let (mut out, mut rest) = (vec![], line);
|
||||
while let Some(&(id, ..)) = rest.first() {
|
||||
// The part whose shapes the next crossing is on, and its crossings.
|
||||
let j = starts.partition_point(|&s| base + s <= id).saturating_sub(1);
|
||||
let (Some(r), Some(l), Some(&start)) = (parts.get(j), layouts.get(j), starts.get(j)) else { break };
|
||||
let end = starts.get(j + 1).map_or(usize::MAX, |&s| base + s);
|
||||
let n = rest.partition_point(|c| c.0 < end);
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
let (mine, after) = rest.split_at(n);
|
||||
out.extend(r.spans_on(l, mine, base + start));
|
||||
rest = after;
|
||||
}
|
||||
merged(out)
|
||||
}
|
||||
(Region::Clip { clip, content }, Layout::Clip { clip_shapes, clip: lc, content: lt }) => {
|
||||
let (a, b) = line.split_at(line.partition_point(|c| c.0 < base + clip_shapes));
|
||||
if a.is_empty() || b.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
intersected(&clip.spans_on(lc, a, base), &content.spans_on(lt, b, base + clip_shapes))
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `p` inside the region's area or on one of `segments`, the outlines it shows?
|
||||
fn contains(&self, p: Point, segments: &[Segment]) -> bool {
|
||||
const EPS: f64 = 1e-7;
|
||||
self.spans(false, p.y).iter().any(|&(a, b)| p.x >= a - EPS && p.x <= b + EPS) || segments.iter().any(|&(a, b)| distance(p, a, b) <= EPS)
|
||||
}
|
||||
|
||||
/// The pieces of outline the region shows: every outline of a shape and of a group's members,
|
||||
/// and in a clip group the members' outlines inside the clipping path and the clipping path's
|
||||
/// outline where the members' area or outlines are. Errs past [`MAX_PAIRS`], counted over
|
||||
/// every clip group in the region together.
|
||||
pub(super) fn outline(&self) -> Result<Vec<Segment>, String> {
|
||||
self.outline_counted(&mut 0)
|
||||
}
|
||||
|
||||
/// [`Region::outline`], adding the measure's work to `work`.
|
||||
fn outline_counted(&self, work: &mut usize) -> Result<Vec<Segment>, String> {
|
||||
match self {
|
||||
Region::Shape { polys, .. } => Ok(polys.iter().flat_map(Poly::segments).collect()),
|
||||
Region::Union(parts) => {
|
||||
let mut out = vec![];
|
||||
for r in parts {
|
||||
out.extend(r.outline_counted(work)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
Region::Clip { clip, content } => {
|
||||
// Each side's area is bounded by the outlines it shows, so the pieces are cut and
|
||||
// tested against those, never against art a nested clip hides.
|
||||
let (clip_shown, content_shown) = (clip.outline_counted(work)?, content.outline_counted(work)?);
|
||||
let mut out = within(&content_shown, clip, &clip_shown, work)?;
|
||||
out.extend(within(&clip_shown, content, &content_shown, work)?);
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of the region's closed outlines, those a nested clip hides included: what one
|
||||
/// [`Region::spans`] looks at, at most.
|
||||
fn closed_points(&self) -> usize {
|
||||
match self {
|
||||
Region::Shape { polys, .. } => polys.iter().filter(|p| p.closed).map(|p| p.points.len()).sum(),
|
||||
Region::Union(parts) => parts.iter().map(Region::closed_points).sum(),
|
||||
Region::Clip { clip, content } => clip.closed_points().saturating_add(content.closed_points()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn too_complex_clip() -> String {
|
||||
"a clip group in the selection has too many outline segments to measure".into()
|
||||
}
|
||||
|
||||
/// The pieces of `segments` inside `region` (or on its outlines), cut where they cross
|
||||
/// `region_segments`, the outlines the region shows. Each segment, and each piece of one tested
|
||||
/// for being inside, adds the region's closed outline points (hidden ones included) and its
|
||||
/// shown segment count to `work`, and the measure errs past [`MAX_PAIRS`].
|
||||
fn within(segments: &[Segment], region: &Region, region_segments: &[Segment], work: &mut usize) -> Result<Vec<Segment>, String> {
|
||||
let mut out = vec![];
|
||||
let cost = region.closed_points().saturating_add(region_segments.len()).max(1);
|
||||
let charge = |work: &mut usize| {
|
||||
*work = work.saturating_add(cost);
|
||||
if *work > MAX_PAIRS { Err(too_complex_clip()) } else { Ok(()) }
|
||||
};
|
||||
for &(a, b) in segments {
|
||||
charge(work)?;
|
||||
let mut cuts = vec![0.0, 1.0];
|
||||
let seg_box = Rect::from_points(a, b);
|
||||
for &(c, d) in region_segments {
|
||||
if touches(seg_box, Rect::from_points(c, d)) {
|
||||
cuts.extend(crossing(a, b, c, d));
|
||||
}
|
||||
}
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
cuts.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
|
||||
let at = |t: f64| a + (b - a) * t;
|
||||
for w in cuts.windows(2) {
|
||||
let (t0, t1) = (w[0], w[1]);
|
||||
if t1 - t0 < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
charge(work)?;
|
||||
if region.contains(at((t0 + t1) / 2.0), region_segments) {
|
||||
out.push((at(t0), at(t1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Do boxes `a` and `b` overlap or touch?
|
||||
fn touches(a: Rect, b: Rect) -> bool {
|
||||
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
|
||||
}
|
||||
|
||||
/// Where along a→b (0 to 1) segment c→d crosses or touches it: one place, or the ends of the
|
||||
/// shared stretch when the two lie on one line.
|
||||
fn crossing(a: Point, b: Point, c: Point, d: Point) -> Vec<f64> {
|
||||
let (r, s) = (b - a, d - c);
|
||||
let denom = r.cross(s);
|
||||
let qp = c - a;
|
||||
let len2 = r.hypot2();
|
||||
if len2 == 0.0 {
|
||||
return vec![];
|
||||
}
|
||||
if denom.abs() <= 1e-12 * len2.sqrt() * s.hypot().max(1e-300) {
|
||||
// Parallel: the ends of c→d on a→b when the two lie on one line.
|
||||
if qp.cross(r).abs() > 1e-9 * len2.sqrt() {
|
||||
return vec![];
|
||||
}
|
||||
return [c, d].iter().map(|p| (*p - a).dot(r) / len2).filter(|t| (0.0..=1.0).contains(t)).collect();
|
||||
}
|
||||
let t = qp.cross(s) / denom;
|
||||
let u = qp.cross(r) / denom;
|
||||
if (0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u) { vec![t] } else { vec![] }
|
||||
}
|
||||
|
||||
/// The distance from `p` to segment a→b.
|
||||
fn distance(p: Point, a: Point, b: Point) -> f64 {
|
||||
let ab = b - a;
|
||||
let len2 = ab.hypot2();
|
||||
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(p - (a + ab * t)).hypot()
|
||||
}
|
||||
|
||||
/// The stretch of the line `across` = `c` within `gap` of segment a→b, `None` when the line
|
||||
/// passes farther away. With no gap it is where the segment meets the line.
|
||||
fn near(a: Point, b: Point, vertical: bool, c: f64, gap: f64) -> Option<(f64, f64)> {
|
||||
let ((u0, v0), (u1, v1)) = (uv(a, vertical), uv(b, vertical));
|
||||
if gap <= 0.0 {
|
||||
if v0 == v1 {
|
||||
return (v0 == c).then_some((u0.min(u1), u0.max(u1)));
|
||||
}
|
||||
if c < v0.min(v1) || c > v0.max(v1) {
|
||||
return None;
|
||||
}
|
||||
let u = u0 + (c - v0) * (u1 - u0) / (v1 - v0);
|
||||
return Some((u, u));
|
||||
}
|
||||
let mut lo = f64::INFINITY;
|
||||
let mut hi = f64::NEG_INFINITY;
|
||||
let mut take = |x: f64, y: f64| {
|
||||
lo = lo.min(x);
|
||||
hi = hi.max(y);
|
||||
};
|
||||
// The round ends.
|
||||
for (u, v) in [(u0, v0), (u1, v1)] {
|
||||
let dv = (c - v).abs();
|
||||
if dv <= gap {
|
||||
let h = (gap * gap - dv * dv).max(0.0).sqrt();
|
||||
take(u - h, u + h);
|
||||
}
|
||||
}
|
||||
// The band along the segment: points whose foot falls on it, within the gap of it.
|
||||
let (du, dv) = (u1 - u0, v1 - v0);
|
||||
let len = du.hypot(dv);
|
||||
if len > 0.0 {
|
||||
// Each condition is linear in the position x along the line: k·x + m ≥ 0.
|
||||
let mut range = (f64::NEG_INFINITY, f64::INFINITY);
|
||||
let mut keep = |k: f64, m: f64| {
|
||||
if k == 0.0 {
|
||||
if m < 0.0 {
|
||||
range = (1.0, 0.0);
|
||||
}
|
||||
} else if k > 0.0 {
|
||||
range.0 = range.0.max(-m / k);
|
||||
} else {
|
||||
range.1 = range.1.min(-m / k);
|
||||
}
|
||||
};
|
||||
// The foot at or after a: (x - u0)·du + (c - v0)·dv ≥ 0.
|
||||
keep(du, -u0 * du + (c - v0) * dv);
|
||||
// The foot at or before b.
|
||||
keep(-du, u0 * du - (c - v0) * dv + len * len);
|
||||
// Within the gap on either side: |(x - u0)·dv - (c - v0)·du| ≤ gap·len.
|
||||
let cross0 = -u0 * dv - (c - v0) * du;
|
||||
keep(-dv, -cross0 + gap * len);
|
||||
keep(dv, cross0 + gap * len);
|
||||
if range.0 <= range.1 {
|
||||
take(range.0, range.1);
|
||||
}
|
||||
}
|
||||
(lo <= hi).then_some((lo, hi))
|
||||
}
|
||||
|
||||
/// How many weeding lines run each way.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Counts {
|
||||
pub horizontal: usize,
|
||||
pub vertical: usize,
|
||||
}
|
||||
|
||||
/// The weeding lines across `frame`: `n.horizontal` horizontal and `n.vertical` vertical lines that
|
||||
/// divide it evenly, each from one side of the frame to the other, left out where it is inside the
|
||||
/// region's area or within `gap` of one of its outlines (`outline`). Pieces are in order along each
|
||||
/// line, the horizontal lines first, top to bottom. Errs past [`MAX_NEAR`] pairs of an outline
|
||||
/// segment and a line it comes within `gap` of, past [`MAX_NEAR`] crossings of the region's
|
||||
/// outlines with the lines one way, or past `max_pieces` pieces.
|
||||
pub(super) fn lines(region: &Region, outline: &[Segment], frame: Rect, n: Counts, gap: f64, max_pieces: usize) -> Result<Vec<Segment>, String> {
|
||||
let mut out = vec![];
|
||||
let (layout, _) = Layout::of(region);
|
||||
for (vertical, count) in [(false, n.horizontal), (true, n.vertical)] {
|
||||
let ((u0, v0), (u1, v1)) = (uv(Point::new(frame.x0, frame.y0), vertical), uv(Point::new(frame.x1, frame.y1), vertical));
|
||||
let step = (v1 - v0) / (count as f64 + 1.0);
|
||||
// A frame with no height (for horizontal lines) or no width has no waste to divide.
|
||||
if step <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
// The lines (0-based) each outline segment comes within `gap` of: lines k (1-based) lie at
|
||||
// v0 + k·step.
|
||||
let reach = |&(a, b): &Segment| {
|
||||
let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1);
|
||||
let (lo, hi) = (va.min(vb) - gap, va.max(vb) + gap);
|
||||
let first = ((lo - v0) / step).ceil().max(1.0);
|
||||
let last = ((hi - v0) / step).floor().min(count as f64);
|
||||
if step > 0.0 && first <= last { (first as usize - 1)..(last as usize) } else { 0..0 }
|
||||
};
|
||||
// The outlines near each line, found once for all of them, by index into `outline`.
|
||||
let pairs = outline.iter().fold(0usize, |sum, s| sum.saturating_add(reach(s).len()));
|
||||
if pairs > MAX_NEAR {
|
||||
return Err("the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap".into());
|
||||
}
|
||||
let mut near_line: Vec<Vec<usize>> = vec![vec![]; count];
|
||||
for (j, s) in outline.iter().enumerate() {
|
||||
for k in reach(s) {
|
||||
if let Some(list) = near_line.get_mut(k) {
|
||||
list.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
let crossed = crossings(region, vertical, v0, step, count)?;
|
||||
for (i, segments) in near_line.iter().enumerate() {
|
||||
let c = v0 + step * (i as f64 + 1.0);
|
||||
let mut blocked = region.spans_on(&layout, crossed.get(i).map(Vec::as_slice).unwrap_or_default(), 0);
|
||||
blocked.extend(segments.iter().filter_map(|&j| outline.get(j)).filter_map(|&(a, b)| near(a, b, vertical, c, gap)));
|
||||
let mut from = u0;
|
||||
let point = |u: f64| if vertical { Point::new(c, u) } else { Point::new(u, c) };
|
||||
for (a, b) in merged(blocked) {
|
||||
if a - from >= MIN_PIECE && a <= u1 {
|
||||
out.push((point(from), point(a.min(u1))));
|
||||
}
|
||||
from = from.max(b);
|
||||
}
|
||||
if u1 - from >= MIN_PIECE {
|
||||
out.push((point(from), point(u1)));
|
||||
}
|
||||
if out.len() > max_pieces {
|
||||
return Err(format!("the weeding lines would be more than {max_pieces} pieces"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,915 @@
|
||||
//! Tests for `addon.cutting.weed`: a weed box around the selected art and weeding lines across it
|
||||
//! that stop at the art's outlines.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes};
|
||||
|
||||
use super::super::super::super::pathops::text_outline;
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, pts: &[(f64, f64)]) -> NodeId {
|
||||
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
|
||||
id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
/// Runs Weed Box and Lines with `p` and gives the group it made.
|
||||
fn weed(s: &mut Session, p: Value) -> (Value, Node) {
|
||||
let r = s.execute("addon.cutting.weed", &p).unwrap();
|
||||
let g = node(s, id_of(&r));
|
||||
(r, g)
|
||||
}
|
||||
|
||||
/// The weed box's rectangle in group `g`, if it has one.
|
||||
fn weed_box(g: &Node) -> Option<Rect> {
|
||||
g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Weed Box")).map(|c| c.geometric_bounds().unwrap())
|
||||
}
|
||||
|
||||
/// The weeding lines in group `g` as their two ends, rounded to 1/1000 pt.
|
||||
fn lines(g: &Node) -> Vec<((f64, f64), (f64, f64))> {
|
||||
let r = |v: f64| (v * 1000.0).round() / 1000.0;
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|c| c.name.is_none())
|
||||
.map(|c| match &c.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
let a: Vec<Point> = path.anchors().map(|(_, _, a)| a.p).collect();
|
||||
assert_eq!(a.len(), 2, "a weeding line is one straight segment");
|
||||
((r(a[0].x), r(a[0].y)), (r(a[1].x), r(a[1].y)))
|
||||
}
|
||||
other => panic!("not a path: {other:?}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_weed_box_and_lines_go_around_a_rectangle() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let (r, g) = weed(&mut s, json!({"margin": 10}));
|
||||
assert_eq!(g.name.as_deref(), Some("Weeding"));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 160.0, 150.0)));
|
||||
// One line each way through the middle, left out over the art.
|
||||
assert_eq!(
|
||||
lines(&g),
|
||||
[((90.0, 120.0), (100.0, 120.0)), ((150.0, 120.0), (160.0, 120.0)), ((125.0, 90.0), (125.0, 100.0)), ((125.0, 140.0), (125.0, 150.0))]
|
||||
);
|
||||
assert_eq!(r["lines"], json!(4));
|
||||
assert_eq!(r["box"], json!(weed_box_id(&g)));
|
||||
// Stroked in Registration with no fill, selected, as one undo step that takes it all away.
|
||||
for c in g.children().unwrap() {
|
||||
assert_eq!(c.appearance.fill_paint(), Paint::None, "no fill");
|
||||
assert!(c.appearance.stroke_paint().is_registration());
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [g.id]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g.id).is_none());
|
||||
}
|
||||
|
||||
fn weed_box_id(g: &Node) -> u64 {
|
||||
g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Weed Box")).unwrap().id.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_stop_at_the_outline_and_cross_the_hole_of_a_compound_path() {
|
||||
let mut s = session();
|
||||
let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let inner = rect(&mut s, 130.0, 130.0, 40.0, 40.0);
|
||||
select(&mut s, &[outer, inner]);
|
||||
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
// Both subpaths wind the same way, so the fill rule alone decides whether the inner one is a
|
||||
// hole.
|
||||
let same_way = |rule: FillRule| {
|
||||
move |d: &mut vectorcraft_doc::Document, _: &mut vectorcraft_doc::Selection| -> Result<()> {
|
||||
let Some(NodeKind::Compound { children, rule: r }) = d.node_mut(c).map(|n| &mut n.kind) else { panic!("not a compound path") };
|
||||
*r = rule;
|
||||
let area = |n: &Node| match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths[0].signed_area(),
|
||||
_ => panic!("not a path"),
|
||||
};
|
||||
let outer = area(&children[0]).signum();
|
||||
for child in children.iter_mut() {
|
||||
if area(child).signum() != outer
|
||||
&& let NodeKind::Path { path, .. } = &mut std::sync::Arc::make_mut(child).kind
|
||||
{
|
||||
path.reverse();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
s.edit("even-odd", same_way(FillRule::EvenOdd)).unwrap();
|
||||
select(&mut s, &[c]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
// The waste in the hole is cut too; the ring itself is not.
|
||||
assert_eq!(lines(&g), [((90.0, 150.0), (100.0, 150.0)), ((130.0, 150.0), (170.0, 150.0)), ((200.0, 150.0), (210.0, 150.0))]);
|
||||
// With the non-zero rule the inner subpath fills, and no line crosses it.
|
||||
s.edit("non-zero", same_way(FillRule::NonZero)).unwrap();
|
||||
select(&mut s, &[c]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
assert_eq!(lines(&g), [((90.0, 150.0), (100.0, 150.0)), ((200.0, 150.0), (210.0, 150.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gap_keeps_the_lines_away_from_the_outline() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 20, "gap": 5, "direction": "horizontal"}));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(80.0, 80.0, 170.0, 160.0)));
|
||||
assert_eq!(lines(&g), [((80.0, 120.0), (95.0, 120.0)), ((155.0, 120.0), (170.0, 120.0))]);
|
||||
// The gap is a distance from the outline: a line passing 5 pt beside a corner, with a gap of
|
||||
// 6, stops √11 pt short of the corner's height.
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let b = rect(&mut s, 200.0, 60.0, 10.0, 120.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 0, "gap": 6, "direction": "vertical"}));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(100.0, 60.0, 210.0, 180.0)));
|
||||
assert_eq!(lines(&g), [((155.0, 60.0), (155.0, 96.683)), ((155.0, 143.317), (155.0, 180.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_with_no_height_gets_no_lines_across_it() {
|
||||
// A horizontal line with no margin: the box is as flat as the line, and no weeding line runs
|
||||
// along it.
|
||||
let mut s = session();
|
||||
let l = line(&mut s, &[(100.0, 150.0), (200.0, 150.0)]);
|
||||
let n = s.doc().unwrap().doc.node_count();
|
||||
assert!(s.execute("addon.cutting.weed", &json!({"margin": 0, "direction": "horizontal", "box": false})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), n, "nothing to add");
|
||||
select(&mut s, &[l]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 0, "direction": "horizontal"}));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(100.0, 150.0, 200.0, 150.0)));
|
||||
assert_eq!(lines(&g), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_stops_a_line_where_it_crosses() {
|
||||
let mut s = session();
|
||||
line(&mut s, &[(100.0, 100.0), (100.0, 200.0)]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal", "gap": 2}));
|
||||
assert_eq!(lines(&g), [((90.0, 150.0), (98.0, 150.0)), ((102.0, 150.0), (110.0, 150.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_is_measured_by_its_glyph_outlines() {
|
||||
let mut s = session();
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "OHO", "size": 72})).unwrap());
|
||||
let glyphs = match &node(&s, t).kind {
|
||||
NodeKind::Text(t) => text_outline(t),
|
||||
_ => panic!("not type"),
|
||||
};
|
||||
let ink = glyphs.bounds().unwrap();
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "count": 3, "direction": "horizontal"}));
|
||||
let b = weed_box(&g).unwrap();
|
||||
for (got, want) in [(b.x0, ink.x0 - 10.0), (b.y0, ink.y0 - 10.0), (b.x1, ink.x1 + 10.0), (b.y1, ink.y1 + 10.0)] {
|
||||
assert!((got - want).abs() < 0.05, "the box is 10 pt around the glyphs: {b:?} vs {ink:?}");
|
||||
}
|
||||
// No piece of line runs over a glyph: each piece's middle is outside the ink.
|
||||
let shape = glyphs.to_bezpath();
|
||||
let pieces = lines(&g);
|
||||
assert!(pieces.len() > 3, "the letters break the lines: {pieces:?}");
|
||||
for ((x0, y0), (x1, y1)) in pieces {
|
||||
let mid = Point::new((x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
assert_eq!(shape.winding(mid), 0, "{mid:?} is outside the glyphs");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_group_is_measured_by_what_shows() {
|
||||
let mut s = session();
|
||||
let big = rect(&mut s, 0.0, 0.0, 400.0, 300.0);
|
||||
let clip = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
select(&mut s, &[big, clip]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10}));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 160.0, 150.0)));
|
||||
assert_eq!(lines(&g).len(), 4);
|
||||
// Art that shows only partly: the clip path's edge where the art is, and the art's edge
|
||||
// inside the clip.
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 120.0, 0.0, 100.0, 300.0);
|
||||
let clip = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
select(&mut s, &[art, clip]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
|
||||
assert_eq!(lines(&g), [((110.0, 120.0), (120.0, 120.0)), ((150.0, 120.0), (160.0, 120.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_as_the_clipping_path_clips_by_its_members() {
|
||||
// Make Clipping Mask takes a path, a compound path or type; an opened file can clip by a
|
||||
// group, as this one does.
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let id = s
|
||||
.edit("clip group", |d, sel| {
|
||||
let mut r = |x: f64, w: f64, y: f64, h: f64| {
|
||||
Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + w, y + h)), Appearance::default()))
|
||||
};
|
||||
let (a, b, art) = (r(100.0, 50.0, 100.0, 40.0), r(250.0, 50.0, 100.0, 40.0), r(0.0, 400.0, 0.0, 300.0));
|
||||
let clip = Arc::new(Node::group(d.alloc_id(), vec![a, b]));
|
||||
let mut g = Node::group(d.alloc_id(), vec![clip, art]);
|
||||
if let NodeKind::Group { clip, .. } = &mut g.kind {
|
||||
*clip = true;
|
||||
}
|
||||
let id = g.id;
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
// The art shows through both rectangles, and the line is cut between them too.
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 310.0, 150.0)));
|
||||
assert_eq!(lines(&g), [((90.0, 120.0), (100.0, 120.0)), ((150.0, 120.0), (250.0, 120.0)), ((300.0, 120.0), (310.0, 120.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_near_too_many_outline_segments_are_refused() {
|
||||
let mut s = session();
|
||||
// A zigzag of 12,000 segments; with a gap as tall as the box, each of 1,000 lines comes near
|
||||
// every segment.
|
||||
let mut zigzag = BezPath::new();
|
||||
zigzag.move_to((100.0, 100.0));
|
||||
for i in 1..=12_000 {
|
||||
zigzag.line_to((100.0 + f64::from(i) * 0.01, if i % 2 == 0 { 100.0 } else { 101.0 }));
|
||||
}
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let id = s
|
||||
.edit("zigzag", |d, sel| {
|
||||
let n = Node::path(d.alloc_id(), PathData::from_bezpath(&zigzag), Appearance::default());
|
||||
let id = n.id;
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let n = s.doc().unwrap().doc.node_count();
|
||||
let e = s.execute("addon.cutting.weed", &json!({"count": 1000, "gap": 50, "direction": "horizontal"})).unwrap_err();
|
||||
assert!(e.to_string().contains("too many outline segments"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), n);
|
||||
// Fewer lines measure.
|
||||
s.execute("addon.cutting.weed", &json!({"count": 10, "gap": 50, "direction": "horizontal"})).unwrap();
|
||||
}
|
||||
|
||||
/// Adds a clip group, clipping path `clip` over `art` (both unpainted), and selects it.
|
||||
fn clip_group(s: &mut Session, clip: PathData, art: PathData) -> NodeId {
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let id = s
|
||||
.edit("clip group", |d, sel| {
|
||||
let clip = Arc::new(Node::path(d.alloc_id(), clip, Appearance::default()));
|
||||
let art = Arc::new(Node::path(d.alloc_id(), art, Appearance::default()));
|
||||
let mut g = Node::group(d.alloc_id(), vec![clip, art]);
|
||||
if let NodeKind::Group { clip, .. } = &mut g.kind {
|
||||
*clip = true;
|
||||
}
|
||||
let id = g.id;
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(s, &[id]);
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_clipping_path_clips_as_if_closed() {
|
||||
let mut s = session();
|
||||
let mut v = BezPath::new();
|
||||
v.move_to((100.0, 100.0));
|
||||
v.line_to((150.0, 200.0));
|
||||
v.line_to((200.0, 100.0));
|
||||
clip_group(&mut s, PathData::from_bezpath(&v), shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 300.0)));
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
// The art shows inside the triangle the V closes; the line stops at its sides.
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 210.0, 210.0)));
|
||||
assert_eq!(lines(&g), [((90.0, 150.0), (125.0, 150.0)), ((175.0, 150.0), (210.0, 150.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_a_nested_clip_hides_adds_no_outline() {
|
||||
// A clip group, clipping path A, holding a clip group whose clipping path B shows a small
|
||||
// rectangle and hides a line that runs along A's bottom edge.
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let id = s
|
||||
.edit("nested clips", |d, sel| {
|
||||
let mut path = |p: PathData| Arc::new(Node::path(d.alloc_id(), p, Appearance::default()));
|
||||
let mut l = BezPath::new();
|
||||
l.move_to((0.0, 200.0));
|
||||
l.line_to((400.0, 200.0));
|
||||
let (b, shown, hidden) = (
|
||||
path(shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0))),
|
||||
path(shapes::rectangle(Rect::new(110.0, 110.0, 140.0, 130.0))),
|
||||
path(PathData::from_bezpath(&l)),
|
||||
);
|
||||
let a = path(shapes::rectangle(Rect::new(50.0, 50.0, 300.0, 200.0)));
|
||||
let clipped = |mut g: Node| {
|
||||
if let NodeKind::Group { clip, .. } = &mut g.kind {
|
||||
*clip = true;
|
||||
}
|
||||
g
|
||||
};
|
||||
let inner = Arc::new(clipped(Node::group(d.alloc_id(), vec![b, shown, hidden])));
|
||||
let outer = clipped(Node::group(d.alloc_id(), vec![a, inner]));
|
||||
let id = outer.id;
|
||||
d.insert(parent, usize::MAX, outer)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "count": 0}));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(100.0, 100.0, 150.0, 140.0)), "only the shown rectangle is measured");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_a_nested_clip_hides_counts_toward_the_clip_limit() {
|
||||
// A clip group, clipping path A of 20,000 segments, holding a clip group whose small clipping
|
||||
// path B shows a rectangle and hides a closed zigzag C of 20,000 points across every row of A.
|
||||
// The inner group shows four outline pieces, but testing each piece of A for being inside it
|
||||
// looks at all of C.
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let id = s
|
||||
.edit("nested clips", |d, sel| {
|
||||
let mut path = |p: BezPath| Arc::new(Node::path(d.alloc_id(), PathData::from_bezpath(&p), Appearance::default()));
|
||||
let mut a = BezPath::new();
|
||||
a.move_to((0.0, 0.0));
|
||||
for i in 1..=20_000 {
|
||||
a.line_to((f64::from(i) * 0.02, if i % 2 == 0 { 0.0 } else { 0.5 }));
|
||||
}
|
||||
a.line_to((400.0, 300.0));
|
||||
a.line_to((0.0, 300.0));
|
||||
a.close_path();
|
||||
let mut c = BezPath::new();
|
||||
c.move_to((300.0, 0.0));
|
||||
for i in 1..=20_000 {
|
||||
c.line_to((300.0 + f64::from(i) * 0.002, if i % 2 == 0 { 0.0 } else { 300.0 }));
|
||||
}
|
||||
c.close_path();
|
||||
let b = path(shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)).to_bezpath());
|
||||
let shown = path(shapes::rectangle(Rect::new(110.0, 110.0, 140.0, 130.0)).to_bezpath());
|
||||
let (a, c) = (path(a), path(c));
|
||||
let clipped = |mut g: Node| {
|
||||
if let NodeKind::Group { clip, .. } = &mut g.kind {
|
||||
*clip = true;
|
||||
}
|
||||
g
|
||||
};
|
||||
let inner = Arc::new(clipped(Node::group(d.alloc_id(), vec![b, shown, c])));
|
||||
let outer = clipped(Node::group(d.alloc_id(), vec![a, inner]));
|
||||
let id = outer.id;
|
||||
d.insert(parent, usize::MAX, outer)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let n = s.doc().unwrap().doc.node_count();
|
||||
let e = s.execute("addon.cutting.weed", &json!({"margin": 10, "count": 0})).unwrap_err();
|
||||
assert!(e.to_string().contains("too many outline segments"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_selected_inside_a_clip_group_is_measured_by_what_shows() {
|
||||
// The rectangle runs far outside the clipping path; selected on its own, it still shows only
|
||||
// inside it.
|
||||
let mut s = session();
|
||||
let clip = shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0));
|
||||
let g = clip_group(&mut s, clip, shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0)));
|
||||
let art = node(&s, g).children().unwrap()[1].id;
|
||||
select(&mut s, &[art]);
|
||||
let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
|
||||
assert_eq!(lines(&w), [((110.0, 120.0), (120.0, 120.0)), ((150.0, 120.0), (160.0, 120.0))]);
|
||||
// The clipping path selected on its own is measured by the art it shows.
|
||||
let clip_path = node(&s, g).children().unwrap()[0].id;
|
||||
select(&mut s, &[clip_path]);
|
||||
let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
|
||||
// With the art selected too, or the group, the group is measured once.
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let outline = |ids: &[NodeId]| super::geometry::Reader::new(d).read_ids(ids).unwrap().unwrap().outline().unwrap().len();
|
||||
assert_eq!(outline(&[clip_path, art]), outline(&[g]));
|
||||
assert_eq!(outline(&[g, art, g]), outline(&[g]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_in_a_hidden_group_is_left_out() {
|
||||
let mut s = session();
|
||||
let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let b = rect(&mut s, 200.0, 100.0, 50.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.edit("hide", |d, _| {
|
||||
if let Some(n) = d.node_mut(g) {
|
||||
n.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[a]);
|
||||
assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "nothing selected shows");
|
||||
select(&mut s, &[a, shown]);
|
||||
let (_, w) = weed(&mut s, json!({"margin": 10}));
|
||||
assert_eq!(weed_box(&w), Some(Rect::new(290.0, 290.0, 330.0, 330.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_in_a_hidden_group_is_not_measured() {
|
||||
// Selected art in a hidden group with more outline points than the limit doesn't count toward
|
||||
// it.
|
||||
let mut s = session();
|
||||
let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((100.0, 100.0));
|
||||
for i in 1..=super::geometry::MAX_POINTS as u32 {
|
||||
p.line_to((100.0 + f64::from(i) * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 }));
|
||||
}
|
||||
let dense = insert(&mut s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default()));
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.edit("hide", |d, _| {
|
||||
if let Some(n) = d.node_mut(g) {
|
||||
n.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[dense, shown]);
|
||||
let (_, w) = weed(&mut s, json!({"margin": 10}));
|
||||
assert_eq!(weed_box(&w), Some(Rect::new(290.0, 290.0, 330.0, 330.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_outlines_crossing_too_often_are_refused() {
|
||||
// A clipping path whose 700 edges each run across the art, and open art whose 700 segments
|
||||
// each run down across the clipping path: every pair crosses, and each of the 490,000 pieces
|
||||
// of art between crossings would be tested against all 700 edges.
|
||||
let zigzag = |across: bool| {
|
||||
let mut p = BezPath::new();
|
||||
for i in 0..=700 {
|
||||
let (along, side) = (100.0 + f64::from(i) * 0.25, if i % 2 == 0 { 100.0 } else { 300.0 });
|
||||
let pt = if across { (side, along) } else { (along, side) };
|
||||
if i == 0 { p.move_to(pt) } else { p.line_to(pt) }
|
||||
}
|
||||
p
|
||||
};
|
||||
let mut clip = zigzag(true);
|
||||
clip.close_path();
|
||||
let mut s = session();
|
||||
clip_group(&mut s, PathData::from_bezpath(&clip), PathData::from_bezpath(&zigzag(false)));
|
||||
let n = s.doc().unwrap().doc.node_count();
|
||||
let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("too many outline segments"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), n);
|
||||
}
|
||||
|
||||
/// Each weeding line's stretches inside the art, found from the crossings indexed once for all the
|
||||
/// lines, match those found by measuring the whole art along that line.
|
||||
#[test]
|
||||
fn indexed_crossings_find_the_same_stretches() {
|
||||
let mut s = session();
|
||||
let mut ids = vec![];
|
||||
let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let inner = rect(&mut s, 130.0, 130.0, 40.0, 40.0);
|
||||
select(&mut s, &[outer, inner]);
|
||||
ids.push(id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()));
|
||||
let big = rect(&mut s, 220.0, 50.0, 200.0, 200.0);
|
||||
let window = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 80, "width": 90, "height": 120})).unwrap());
|
||||
select(&mut s, &[big, window]);
|
||||
ids.push(id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()));
|
||||
ids.push(id_of(&s.execute("text.create", &json!({"x": 100, "y": 320, "text": "WEED 8", "size": 60})).unwrap()));
|
||||
ids.push(line(&mut s, &[(90.0, 40.0), (450.0, 380.0)]));
|
||||
let a = rect(&mut s, 300.0, 300.0, 30.0, 30.0);
|
||||
let b = id_of(&s.execute("shape.ellipse", &json!({"x": 320, "y": 310, "width": 60, "height": 40})).unwrap());
|
||||
select(&mut s, &[a, b]);
|
||||
ids.push(id_of(&s.execute("object.group", &json!({})).unwrap()));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let nodes: Vec<&Node> = ids.iter().filter_map(|id| d.node(*id)).collect();
|
||||
let region = super::geometry::Reader::new(d).read(&nodes).unwrap().unwrap();
|
||||
let (layout, _) = super::geometry::Layout::of(®ion);
|
||||
let count = 97;
|
||||
for vertical in [false, true] {
|
||||
let (v0, v1) = (30.0, 400.0);
|
||||
let step = (v1 - v0) / (count as f64 + 1.0);
|
||||
let crossed = super::geometry::crossings(®ion, vertical, v0, step, count).unwrap();
|
||||
assert_eq!(crossed.len(), count);
|
||||
let mut hit = 0;
|
||||
for (k, line) in crossed.iter().enumerate() {
|
||||
let c = v0 + step * (k as f64 + 1.0);
|
||||
let want = region.spans(vertical, c);
|
||||
hit += usize::from(!want.is_empty());
|
||||
assert_eq!(region.spans_on(&layout, line, 0), want, "line {k}, vertical {vertical}");
|
||||
}
|
||||
assert!(hit > count / 2, "most lines cross the art ({hit})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_nested_too_deep_is_refused() {
|
||||
// A rectangle inside `levels` groups, each holding the next. A document keeps none this deep,
|
||||
// but the art symbol instances and live objects draw nests further.
|
||||
let doc = vectorcraft_doc::Document::new(800.0, 600.0);
|
||||
let nested = |levels: usize| {
|
||||
let mut n = Node::path(NodeId(1), shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), Appearance::default());
|
||||
for i in 0..levels {
|
||||
n = Node::group(NodeId(i as u64 + 2), vec![Arc::new(n)]);
|
||||
}
|
||||
n
|
||||
};
|
||||
let read = |n: &Node| super::geometry::Reader::new(&doc).read(&[n]);
|
||||
assert!(read(&nested(super::geometry::MAX_DEPTH)).unwrap().is_some());
|
||||
let e = read(&nested(super::geometry::MAX_DEPTH + 1)).unwrap_err();
|
||||
assert!(e.contains("nested more than"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacing_divides_the_box_into_strips_no_wider() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 10.0, 40.0);
|
||||
// The box is 60 pt tall: three strips of 20 pt.
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "spacing": 25, "direction": "horizontal", "box": false}));
|
||||
assert_eq!(weed_box(&g), None);
|
||||
let ys: Vec<f64> = lines(&g).iter().map(|l| l.0.1).collect();
|
||||
assert_eq!(ys, [110.0, 110.0, 130.0, 130.0]);
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 10.0, 40.0);
|
||||
assert!(s.execute("addon.cutting.weed", &json!({"spacing": 0.01})).is_err(), "too many lines");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lines_take_a_swatch() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Cut", "color": "cmyk 0 100 0 0", "spot": true})).unwrap();
|
||||
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let (_, g) = weed(&mut s, json!({"swatch": "Cut", "weight": 1}));
|
||||
for c in g.children().unwrap() {
|
||||
match c.appearance.stroke_paint() {
|
||||
Paint::Solid { swatch, .. } => assert_eq!(swatch.as_deref(), Some("Cut")),
|
||||
other => panic!("stroke {other:?}"),
|
||||
}
|
||||
assert_eq!(c.appearance.stroke_width(), 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the object `make` makes with a new id to the current layer, selects it and gives its id.
|
||||
fn insert(s: &mut Session, make: impl FnOnce(NodeId) -> Node) -> NodeId {
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let id = s
|
||||
.edit("insert", |d, _| {
|
||||
let n = make(d.alloc_id());
|
||||
let id = n.id;
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(s, &[id]);
|
||||
id
|
||||
}
|
||||
|
||||
/// A 100 pt square turned 45° about (300, 300): a diamond 141.42 pt across.
|
||||
fn diamond_xf() -> Affine {
|
||||
Affine::translate((300.0, 300.0)) * Affine::rotate(std::f64::consts::FRAC_PI_4) * Affine::translate((-50.0, -50.0))
|
||||
}
|
||||
|
||||
/// The weeding lines of `g` at height `y` (to 1/1000 pt).
|
||||
fn at(g: &Node, y: f64) -> Vec<(f64, f64)> {
|
||||
lines(g).into_iter().filter(|((_, y0), (_, y1))| *y0 == y && *y1 == y).map(|((x0, _), (x1, _))| (x0, x1)).collect()
|
||||
}
|
||||
|
||||
/// The diamond's weeding with three horizontal lines and a margin of 10: the box, and where the
|
||||
/// first line's left piece ends.
|
||||
fn diamond_weeding(s: &mut Session) -> (Rect, f64) {
|
||||
let (_, g) = weed(s, json!({"margin": 10, "count": 3, "direction": "horizontal"}));
|
||||
let b = weed_box(&g).unwrap();
|
||||
let y = ((b.y0 + b.height() / 4.0) * 1000.0).round() / 1000.0;
|
||||
let first = at(&g, y);
|
||||
assert_eq!(first.len(), 2, "{first:?}");
|
||||
(b, first[0].1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_is_measured_by_its_frame_as_turned() {
|
||||
let mut s = session();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "image".into(),
|
||||
width: 100,
|
||||
height: 100,
|
||||
xf: diamond_xf(),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
insert(&mut s, |id| Node::new(id, NodeKind::Image(Box::new(im))));
|
||||
let (b, end) = diamond_weeding(&mut s);
|
||||
let half = 50.0 * std::f64::consts::SQRT_2;
|
||||
assert!((b.x0 - (290.0 - half)).abs() < 1e-3 && (b.y1 - (310.0 + half)).abs() < 1e-3, "{b:?}");
|
||||
// A quarter of the box down, the line meets the diamond's upper left edge, not its bounds.
|
||||
let y = b.y0 + b.height() / 4.0;
|
||||
assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_file_is_measured_by_the_art_it_shows() {
|
||||
let dir = crate::tests_links::Folder::new("weed-placed");
|
||||
// A file with a 60 × 40 artboard and a 20 pt wide rectangle at each side (hidden when
|
||||
// `hidden`), placed centered on (200, 150) and selected.
|
||||
let place = |s: &mut Session, name: &str, hidden: bool| {
|
||||
let src = dir.file(name);
|
||||
let mut d = vectorcraft_doc::Document::new(60.0, 40.0);
|
||||
let layer = d.layers[0].id;
|
||||
for x in [0.0, 40.0] {
|
||||
let id = d.alloc_id();
|
||||
let look = Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0);
|
||||
let mut n = Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 40.0)), look);
|
||||
n.visible = !hidden;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
}
|
||||
crate::tests_links::write(&src, &vectorcraft_format::save_file(&d));
|
||||
let r = s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap();
|
||||
select(s, &[NodeId(r["ids"][0].as_u64().unwrap())]);
|
||||
};
|
||||
let mut s = session();
|
||||
place(&mut s, "pair.vectorcraft", false);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
// The rectangles lie at 170..190 and 210..230; the line runs between them too.
|
||||
assert_eq!(at(&g, 150.0), [(160.0, 170.0), (190.0, 210.0), (230.0, 240.0)]);
|
||||
// A file read but shown in a box with no size shows nothing, and its box isn't measured.
|
||||
let id = NodeId(s.execute("file.place", &json!({"path": dir.file("pair.vectorcraft"), "at": [400, 150]})).unwrap()["ids"][0].as_u64().unwrap());
|
||||
s.edit("no size", |d, _| {
|
||||
if let Some(NodeKind::PlacedDocument(p)) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
(p.width, p.height) = (0.0, 0.0);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("has no outlines"), "{e}");
|
||||
// A file read with nothing showing has no outlines, and its box isn't measured instead.
|
||||
let mut s = session();
|
||||
place(&mut s, "hidden.vectorcraft", true);
|
||||
let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("has no outlines"), "{e}");
|
||||
// A file whose art is an instance of a symbol of its own: the instance's art is measured.
|
||||
let src = dir.file("symbol.vectorcraft");
|
||||
let mut d = vectorcraft_doc::Document::new(60.0, 40.0);
|
||||
let look = Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0);
|
||||
let art = Node::path(NodeId(900), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 40.0)), look);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(art) });
|
||||
let (layer, id) = (d.layers[0].id, d.alloc_id());
|
||||
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY })).unwrap();
|
||||
crate::tests_links::write(&src, &vectorcraft_format::save_file(&d));
|
||||
let mut s = session();
|
||||
let r = s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap();
|
||||
select(&mut s, &[NodeId(r["ids"][0].as_u64().unwrap())]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10}));
|
||||
let b = weed_box(&g).unwrap();
|
||||
assert!(b.x0 >= 160.0 - 1e-6 && b.x1 <= 240.0 + 1e-6 && b.width() < 41.0, "the bar, not the whole box: {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_file_that_cant_be_read_is_measured_by_its_box_as_turned() {
|
||||
let mut s = session();
|
||||
let p = vectorcraft_doc::PlacedDocument {
|
||||
link: vectorcraft_doc::LinkInfo::new("/no/such/file.pdf"),
|
||||
key: "missing".into(),
|
||||
bounding: false,
|
||||
page_box: Default::default(),
|
||||
width: 100.0,
|
||||
height: 100.0,
|
||||
xf: diamond_xf(),
|
||||
placement: Default::default(),
|
||||
};
|
||||
insert(&mut s, |id| Node::new(id, NodeKind::PlacedDocument(Box::new(p))));
|
||||
let (b, end) = diamond_weeding(&mut s);
|
||||
let half = 50.0 * std::f64::consts::SQRT_2;
|
||||
let y = b.y0 + b.height() / 4.0;
|
||||
assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_instance_is_measured_by_its_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 20.0, 40.0);
|
||||
let b = rect(&mut s, 140.0, 100.0, 20.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let inst = id_of(&s.execute("symbol.new", &json!({"name": "Pair"})).unwrap());
|
||||
select(&mut s, &[inst]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
// The line runs between the two rectangles too.
|
||||
assert_eq!(at(&g, 120.0), [(90.0, 100.0), (120.0, 140.0), (160.0, 170.0)]);
|
||||
// An instance of a symbol the document doesn't have draws nothing, and has no outlines.
|
||||
s.edit("lose the symbol", |d, _| {
|
||||
if let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node_mut(inst).map(|n| &mut n.kind) {
|
||||
*symbol = "Missing".into();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[inst]);
|
||||
let n = s.doc().unwrap().doc.node_count();
|
||||
let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("has no outlines"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), n);
|
||||
let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
|
||||
select(&mut s, &[inst, shown]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10}));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(290.0, 290.0, 330.0, 330.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blend_is_measured_by_the_art_it_draws() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 20.0, 40.0);
|
||||
let b = rect(&mut s, 200.0, 100.0, 20.0, 40.0);
|
||||
let blend = id_of(&s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap());
|
||||
select(&mut s, &[blend]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
// The step halfway between the two rectangles stops the line too.
|
||||
assert_eq!(at(&g, 120.0), [(90.0, 100.0), (120.0, 150.0), (170.0, 200.0), (220.0, 230.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_group_goes_on_top_of_the_current_layer_and_hidden_layers_are_left_out() {
|
||||
let mut s = session();
|
||||
let first = s.doc().unwrap().doc.layers[0].id;
|
||||
let hidden = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let art = id_of(&s.execute("layer.new", &json!({"name": "Art"})).unwrap());
|
||||
let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
|
||||
let below = rect(&mut s, 400.0, 400.0, 20.0, 20.0);
|
||||
s.edit("hide", |d, _| {
|
||||
if let Some(n) = d.node_mut(first) {
|
||||
n.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[hidden]);
|
||||
assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "art in a hidden layer doesn't show");
|
||||
select(&mut s, &[hidden, shown]);
|
||||
let (_, g) = weed(&mut s, json!({"margin": 10}));
|
||||
assert_eq!(weed_box(&g), Some(Rect::new(290.0, 290.0, 330.0, 330.0)));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(g.id), Some(art));
|
||||
assert_eq!(d.node(art).unwrap().children().unwrap().last().map(|c| c.id), Some(g.id), "on top");
|
||||
// A hidden object selected on its own shows nothing.
|
||||
s.edit("hide", |d, _| {
|
||||
if let Some(n) = d.node_mut(below) {
|
||||
n.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[below]);
|
||||
assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "a hidden object doesn't show");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_group_goes_outside_a_clip_group_edited_in_isolation() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let g = clip_group(&mut s, shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0)));
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let art = node(&s, g).children().unwrap()[1].id;
|
||||
select(&mut s, &[art]);
|
||||
let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
// The clipping path would hide the lines and the box around the art inside it.
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(w.id), Some(layer));
|
||||
assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
|
||||
// A plain group edited in isolation inside a clip group: the group goes outside the clip group.
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let (inner, art) = s
|
||||
.edit("clip group around a group", |d, _| {
|
||||
let clip = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), Appearance::default()));
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0)), Appearance::default());
|
||||
let art_id = art.id;
|
||||
let inner = Node::group(d.alloc_id(), vec![Arc::new(art)]);
|
||||
let inner_id = inner.id;
|
||||
let mut g = Node::group(d.alloc_id(), vec![clip, Arc::new(inner)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut g.kind {
|
||||
*clip = true;
|
||||
}
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
Ok((inner_id, art_id))
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("object.isolate", &json!({"id": inner.0})).unwrap();
|
||||
select(&mut s, &[art]);
|
||||
let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(w.id), parent);
|
||||
assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
|
||||
}
|
||||
|
||||
/// Adds one path of `count` open vertical subpaths 2 pt apart, from (100, 100) down to y = 200.
|
||||
fn bars(s: &mut Session, count: u32) -> NodeId {
|
||||
let mut p = BezPath::new();
|
||||
for i in 0..count {
|
||||
let x = 100.0 + f64::from(i) * 2.0;
|
||||
p.move_to((x, 100.0));
|
||||
p.line_to((x, 200.0));
|
||||
}
|
||||
insert(s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_than_the_most_pieces_of_line_is_refused() {
|
||||
// 1,000 lines each cut into 100 pieces by 101 bars: as many as one run adds.
|
||||
let mut s = session();
|
||||
bars(&mut s, 101);
|
||||
let r = s.execute("addon.cutting.weed", &json!({"margin": 0, "count": 1000, "direction": "horizontal"})).unwrap();
|
||||
assert_eq!(r["lines"], json!(super::MAX_PIECES));
|
||||
// One bar more makes 1,000 pieces more.
|
||||
let mut s = session();
|
||||
bars(&mut s, 102);
|
||||
let n = s.doc().unwrap().doc.node_count();
|
||||
let e = s.execute("addon.cutting.weed", &json!({"margin": 0, "count": 1000, "direction": "horizontal"})).unwrap_err();
|
||||
assert!(e.to_string().contains("more than 100000 pieces"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_with_more_than_the_most_outline_points_is_refused() {
|
||||
// An open zigzag of `points` points: one subpath, measured by its points.
|
||||
let zigzag = |s: &mut Session, points: u32| {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((100.0, 100.0));
|
||||
for i in 1..points {
|
||||
p.line_to((100.0 + f64::from(i) * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 }));
|
||||
}
|
||||
insert(s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default()));
|
||||
};
|
||||
let mut s = session();
|
||||
zigzag(&mut s, super::geometry::MAX_POINTS as u32);
|
||||
s.execute("addon.cutting.weed", &json!({"count": 0})).unwrap();
|
||||
let mut s = session();
|
||||
zigzag(&mut s, super::geometry::MAX_POINTS as u32 + 1);
|
||||
let e = s.execute("addon.cutting.weed", &json!({"count": 0})).unwrap_err();
|
||||
assert!(e.to_string().contains("too many outline points"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_and_an_empty_selection_are_refused() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
for p in [
|
||||
json!({"margin": -1}),
|
||||
json!({"gap": "x"}),
|
||||
json!({"count": 1.5}),
|
||||
json!({"count": 1001}),
|
||||
json!({"count": 2, "spacing": 10}),
|
||||
json!({"spacing": 0}),
|
||||
json!({"direction": "diagonal"}),
|
||||
json!({"box": "yes"}),
|
||||
json!({"weight": 0}),
|
||||
json!({"swatch": "no such swatch"}),
|
||||
json!({"swatch": 3}),
|
||||
json!({"box": false, "count": 0}),
|
||||
] {
|
||||
let n = s.doc().unwrap().doc.node_count();
|
||||
assert!(s.execute("addon.cutting.weed", &p).is_err(), "{p}");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), n, "nothing added for {p}");
|
||||
}
|
||||
// The same art with good params is weeded; with nothing selected it is refused.
|
||||
s.execute("addon.cutting.weed", &json!({"count": 2, "gap": "1 mm"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
assert!(s.execute("addon.cutting.weed", &json!({})).is_err());
|
||||
}
|
||||
@@ -21,7 +21,7 @@ use super::super::menucmds::whole_or;
|
||||
use super::super::object::choice;
|
||||
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
|
||||
use super::super::typecmd::refresh_bounds;
|
||||
use super::super::typemenu::text_ids;
|
||||
use super::super::typemenu::{bake_dynamic_text, text_ids};
|
||||
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Release Type on a Path…",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
has_selection,
|
||||
release_path
|
||||
),
|
||||
@@ -230,8 +230,9 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> {
|
||||
|
||||
/// `t`, type on a path, as point type on one straight line: the same runs and character and
|
||||
/// paragraph attributes, its baseline starting where its first character sat on the path (in the
|
||||
/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for
|
||||
/// other type, or when it can't be placed.
|
||||
/// object's own text space, so its transform stays). Type on a Path Options are dropped, and
|
||||
/// Dynamic Text is turned off at the sizes it draws the text at. None for other type, or when it
|
||||
/// can't be placed.
|
||||
fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
let TextKind::OnPath { path, .. } = &t.kind else { return None };
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
@@ -244,6 +245,8 @@ fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some(p)
|
||||
})?;
|
||||
let mut out = t.clone();
|
||||
// Point type has no brackets to fit: it keeps the sizes the path drew it at.
|
||||
bake_dynamic_text(&mut out);
|
||||
out.kind = TextKind::Point;
|
||||
out.path_effect = Default::default();
|
||||
out.path_align = Default::default();
|
||||
|
||||
@@ -32,8 +32,8 @@ use super::opacitymask::percent;
|
||||
use super::paint::paint_from;
|
||||
use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs};
|
||||
use super::{
|
||||
CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, id_param, ids_param, index, leaf_targets,
|
||||
ok, paint_targets, str_param, switch_or, targets,
|
||||
CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, ids_param, index, leaf_targets,
|
||||
object_param, ok, paint_targets, str_param, switch_or, targets,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -726,8 +726,8 @@ fn clear(n: &mut Node) {
|
||||
|
||||
fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.transfer";
|
||||
let source = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let target = id_param(p, "target").ok_or_else(|| bad(C, "missing `target` id"))?;
|
||||
let source = object_param(p, "source", C)?.ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let target = object_param(p, "target", C)?.ok_or_else(|| bad(C, "missing `target` id"))?;
|
||||
if source == target {
|
||||
return Err(bad(C, "`source` and `target` are the same object"));
|
||||
}
|
||||
@@ -1201,7 +1201,7 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Sample enabled attributes with transform-aware character dimensions and atomic validation.
|
||||
fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.copyFrom";
|
||||
let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let clicked = object_param(p, "source", C)?.ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?);
|
||||
let defaults_only = switch_or(p, "defaultsOnly", false, C)?;
|
||||
if defaults_only && (reverse || append || p.get("ids").is_some()) {
|
||||
@@ -1512,6 +1512,9 @@ impl Picked {
|
||||
stroke_width: st.stroke_width,
|
||||
overprint_fill: st.overprint_fill,
|
||||
overprint_stroke: st.overprint_stroke,
|
||||
// The space before a line's first character belongs to where the character is,
|
||||
// not to how it looks: a sample from one doesn't move the target's (#5111).
|
||||
kerning_before: st.kerning_before,
|
||||
..cs.clone()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ use std::collections::HashSet;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{self as brush, ArtBrush, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation};
|
||||
use vectorcraft_brush::{
|
||||
self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation,
|
||||
};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
@@ -169,10 +171,12 @@ pub struct BuiltinBrushLibrary {
|
||||
pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
|
||||
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
|
||||
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -290,6 +294,31 @@ fn calligraphic_nibs() -> BrushLibrary {
|
||||
built("Calligraphic Nibs", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// A bristle brush: `shape`, then size (pt), bristle length, density, thickness, paint opacity
|
||||
/// and stiffness (%).
|
||||
fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, opacity, stiffness]: [f64; 6]) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) }
|
||||
}
|
||||
|
||||
/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for
|
||||
/// blending and texture.
|
||||
fn bristle_brushes() -> BrushLibrary {
|
||||
use BristleShape::*;
|
||||
let brushes = vec![
|
||||
bristle("Fine Liner", RoundPoint, [2.0, 140.0, 30.0, 30.0, 90.0, 75.0]),
|
||||
bristle("Pointed Flat", FlatPoint, [5.0, 120.0, 55.0, 35.0, 80.0, 60.0]),
|
||||
bristle("Stubby Round", RoundBlunt, [8.0, 60.0, 70.0, 50.0, 85.0, 80.0]),
|
||||
bristle("Dry Scrub", FlatBlunt, [10.0, 40.0, 25.0, 60.0, 60.0, 95.0]),
|
||||
bristle("Soft Dome", RoundCurve, [12.0, 160.0, 85.0, 20.0, 45.0, 25.0]),
|
||||
bristle("Filbert", FlatCurve, [9.0, 110.0, 65.0, 40.0, 70.0, 45.0]),
|
||||
bristle("Angled Round", RoundAngle, [7.0, 130.0, 50.0, 35.0, 75.0, 55.0]),
|
||||
bristle("Angled Flat", FlatAngle, [11.0, 100.0, 60.0, 45.0, 80.0, 65.0]),
|
||||
bristle("Fan Blender", RoundFan, [16.0, 220.0, 40.0, 15.0, 35.0, 20.0]),
|
||||
bristle("Grass Fan", FlatFan, [20.0, 260.0, 15.0, 25.0, 65.0, 35.0]),
|
||||
];
|
||||
built("Bristle Brushes", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
fn border(name: &str, side: Node, corner: Option<Node>, fit: PatternFit) -> Brush {
|
||||
let kind = BrushKind::Pattern(PatternBrush { side, outer_corner: corner.clone(), inner_corner: corner, fit, ..Default::default() });
|
||||
Brush { name: name.into(), kind }
|
||||
@@ -446,6 +475,170 @@ fn energy_beams() -> BrushLibrary {
|
||||
built("Energy Beams", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// The fixed-seed number source of the Dry Media grain: integer steps and plain arithmetic, so the
|
||||
/// art is the same on every run and every platform.
|
||||
struct Grain(u64);
|
||||
|
||||
impl Grain {
|
||||
/// The next number in 0..1.
|
||||
fn next(&mut self) -> f64 {
|
||||
self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
|
||||
(self.0 >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
/// The next number in `a`..`b`.
|
||||
fn range(&mut self, a: f64, b: f64) -> f64 {
|
||||
a + (b - a) * self.next()
|
||||
}
|
||||
}
|
||||
|
||||
/// `floor` at x = `x0` and `x1`, rising smoothly to 1 within `ramp` pt of each.
|
||||
fn ends(x: f64, x0: f64, x1: f64, ramp: f64, floor: f64) -> f64 {
|
||||
let t = ((x - x0).min(x1 - x) / ramp).clamp(0.0, 1.0);
|
||||
floor + (1.0 - floor) * t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// A closed band from x = `x0` to `x1` in `n` steps, at most `half` pt either side of y = 0 times
|
||||
/// `taper(x)`; each edge point is pulled in by up to `rough` of that.
|
||||
fn rough_band(g: &mut Grain, (x0, x1): (f64, f64), n: usize, half: f64, rough: f64, taper: impl Fn(f64) -> f64) -> PathData {
|
||||
let xs: Vec<f64> = (0..=n).map(|i| x0 + (x1 - x0) * i as f64 / n as f64).collect();
|
||||
let mut pts: Vec<Point> = xs.iter().map(|&x| Point::new(x, -half * taper(x) * (1.0 - rough * g.next()))).collect();
|
||||
let bottom: Vec<Point> = xs.iter().rev().map(|&x| Point::new(x, half * taper(x) * (1.0 - rough * g.next()))).collect();
|
||||
pts.extend(bottom);
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
}
|
||||
|
||||
/// A small four-cornered fleck around (`cx`, `cy`), at most `w` × `h` pt either side; one corner
|
||||
/// in each direction, so its outline never crosses itself.
|
||||
fn fleck(g: &mut Grain, cx: f64, cy: f64, w: f64, h: f64) -> PathData {
|
||||
let mut side = |a: f64, b: f64| g.range(a, b);
|
||||
let pts = [
|
||||
(cx - w * side(0.6, 1.0), cy + h * side(-0.3, 0.3)),
|
||||
(cx + w * side(-0.3, 0.3), cy - h * side(0.6, 1.0)),
|
||||
(cx + w * side(0.6, 1.0), cy + h * side(-0.3, 0.3)),
|
||||
(cx + w * side(-0.3, 0.3), cy + h * side(0.6, 1.0)),
|
||||
];
|
||||
polygon(&pts)
|
||||
}
|
||||
|
||||
/// `body` with `holes` (inside it, apart from each other) cut out, even-odd, in gray `k`: what
|
||||
/// lies under the stroke shows through the holes.
|
||||
fn holed(body: PathData, holes: Vec<PathData>, k: f32) -> Node {
|
||||
let children = std::iter::once(body).chain(holes).map(|p| Arc::new(Node::path(NodeId(0), p, Appearance::default()))).collect();
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Compound { children, rule: FillRule::EvenOdd });
|
||||
n.appearance = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::gray(k))))], ..Default::default() }.into();
|
||||
n
|
||||
}
|
||||
|
||||
/// Path `p` filled with gray `k` (1 is black).
|
||||
fn ink(p: PathData, k: f32) -> Node {
|
||||
filled(p, Paint::solid(Color::gray(k)))
|
||||
}
|
||||
|
||||
/// Slivers `w` × `h` pt (ranges) in `count` slots along x = 6..94 inside a band `half` pt wide
|
||||
/// times `taper`. Each stays within `reach` of the band's half width from y = 0, taken where the
|
||||
/// band is narrowest over the sliver and the 3 pt either side of it, so with `reach` below the
|
||||
/// band's roughness margin no sliver touches the band's edge or another sliver.
|
||||
fn slivers(g: &mut Grain, count: usize, half: f64, reach: f64, (w, h): ((f64, f64), (f64, f64)), taper: impl Fn(f64) -> f64) -> Vec<PathData> {
|
||||
let slot = 88.0 / count as f64;
|
||||
(0..count)
|
||||
.map(|i| {
|
||||
let cx = 6.0 + slot * (i as f64 + 0.5);
|
||||
let (w, h) = (g.range(w.0, w.1), g.range(h.0, h.1));
|
||||
let room = reach * half * taper(cx - w - 3.0).min(taper(cx + w + 3.0));
|
||||
let cy = g.range(-1.0, 1.0) * (room - h).max(0.0);
|
||||
fleck(g, cx, cy, w, h)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Dry Media: art brushes of grainy dry drawing marks, chalk, pencil, crayon and charcoal (original
|
||||
/// vector grain from fixed seeds; every brush 100 pt long, black and grays that take the stroke
|
||||
/// color as tints, gaps cut out so the paper shows).
|
||||
pub(crate) fn dry_media() -> BrushLibrary {
|
||||
// Chalk Grain, 100 × 8 pt: a soft band with narrow scratches and chips along its edges.
|
||||
let chalk = {
|
||||
let mut g = Grain(0x0c4a_1c0a);
|
||||
let taper = |x: f64| ends(x, 0.0, 100.0, 10.0, 0.35);
|
||||
let body = rough_band(&mut g, (0.0, 100.0), 36, 4.0, 0.25, taper);
|
||||
let scratches = slivers(&mut g, 14, 4.0, 0.7, ((1.2, 2.4), (0.15, 0.3)), taper);
|
||||
let mut parts = vec![holed(body, scratches, 0.8)];
|
||||
for i in 0..18 {
|
||||
let cx = 3.0 + 94.0 * (i as f64 + g.range(0.2, 0.8)) / 18.0;
|
||||
let side = if i % 2 == 0 { -1.0 } else { 1.0 };
|
||||
let cy = side * 4.0 * taper(cx) * g.range(0.7, 0.95);
|
||||
let (w, h) = (g.range(0.3, 0.7), g.range(0.25, 0.5));
|
||||
let f = fleck(&mut g, cx, cy, w, h);
|
||||
parts.push(ink(f, 1.0));
|
||||
}
|
||||
group(parts)
|
||||
};
|
||||
// Graphite Pencil, 100 × 2.5 pt: a solid tapered core with fine slanted hatching at its edges.
|
||||
let pencil = {
|
||||
let mut g = Grain(0x009e_4c11);
|
||||
let core = rough_band(&mut g, (0.0, 100.0), 40, 0.8, 0.12, |x| ends(x, 0.0, 100.0, 18.0, 0.25));
|
||||
let mut parts = vec![ink(core, 1.0)];
|
||||
for i in 0..24 {
|
||||
let x0 = 2.0 + 92.0 * (i as f64 + g.range(0.0, 0.4)) / 24.0;
|
||||
let len = g.range(1.5, 3.0);
|
||||
let t = g.range(0.12, 0.2);
|
||||
let slant = g.range(0.1, 0.3);
|
||||
let y0 = if i % 2 == 0 { -g.range(0.85, 1.05) } else { g.range(0.85, 1.25) - t - slant };
|
||||
parts.push(ink(polygon(&[(x0, y0 + slant), (x0 + len, y0), (x0 + len, y0 + t), (x0, y0 + slant + t)]), 0.6));
|
||||
}
|
||||
group(parts)
|
||||
};
|
||||
// Wax Crayon, 100 × 6 pt: a dense band with small gaps in its middle and short overlapping
|
||||
// marks along both edges.
|
||||
let crayon = {
|
||||
let mut g = Grain(0x00c0_a7e5);
|
||||
let taper = |x: f64| ends(x, 0.0, 100.0, 6.0, 0.5);
|
||||
let body = rough_band(&mut g, (0.0, 100.0), 30, 2.6, 0.2, taper);
|
||||
let gaps = slivers(&mut g, 16, 2.6, 0.34, ((0.6, 1.6), (0.15, 0.3)), taper);
|
||||
let mut parts = vec![holed(body, gaps, 0.9)];
|
||||
for i in 0..36 {
|
||||
let w = g.range(1.0, 2.2);
|
||||
let cx = (1.0 + w).max(98.0 * (i as f64 + g.range(0.0, 1.0)) / 36.0).min(99.0 - w);
|
||||
let side = if i % 2 == 0 { -1.0 } else { 1.0 };
|
||||
let h = g.range(0.4, 0.6);
|
||||
// Clear of the gaps, which stay within 0.9 pt of the middle.
|
||||
let inner = 0.9 + h;
|
||||
let cy = side * g.range(inner, (2.4 * taper(cx)).max(inner));
|
||||
let f = fleck(&mut g, cx, cy, w, h);
|
||||
parts.push(ink(f, 1.0));
|
||||
}
|
||||
group(parts)
|
||||
};
|
||||
// Charcoal Dust, 100 × 7 pt: a dark band broken into pieces, with flecks of dust either side.
|
||||
let dust = {
|
||||
let mut g = Grain(0xc4a2_c0a1);
|
||||
let mut parts = vec![];
|
||||
let mut x0 = 0.0;
|
||||
while x0 < 100.0 {
|
||||
let x1 = (x0 + g.range(14.0, 24.0)).min(100.0);
|
||||
let x1 = if 100.0 - x1 < 8.0 { 100.0 } else { x1 };
|
||||
let piece = rough_band(&mut g, (x0, x1), 10, 2.0, 0.3, |x| ends(x, 0.0, 100.0, 8.0, 0.4) * ends(x, x0, x1, 2.0, 0.3));
|
||||
parts.push(ink(piece, 1.0));
|
||||
x0 = x1 + g.range(1.5, 3.0);
|
||||
}
|
||||
for i in 0..30 {
|
||||
let cx = 2.0 + 96.0 * (i as f64 + g.range(0.2, 0.8)) / 30.0;
|
||||
let side = if g.next() < 0.5 { -1.0 } else { 1.0 };
|
||||
let s = g.range(0.15, 0.3);
|
||||
let cy = side * g.range(2.3, 3.5 - s);
|
||||
let f = fleck(&mut g, cx, cy, s, s);
|
||||
parts.push(ink(f, if i % 3 == 0 { 0.7 } else { 1.0 }));
|
||||
}
|
||||
group(parts)
|
||||
};
|
||||
let brushes = vec![
|
||||
art("Chalk Grain", chalk, Colorization::Tints),
|
||||
art("Graphite Pencil", pencil, Colorization::Tints),
|
||||
art("Wax Crayon", crayon, Colorization::Tints),
|
||||
art("Charcoal Dust", dust, Colorization::Tints),
|
||||
];
|
||||
built("Dry Media", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
|
||||
|
||||
@@ -33,10 +33,10 @@ mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove,
|
||||
brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art,
|
||||
brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
pub(crate) use dynamic::{edit_part, part_only, selected_part};
|
||||
pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{
|
||||
@@ -67,6 +67,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
brush_selection_art
|
||||
),
|
||||
cmd!(
|
||||
"brush.placeArt",
|
||||
"Place Brush Art",
|
||||
[],
|
||||
None,
|
||||
"{name, x?, y?} place a copy of the art a scatter, art or pattern brush is made of, centered on (x, y) (default: the center of the first artboard), and select it, as dragging the brush from the Brushes panel onto an empty part of the canvas does; a pattern brush places its tiles left to right (side, outer corner, inner corner, start, end; the ones it has art for) 10 pt apart, each in a group named Side Tile, Outer Corner Tile, Inner Corner Tile, Start Tile or End Tile, with an unpainted rectangle at the back of a tile that has a repeat frame marking that frame; a calligraphic or bristle brush is refused → {id}",
|
||||
has_doc,
|
||||
brush_place_art
|
||||
),
|
||||
cmd!(
|
||||
"brush.replaceArt",
|
||||
"Replace Brush Art",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?, applyToStrokes?: true} make the selected art (several objects become one group, as in brush.new) the art of a scatter, art or pattern brush, keeping its other options, as Alt-dragging (Option-dragging on macOS) art onto the brush in the Brushes panel does; a pattern brush takes a group named for one of its tiles, or a group of such groups (as brush.placeArt places them), tile by tile (of two named for one tile, the frontmost), each with the repeat frame an unpainted rectangle at its back marks (other tiles stay as they are), and other art as its side tile; when strokes use the brush and applyToStrokes is false, the brush and its strokes stay as they were and a copy of the brush with the new art, named `<name> copy`, goes after it and becomes the current brush; otherwise the strokes redraw with the new art; one undo step; refused for a calligraphic or bristle brush, with nothing selected, and for art (or a tile) with no width → {name: the brush that has the new art}",
|
||||
has_doc,
|
||||
brush_replace_art
|
||||
),
|
||||
cmd!(
|
||||
"brush.apply",
|
||||
"Apply Brush",
|
||||
@@ -144,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
|
||||
@@ -239,7 +239,7 @@ pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& v.get(k).is_none()
|
||||
{
|
||||
let art = selection_art(s, p)?.ok_or_else(|| bad(C, format!("{ty} brushes need selected art (or params.{k})")))?;
|
||||
if art.geometric_bounds().is_none_or(|b| b.width() <= 1e-6) {
|
||||
if !has_width(&art, &s.doc()?.doc.symbol_boxes()) {
|
||||
return Err(bad(C, "the selected art has no width"));
|
||||
}
|
||||
v[k] = serde_json::to_value(&art).unwrap_or_default();
|
||||
@@ -249,6 +249,12 @@ pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Whether art `n` has width for a brush to be made of, with symbol instances measured by their
|
||||
/// symbols' art in `symbols`.
|
||||
fn has_width(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> bool {
|
||||
n.geometric_bounds_with(symbols).is_some_and(|b| b.width() > 1e-6)
|
||||
}
|
||||
|
||||
/// Refuses `name` for a bristle brush when it has more than [`Bristle::MAX_NAME_CHARS`] characters.
|
||||
fn bristle_name_fits(cmd: &str, name: &str) -> Result<()> {
|
||||
let (count, max) = (name.chars().count(), Bristle::MAX_NAME_CHARS);
|
||||
@@ -367,6 +373,12 @@ fn art_brushes(n: &Node, out: &mut Vec<String>) {
|
||||
pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let lib = brush::library(d);
|
||||
let names = brush_unused_in(d, &lib);
|
||||
Ok(json!({ "names": names }))
|
||||
}
|
||||
|
||||
/// The brushes of `lib` no stroke in `d` paints with, in library order ([`brush_unused`]).
|
||||
fn brush_unused_in(d: &Document, lib: &[Brush]) -> Vec<String> {
|
||||
let mut todo = vec![];
|
||||
let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art));
|
||||
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
|
||||
@@ -379,8 +391,7 @@ pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
used.insert(name);
|
||||
}
|
||||
}
|
||||
let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).filter(|n| !used.contains(*n)).collect();
|
||||
Ok(json!({ "names": names }))
|
||||
lib.iter().map(|b| b.name.clone()).filter(|n| !used.contains(n)).collect()
|
||||
}
|
||||
|
||||
pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -483,6 +494,217 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": out }))
|
||||
}
|
||||
|
||||
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
|
||||
/// places them; `brush.replaceArt` reads a group of that name as that tile.
|
||||
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
|
||||
|
||||
/// The space between the pattern brush tiles `brush.placeArt` places, in points.
|
||||
const TILE_GAP: f64 = 10.0;
|
||||
|
||||
/// The message for a brush that is not made of art.
|
||||
fn no_art(name: &str) -> String {
|
||||
format!("`{name}` has no art (only scatter, art and pattern brushes do)")
|
||||
}
|
||||
|
||||
/// Tile `i` of `p` ([`TILE_NAMES`] order): its art and its repeat frame, when it has art.
|
||||
fn tile(p: &brush::PatternBrush, i: usize) -> Option<(&Node, Option<vectorcraft_geom::Rect>)> {
|
||||
match i {
|
||||
0 => Some((&p.side, p.side_frame)),
|
||||
1 => p.outer_corner.as_ref().map(|n| (n, p.outer_corner_frame)),
|
||||
2 => p.inner_corner.as_ref().map(|n| (n, p.inner_corner_frame)),
|
||||
3 => p.start.as_ref().map(|n| (n, p.start_frame)),
|
||||
_ => p.end.as_ref().map(|n| (n, p.end_frame)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives tile `i` of `p` ([`TILE_NAMES`] order) the art `art` and the repeat frame `frame`. The tile
|
||||
/// no longer comes from a pattern swatch, and a corner draws its own art.
|
||||
fn set_tile(p: &mut brush::PatternBrush, i: usize, art: Node, frame: Option<vectorcraft_geom::Rect>) {
|
||||
match i {
|
||||
0 => (p.side, p.side_frame, p.side_swatch) = (art, frame, None),
|
||||
1 => (p.outer_corner, p.outer_corner_frame, p.outer_corner_swatch, p.outer_source) = (Some(art), frame, None, None),
|
||||
2 => (p.inner_corner, p.inner_corner_frame, p.inner_corner_swatch, p.inner_source) = (Some(art), frame, None, None),
|
||||
3 => (p.start, p.start_frame, p.start_swatch) = (Some(art), frame, None),
|
||||
_ => (p.end, p.end_frame, p.end_swatch) = (Some(art), frame, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The art `brush.placeArt` places for brush `b`, in the brush's own coordinates: a scatter or art
|
||||
/// brush's art, or a pattern brush's tiles in a row, each in a group named for its tile
|
||||
/// ([`TILE_NAMES`]), with an unpainted rectangle at the back of a tile that has a repeat frame
|
||||
/// marking that frame. `None` for a brush that is not made of art. Symbol instances in the art are
|
||||
/// measured by their symbols' art in `symbols`.
|
||||
fn placed_art(b: &Brush, symbols: &vectorcraft_doc::SymbolBoxes) -> Option<Node> {
|
||||
match &b.kind {
|
||||
BrushKind::Scatter(sc) => Some(sc.art.clone()),
|
||||
BrushKind::Art(a) => Some(a.art.clone()),
|
||||
BrushKind::Pattern(pb) => {
|
||||
let mut tiles = vec![];
|
||||
let mut x = 0.0;
|
||||
for (i, tile_name) in TILE_NAMES.iter().enumerate() {
|
||||
let Some((art, frame)) = tile(pb, i) else { continue };
|
||||
let mut children = vec![];
|
||||
if let Some(f) = frame {
|
||||
let marker = Node::path(
|
||||
NodeId(0),
|
||||
vectorcraft_geom::shapes::rectangle(f),
|
||||
vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0),
|
||||
);
|
||||
children.push(Arc::new(marker));
|
||||
}
|
||||
children.push(Arc::new(art.clone()));
|
||||
let mut g = Node::group(NodeId(0), children);
|
||||
g.name = Some((*tile_name).to_string());
|
||||
let Some(r) = g.geometric_bounds_with(symbols) else { continue };
|
||||
// Each tile sits right of the one before it, centered on the line y = 0.
|
||||
g.transform(vectorcraft_geom::Affine::translate((x - r.x0, -r.center().y)), false);
|
||||
x += r.width() + TILE_GAP;
|
||||
tiles.push(Arc::new(g));
|
||||
}
|
||||
Some(Node::group(NodeId(0), tiles))
|
||||
}
|
||||
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `brush.placeArt`: a copy of the art brush `name` is made of, centered on (`x`, `y`) (default: the
|
||||
/// center of the first artboard) in the layer new art goes into, and selected, as one undo step.
|
||||
/// Scatter and art brushes place their art; pattern brushes place their tiles ([`placed_art`]).
|
||||
pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.placeArt";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
let d = &s.doc()?.doc;
|
||||
let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(super::Point::ZERO);
|
||||
let at = super::Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?);
|
||||
let b = brush::find(d, &name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
|
||||
let symbols = d.symbol_boxes();
|
||||
let mut art = placed_art(&b, &symbols).ok_or_else(|| bad(C, no_art(&name)))?;
|
||||
if let Some(r) = art.geometric_bounds_with(&symbols) {
|
||||
art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false);
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Place Brush Art", |d, sel| {
|
||||
let art = d.reid(&art);
|
||||
let id = art.id;
|
||||
d.insert(parent, usize::MAX, art)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the
|
||||
/// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its
|
||||
/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance.
|
||||
fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> {
|
||||
let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None };
|
||||
let unpainted = n.appearance.effects.is_empty()
|
||||
&& n.appearance.items.iter().all(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.is_none(),
|
||||
AppearanceItem::Stroke(st) => st.paint.is_none(),
|
||||
});
|
||||
let [sp] = path.subpaths.as_slice() else { return None };
|
||||
let r = n.geometric_bounds()?;
|
||||
let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)];
|
||||
let at_corners = sp.anchors.len() == 4
|
||||
&& sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)
|
||||
&& corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c));
|
||||
(unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r)
|
||||
}
|
||||
|
||||
/// The tiles in `art` for a pattern brush, by tile ([`TILE_NAMES`] order), with their repeat frames:
|
||||
/// a group named for a tile, as `brush.placeArt` places them, is the art of its tile (an unpainted
|
||||
/// rectangle at its back marks the tile's frame, [`frame_marker`], and is left out of the art; a
|
||||
/// group left with one member gives that member), and so is each member of a group whose members
|
||||
/// are all such groups; any other art is the side tile.
|
||||
fn tiles_of(art: Node) -> Vec<(usize, Node, Option<vectorcraft_geom::Rect>)> {
|
||||
let named = |c: &Node| matches!(c.kind, NodeKind::Group { clip: false, .. }) && c.name.as_deref().is_some_and(|n| TILE_NAMES.contains(&n));
|
||||
let tiles = match &art.kind {
|
||||
_ if named(&art) => vec![Arc::new(art)],
|
||||
NodeKind::Group { children, clip: false } if !children.is_empty() && children.iter().all(|c| named(c)) => children.clone(),
|
||||
_ => return vec![(0, art, None)],
|
||||
};
|
||||
let mut out: Vec<(usize, Node, Option<vectorcraft_geom::Rect>)> = vec![];
|
||||
for t in tiles {
|
||||
let Some(i) = t.name.as_deref().and_then(|n| TILE_NAMES.iter().position(|x| *x == n)) else { continue };
|
||||
let mut g = (*t).clone();
|
||||
let mut frame = None;
|
||||
if let NodeKind::Group { children, .. } = &mut g.kind
|
||||
&& let Some(f) = children.first().and_then(|c| frame_marker(c))
|
||||
{
|
||||
frame = Some(f);
|
||||
children.remove(0);
|
||||
}
|
||||
g.name = None;
|
||||
// The group `brush.placeArt` put around the tile's art: the art itself goes back, so a
|
||||
// tile does not gain a group each time it goes out and back.
|
||||
if let NodeKind::Group { children, clip: false } = &g.kind
|
||||
&& let [only] = children.as_slice()
|
||||
&& g == Node::group(g.id, children.clone())
|
||||
{
|
||||
g = (**only).clone();
|
||||
}
|
||||
// A tile named twice: the frontmost one counts.
|
||||
out.retain(|(j, ..)| *j != i);
|
||||
out.push((i, g, frame));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `brush.replaceArt`: the selected art (or `ids`/`id`; several objects become one group, as in
|
||||
/// `brush.new`) becomes the art of scatter, art or pattern brush `name`, keeping its other options,
|
||||
/// as one undo step. A pattern brush takes the tiles `brush.placeArt` places by their names
|
||||
/// ([`tiles_of`]) and other art as its side tile. When strokes use the brush and `applyToStrokes` is
|
||||
/// false, the brush and its strokes stay as they were and a copy of the brush with the new art is
|
||||
/// added after it and becomes the current brush; otherwise the strokes redraw with the new art.
|
||||
pub(super) fn brush_replace_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.replaceArt";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
let apply = super::switch_or(p, "applyToStrokes", true, C)?;
|
||||
let mut lib = brush::library(&s.doc()?.doc);
|
||||
let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
|
||||
if lib[i].art().is_empty() {
|
||||
return Err(bad(C, no_art(&name)));
|
||||
}
|
||||
let art = selection_art(s, p)?.ok_or_else(|| bad(C, "nothing selected"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let check = |n: &Node| if has_width(n, &symbols) { Ok(()) } else { Err(bad(C, "the selected art has no width")) };
|
||||
let mut b = lib[i].clone();
|
||||
match &mut b.kind {
|
||||
BrushKind::Scatter(sc) => {
|
||||
check(&art)?;
|
||||
sc.art = art;
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
check(&art)?;
|
||||
a.art = art;
|
||||
}
|
||||
BrushKind::Pattern(pb) => {
|
||||
for (t, art, frame) in tiles_of(art) {
|
||||
check(&art)?;
|
||||
set_tile(pb, t, art, frame);
|
||||
}
|
||||
}
|
||||
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => return Err(bad(C, no_art(&name))),
|
||||
}
|
||||
let used = !brush_unused_in(d, &lib).contains(&name);
|
||||
if apply || !used {
|
||||
lib[i] = b;
|
||||
save_library(s, "Replace Brush Art", lib, &[])?;
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
b.name = brush::unique_name(&lib, &format!("{} copy", name.trim()));
|
||||
let copy = b.name.clone();
|
||||
lib.insert(i + 1, b);
|
||||
s.edit("Replace Brush Art", |d, _| {
|
||||
d.unknown.insert(brush::CURRENT_KEY.into(), json!(copy));
|
||||
brush::store(d, &lib);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": copy }))
|
||||
}
|
||||
|
||||
pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! appearance of objects in the symbol's art and stays linked to the symbol
|
||||
//! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance
|
||||
//! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still
|
||||
//! there ([`fit_overrides`]).
|
||||
//! there and draws them ([`fit_overrides`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -27,7 +27,7 @@ pub(super) fn type_id(dynamic: bool) -> &'static str {
|
||||
}
|
||||
|
||||
/// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or
|
||||
/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art.
|
||||
/// missing) symbol keeps none, an instance of a dynamic one those its art still draws ([`fit_parts`]).
|
||||
pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
let art = match d.node(*id) {
|
||||
@@ -40,7 +40,7 @@ pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let mut e = n.extras_mut();
|
||||
match art {
|
||||
Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art),
|
||||
Some(art) => fit_parts(&mut e.symbol_overrides, &art),
|
||||
None => e.symbol_overrides.clear(),
|
||||
}
|
||||
}
|
||||
@@ -177,17 +177,42 @@ fn check_paint_kinds(p: &Value, art: &Node, path: &[u32], cmd: &str) -> Result<(
|
||||
fn solid_fill_check(p: &Value, art: &Node, path: &[u32], fill: Option<&vectorcraft_color::Paint>, cmd: &str) -> Result<()> {
|
||||
let asked = p.get("fill").is_some_and(|v| !v.is_null());
|
||||
let is_instance = symbol_overrides::part(art, path).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }));
|
||||
let draws_nothing = |f: &vectorcraft_color::Paint| match f {
|
||||
vectorcraft_color::Paint::Gradient(_) => true,
|
||||
vectorcraft_color::Paint::Pattern { .. } => true,
|
||||
vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => false,
|
||||
};
|
||||
if asked && is_instance && fill.is_some_and(draws_nothing) {
|
||||
if asked && is_instance && fill.is_some_and(|f| !stains(f)) {
|
||||
return Err(bad(cmd, "fill on a symbol instance must be a solid color or none"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Can a symbol instance's fill be `f`? An instance stains its art with a solid fill only.
|
||||
fn stains(f: &vectorcraft_color::Paint) -> bool {
|
||||
match f {
|
||||
vectorcraft_color::Paint::Gradient(_) => false,
|
||||
vectorcraft_color::Paint::Pattern { .. } => false,
|
||||
vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the appearance changes `overrides` that name an object of `art` (a symbol's new art), each
|
||||
/// without a fill or stroke that object does not draw ([`paint_refusal`], [`stains`]); a change
|
||||
/// left with nothing in it is dropped.
|
||||
pub(crate) fn fit_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) {
|
||||
symbol_overrides::retain_parts(overrides, art);
|
||||
for o in overrides.iter_mut() {
|
||||
let Some(n) = symbol_overrides::part(art, &o.path) else { continue };
|
||||
let instance = matches!(n.kind, NodeKind::SymbolInstance { .. });
|
||||
if paint_refusal(n, "fill", FIT).is_some() || (instance && o.fill.as_ref().is_some_and(|f| !stains(f))) {
|
||||
o.fill = None;
|
||||
}
|
||||
if paint_refusal(n, "stroke", FIT).is_some() {
|
||||
o.stroke = None;
|
||||
}
|
||||
}
|
||||
overrides.retain(|o| !o.is_empty());
|
||||
}
|
||||
|
||||
/// The command name [`fit_parts`] gives [`paint_refusal`], whose refusal it does not show.
|
||||
const FIT: &str = "symbol.update";
|
||||
|
||||
/// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or
|
||||
/// an object of `paint.setFill`'s paint params sets it.
|
||||
fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Option<vectorcraft_color::Paint>>> {
|
||||
|
||||
@@ -29,8 +29,8 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::paint::paint_from;
|
||||
use super::pathops::{Beside, shape_node};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, id_param, named_ids,
|
||||
number_or, point_param, str_param, switch_or,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, named_ids, number_or,
|
||||
object_param, point_param, str_param, switch_or,
|
||||
};
|
||||
|
||||
mod live_paint;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, Paint, PathData, Point,
|
||||
Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, id_param, ids_json,
|
||||
is_live_paint, json, number_or, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or,
|
||||
Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint,
|
||||
json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -303,7 +303,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
|
||||
let group = id_param(p, "group");
|
||||
let group = object_param(p, "group", C)?;
|
||||
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
|
||||
let (g, face) = s.edit("Live Paint Bucket", |d, sel| {
|
||||
let gid = match group {
|
||||
@@ -367,7 +367,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.strokeEdge";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let g = id_param(p, "group").ok_or_else(|| bad(C, "missing group"))?;
|
||||
let g = object_param(p, "group", C)?.ok_or_else(|| bad(C, "missing group"))?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.stroke.clone());
|
||||
let width = number_or(p, "width", s.paint.stroke_width.max(0.0), C)?;
|
||||
@@ -390,7 +390,10 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let g = id_param(p, "group").or_else(|| id_param(p, "id")).ok_or_else(|| bad("livePaint.info", "missing group"))?;
|
||||
let g = match object_param(p, "group", "livePaint.info")? {
|
||||
Some(g) => g,
|
||||
None => object_param(p, "id", "livePaint.info")?.ok_or_else(|| bad("livePaint.info", "missing group"))?,
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad("livePaint.info", format!("{g} is not a Live Paint group")))?;
|
||||
let faces: Vec<Value> = b::faces(n)
|
||||
|
||||
@@ -783,12 +783,14 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The paragraph attributes new type gets (the Type tools, `text.create`): aligned to the start of
|
||||
/// each paragraph's direction (left, right for Hebrew and Arabic), Japanese punctuation composed
|
||||
/// with Line-end Punctuation Half Width and Standard burasagari. Imported text keeps its own.
|
||||
/// with Line-end Punctuation Half Width and Standard burasagari, and Korean words kept whole
|
||||
/// (Korean Line Break Anywhere off). Imported text keeps its own.
|
||||
pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
|
||||
vectorcraft_doc::ParaStyle {
|
||||
justify: vectorcraft_doc::Justify::Auto,
|
||||
mojikumi: vectorcraft_doc::Mojikumi::LineEndHalf,
|
||||
burasagari: vectorcraft_doc::Burasagari::Standard,
|
||||
korean_line_break_anywhere: false,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project
|
||||
|
||||
use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, id_param,
|
||||
matrix_param, named_id, named_ids, number_or, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param,
|
||||
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -305,7 +305,7 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool {
|
||||
|
||||
fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.widthPoint.set";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let t = f64_req(p, "t", C)?.clamp(0.0, 1.0);
|
||||
let (left, right) = (f64_req(p, "left", C)?, f64_req(p, "right", C)?);
|
||||
if !(left.is_finite() && right.is_finite()) || left < 0.0 || right < 0.0 || left.max(right) > 1.0e5 {
|
||||
@@ -362,7 +362,7 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn width_point_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.widthPoint.copy";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let t = f64_req(p, "t", C)?.clamp(0.0, 1.0);
|
||||
// When the profile comes out as it was (the copy replaces a side of a discontinuous point that has
|
||||
// its widths already), the document and its undo history stay as they are.
|
||||
@@ -382,7 +382,7 @@ fn width_point_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn width_point_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.widthPoint.remove";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let indices = match (p.get("indices"), p.get("index")) {
|
||||
(Some(a), _) => point_indices(a),
|
||||
(None, Some(i)) => point_indices(&json!([i])),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Document Info panel data, its categories and the text report (Document Info › Save…, File →
|
||||
//! Package), and Object → Make Pixel Perfect.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -40,7 +40,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
("objects", "Objects"),
|
||||
("graphicStyles", "Graphic Styles"),
|
||||
("brushes", "Brushes"),
|
||||
("spotColors", "Spot Colors"),
|
||||
("spotColors", "Spot Color Objects"),
|
||||
("patterns", "Pattern Objects"),
|
||||
("gradients", "Gradient Objects"),
|
||||
("symbols", "Symbols"),
|
||||
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
];
|
||||
|
||||
/// The object counts of `document.info` and their labels.
|
||||
const OBJECT_LABELS: [(&str, &str); 18] = [
|
||||
const OBJECT_LABELS: [(&str, &str); 19] = [
|
||||
("paths", "Paths"),
|
||||
("compoundPaths", "Compound Paths"),
|
||||
("groups", "Groups"),
|
||||
@@ -63,6 +63,7 @@ const OBJECT_LABELS: [(&str, &str); 18] = [
|
||||
("symbolInstances", "Symbol Instances"),
|
||||
("gradients", "Gradient Objects"),
|
||||
("patterns", "Pattern Objects"),
|
||||
("spots", "Spot Color Objects"),
|
||||
("meshes", "Gradient Meshes"),
|
||||
("blends", "Blends"),
|
||||
("envelopes", "Envelopes"),
|
||||
@@ -131,7 +132,7 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
|
||||
/// rows of its objects filled or stroked with a pattern and with a gradient.
|
||||
/// rows of its objects filled or stroked with a spot color, with a pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
@@ -139,6 +140,7 @@ fn sections(
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
images: &[ImageRow],
|
||||
repeats: &[(String, String)],
|
||||
spot_objects: &[(String, String)],
|
||||
pattern_objects: &[(String, String)],
|
||||
gradient_objects: &[(String, String)],
|
||||
category: Option<&str>,
|
||||
@@ -183,7 +185,7 @@ fn sections(
|
||||
}
|
||||
"graphicStyles" => names("graphicStyleNames"),
|
||||
"brushes" => names("brushNames"),
|
||||
"spotColors" => names("spotColors"),
|
||||
"spotColors" => spot_objects.to_vec(),
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => gradient_objects.to_vec(),
|
||||
"symbols" => names("symbols"),
|
||||
@@ -273,15 +275,50 @@ fn gradient_label(p: &Paint) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient:
|
||||
/// the runs with a glyph outline (list markers and ruby included) or an underline or strikethrough
|
||||
/// bar. Spaces and line breaks draw no outline. A type object's characters carry their own fill and
|
||||
/// stroke, and the type object's own fills and strokes paint on its characters, so only those runs
|
||||
/// paint. The type is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the
|
||||
/// renderer lays it out.
|
||||
fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
|
||||
/// The names of `d`'s spot color swatches: the swatches whose prints go to a plate of their own
|
||||
/// ([`vectorcraft_doc::inks::inks`]). A name held by several swatches is the first one's, as
|
||||
/// [`Document::swatch`] finds it, and the Registration swatch prints on every plate, so it is not
|
||||
/// one.
|
||||
fn spot_swatches(d: &Document) -> HashSet<&str> {
|
||||
let mut first: BTreeMap<&str, bool> = BTreeMap::new();
|
||||
for s in d.swatches_iter() {
|
||||
first.entry(s.name.as_str()).or_insert(s.spot && s.paint.color().is_some());
|
||||
}
|
||||
first.into_iter().filter(|&(name, spot)| spot && name != vectorcraft_color::swatch::REGISTRATION).map(|(name, _)| name).collect()
|
||||
}
|
||||
|
||||
/// The spot colors paint `p` prints (`spots`: [`spot_swatches`]): the spot swatch a solid color is
|
||||
/// linked to, or those a gradient's stops are linked to, each once, in the order of the stops. A
|
||||
/// link at a tint of 0 prints no ink, a gradient whose stops are all at an opacity of 0 draws
|
||||
/// nothing, and a color that only looks like a spot color is not linked to one.
|
||||
fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec<String> {
|
||||
let mut out: Vec<String> = vec![];
|
||||
let mut add = |swatch: &Option<String>, tint: f32| {
|
||||
if let Some(name) = swatch
|
||||
&& tint > 0.0
|
||||
&& spots.contains(name.as_str())
|
||||
&& !out.contains(name)
|
||||
{
|
||||
out.push(name.clone());
|
||||
}
|
||||
};
|
||||
match p {
|
||||
Paint::Solid { swatch, tint, .. } => add(swatch, *tint),
|
||||
Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity > 0.0) => g.gradient.stops.iter().for_each(|s| add(&s.swatch, s.tint)),
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a spot color, a pattern or
|
||||
/// a gradient (`spots`: [`spot_swatches`]): the runs with a glyph outline (list markers and ruby
|
||||
/// included) or an underline or strikethrough bar. Spaces and line breaks draw no outline. A type
|
||||
/// object's characters carry their own fill and stroke, and the type object's own fills and strokes
|
||||
/// paint on its characters, so only those runs paint. The type is laid out with its inline
|
||||
/// graphics' bounds resolved from `d`'s symbols, as the renderer lays it out.
|
||||
fn painted_runs<'a>(d: &Document, spots: &HashSet<&str>, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_));
|
||||
let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_)) || !spot_labels(spots, p).is_empty();
|
||||
let own = n.appearance.items.iter().any(|i| match i {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint),
|
||||
@@ -297,43 +334,53 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T
|
||||
Some((t, painted))
|
||||
}
|
||||
|
||||
/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `n`'s own
|
||||
/// fills and strokes paint, each once. A hidden fill or stroke and a stroke with no width paint
|
||||
/// nothing, and neither does any fill or stroke of a guide (drawn in the guide color), of a compound
|
||||
/// path's member (`members`: the compound path's own fills and strokes paint it) or of type whose
|
||||
/// layout draws nothing (`painted_runs`). An image's fills and strokes paint only where an effect
|
||||
/// gives them a shape.
|
||||
/// The names a paint is listed by in a Document Info category: its spot colors, its pattern or its
|
||||
/// gradient.
|
||||
type PaintNames<'a> = dyn Fn(&Paint) -> Vec<String> + 'a;
|
||||
|
||||
/// The spot colors, patterns or gradients (`label`: [`spot_labels`], [`pattern_label`] or
|
||||
/// [`gradient_label`], each paint's names) that `n`'s own fills and strokes paint, each once. A
|
||||
/// hidden fill or stroke and a stroke with no width paint nothing, and neither does any fill or
|
||||
/// stroke of a guide (drawn in the guide color), of a compound path's member (`members`: the
|
||||
/// compound path's own fills and strokes paint it) or of type whose layout draws nothing
|
||||
/// (`painted_runs`). An image's fills and strokes paint only where an effect gives them a shape.
|
||||
fn own_paints(
|
||||
d: &Document,
|
||||
n: &Node,
|
||||
members: &HashSet<*const Node>,
|
||||
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>,
|
||||
label: fn(&Paint) -> Option<String>,
|
||||
label: &PaintNames<'_>,
|
||||
) -> Vec<String> {
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| members.contains(&std::ptr::from_ref(n))
|
||||
|| painted_runs.is_some_and(|(_, r)| r.is_empty())
|
||||
|| !n.appearance.items.iter().any(|i| label(i.paint()).is_some())
|
||||
|| n.appearance.items.iter().all(|i| label(i.paint()).is_empty())
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
// The patterns or gradients an image's shaped fills and strokes paint (their effects can
|
||||
// transform the paint, so they are matched by label).
|
||||
// The names an image's shaped fills and strokes paint (their effects can transform the paint,
|
||||
// so they are matched by name).
|
||||
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_))
|
||||
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect());
|
||||
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().flat_map(|(_, _, item)| label(item.paint())).collect());
|
||||
let mut out: Vec<String> = vec![];
|
||||
for item in &n.appearance.items {
|
||||
let Some(name) = label(item.paint()) else { continue };
|
||||
let paints = item.visible()
|
||||
&& !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
|
||||
&& shaped.as_ref().is_none_or(|s| s.contains(&name));
|
||||
if paints && !out.contains(&name) {
|
||||
out.push(name);
|
||||
if !item.visible() || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
for name in label(item.paint()) {
|
||||
if shaped.as_ref().is_none_or(|s| s.contains(&name)) && !out.contains(&name) {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [`pattern_label`] or [`gradient_label`] as the names [`own_paints`] takes.
|
||||
fn one_label(label: fn(&Paint) -> Option<String>) -> impl Fn(&Paint) -> Vec<String> {
|
||||
move |p| label(p).into_iter().collect()
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.info";
|
||||
let category = str_param(p, "category");
|
||||
@@ -358,9 +405,25 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut fonts = BTreeSet::new();
|
||||
let mut images: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let mut image_rows: Vec<ImageRow> = vec![];
|
||||
// Whether the request being served may read each linked file (a relative path read from the
|
||||
// document's folder), checked once per file.
|
||||
let mut readable: HashMap<String, bool> = HashMap::new();
|
||||
let link_doc = super::links::LinkBase::of(st).doc;
|
||||
let mut may_read = |stored: &str| {
|
||||
*readable.entry(stored.to_string()).or_insert_with(|| {
|
||||
let resolved = super::fileio::document_path(stored, link_doc).ok();
|
||||
crate::file_access::check_read(resolved.as_deref().unwrap_or(stored)).is_ok()
|
||||
})
|
||||
};
|
||||
let mut patterns = BTreeSet::new();
|
||||
let mut symbols = BTreeSet::new();
|
||||
// `spot_objects`, `spot_rows` and `spot` hold the `spotObjects` entries, the rows of the objects filled or stroked with a spot
|
||||
// color, in walk order, and the spot colors they use. `spot_swatches` names the document's spot colors once, for every paint.
|
||||
let spot_swatches = spot_swatches(d);
|
||||
let mut spot_objects: Vec<Value> = vec![];
|
||||
let mut spot_rows: Vec<(String, String)> = vec![];
|
||||
let mut spot = BTreeSet::new();
|
||||
let (spot_label, pattern, gradient) = (|p: &Paint| spot_labels(&spot_swatches, p), one_label(pattern_label), one_label(gradient_label));
|
||||
let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() };
|
||||
// `brushes` holds the Brushes panel's brushes, or with selectionOnly it holds the brushes that the selected objects' strokes use.
|
||||
let mut brushes: Vec<String> = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() };
|
||||
@@ -411,12 +474,15 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some("textObjects")
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
// A linked file outside a confined request's read roots: `link` is null, and the row
|
||||
// names the file alone.
|
||||
let link = im.link.as_ref().map(|l| (l, may_read(&l.path)));
|
||||
images.insert(
|
||||
im.key.clone(),
|
||||
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": im.link.as_ref().map(|l| &l.path) }),
|
||||
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }),
|
||||
);
|
||||
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
|
||||
image_rows.push((name, im.width, im.height, im.link.as_ref().map(|l| l.path.clone())));
|
||||
image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() })));
|
||||
Some("images")
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
@@ -433,17 +499,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(k) = k {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
}
|
||||
for item in &n.appearance.items {
|
||||
if let Paint::Solid { swatch: Some(name), .. } = item.paint()
|
||||
&& d.swatch(name).is_some_and(|s| s.spot)
|
||||
{
|
||||
spot.insert(name.clone());
|
||||
}
|
||||
}
|
||||
// The patterns and the gradients this object's fills and strokes paint, each once.
|
||||
let painted_runs = painted_runs(d, n);
|
||||
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label);
|
||||
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label);
|
||||
// The spot colors, the patterns and the gradients this object's fills and strokes paint, each once.
|
||||
let painted_runs = painted_runs(d, &spot_swatches, n);
|
||||
let mut used_spots = own_paints(d, n, &members, painted_runs.as_ref(), &spot_label);
|
||||
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), &pattern);
|
||||
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), &gradient);
|
||||
// The characters' own paints: an inline graphic draws no outline and does not take its
|
||||
// run's paint (a list marker set in its run does), and a stroke with no width paints
|
||||
// nothing.
|
||||
@@ -451,19 +511,38 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
|
||||
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
|
||||
for paint in std::iter::once(&run.style.fill).chain(stroke) {
|
||||
for (used, label) in
|
||||
[(&mut used_patterns, pattern_label as fn(&Paint) -> Option<String>), (&mut used_gradients, gradient_label)]
|
||||
{
|
||||
if let Some(name) = label(paint)
|
||||
&& !used.contains(&name)
|
||||
{
|
||||
used.push(name);
|
||||
let labels: [(&mut Vec<String>, &PaintNames<'_>); 3] =
|
||||
[(&mut used_spots, &spot_label), (&mut used_patterns, &pattern), (&mut used_gradients, &gradient)];
|
||||
for (used, label) in labels {
|
||||
for name in label(paint) {
|
||||
if !used.contains(&name) {
|
||||
used.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Objects counts the objects that Pattern Objects and Gradient Objects list.
|
||||
// A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take
|
||||
// the color, as the renderer draws it.
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& let Some(colorize) = n.extras().colorize.as_deref()
|
||||
&& d.image_blob(im).is_some_and(|b| b.takes_colorize())
|
||||
{
|
||||
for name in spot_label(colorize) {
|
||||
if !used_spots.contains(&name) {
|
||||
used_spots.insert(0, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Objects counts the objects that Spot Color Objects, Pattern Objects and Gradient Objects list.
|
||||
if !used_spots.is_empty() {
|
||||
let name = n.display_name();
|
||||
spot.extend(used_spots.iter().cloned());
|
||||
spot_rows.push((name.clone(), used_spots.join(", ")));
|
||||
spot_objects.push(json!({ "id": n.id.0, "name": name, "spotColors": used_spots }));
|
||||
*counts.entry("spots").or_default() += 1;
|
||||
}
|
||||
if !used_patterns.is_empty() {
|
||||
let name = n.display_name();
|
||||
patterns.extend(used_patterns.iter().cloned());
|
||||
@@ -516,6 +595,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"images": images,
|
||||
"symbols": symbols,
|
||||
"spotColors": spot,
|
||||
"spotColorNames": spot,
|
||||
"spotObjects": spot_objects,
|
||||
"swatches": d.swatches_iter().count(),
|
||||
"graphicStyles": d.graphic_styles.len(),
|
||||
"graphicStyleNames": styles,
|
||||
@@ -531,7 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, &gradient_rows, category);
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -984,6 +1065,169 @@ mod tests {
|
||||
assert!(!text.contains("Spare"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Spot Color Objects lists each object filled or stroked with a spot color once,
|
||||
/// with the spot colors it uses, as a solid color or in a gradient's stops, one in a group and a
|
||||
/// type object whose characters use one included. A spot swatch no art uses adds no row; a
|
||||
/// process color that looks the same, Registration and a tint of 0 are not spot colors; paint
|
||||
/// that draws nothing is left out by the rules Pattern Objects follows; and Objects counts the
|
||||
/// listed objects. With Selection Only it lists the objects in the selection, each once, and the
|
||||
/// report writes the same rows.
|
||||
#[test]
|
||||
fn info_lists_the_spot_color_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
// An empty document lists none.
|
||||
let i = s.execute("document.info", &json!({"category": "spotColors"})).unwrap();
|
||||
assert_eq!((i["spotObjects"].clone(), i["spotColorNames"].clone(), i["spotColors"].clone()), (json!([]), json!([]), json!([])));
|
||||
assert!(i["objects"]["spots"].is_null() && i["sections"][0]["rows"] == json!([]), "{i}");
|
||||
let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nSPOT COLOR OBJECTS\nNone\n"), "{text}");
|
||||
let ink = |c: f64| json!({"model": "cmyk", "c": c, "m": 0.5, "y": 0.0, "k": 0.0});
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": ink(1.0), "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": ink(0.2), "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Spare", "color": ink(0.4), "spot": true})).unwrap();
|
||||
// A global process color of the same color as Ink.
|
||||
s.execute("swatch.new", &json!({"name": "Look", "color": ink(1.0), "global": true})).unwrap();
|
||||
let square =
|
||||
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let ramp = |a: &str, b: &str| json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000", "swatch": a}, {"offset": 1, "color": "#fff", "swatch": b}]});
|
||||
let (a, b, c, f, g, h) =
|
||||
(square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0), square(&mut s, 80.0), square(&mut s, 100.0));
|
||||
s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ink"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [a], "swatch": "Gold", "tint": 40})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [b], "swatch": "Look"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [b], "swatch": "Ink", "tint": 50})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [c], "swatch": "Ink", "tint": 0})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("Gold", "Look")})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [g], "gradient": ramp("Look", "Look")})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [h], "swatch": "[Registration]"})).unwrap();
|
||||
for id in [&c, &g, &h] {
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
|
||||
// A type object whose characters are filled with a spot color.
|
||||
let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ink"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [t], "none": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
|
||||
// A hidden spot fill and a spot stroke with no width paint nothing, so neither object is listed.
|
||||
let (d, e) = (square(&mut s, 120.0), square(&mut s, 140.0));
|
||||
s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ink"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Ink"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
|
||||
// Type with no characters, or of only spaces and a line break, paints nothing, and neither
|
||||
// does a guide made from a path with a spot color.
|
||||
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ink"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap();
|
||||
let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ink"})).unwrap();
|
||||
let guide = square(&mut s, 300.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ink"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
// Nor does a compound path's member's own spot fill, or an image's spot fill without an
|
||||
// effect that gives it a shape.
|
||||
let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0));
|
||||
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap();
|
||||
let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
|
||||
let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance);
|
||||
let pic = square(&mut s, 360.0);
|
||||
s.execute("select.set", &json!({"ids": [pic]})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
let image = s.doc().unwrap().selection.objects[0];
|
||||
s.edit("own paint", |d, _| {
|
||||
d.node_mut(member).unwrap().appearance = paint.clone();
|
||||
d.node_mut(image).unwrap().appearance = paint;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
i["spotObjects"],
|
||||
json!([
|
||||
{"id": a, "name": "Both", "spotColors": ["Ink", "Gold"]},
|
||||
{"id": b, "name": "<Rectangle>", "spotColors": ["Ink"]},
|
||||
{"id": f, "name": "<Rectangle>", "spotColors": ["Gold"]},
|
||||
{"id": t, "name": "Type", "spotColors": ["Ink"]},
|
||||
])
|
||||
);
|
||||
assert_eq!((i["spotColorNames"].clone(), i["spotColors"].clone()), (json!(["Gold", "Ink"]), json!(["Gold", "Ink"])));
|
||||
// Objects counts the objects that Spot Color Objects lists.
|
||||
assert_eq!(i["objects"]["spots"].as_u64(), Some(4), "{}", i["objects"]);
|
||||
let objects = s.execute("document.info", &json!({"category": "objects"})).unwrap()["sections"][0]["rows"].clone();
|
||||
assert!(objects.as_array().unwrap().contains(&json!(["Spot Color Objects", "4"])), "{objects}");
|
||||
s.execute("select.set", &json!({"ids": [c, g, h, d, e, empty, blank, guide, compound, image.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
|
||||
assert!(i["objects"]["spots"].is_null() && i["spotObjects"] == json!([]) && i["spotColors"] == json!([]), "{i}");
|
||||
let i = s.execute("document.info", &json!({"category": "spotColors"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("spotColors"), Some("Spot Color Objects")));
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["Both", "Ink, Gold"], ["<Rectangle>", "Ink"], ["<Rectangle>", "Gold"], ["Type", "Ink"]]));
|
||||
// A selection that holds the group and the object inside it lists that object once.
|
||||
for ids in [json!([group, b]), json!([b, group])] {
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "spotColors"})).unwrap();
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Ink"]]), "{ids}");
|
||||
assert_eq!((i["objects"]["spots"].as_u64(), i["spotColorNames"].clone()), (Some(1), json!(["Ink"])), "{ids}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "spotColors"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["rows"].clone(), i["spotColors"].clone()), (json!([["Type", "Ink"]]), json!(["Ink"])));
|
||||
let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nSPOT COLOR OBJECTS\nBoth: Ink, Gold\n<Rectangle>: Ink\n<Rectangle>: Gold\nType: Ink\n"), "{text}");
|
||||
assert!(!text.contains("Spare") && !text.contains("Look"), "{text}");
|
||||
}
|
||||
|
||||
/// Spot Color Objects lists a grayscale image colorized with a spot color, and leaves out a
|
||||
/// gradient whose stops are all at an opacity of 0, which draws nothing.
|
||||
#[test]
|
||||
fn spot_color_objects_take_colorized_images_and_skip_clear_gradients() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())
|
||||
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let image = s
|
||||
.edit("Place", |d, sel| {
|
||||
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes));
|
||||
let id = d.alloc_id();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "gray".into(),
|
||||
width: 2,
|
||||
height: 1,
|
||||
xf: Default::default(),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(image).unwrap().extras().colorize.is_some());
|
||||
let clear = s.execute("shape.rectangle", &json!({"x": 0, "y": 50, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let stops =
|
||||
json!([{"offset": 0, "color": "#000", "swatch": "Ink", "opacity": 0}, {"offset": 1, "color": "#fff", "swatch": "Ink", "opacity": 0}]);
|
||||
s.execute("paint.setFill", &json!({"ids": [clear], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
let name = s.doc().unwrap().doc.node(image).unwrap().display_name();
|
||||
assert_eq!(i["spotObjects"], json!([{"id": image.0, "name": name, "spotColors": ["Ink"]}]), "{i}");
|
||||
assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]);
|
||||
}
|
||||
|
||||
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
|
||||
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
|
||||
/// it counts that object once.
|
||||
|
||||
@@ -18,8 +18,8 @@ use super::create::{add_look, insert_look};
|
||||
use super::newart::NewArt;
|
||||
use super::pathops::{Beside, remove_each};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, f64_or, has_anchors, has_doc, has_selection, id_param, index, number_or, ok, str_param,
|
||||
switch_or,
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, f64_or, has_anchors, has_doc, has_selection, index, number_or, object_param, ok,
|
||||
str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound};
|
||||
use super::{
|
||||
Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2,
|
||||
add_look, bad, check_numbers, f64_or, id_param, json, number_or, ok, po, str_param, switch_or,
|
||||
add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or,
|
||||
};
|
||||
|
||||
// ---------- Curvature ----------
|
||||
@@ -41,7 +41,7 @@ enum CurvatureOp {
|
||||
pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_tools::draw2::{EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move};
|
||||
const C: &str = "path.curvatureEdit";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
check_numbers(p, &["x", "y", "t"], C)?;
|
||||
let at = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) {
|
||||
@@ -106,7 +106,7 @@ pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.removeAnchor";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let ai = usize_req(p, "anchor", C)?;
|
||||
let curvature = switch_or(p, "curvature", false, C)?;
|
||||
@@ -220,7 +220,7 @@ fn remove_anchors_of(
|
||||
|
||||
pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.convertAnchor";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let ai = usize_req(p, "anchor", C)?;
|
||||
let smooth = str_param(p, "to") == Some("smooth");
|
||||
@@ -257,7 +257,7 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.reshapeSegment";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let seg = usize_req(p, "segment", C)?;
|
||||
let t = number_or(p, "t", 0.5, C)?.clamp(0.05, 0.95);
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::common::{
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath,
|
||||
Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, id_param, json, number_or, po,
|
||||
Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
};
|
||||
|
||||
/// Split a filled path into connected pieces (each outer contour with its holes).
|
||||
@@ -170,7 +170,7 @@ pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(
|
||||
|
||||
pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.split";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let anchor = usize_opt(p, "anchor", C)?;
|
||||
let seg = usize_opt(p, "segment", C)?;
|
||||
|
||||
@@ -4,7 +4,8 @@ use super::common::{
|
||||
};
|
||||
use super::{
|
||||
Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point,
|
||||
Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, id_param, insert_look, json, number_or, po, remove_each, str_param, switch_or,
|
||||
Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, insert_look, json, number_or, object_param, po, remove_each, str_param,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
// ---------- Pencil / Paintbrush ----------
|
||||
@@ -158,7 +159,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let id = id_param(ext, "id").ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
@@ -179,7 +180,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// open subpath, that subpath starting at the end the stroke ends on, it ends at its end).
|
||||
let connect = match p.get("connect").filter(|v| !v.is_null()) {
|
||||
Some(cn) => {
|
||||
let other = id_param(cn, "id").ok_or_else(|| bad(C, "connect needs id"))?;
|
||||
let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?;
|
||||
if other == id {
|
||||
return Err(bad(C, "connect needs a path other than the one extended"));
|
||||
}
|
||||
@@ -299,7 +300,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
if let Some(rd) = p.get("redraw").filter(|v| !v.is_null()) {
|
||||
let id = id_param(rd, "id").ok_or_else(|| bad(C, "redraw needs id"))?;
|
||||
let id = object_param(rd, "id", C)?.ok_or_else(|| bad(C, "redraw needs id"))?;
|
||||
let within = number_or(rd, "within", 12.0, C)?;
|
||||
if !within.is_finite() || within < 0.0 {
|
||||
return Err(bad(C, "redraw within must be a finite distance of 0 or more"));
|
||||
|
||||
@@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, can_clear_history, can_redo, can_undo, check_numbers, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index,
|
||||
number_or, ok, point_param, str_param, switch_or,
|
||||
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or,
|
||||
object_param, ok, point_param, str_param, switch_or,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New…",
|
||||
["File"],
|
||||
None,
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
always,
|
||||
super::newdoc::file_new
|
||||
),
|
||||
@@ -267,7 +267,7 @@ fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn doc_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?;
|
||||
let id = object_param(p, "id", "document.node")?.ok_or_else(|| bad("document.node", "missing id"))?;
|
||||
let mut opts = slice_opts(p, "document.node")?;
|
||||
let summary = switch_or(p, "summary", false, "document.node")?;
|
||||
if !summary && (opts.depth.is_some() || opts.child_limit.is_some()) {
|
||||
|
||||
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"3D Lighting Preset",
|
||||
[],
|
||||
None,
|
||||
"{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), which has no lighting presets; one undo step → {ids}",
|
||||
"{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic), which have no lighting presets; one undo step → {ids}",
|
||||
has_doc,
|
||||
lighting_preset
|
||||
),
|
||||
@@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Refresh Deferred Effects",
|
||||
["Effect"],
|
||||
None,
|
||||
"{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
|
||||
"{ids?|id?: [object id] (objects of the document, also in the art of a symbol, pattern, brush or opacity mask; an object without a deferred stage adds nothing; an id of no object is an error; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
|
||||
has_deferred,
|
||||
refresh_deferred
|
||||
),
|
||||
@@ -150,16 +150,27 @@ fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) ->
|
||||
None => rest.push(object),
|
||||
}
|
||||
}
|
||||
if rest.is_empty() {
|
||||
for (id, n) in definition_objects(d, &rest) {
|
||||
out.entry(id).or_insert((n, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The objects of `ids` found in the art `d` draws from outside its layers: the art of its
|
||||
/// symbols, patterns and brushes, and opacity masks (in that art or in the layers).
|
||||
fn definition_objects(d: &Document, ids: &[u64]) -> std::collections::HashMap<u64, Arc<Node>> {
|
||||
let mut out = std::collections::HashMap::new();
|
||||
if ids.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let ids: std::collections::HashSet<u64> = ids.iter().copied().collect();
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let symbols = d.symbols.iter().map(|s| &*s.art);
|
||||
let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a));
|
||||
let layers = d.layers.iter().map(|a| &**a);
|
||||
let mut look = |n: &Node| {
|
||||
if rest.contains(&n.id.0) {
|
||||
out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false));
|
||||
if ids.contains(&n.id.0) {
|
||||
out.entry(n.id.0).or_insert_with(|| Arc::new(n.clone()));
|
||||
}
|
||||
};
|
||||
for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) {
|
||||
@@ -231,10 +242,19 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone());
|
||||
let ids = super::named_ids(p)?;
|
||||
let objects = prune(&doc, &fx);
|
||||
if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
// An object of the art drawn outside the layers is valid whether or not it has a stage.
|
||||
let elsewhere: Vec<u64> = ids.iter().flatten().filter(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)).map(|id| id.0).collect();
|
||||
let found = definition_objects(&doc, &elsewhere);
|
||||
if let Some(id) = elsewhere.iter().find(|id| !found.contains_key(id)) {
|
||||
return Err(EngineError::NoNode(NodeId(*id)));
|
||||
}
|
||||
let ids: Option<Vec<u64>> = ids.map(|ids| ids.iter().map(|id| id.0).collect());
|
||||
// Only the objects with a stage have anything to refresh.
|
||||
let ids: Option<Vec<u64>> = ids.map(|ids| {
|
||||
let mut ids: Vec<u64> = ids.iter().map(|id| id.0).filter(|id| objects.contains_key(id)).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
ids
|
||||
});
|
||||
let counts = fx.refresh(ids.as_deref(), |targets| {
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let mut whole = Vec::new();
|
||||
@@ -656,12 +676,10 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !effect.is_some_and(|e| effects::is_three_d(&e.id)) {
|
||||
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
|
||||
}
|
||||
// Extrude & Bevel (Classic) has no lighting presets; its lights are set in its own options.
|
||||
if effect.is_some_and(|e| e.id == effects::CLASSIC_EXTRUDE) {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("object {}: Extrude & Bevel (Classic) at index {index} has no lighting presets; set its lights with effect.setParams", id.0),
|
||||
));
|
||||
// The classic 3D effects have no lighting presets; their lights are set in their own options.
|
||||
if let Some(e) = effect.filter(|e| effects::is_classic_three_d(&e.id)) {
|
||||
let name = effects::effect_info(&e.id).map_or("This effect", |info| info.label.trim_end_matches('…'));
|
||||
return Err(bad(C, format!("object {}: {name} at index {index} has no lighting presets; set its lights with effect.setParams", id.0)));
|
||||
}
|
||||
}
|
||||
let mut options = p.clone();
|
||||
|
||||
@@ -115,3 +115,32 @@ fn lighting_presets_refuse_extrude_and_bevel_classic_and_leave_a_mixed_selection
|
||||
let params = &s.doc().unwrap().doc.node(NodeId(classic)).unwrap().appearance.effects[0].params;
|
||||
assert_eq!((params["lightRotation"].as_f64(), params["lightHeight"].as_f64()), (Some(135.0), Some(45.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lighting_presets_refuse_revolve_classic() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = s.execute("path.create", &json!({"d":"M100 40 L130 60 L130 140 L100 160"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color":"#3366cc"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.classicRevolve","item":null,"params":{"surface":"diffuse"}})).unwrap();
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("effect.lightingPreset", &json!({"ids":[id],"index":0,"item":null,"preset":"topLeft"})).unwrap_err().to_string();
|
||||
assert!(err.contains(&format!("object {id}: Revolve (Classic) at index 0 has no lighting presets")), "{err}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lighting_presets_refuse_rotate_classic() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x":100,"y":100,"width":80,"height":60})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.classicRotate","item":null,"params":{"lightRotation":40}})).unwrap();
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("effect.lightingPreset", &json!({"ids":[id],"index":0,"item":null,"preset":"diffuse"})).unwrap_err().to_string();
|
||||
assert!(err.contains(&format!("object {id}: Rotate (Classic) at index 0 has no lighting presets")), "{err}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const TYPES: [&str; 5] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.revolve"];
|
||||
const TYPES: [&str; 6] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.classicRotate", "threeD.revolve"];
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand…",
|
||||
["Object"],
|
||||
None,
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
has_selection,
|
||||
expand
|
||||
),
|
||||
@@ -476,11 +476,14 @@ fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &F
|
||||
let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds, d.color_mode.model()))?;
|
||||
vec![Node::new(d.alloc_id(), NodeKind::Mesh(m))]
|
||||
} else {
|
||||
// A gradient that repeats or reflects expands as its stops repeated over the box.
|
||||
let (g, runs) = padded_on(g, bounds);
|
||||
let g = &*g;
|
||||
let frame = Frame::new(g, bounds);
|
||||
match to {
|
||||
GradientTo::Mesh => vec![Node::new(d.alloc_id(), NodeKind::Mesh(frame.mesh(&g.gradient)))],
|
||||
GradientTo::Objects(n) => frame
|
||||
.pieces(&g.gradient, n as usize)
|
||||
.pieces(&g.gradient, n as usize, runs)
|
||||
.into_iter()
|
||||
.map(|(shape, (color, opacity))| {
|
||||
let fill = FillLayer { opacity, overprint: f.overprint, ..FillLayer::new(Paint::solid(color)) };
|
||||
@@ -1234,8 +1237,64 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model
|
||||
(super::paint::stored_color(store_in, c), a)
|
||||
});
|
||||
}
|
||||
let (geom, spread) = (g.resolve(bounds), g.gradient.spreader());
|
||||
Box::new(move |p| g.gradient.sample_keep_model(spread(geom.param_at(g.gradient.kind, p)) as f32))
|
||||
}
|
||||
|
||||
/// `g` placed on box `bounds` as a gradient that pads past its ends: a linear, radial or diamond
|
||||
/// gradient that repeats or reflects with its stops repeated as many times as the box needs
|
||||
/// ([`vectorcraft_color::Gradient::padded_over`]), a conic one with its stops repeated around the
|
||||
/// turn ([`vectorcraft_color::Gradient::unrolled`]); others as they are. With it, for the repeated
|
||||
/// stops, where along the vector (0 to 1) their first run starts and how many runs lie evenly from
|
||||
/// there to 1.
|
||||
fn padded_on(g: &GradientPaint, bounds: Rect) -> (std::borrow::Cow<'_, GradientPaint>, Option<(f64, usize)>) {
|
||||
use std::borrow::Cow;
|
||||
if !g.gradient.is_spread() {
|
||||
return (Cow::Borrowed(g), None);
|
||||
}
|
||||
let geom = g.resolve(bounds);
|
||||
Box::new(move |p| g.gradient.sample_keep_model(geom.param_at(g.gradient.kind, p) as f32))
|
||||
match g.gradient.padded_over(&geom, bounds) {
|
||||
Some(p) => {
|
||||
let runs = Some((p.first, p.runs));
|
||||
(Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs)
|
||||
}
|
||||
None => {
|
||||
let runs = Some((0.0, g.gradient.repeat_count() as usize));
|
||||
(Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The edges (gradient parameters, from `lo` to `hi`) of about `n` bands [`Frame::pieces`] cuts:
|
||||
/// evenly spaced, or for stops repeated in `runs` ([`padded_on`]: where the first run starts and
|
||||
/// how many runs lie evenly from there to 1) the same whole number of bands in each run between
|
||||
/// `lo` and `hi` (at least one, about `n` in all), so every run starts on an edge and no band
|
||||
/// holds two runs' colors.
|
||||
fn band_edges(lo: f64, hi: f64, n: usize, runs: Option<(f64, usize)>) -> Vec<f64> {
|
||||
let n = n.max(1);
|
||||
let even = || {
|
||||
let step = (hi - lo) / n as f64;
|
||||
(0..=n).map(|k| lo + k as f64 * step).collect()
|
||||
};
|
||||
let Some((first, count)) = runs.filter(|&(first, count)| count > 0 && (0.0..1.0).contains(&first)) else { return even() };
|
||||
let run = (1.0 - first) / count as f64;
|
||||
let (from, to) = (lo.max(first), hi.min(1.0));
|
||||
let shown = (to - from) / run;
|
||||
if !(shown > 0.0 && shown.is_finite()) {
|
||||
return even();
|
||||
}
|
||||
let step = run / (n as f64 / shown).round().max(1.0);
|
||||
// Both whole numbers of steps from `first`, at most `n` plus the runs shown, plus one.
|
||||
let (k0, k1) = (((from - first) / step).ceil(), ((to - first) / step).floor());
|
||||
let mut edges = vec![lo];
|
||||
for k in (k0 as usize)..(k1 as usize).saturating_add(1) {
|
||||
let t = first + k as f64 * step;
|
||||
if t > edges.last().copied().unwrap_or(lo) + 1e-12 && t < hi - 1e-12 {
|
||||
edges.push(t);
|
||||
}
|
||||
}
|
||||
edges.push(hi);
|
||||
edges
|
||||
}
|
||||
|
||||
/// Where the colour changes along a gradient between parameters `t0` and `t1`: both ends, every
|
||||
@@ -1404,10 +1463,17 @@ impl Frame {
|
||||
/// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the
|
||||
/// center from each band's start to the seam, for a diamond one, nested squares (largest
|
||||
/// first). Each paints over the ones below except its band, so no seam shows between bands.
|
||||
/// With translucent stops each shape is just its band, so nothing doubles up.
|
||||
fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> {
|
||||
/// With translucent stops each shape is just its band, so nothing doubles up. Stops repeated
|
||||
/// in `runs` ([`padded_on`]) get the same whole number of bands in each run ([`band_edges`]).
|
||||
fn pieces(&self, g: &Gradient, n: usize, runs: Option<(f64, usize)>) -> Vec<(PathData, (Color, f32))> {
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
let color = |e: &[f64], k: usize| {
|
||||
let (a, b) = (e.get(k).copied().unwrap_or(0.0), e.get(k + 1).copied().unwrap_or(1.0));
|
||||
g.sample_keep_model(((a + b) / 2.0) as f32)
|
||||
};
|
||||
if let Some((geom, b, _)) = &self.conic {
|
||||
// Evenly spaced around the turn, as the wedges are.
|
||||
let n = band_edges(0.0, 1.0, n, runs).len().saturating_sub(1);
|
||||
return geom
|
||||
.conic_wedges(*b, n, opaque)
|
||||
.into_iter()
|
||||
@@ -1419,51 +1485,52 @@ impl Frame {
|
||||
return vec![(shapes::rectangle(*b), g.sample_keep_model(1.0))];
|
||||
};
|
||||
// Nested squares about the center, largest first, as a radial gradient's ellipses.
|
||||
let step = reach / n as f64;
|
||||
let edges = band_edges(0.0, *reach, n, runs);
|
||||
let square = |t: f64| -> SubPath {
|
||||
let pts: Vec<Point> = [0.0, 0.25, 0.5, 0.75].iter().map(|&u| *frame * (diamond_perimeter(u).to_vec2() * t).to_point()).collect();
|
||||
SubPath::polyline(&pts, true)
|
||||
};
|
||||
return (0..n)
|
||||
return (0..edges.len().saturating_sub(1))
|
||||
.rev()
|
||||
.map(|k| {
|
||||
let mut shape = PathData::single(square((k + 1) as f64 * step));
|
||||
let mut shape = PathData::single(square(edges.get(k + 1).copied().unwrap_or(*reach)));
|
||||
if !opaque && k > 0 {
|
||||
let mut hole = square(k as f64 * step);
|
||||
let mut hole = square(edges.get(k).copied().unwrap_or(0.0));
|
||||
hole.reverse();
|
||||
shape.subpaths.push(hole);
|
||||
}
|
||||
(shape, g.sample_keep_model(((k as f64 + 0.5) * step) as f32))
|
||||
(shape, color(&edges, k))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let step = (self.t1 - self.t0) / n as f64;
|
||||
let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32);
|
||||
let edges = band_edges(self.t0, self.t1, n, runs);
|
||||
let bands = edges.len().saturating_sub(1);
|
||||
let edge = |k: usize| edges.get(k).copied().unwrap_or(self.t1);
|
||||
if self.radial {
|
||||
let ellipse = |t: f64| {
|
||||
let c = self.focal + (self.start - self.focal) * t;
|
||||
let m = Affine::new([self.along.x * t, self.along.y * t, self.across.x * t, self.across.y * t, c.x, c.y]);
|
||||
shapes::ellipse(Rect::new(-1.0, -1.0, 1.0, 1.0)).transformed(m)
|
||||
};
|
||||
return (0..n)
|
||||
return (0..bands)
|
||||
.rev()
|
||||
.map(|k| {
|
||||
let mut shape = ellipse((k + 1) as f64 * step);
|
||||
let mut shape = ellipse(edge(k + 1));
|
||||
if !opaque && k > 0 {
|
||||
let mut hole = ellipse(k as f64 * step).subpaths.remove(0);
|
||||
let mut hole = ellipse(edge(k)).subpaths.remove(0);
|
||||
hole.reverse();
|
||||
shape.subpaths.push(hole);
|
||||
}
|
||||
(shape, color(k))
|
||||
(shape, color(&edges, k))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
(0..n)
|
||||
(0..bands)
|
||||
.map(|k| {
|
||||
let a = self.t0 + k as f64 * step;
|
||||
let b = if opaque { self.t1 } else { a + step };
|
||||
let a = edge(k);
|
||||
let b = if opaque { self.t1 } else { edge(k + 1) };
|
||||
let pts = [self.at(a, self.s0), self.at(b, self.s0), self.at(b, self.s1), self.at(a, self.s1)];
|
||||
(PathData::single(SubPath::polyline(&pts, true)), color(k))
|
||||
(PathData::single(SubPath::polyline(&pts, true)), color(&edges, k))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! File → File Info (`file.info`): the document title and its descriptive metadata (author,
|
||||
//! description, keywords, rating, copyright), with the read-only created and modified dates. The
|
||||
//! SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or `.ai` opens with the File Info
|
||||
//! it gives ([`read_pdf`]).
|
||||
//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]),
|
||||
//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or
|
||||
//! `.ai` opens with the File Info it gives ([`read_pdf`]).
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::metadata::{MAX_RATING, iso8601};
|
||||
@@ -22,7 +23,7 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb
|
||||
pub(crate) fn info_json(d: &Document) -> Value {
|
||||
let m = &d.metadata;
|
||||
json!({
|
||||
"title": d.title,
|
||||
"title": d.info_title(),
|
||||
"author": m.author,
|
||||
"authorTitle": m.author_title,
|
||||
"description": m.description,
|
||||
@@ -48,14 +49,22 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(C, "params must be an object")),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let (mut title, mut m) = (d.title.clone(), d.metadata.clone());
|
||||
let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone());
|
||||
for (k, v) in o {
|
||||
apply(&mut title, &mut m, k, v)?;
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
if title != d.title || m != d.metadata {
|
||||
// A title File Info changes becomes the document's own, as it always has (the tab and Save As
|
||||
// offer it where the document has no file), and replaces the one its file gave.
|
||||
let retitled = title != d.info_title();
|
||||
if retitled {
|
||||
m.title = None;
|
||||
}
|
||||
if retitled || m != d.metadata {
|
||||
s.edit("File Info", |d, _| {
|
||||
d.title = title;
|
||||
if retitled {
|
||||
d.title = title;
|
||||
}
|
||||
d.metadata = m;
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -64,8 +73,8 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each
|
||||
/// field that `file.info` would take (a value it refuses is left out), and the created and
|
||||
/// modified dates.
|
||||
/// field that `file.info` would take (a value it refuses is left out), its title ([`imported_title`])
|
||||
/// as the File Info title, and the created and modified dates.
|
||||
pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
|
||||
let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
|
||||
let fields = [
|
||||
@@ -83,6 +92,7 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
|
||||
let _ = apply(&mut title, m, k, &v);
|
||||
}
|
||||
}
|
||||
m.title = f.title.as_deref().and_then(imported_title);
|
||||
m.created = f.created.or(m.created);
|
||||
m.modified = f.modified.or(m.modified);
|
||||
}
|
||||
@@ -141,6 +151,18 @@ fn text(k: &str, v: &Value, multiline: bool) -> Result<String> {
|
||||
Ok(s.to_string())
|
||||
}
|
||||
|
||||
/// The File Info title `raw`, read from a file, makes: runs of white space (line breaks too)
|
||||
/// become single spaces, other control characters are dropped, at most [`MAX_TEXT`] characters
|
||||
/// are kept, as `file.info` takes a title. `None` when nothing is left, or when it is the
|
||||
/// Untitled-N name New gives (what a document that never had a title writes to its files).
|
||||
pub(crate) fn imported_title(raw: &str) -> Option<String> {
|
||||
let words: Vec<String> =
|
||||
raw.split_whitespace().map(|w| w.chars().filter(|c| !c.is_control()).collect::<String>()).filter(|w| !w.is_empty()).collect();
|
||||
let title: String = words.join(" ").chars().take(MAX_TEXT).collect();
|
||||
let title = title.trim_end();
|
||||
super::fileio::is_own_title(title).then(|| title.to_string())
|
||||
}
|
||||
|
||||
/// Keywords from a list or a comma- or semicolon-separated string: trimmed, each once (ignoring
|
||||
/// case), empty ones dropped.
|
||||
fn keywords(v: &Value) -> Result<Vec<String>> {
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place.
|
||||
//! - `hpgl`: HP-GL export options and plots.
|
||||
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
|
||||
//! built-in format reads).
|
||||
//! - `mesh3d`: 3D assets as OBJ, glTF, USDA and USDZ mesh files (`assets.export3D`).
|
||||
@@ -40,6 +41,7 @@ mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
mod jp2read;
|
||||
mod metafile;
|
||||
mod naming;
|
||||
@@ -90,9 +92,9 @@ pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
pub use save::{
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option,
|
||||
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
|
||||
templates_folder,
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, documents_dialog_folder, export_folder,
|
||||
leave_out_unreadable_save_paths, reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan,
|
||||
save_with, stamp_save_dates, template_filters, templates_dialog_folder, templates_folder,
|
||||
};
|
||||
pub(crate) use screens::{
|
||||
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
|
||||
@@ -121,10 +123,15 @@ mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::write_file_with;
|
||||
pub use access::{write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_readonly;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::{Placed, copy_new, file_metadata};
|
||||
pub(crate) use access::{absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, write_file, write_new_file};
|
||||
pub(crate) use access::{
|
||||
absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, shown_link, shown_path, write_file, write_new_file,
|
||||
};
|
||||
#[cfg(all(test, windows))]
|
||||
pub(crate) use access::{document_path_on, document_path_with};
|
||||
#[cfg(test)]
|
||||
@@ -139,6 +146,7 @@ pub(crate) use export_names::{
|
||||
artboard_file_names_keeping_dots, default_name, merge, unique_file_names_keeping_dots, with_black_output, write_or_return,
|
||||
};
|
||||
use export_names::{distinct_names_by, write_encoded};
|
||||
pub(crate) use formats::is_own_title;
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
|
||||
pub use formats::{
|
||||
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
|
||||
|
||||
@@ -42,6 +42,29 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
(out, seen)
|
||||
}
|
||||
|
||||
/// May a reply to the request being served name `path`, a file or folder the client did not give?
|
||||
/// Always without roots in force; with them, only inside the read roots ([`crate::file_access::check_read`]).
|
||||
pub(crate) fn shown(path: &str) -> bool {
|
||||
crate::file_access::check_read(path).is_ok()
|
||||
}
|
||||
|
||||
/// `path` as a reply to the request being served names it: whole when [`shown`], else its file name,
|
||||
/// after the last `/` or `\` whichever platform wrote it (empty for a path that ends in no name, such
|
||||
/// as `..` or a folder ending in a separator).
|
||||
pub(crate) fn shown_path(path: &str) -> std::borrow::Cow<'_, str> {
|
||||
shown_link(path, None)
|
||||
}
|
||||
|
||||
/// A link's `stored` path as a reply to the request being served names it: whole when the file it
|
||||
/// names (`resolved`, else `stored` itself) is [`shown`], else its file name as [`shown_path`] gives it.
|
||||
pub(crate) fn shown_link<'a>(stored: &'a str, resolved: Option<&str>) -> std::borrow::Cow<'a, str> {
|
||||
if shown(resolved.unwrap_or(stored)) {
|
||||
return std::borrow::Cow::Borrowed(stored);
|
||||
}
|
||||
let name = stored.rsplit(vectorcraft_doc::links::path_separators(stored)).next().unwrap_or_default();
|
||||
std::borrow::Cow::Borrowed(if matches!(name, "." | "..") { "" } else { name })
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
@@ -89,6 +112,31 @@ pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write)
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
|
||||
/// writers keep their existing errors; an automation-root refusal is never reclassified.
|
||||
pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
write_save_file_with(path, &mut |w| w.write_all(bytes))
|
||||
}
|
||||
|
||||
/// [`write_save_file`] for a streamed save.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
let reason = format!("{path}: {error}");
|
||||
if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) }
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
write_file_with(path, fill)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn create_dir(path: &str) -> Result<()> {
|
||||
may_write(path)?;
|
||||
|
||||
@@ -536,6 +536,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
|
||||
| "dxf"
|
||||
| "emf"
|
||||
| "wmf"
|
||||
| "hpgl"
|
||||
| "ai"
|
||||
)
|
||||
};
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path",
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel,
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Presets",
|
||||
[],
|
||||
None,
|
||||
"{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones; any name works as document.exportForScreens' exportPreset",
|
||||
"{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones (a folder outside the automation read roots is left out of settings); any name works as document.exportForScreens' exportPreset",
|
||||
always,
|
||||
screens::presets_list
|
||||
),
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Export Presets",
|
||||
[],
|
||||
None,
|
||||
"{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}",
|
||||
"{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON; a folder outside the automation read roots is left out); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}",
|
||||
always,
|
||||
screens::presets_export
|
||||
),
|
||||
@@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens Settings",
|
||||
[],
|
||||
None,
|
||||
"{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them)",
|
||||
"{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them; a folder outside the automation read roots is left out)",
|
||||
has_doc,
|
||||
screens::export_settings
|
||||
),
|
||||
|
||||
@@ -464,7 +464,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
|
||||
// themselves: SVG only when it outlines or embeds fonts).
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf"))
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl"))
|
||||
&& let Some(w) = crate::cmd::fonts::substitution_warning(doc)
|
||||
{
|
||||
enc.warnings.push(w);
|
||||
@@ -503,7 +503,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf") { use_artboards(p)? } else { None };
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -536,6 +536,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"eps" => return super::eps::encode(doc, p),
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
"wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf),
|
||||
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
|
||||
"ai" => return super::save::encode_ai(C, f, doc, p),
|
||||
"pdf" => {
|
||||
let (bytes, warnings) = super::pdf::encode(C, doc, p)?;
|
||||
@@ -591,7 +592,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let bytes = renderer.export_region(doc, region, format, &settings).map_err(EngineError::Other)?;
|
||||
// File Info as PNG text chunks.
|
||||
let bytes = if matches!(format, RasterFormat::Png | RasterFormat::Png8) {
|
||||
vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(&doc.title))
|
||||
vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(doc.info_title()))
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
|
||||
@@ -370,7 +370,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
|
||||
let o = EpsOptions {
|
||||
region,
|
||||
origin,
|
||||
title: doc.title.clone(),
|
||||
title: doc.info_title().to_owned(),
|
||||
created,
|
||||
native: Some(native(&editing, if whole { None } else { board }, set.include_linked)),
|
||||
..set.eps.clone()
|
||||
|
||||
Loaded 100 of 515 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user