mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 09:54:09 +01:00
Merge main into feat/3d-graphics-inflate
This commit is contained in:
commit
cb96dc123a
674 files changed
+107656
-3821
No files matched your search
@@ -135,6 +135,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-curvature-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (an arch with the circle that touches it at its top, and that circle's center) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-dash-exact.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-dimension.svg` | Osama Amin | Original work, drawn for VectorCraft: a dimension line with arrowheads between two extension lines | MIT OR Apache-2.0 | |
|
||||
@@ -220,6 +221,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-polygon.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-pucker.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
Generated
+27
@@ -1044,6 +1044,20 @@ name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"kurbo 0.13.1",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"unicode-segmentation",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
@@ -6630,6 +6644,7 @@ dependencies = [
|
||||
"webbrowser",
|
||||
"windows",
|
||||
"winit",
|
||||
"winreg",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"wl-clipboard-rs",
|
||||
@@ -6685,6 +6700,16 @@ dependencies = [
|
||||
"vectorcraft-text",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cdr"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"proptest",
|
||||
"vectorcraft-cdr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.24.1"
|
||||
@@ -6799,6 +6824,7 @@ dependencies = [
|
||||
"vectorcraft-apischema",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-cad",
|
||||
"vectorcraft-cdr",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-eps",
|
||||
@@ -7109,6 +7135,7 @@ dependencies = [
|
||||
name = "vectorcraft-text"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-font-catalog",
|
||||
"craft-proof",
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
|
||||
@@ -77,6 +77,7 @@ vectorcraft-affinity = { path = "crates/affinity" }
|
||||
vectorcraft-scriptcheck = { path = "crates/scriptcheck" }
|
||||
vectorcraft-js = { path = "crates/js" }
|
||||
vectorcraft-apischema = { path = "crates/apischema" }
|
||||
vectorcraft-cdr = { path = "crates/cdr" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
|
||||
@@ -35,6 +35,11 @@ based in part on the work of the Independent JPEG Group.
|
||||
WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is
|
||||
under the Apache License 2.0 with the LLVM exception.
|
||||
|
||||
The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification
|
||||
coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach
|
||||
Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part
|
||||
of either specification is copied into the crate; the license text is in crates/cdr/LICENSE-kaitai.txt.
|
||||
|
||||
Builds made with craft-fonts (the CRAFT_FONTS_DIR build option; all official releases) embed the
|
||||
fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic,
|
||||
Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest;
|
||||
|
||||
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
|
||||
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
|
||||
|
||||
@@ -140,8 +142,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers 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-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers 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.
|
||||
@@ -150,12 +154,16 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 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).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 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.
|
||||
|
||||
@@ -40,6 +40,9 @@ craft-print = { workspace = true }
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
clipboard-win = { workspace = true }
|
||||
# Reads a print queue's Standard TCP/IP RAW port for the direct-PDF transport (src/direct_pdf.rs).
|
||||
# MIT, already in the build through the update client.
|
||||
winreg = "0.55"
|
||||
# Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the
|
||||
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
|
||||
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
|
||||
|
||||
@@ -459,6 +459,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
open_file: Some(Box::new(open_file)),
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))),
|
||||
open_in_application: Some(Box::new(open_in_application)),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())),
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
@@ -507,15 +509,32 @@ fn open_in_photocraft(path: &str) -> Result<bool, String> {
|
||||
explorer_safe(path)?;
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from);
|
||||
let Some(app) = find_photocraft(home.as_deref(), std::env::var_os("PATH").as_deref()) else { return Ok(false) };
|
||||
launch_application(&app, path)
|
||||
}
|
||||
|
||||
/// A missing chosen editor falls back; invalid applications and failed launches remain errors.
|
||||
fn open_in_application(app: &str, path: &str) -> Result<bool, String> {
|
||||
explorer_safe(path)?;
|
||||
let app = std::path::Path::new(app);
|
||||
match std::fs::metadata(app) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(e) => return Err(format!("cannot inspect {}: {e}", app.display())),
|
||||
Ok(_) => {}
|
||||
}
|
||||
check_app(app)?;
|
||||
launch_application(app, path)
|
||||
}
|
||||
|
||||
fn launch_application(app: &std::path::Path, path: &str) -> Result<bool, String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let mut c = {
|
||||
let mut c = std::process::Command::new("open");
|
||||
c.arg("-a").arg(&app).arg(path);
|
||||
c.arg("-a").arg(app).arg(path);
|
||||
c
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let mut c = {
|
||||
let mut c = std::process::Command::new(&app);
|
||||
let mut c = std::process::Command::new(app);
|
||||
c.arg(path);
|
||||
c
|
||||
};
|
||||
@@ -688,6 +707,17 @@ mod open_with_tests {
|
||||
tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chosen_editor_only_falls_back_when_missing() {
|
||||
let dir = scratch("chosen");
|
||||
let missing = dir.path().join("Missing.exe");
|
||||
assert!(!super::open_in_application(&missing.to_string_lossy(), "image with spaces.png").unwrap());
|
||||
let doc = dir.path().join("notes.txt");
|
||||
std::fs::write(&doc, "not an application").unwrap();
|
||||
assert!(super::open_in_application(&doc.to_string_lossy(), "image.png").is_err());
|
||||
assert!(super::open_in_application(&dir.path().to_string_lossy(), "image.png").is_err());
|
||||
}
|
||||
|
||||
/// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing
|
||||
/// path.
|
||||
#[test]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764). winit 0.30
|
||||
//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764), and an airbrush
|
||||
//! pen's finger wheel. winit 0.30
|
||||
//! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit
|
||||
//! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas
|
||||
//! reads, as on X11 ([`crate::tablet`]).
|
||||
@@ -14,8 +15,9 @@
|
||||
//! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the
|
||||
//! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read
|
||||
//! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation
|
||||
//! from one held upright and unturned. Each reads as none until the pen reports a value other
|
||||
//! than 0 after it comes near ([`Pen`]).
|
||||
//! from one held upright and unturned. Its `tangentialPressure` (−1..1, an airbrush pen's finger
|
||||
//! wheel) goes into the pose as the wheel, 0 for a pen without one as well. Each reads as none
|
||||
//! until the pen reports a value other than 0 after it comes near ([`Pen`]).
|
||||
//! A mouse event of any other subtype is a mouse's or a trackpad's: the feed is set to `None`.
|
||||
//! - An `NSEventTypeTabletPoint` event carries the same pressure, tilt and rotation without a move.
|
||||
//! - A tablet proximity event (`NSEventTypeTabletProximity`, or a mouse event of that subtype) says
|
||||
@@ -68,6 +70,8 @@ struct RawEvent {
|
||||
tilt: (f64, f64),
|
||||
/// `rotation`, in degrees (the same events as `pressure`).
|
||||
rotation: f32,
|
||||
/// `tangentialPressure`, −1..1 (the same events as `pressure`).
|
||||
tangential: f32,
|
||||
/// `pointingDeviceType` (proximity events only).
|
||||
device: usize,
|
||||
/// `isEnteringProximity` (proximity events only).
|
||||
@@ -107,18 +111,42 @@ impl RawEvent {
|
||||
/// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the
|
||||
/// angle is negated and brought into 0..360.
|
||||
///
|
||||
/// The tilt is left out unless `tilts`, and the rotation unless `turns` ([`Pen`]).
|
||||
fn pose(&self, tilts: bool, turns: bool) -> PenPose {
|
||||
/// AppKit's `tangentialPressure` is −1.0..1.0, the finger wheel of an airbrush pen on the
|
||||
/// devices that have one (<https://developer.apple.com/documentation/appkit/nsevent/tangentialpressure>).
|
||||
/// It becomes [`PenPose`]'s wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is
|
||||
/// clamped.
|
||||
///
|
||||
/// The tilt is left out unless `read.tilts`, the rotation unless `read.turns`, and the wheel
|
||||
/// unless `read.wheels` ([`Pen`]).
|
||||
fn pose(&self, read: Reads) -> PenPose {
|
||||
let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32;
|
||||
// `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0.
|
||||
let rotation = turns.then(|| (0.0 - self.rotation).rem_euclid(360.0));
|
||||
PenPose { tilt: tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation }
|
||||
let rotation = read.turns.then(|| (0.0 - self.rotation).rem_euclid(360.0));
|
||||
let wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0);
|
||||
PenPose { tilt: read.tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation, wheel }
|
||||
}
|
||||
|
||||
/// Whether the event reports a tilt other than 0, and a rotation other than 0.
|
||||
fn reads(&self) -> (bool, bool) {
|
||||
/// Whether the event reports a tilt other than 0, a rotation other than 0, and a tangential
|
||||
/// pressure other than 0.
|
||||
fn reads(&self) -> Reads {
|
||||
let read = |v: f64| v.is_finite() && v != 0.0;
|
||||
(read(self.tilt.0) || read(self.tilt.1), read(f64::from(self.rotation)))
|
||||
Reads { tilts: read(self.tilt.0) || read(self.tilt.1), turns: read(f64::from(self.rotation)), wheels: read(f64::from(self.tangential)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of a pen's tilt, rotation and finger wheel it has reported.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Reads {
|
||||
tilts: bool,
|
||||
turns: bool,
|
||||
wheels: bool,
|
||||
}
|
||||
|
||||
impl Reads {
|
||||
fn add(&mut self, other: Reads) {
|
||||
self.tilts |= other.tilts;
|
||||
self.turns |= other.turns;
|
||||
self.wheels |= other.wheels;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,14 +176,14 @@ impl Update {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which end of the pen is near the tablet, and whether it has reported a tilt or a rotation other
|
||||
/// than 0 since it came near: until it has, its tilt or rotation reads as none, since AppKit gives
|
||||
/// 0 for a pen without one and for one held upright or unturned.
|
||||
/// Which end of the pen is near the tablet, and whether it has reported a tilt, a rotation or a
|
||||
/// tangential pressure other than 0 since it came near: until it has, that value reads as none,
|
||||
/// since AppKit gives 0 for a pen without one and for one held upright, unturned or with its
|
||||
/// wheel half way.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Pen {
|
||||
eraser: bool,
|
||||
tilts: bool,
|
||||
turns: bool,
|
||||
read: Reads,
|
||||
}
|
||||
|
||||
impl Pen {
|
||||
@@ -163,16 +191,14 @@ impl Pen {
|
||||
if e.proximity() {
|
||||
// Entering with the tip or the eraser end: it hovers. A puck, or leaving, is a mouse.
|
||||
self.eraser = e.entering && e.device == device::ERASER;
|
||||
(self.tilts, self.turns) = (false, false);
|
||||
self.read = Reads::default();
|
||||
let pen = e.entering && e.device != device::CURSOR;
|
||||
return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() }));
|
||||
}
|
||||
if e.point() {
|
||||
let (tilts, turns) = e.reads();
|
||||
self.tilts |= tilts;
|
||||
self.turns |= turns;
|
||||
self.read.add(e.reads());
|
||||
}
|
||||
let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.tilts, self.turns) };
|
||||
let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.read) };
|
||||
match (e.point(), e.mouse()) {
|
||||
(true, true) => Update::Move(sample),
|
||||
(true, false) => Update::Set(Some(sample)),
|
||||
@@ -246,6 +272,7 @@ mod monitor {
|
||||
let tilt = e.tilt();
|
||||
raw.tilt = (tilt.x, tilt.y);
|
||||
raw.rotation = e.rotation();
|
||||
raw.tangential = e.tangentialPressure();
|
||||
}
|
||||
if raw.proximity() {
|
||||
raw.device = e.pointingDeviceType().0;
|
||||
@@ -326,26 +353,44 @@ mod tests {
|
||||
let sample = |pressure, pose| PenSample { pressure, eraser: false, pose };
|
||||
assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet");
|
||||
let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) };
|
||||
let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0) };
|
||||
let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0), wheel: None };
|
||||
assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose)));
|
||||
let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) };
|
||||
let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0) };
|
||||
let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0), wheel: None };
|
||||
assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped");
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
|
||||
let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") };
|
||||
assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned");
|
||||
assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}");
|
||||
let feed = StylusFeed::default();
|
||||
p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed);
|
||||
assert_eq!(feed.pose(), Some(PenPose { tilt: None, rotation: Some(90.0) }), "a tilt that is not a number is left out");
|
||||
assert_eq!(feed.pose(), Some(PenPose { rotation: Some(90.0), ..PenPose::default() }), "a tilt that is not a number is left out");
|
||||
p.handle(&proximity(1, true));
|
||||
let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) };
|
||||
let pose = PenPose { tilt: Some([0.0, 30.0]), rotation: None };
|
||||
let pose = PenPose { tilt: Some([0.0, 30.0]), ..PenPose::default() };
|
||||
assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near");
|
||||
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed);
|
||||
assert_eq!(feed.pose(), None, "a mouse moved");
|
||||
}
|
||||
|
||||
/// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the feed as
|
||||
/// 0..1, once the pen has reported a value other than 0 since it came near.
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_feed() {
|
||||
let mut p = Pen::default();
|
||||
let wheel = |p: &mut Pen, tangential: f32| match p.handle(&RawEvent { tangential, ..pen(DRAG, 0.5) }) {
|
||||
Update::Move(s) => s.pose.wheel,
|
||||
u => panic!("a pen's drag is a move: {u:?}"),
|
||||
};
|
||||
assert_eq!(wheel(&mut p, 0.0), None, "no wheel reported yet");
|
||||
assert_eq!(wheel(&mut p, -1.0), Some(0.0));
|
||||
assert_eq!(wheel(&mut p, 0.5), Some(0.75));
|
||||
assert_eq!(wheel(&mut p, 0.0), Some(0.5), "once reported, 0 is half way");
|
||||
assert_eq!(wheel(&mut p, 3.0), Some(1.0), "clamped");
|
||||
p.handle(&proximity(1, true));
|
||||
assert_eq!(wheel(&mut p, 0.0), None, "not reported since the pen came near");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_feed_gets_each_moves_pressure_within_0_to_1() {
|
||||
let feed = StylusFeed::default();
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
use std::process::Command;
|
||||
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
|
||||
mod direct_pdf;
|
||||
|
||||
pub struct SystemPrint;
|
||||
impl PrintService for SystemPrint {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
@@ -43,6 +45,9 @@ mod system {
|
||||
craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect()
|
||||
}
|
||||
pub fn print(job: &PrintJob) -> Result<String, String> {
|
||||
if job.direct_pdf {
|
||||
return super::direct_pdf::print(job);
|
||||
}
|
||||
// Copies, layout, marks and colour management are already in the PDF. Preserve its
|
||||
// physical sheet size and the queue's duplex default without printing copies twice.
|
||||
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Send the print-ready PDF to the printer's own PDF interpreter over its RAW TCP port.
|
||||
//!
|
||||
//! This is the opt-in escape hatch for large-format PCL drivers that rewrite a custom page
|
||||
//! (the HP DesignJet Z5200ps V4 driver emits a square PCL page for a 1067 x 480 mm sheet). The
|
||||
//! PDF already carries the paper size, so the printer's interpreter prints it as laid out.
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use std::io::Write;
|
||||
use std::net::{Shutdown, TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
|
||||
use vectorcraft_ui_egui::print::PrintJob;
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ};
|
||||
|
||||
/// Submit one composed PDF to the selected printer's Standard TCP/IP RAW port.
|
||||
pub fn print(job: &PrintJob) -> Result<String, String> {
|
||||
let printer = job
|
||||
.printer
|
||||
.map(str::to_string)
|
||||
.or_else(|| craft_print::printers().into_iter().find(|p| p.default).map(|p| p.name))
|
||||
.ok_or("direct PDF needs a selected printer")?;
|
||||
let (host, port) = tcp_port(&printer)?;
|
||||
send(&host, port, &pjl(job.title, job.pdf))?;
|
||||
Ok(format!(" (direct PDF to {host}:{port})"))
|
||||
}
|
||||
|
||||
/// The `HostName` and port of a printer port registered as a Standard TCP/IP RAW port.
|
||||
fn tcp_port(printer: &str) -> Result<(String, u16), String> {
|
||||
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
|
||||
let printer_key = hklm
|
||||
.open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Printers\{printer}"), KEY_READ)
|
||||
.map_err(|e| format!("direct PDF: cannot read the printer settings for {printer}: {e}"))?;
|
||||
let port_name: String = printer_key.get_value("Port").map_err(|e| format!("direct PDF: {printer} has no port: {e}"))?;
|
||||
let port_key = hklm
|
||||
.open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\{port_name}"), KEY_READ)
|
||||
.map_err(|e| format!("direct PDF: {printer} does not use a Standard TCP/IP port ({port_name}): {e}"))?;
|
||||
let protocol: u32 = port_key.get_value("Protocol").unwrap_or(1);
|
||||
if protocol != 1 {
|
||||
return Err(format!("direct PDF: {printer}'s port ({port_name}) is not a RAW TCP/IP port"));
|
||||
}
|
||||
let host = port_key
|
||||
.get_value::<String, _>("HostName")
|
||||
.ok()
|
||||
.filter(|h| !h.trim().is_empty())
|
||||
.or_else(|| port_key.get_value::<String, _>("IPAddress").ok().filter(|h| !h.trim().is_empty()))
|
||||
.ok_or_else(|| format!("direct PDF: {printer}'s port ({port_name}) has no host address"))?;
|
||||
let number = port_key.get_value::<u32, _>("PortNumber").unwrap_or(9100);
|
||||
let port = u16::try_from(number).map_err(|_| format!("direct PDF: invalid port number {number}"))?;
|
||||
Ok((host.trim().to_string(), port))
|
||||
}
|
||||
|
||||
/// Frame the PDF for the printer's PJL interpreter.
|
||||
fn pjl(title: &str, pdf: &[u8]) -> Vec<u8> {
|
||||
let mut name: String = title.chars().map(|c| if (c.is_ascii_graphic() || c == ' ') && c != '"' { c } else { '_' }).take(80).collect();
|
||||
if name.is_empty() {
|
||||
name.push_str("VectorCraft");
|
||||
}
|
||||
let mut out = Vec::with_capacity(pdf.len() + 96);
|
||||
out.extend_from_slice(b"\x1b%-12345X@PJL JOB NAME=\"");
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.extend_from_slice(b"\"\r\n@PJL ENTER LANGUAGE=PDF\r\n");
|
||||
out.extend_from_slice(pdf);
|
||||
out.extend_from_slice(b"\r\n\x1b%-12345X@PJL EOJ\r\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// Stream `data` to the first reachable address of `host:port`.
|
||||
fn send(host: &str, port: u16, data: &[u8]) -> Result<(), String> {
|
||||
let addrs = (host, port).to_socket_addrs().map_err(|e| format!("direct PDF: cannot resolve {host}: {e}"))?;
|
||||
let mut last = None;
|
||||
for addr in addrs {
|
||||
match TcpStream::connect_timeout(&addr, Duration::from_secs(10)) {
|
||||
Ok(mut stream) => {
|
||||
stream.set_write_timeout(Some(Duration::from_secs(120))).map_err(|e| format!("direct PDF: {e}"))?;
|
||||
stream.write_all(data).map_err(|e| format!("direct PDF: writing to {host}:{port} failed: {e}"))?;
|
||||
stream.shutdown(Shutdown::Write).map_err(|e| format!("direct PDF: finishing {host}:{port} failed: {e}"))?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last = Some(e),
|
||||
}
|
||||
}
|
||||
Err(match last {
|
||||
Some(e) => format!("direct PDF: cannot connect to {host}:{port}: {e}"),
|
||||
None => format!("direct PDF: {host}:{port} has no addresses"),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
use std::net::TcpListener;
|
||||
|
||||
#[test]
|
||||
fn the_pjl_frames_the_pdf() {
|
||||
let out = pjl("witch hat\"", b"%PDF-1.7");
|
||||
let text = String::from_utf8_lossy(&out);
|
||||
assert!(text.starts_with("\u{1b}%-12345X@PJL JOB NAME=\"witch hat_\"\r\n@PJL ENTER LANGUAGE=PDF\r\n"));
|
||||
assert!(text.contains("%PDF-1.7"));
|
||||
assert!(text.ends_with("\r\n\u{1b}%-12345X@PJL EOJ\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pdf_reaches_a_listening_port() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let t = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut got = Vec::new();
|
||||
stream.read_to_end(&mut got).unwrap();
|
||||
got
|
||||
});
|
||||
send("127.0.0.1", port, b"%PDF-1.7 test").unwrap();
|
||||
assert_eq!(t.join().unwrap(), b"%PDF-1.7 test");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use imp::print;
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn print(_: &vectorcraft_ui_egui::print::PrintJob) -> Result<String, String> {
|
||||
Err("direct PDF printing is only available on Windows".into())
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Linux: a drawing tablet's pen pressure, tilt and barrel rotation under X11, XWayland included
|
||||
//! Linux: a drawing tablet's pen pressure, tilt, barrel rotation and airbrush finger wheel under
|
||||
//! X11, XWayland included
|
||||
//! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app
|
||||
//! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`]
|
||||
//! (`Services::stylus`), which the canvas reads.
|
||||
@@ -14,11 +15,17 @@
|
||||
//! - "Abs Tilt X" and "Abs Tilt Y" (a pen that has both), in degrees as they are when the range
|
||||
//! fits in ±90, otherwise scaled to ±[`TILT_DEGREES`];
|
||||
//! - "Abs Rotary Z" (the barrel rotation of an Art Pen), scaled to a turn with the middle of the
|
||||
//! range at 0°.
|
||||
//! range at 0°;
|
||||
//! - "Abs Wheel" (the finger wheel of an airbrush pen), scaled from the valuator's range to 0..1.
|
||||
//! XWayland also sends an Art Pen's barrel rotation on this valuator
|
||||
//! (<https://github.com/mirror/xserver/blob/master/hw/xwayland/xwayland-input.c>), so under
|
||||
//! XWayland it reads as the wheel. A tablet pad's wheel is on a device without a pressure axis,
|
||||
//! which is not read.
|
||||
//!
|
||||
//! Any other pointer device moving sets the feed to `None`. Raw events carry only the valuators
|
||||
//! that changed, so the last value of each axis of each pen is kept; an axis the pen has that no
|
||||
//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing.
|
||||
//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing. The
|
||||
//! wheel reads nothing until an event carries it.
|
||||
//!
|
||||
//! The X server lists a pen's eraser end as a device of its own, whose name or XInput type contains
|
||||
//! "eraser" (xf86-input-wacom's "… Pen eraser" of type `ERASER`, xf86-input-libinput's
|
||||
@@ -60,6 +67,7 @@ enum AxisKind {
|
||||
TiltX,
|
||||
TiltY,
|
||||
Rotation,
|
||||
Wheel,
|
||||
}
|
||||
|
||||
impl AxisKind {
|
||||
@@ -70,6 +78,7 @@ impl AxisKind {
|
||||
"Abs Tilt X" => Some(Self::TiltX),
|
||||
"Abs Tilt Y" => Some(Self::TiltY),
|
||||
"Abs Rotary Z" => Some(Self::Rotation),
|
||||
"Abs Wheel" => Some(Self::Wheel),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -81,6 +90,7 @@ impl AxisKind {
|
||||
Self::TiltX => 1,
|
||||
Self::TiltY => 2,
|
||||
Self::Rotation => 3,
|
||||
Self::Wheel => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,18 +105,22 @@ struct Axis {
|
||||
}
|
||||
|
||||
impl Axis {
|
||||
/// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90) or a
|
||||
/// rotation in degrees (−180..180, the middle of the range at 0). A value that is not a number
|
||||
/// is a mouse's pressure, 1, or a tilt or rotation of 0.
|
||||
/// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90), a rotation
|
||||
/// in degrees (−180..180, the middle of the range at 0) or a wheel of 0..1. A value that is not
|
||||
/// a number is a mouse's pressure, 1, a tilt or rotation of 0, or a wheel half way.
|
||||
fn map(&self, v: f64) -> f32 {
|
||||
if !v.is_finite() {
|
||||
return if self.kind == AxisKind::Pressure { 1.0 } else { 0.0 };
|
||||
return match self.kind {
|
||||
AxisKind::Pressure => 1.0,
|
||||
AxisKind::Wheel => 0.5,
|
||||
_ => 0.0,
|
||||
};
|
||||
}
|
||||
let span = self.max - self.min;
|
||||
let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v };
|
||||
let unit = unit.clamp(0.0, 1.0);
|
||||
match self.kind {
|
||||
AxisKind::Pressure => unit as f32,
|
||||
AxisKind::Pressure | AxisKind::Wheel => unit as f32,
|
||||
AxisKind::TiltX | AxisKind::TiltY if self.min >= -90.0 && self.max <= 90.0 && span > 0.0 => v.clamp(-90.0, 90.0) as f32,
|
||||
AxisKind::TiltX | AxisKind::TiltY => ((unit * 2.0 - 1.0) * TILT_DEGREES) as f32,
|
||||
AxisKind::Rotation => ((unit - 0.5) * 360.0) as f32,
|
||||
@@ -173,7 +187,7 @@ enum Update {
|
||||
#[derive(Debug, Default)]
|
||||
struct Pens {
|
||||
devices: HashMap<u16, Device>,
|
||||
last: HashMap<u16, [Option<f32>; 4]>,
|
||||
last: HashMap<u16, [Option<f32>; 5]>,
|
||||
}
|
||||
|
||||
impl Pens {
|
||||
@@ -200,10 +214,12 @@ impl Pens {
|
||||
}
|
||||
}
|
||||
}
|
||||
// An axis the pen has reads 0 until an event carries it; one it lacks reads nothing.
|
||||
// An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. The
|
||||
// wheel reads nothing until an event carries it: XWayland lists the axis for every pen.
|
||||
let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0));
|
||||
let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]);
|
||||
let pose = PenPose { tilt, rotation: value(AxisKind::Rotation) };
|
||||
let wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten());
|
||||
let pose = PenPose { tilt, rotation: value(AxisKind::Rotation), wheel };
|
||||
Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose }))
|
||||
}
|
||||
|
||||
@@ -430,7 +446,7 @@ mod tests {
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]);
|
||||
let feed = StylusFeed::default();
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
|
||||
pens.raw_event(&feed, 9, &[0b100], &[32767.5]);
|
||||
assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose })));
|
||||
assert_eq!(feed.eraser(), Some(false));
|
||||
@@ -479,10 +495,36 @@ mod tests {
|
||||
// A pen whose tilt and rotation no event has carried yet is upright and unturned.
|
||||
let mut fresh = Pens::default();
|
||||
fresh.set_devices([pen(9)]);
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
|
||||
assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
|
||||
}
|
||||
|
||||
/// An airbrush pen's "Abs Wheel" valuator goes into the feed as 0..1 of its range, once an
|
||||
/// event carries it; a pen that lists it but has not moved it reads no wheel, and a device
|
||||
/// without a pressure axis (a tablet pad's wheel) is not a pen.
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_feed() {
|
||||
let mut valuators = pen_valuators();
|
||||
valuators.push((6, "Abs Wheel".to_string(), 0.0, 1023.0));
|
||||
let airbrush = Device::new(9, "Wacom Intuos Pro M Pen stylus", Some("STYLUS"), valuators);
|
||||
let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(6, "Abs Wheel".to_string(), 0.0, 71.0)]);
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([airbrush, pad, pen(10)]);
|
||||
let feed = StylusFeed::default();
|
||||
pens.raw_event(&feed, 9, &[0b100], &[32767.5]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), None, "no event has carried the wheel yet");
|
||||
pens.raw_event(&feed, 9, &[0b100_0000], &[255.75]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.25));
|
||||
pens.raw_event(&feed, 9, &[0b100_0000], &[5000.0]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "clamped to the range");
|
||||
pens.raw_event(&feed, 9, &[0b100], &[100.0]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "kept while other valuators move");
|
||||
pens.raw_event(&feed, 13, &[0b100_0000], &[30.0]);
|
||||
assert_eq!((feed.held(), feed.pose()), (None, None), "the pad is not a pen");
|
||||
pens.raw_event(&feed, 10, &[0b100_0000], &[512.0]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a pen without the valuator");
|
||||
}
|
||||
|
||||
/// A device listed again unchanged keeps its last tilt and rotation; another device listed
|
||||
/// under the same id starts upright and unturned.
|
||||
#[test]
|
||||
@@ -495,7 +537,7 @@ mod tests {
|
||||
assert_eq!(pose.tilt, Some([-30.0, 45.0]));
|
||||
let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators());
|
||||
pens.set_devices([other]);
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
|
||||
assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
|
||||
}
|
||||
|
||||
|
||||
@@ -133,12 +133,13 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, po
|
||||
|
||||
/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is
|
||||
/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the
|
||||
/// rotation when it reports one, each kept within [`PenPose`]'s ranges.
|
||||
/// rotation when it reports one, each kept within [`PenPose`]'s ranges. `POINTER_PEN_INFO` has no
|
||||
/// field for an airbrush pen's finger wheel, so the pose has none.
|
||||
fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose {
|
||||
let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 };
|
||||
let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]);
|
||||
let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32);
|
||||
PenPose { tilt, rotation }.sanitized()
|
||||
PenPose { tilt, rotation, wheel: None }.sanitized()
|
||||
}
|
||||
|
||||
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
|
||||
@@ -426,12 +427,12 @@ mod tests {
|
||||
#[test]
|
||||
fn a_pens_tilt_and_rotation_come_where_it_reports_them() {
|
||||
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
|
||||
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) });
|
||||
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None });
|
||||
assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither");
|
||||
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis");
|
||||
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel");
|
||||
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis");
|
||||
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel");
|
||||
let wild = pen_pose(all, 400, i32::MIN, 720);
|
||||
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges");
|
||||
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0), wheel: None }, "kept within the ranges");
|
||||
let pose = pen_pose(all, 10, 20, 180);
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose);
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 19Q12 4 21 19"/><circle cx="12" cy="16.9" r="5.4"/><circle cx="12" cy="16.9" r="1" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 306 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 18 L9.5 18 A5.75 5.75 0 0 1 21 18"/><circle cx="3" cy="18" r="1.6" fill="currentColor"/><circle cx="9.5" cy="18" r="1.6" fill="currentColor"/><circle cx="21" cy="18" r="1.6" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 397 B |
@@ -12,13 +12,17 @@ fn luminance(c: &Color) -> f32 {
|
||||
0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
|
||||
// Black ink alone is its own tint: its amount is the tint, not how light it displays (100% K
|
||||
// displays lighter than black).
|
||||
let light = match *c {
|
||||
/// How light `c` is for colorization, 0 black to 1 white. Black ink alone is its own tint: its
|
||||
/// amount is the tint, not how light it displays (100% K displays lighter than black).
|
||||
fn lightness(c: &Color) -> f32 {
|
||||
match *c {
|
||||
Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 => 1.0 - k,
|
||||
_ => luminance(c),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
|
||||
let light = lightness(c);
|
||||
// A process or gray stroke color's tints and shades stay in its model.
|
||||
let (white, black) = match key {
|
||||
Color::Cmyk { .. } => (Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0)),
|
||||
@@ -47,45 +51,61 @@ fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
|
||||
}
|
||||
}
|
||||
|
||||
fn map_paint(p: &mut Paint, mode: Colorization, key: &Color) {
|
||||
/// The swatch a stroke paint links to and its tint, for colorization: Tints of a linked color are
|
||||
/// tints of its swatch (a spot color's tints print on its own plate).
|
||||
type Link<'a> = Option<(&'a str, f32)>;
|
||||
|
||||
fn map_paint(p: &mut Paint, mode: Colorization, key: &Color, link: Link<'_>) {
|
||||
if let Paint::Solid { color, .. } = p {
|
||||
*p = Paint::solid(map_color(color, mode, key));
|
||||
*p = match (mode, link) {
|
||||
(Colorization::Tints, Some((swatch, tint))) => {
|
||||
let t = (1.0 - lightness(color)).clamp(0.0, 1.0);
|
||||
Paint::Solid { color: key.tinted(t), swatch: Some(swatch.to_string()), tint: tint * t }
|
||||
}
|
||||
_ => Paint::solid(map_color(color, mode, key)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Recolour `n` (recursively) for a stroke painted `stroke`, and strip brushes from its strokes so
|
||||
/// brush output never recurses. Non-solid stroke paints leave the art's colours alone. Type is
|
||||
/// brush output never recurses. Non-solid stroke paints leave the art's colours alone. Under Tints,
|
||||
/// a stroke color linked to a swatch gives tints of that swatch, linked to it, as a spot color's
|
||||
/// tints are (the art's darkest parts the stroke's own tint, white none of it). Type is
|
||||
/// recolored like paths: its characters' solid fills and strokes as well as its own.
|
||||
pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
|
||||
let key = match (mode, stroke.color()) {
|
||||
(Colorization::None, _) | (_, None) => None,
|
||||
(_, Some(c)) => Some(c),
|
||||
};
|
||||
fn walk(n: &mut Node, mode: Colorization, key: Option<Color>) {
|
||||
let link = match stroke {
|
||||
Paint::Solid { swatch: Some(s), tint, .. } => Some((s.as_str(), *tint)),
|
||||
_ => None,
|
||||
};
|
||||
fn walk(n: &mut Node, mode: Colorization, key: Option<Color>, link: Link<'_>) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(f) => {
|
||||
if let Some(k) = &key {
|
||||
map_paint(&mut f.paint, mode, k);
|
||||
map_paint(&mut f.paint, mode, k, link);
|
||||
}
|
||||
}
|
||||
AppearanceItem::Stroke(s) => {
|
||||
s.brush = None;
|
||||
if let Some(k) = &key {
|
||||
map_paint(&mut s.paint, mode, k);
|
||||
map_paint(&mut s.paint, mode, k, link);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(k), NodeKind::Text(t)) = (&key, &mut n.kind) {
|
||||
for r in &mut t.runs {
|
||||
map_paint(&mut r.style.fill, mode, k);
|
||||
map_paint(&mut r.style.stroke, mode, k);
|
||||
map_paint(&mut r.style.fill, mode, k, link);
|
||||
map_paint(&mut r.style.stroke, mode, k, link);
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
walk(Arc::make_mut(c), mode, key);
|
||||
walk(Arc::make_mut(c), mode, key, link);
|
||||
}
|
||||
}
|
||||
// A mask's art is drawn too: a brush on its strokes would run this brush again. Its colours
|
||||
@@ -94,7 +114,7 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
|
||||
strip_brushes(Arc::make_mut(&mut m.art));
|
||||
}
|
||||
}
|
||||
walk(n, mode, key);
|
||||
walk(n, mode, key, link);
|
||||
}
|
||||
|
||||
/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own
|
||||
|
||||
+34
-12
@@ -160,7 +160,7 @@ impl Calligraphic {
|
||||
pub fn uses_pressure(&self) -> bool {
|
||||
self.modes().contains(&Variation::Pressure)
|
||||
}
|
||||
/// Does the pen (its pressure, tilt, bearing or rotation) change the nib?
|
||||
/// Does the pen (its pressure, tilt, bearing, rotation or wheel) change the nib?
|
||||
pub fn uses_pen(&self) -> bool {
|
||||
self.modes().iter().any(|m| m.follows_pen())
|
||||
}
|
||||
@@ -202,11 +202,25 @@ pub enum Variation {
|
||||
/// The value plus the variation times the pen barrel's rotation over 180°, counter-clockwise
|
||||
/// from where the pen reports 0° round to ±180°.
|
||||
Rotation,
|
||||
/// From the value less the variation with an airbrush pen's finger wheel at one end of its
|
||||
/// travel to the value plus the variation at the other (the value itself half way).
|
||||
StylusWheel,
|
||||
}
|
||||
|
||||
impl Variation {
|
||||
pub const ALL: [Variation; 6] =
|
||||
pub const ALL: [Variation; 7] =
|
||||
[Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel];
|
||||
/// The modes Brush Options offers for a value other than a size (a Calligraphic brush's Angle
|
||||
/// and Roundness, a Scatter brush's Spacing, Scatter and Rotation): all but
|
||||
/// [`Variation::StylusWheel`], which drives a Calligraphic or Scatter brush's Size and an Art
|
||||
/// brush's Width.
|
||||
pub const OTHER: [Variation; 6] =
|
||||
[Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation];
|
||||
/// The modes Brush Options offers for a size (`true`: [`Self::ALL`]) or another value
|
||||
/// ([`Self::OTHER`]).
|
||||
pub fn offered(size: bool) -> &'static [Variation] {
|
||||
if size { &Self::ALL } else { &Self::OTHER }
|
||||
}
|
||||
/// The name brush definitions use.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
@@ -216,6 +230,7 @@ impl Variation {
|
||||
Variation::Tilt => "tilt",
|
||||
Variation::Bearing => "bearing",
|
||||
Variation::Rotation => "rotation",
|
||||
Variation::StylusWheel => "stylusWheel",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
@@ -226,15 +241,16 @@ impl Variation {
|
||||
Variation::Tilt => "Tilt",
|
||||
Variation::Bearing => "Bearing",
|
||||
Variation::Rotation => "Rotation",
|
||||
Variation::StylusWheel => "Stylus Wheel",
|
||||
}
|
||||
}
|
||||
pub fn parse(id: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|v| v.id() == id)
|
||||
}
|
||||
/// Does the value follow something the pen records along a stroke (Pressure, Tilt, Bearing,
|
||||
/// Rotation)?
|
||||
/// Rotation, Stylus Wheel)?
|
||||
pub fn follows_pen(self) -> bool {
|
||||
matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation)
|
||||
matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation | Variation::StylusWheel)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,12 +267,14 @@ pub(crate) struct PenAt {
|
||||
bearing: f64,
|
||||
/// ½ plus the counter-clockwise barrel rotation over 360°.
|
||||
rotation: f64,
|
||||
/// Where the airbrush finger wheel was set, 0 at one end of its travel to 1 at the other.
|
||||
wheel: f64,
|
||||
}
|
||||
|
||||
impl PenAt {
|
||||
/// Every input at `c`.
|
||||
pub(crate) fn uniform(c: f64) -> Self {
|
||||
Self { pressure: c, tilt: c, bearing: c, rotation: c }
|
||||
Self { pressure: c, tilt: c, bearing: c, rotation: c, wheel: c }
|
||||
}
|
||||
/// What `stroke` recorded at `f` (the fraction of its path's length).
|
||||
pub(crate) fn of(stroke: &StrokeLayer, f: f64) -> Self {
|
||||
@@ -267,6 +285,7 @@ impl PenAt {
|
||||
tilt: 1.0 - stroke.tilt.as_ref().map_or(mid, |p| p.at(f)),
|
||||
bearing: turn(stroke.bearing.as_ref()),
|
||||
rotation: turn(stroke.rotation.as_ref()),
|
||||
wheel: stroke.wheel.as_ref().map_or(mid, |p| p.at(f)),
|
||||
}
|
||||
}
|
||||
/// The 0..1 a value on `mode` takes, or `None` for a mode that doesn't follow the pen.
|
||||
@@ -277,6 +296,7 @@ impl PenAt {
|
||||
Variation::Tilt => self.tilt,
|
||||
Variation::Bearing => self.bearing,
|
||||
Variation::Rotation => self.rotation,
|
||||
Variation::StylusWheel => self.wheel,
|
||||
};
|
||||
Some(if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 })
|
||||
}
|
||||
@@ -307,9 +327,10 @@ pub struct Scatter {
|
||||
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
|
||||
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
|
||||
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
|
||||
/// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°). `None`
|
||||
/// (brushes saved before there were modes): Random where the two differ, else Fixed (see
|
||||
/// [`Scatter::modes`]).
|
||||
/// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°), and Stylus
|
||||
/// Wheel (the size's only) the first at one end of an airbrush pen's finger wheel and the
|
||||
/// second at the other. `None` (brushes saved before there were modes): Random where the two
|
||||
/// differ, else Fixed (see [`Scatter::modes`]).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub modes: Option<[Variation; 4]>,
|
||||
}
|
||||
@@ -384,11 +405,12 @@ pub struct ArtBrush {
|
||||
/// 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°).
|
||||
/// and Rotation from −180° to 180° (half way at 0°), Stylus Wheel from one end of an airbrush
|
||||
/// pen's finger wheel to the other.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_mode: Option<Variation>,
|
||||
/// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or
|
||||
/// at 180° (`width` without one).
|
||||
/// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, at
|
||||
/// 180° or at the wheel's far end (`width` without one).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_max: Option<f64>,
|
||||
pub flip_along: bool,
|
||||
@@ -732,7 +754,7 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0);
|
||||
// The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed.
|
||||
// The width follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed.
|
||||
if !a.width_mode.is_some_and(Variation::follows_pen) {
|
||||
a.width_mode = None;
|
||||
}
|
||||
|
||||
+107
-4
@@ -921,6 +921,47 @@ fn tints_colorization_uses_stroke_colour() {
|
||||
assert_eq!(white.appearance.fill_paint().color().unwrap().to_rgb(), [1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// Under Tints, a stroke color linked to a swatch gives tints of that swatch, linked to it: black
|
||||
/// art the stroke's own tint of it, 60% black ink 60% of that, white none; the colors shown are the
|
||||
/// same as for the unlinked color, a process or an RGB swatch. Tints and Shades stay unlinked.
|
||||
#[test]
|
||||
fn tints_of_a_swatch_stay_linked_to_it() {
|
||||
let spot = Color::cmyk(0.0, 0.5, 1.0, 0.0);
|
||||
let stroke = Paint::Solid { color: spot.tinted(0.8), swatch: Some("Brand orange".into()), tint: 0.8 };
|
||||
let mapped = |art: Color| {
|
||||
let mut n = rect_art(1.0, 1.0);
|
||||
n.appearance.set_fill(Paint::solid(art));
|
||||
colorize(&mut n, Colorization::Tints, &stroke);
|
||||
let mut plain = rect_art(1.0, 1.0);
|
||||
plain.appearance.set_fill(Paint::solid(art));
|
||||
colorize(&mut plain, Colorization::Tints, &Paint::solid(spot.tinted(0.8)));
|
||||
(n.appearance.fill_paint(), plain.appearance.fill_paint().color().unwrap())
|
||||
};
|
||||
for (art, want) in [(Color::cmyk(0.0, 0.0, 0.0, 1.0), 0.8), (Color::cmyk(0.0, 0.0, 0.0, 0.6), 0.48), (Color::cmyk(0.0, 0.0, 0.0, 0.0), 0.0)] {
|
||||
let (paint, shown) = mapped(art);
|
||||
let Paint::Solid { color, swatch: Some(s), tint } = paint else { panic!("linked: {paint:?}") };
|
||||
assert_eq!(s, "Brand orange");
|
||||
assert!((tint - want).abs() < 1e-5, "{art:?}: {tint}");
|
||||
let close = color.to_cmyk().iter().zip(shown.to_cmyk()).all(|(a, b)| (a - b).abs() < 1e-5);
|
||||
assert!(close, "{color:?} {shown:?}");
|
||||
}
|
||||
// An RGB swatch: its tints mix toward white, as the unlinked color's do.
|
||||
let rgb = Color::rgb(1.0, 0.4, 0.0);
|
||||
let mut n = rect_art(1.0, 1.0);
|
||||
n.appearance.set_fill(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.5)));
|
||||
colorize(&mut n, Colorization::Tints, &Paint::Solid { color: rgb, swatch: Some("Brand red".into()), tint: 1.0 });
|
||||
let Paint::Solid { color, swatch: Some(s), tint } = n.appearance.fill_paint() else { panic!("linked") };
|
||||
assert_eq!(s, "Brand red");
|
||||
assert!((tint - 0.5).abs() < 1e-5, "{tint}");
|
||||
let [r, g, b] = color.to_rgb();
|
||||
assert!((r - 1.0).abs() < 1e-5 && (g - 0.7).abs() < 1e-5 && (b - 0.5).abs() < 1e-5, "{r} {g} {b}");
|
||||
// Tints and Shades darken past the swatch, which a tint can't: its pieces stay unlinked.
|
||||
let mut n = rect_art(1.0, 1.0);
|
||||
n.appearance.set_fill(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
colorize(&mut n, Colorization::TintsAndShades, &stroke);
|
||||
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
|
||||
}
|
||||
|
||||
/// Black ink alone is a tint by its amount: a process black stroke leaves it as it is, and another
|
||||
/// process stroke color takes that share of its inks. Tints of a process color stay process.
|
||||
#[test]
|
||||
@@ -1545,6 +1586,64 @@ fn pressure_varies_angle_and_roundness() {
|
||||
assert!(near(h, expected, 0.05), "{h} vs {expected}");
|
||||
}
|
||||
|
||||
/// A stroke that recorded an airbrush pen's finger wheel going from `from` to `to` along it.
|
||||
fn wheeled(from: f64, to: f64) -> StrokeLayer {
|
||||
StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, from), (1.0, to)] }), ..stroke(1.0) }
|
||||
}
|
||||
|
||||
/// Stylus Wheel: a Calligraphic brush's size goes from size − variation at one end of the finger
|
||||
/// wheel to size + variation at the other, a Scatter brush's size from its first value to its
|
||||
/// second, and an Art brush's width from Width to the second width. Each reads only the wheel: the
|
||||
/// pressure, tilt, bearing or rotation recorded instead leaves the value half way.
|
||||
#[test]
|
||||
fn the_stylus_wheel_varies_sizes_and_widths() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
let c = Calligraphic {
|
||||
size: 6.0,
|
||||
variation: [0.0, 0.0, 4.0],
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::StylusWheel]),
|
||||
..Default::default()
|
||||
};
|
||||
let nib = Brush { name: "w".into(), kind: BrushKind::Calligraphic(c) };
|
||||
let out = stroke_pieces(&doc, &nib, &bp, &wheeled(0.0, 1.0));
|
||||
// Round nib: 2 pt across at the start, 10 pt at the end, 6 pt half way.
|
||||
assert!(near(half_width(&out, 0.5, 1.5), 1.0, 0.1), "{}", half_width(&out, 0.5, 1.5));
|
||||
assert!(near(half_width(&out, 98.5, 99.5), 5.0, 0.1), "{}", half_width(&out, 98.5, 99.5));
|
||||
assert!(near(half_width(&out, 49.5, 50.5), 3.0, 0.1), "{}", half_width(&out, 49.5, 50.5));
|
||||
let others = [
|
||||
pressed(vec![(0.0, 0.0), (1.0, 1.0)]),
|
||||
StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) },
|
||||
posed(None, Some(90.0), Some(-90.0)),
|
||||
];
|
||||
for st in &others {
|
||||
let h = bounds(&stroke_pieces(&doc, &nib, &bp, st)).height();
|
||||
assert!(near(h, 6.0, 0.05), "{st:?}: {h}");
|
||||
}
|
||||
// Scatter size 50 % to 300 % of 4 pt art: 2 pt at one end of the wheel, 12 pt at the other.
|
||||
let spray = sized_scatter(50.0, 300.0, Variation::StylusWheel);
|
||||
let h: Vec<f64> =
|
||||
stroke_pieces(&doc, &spray, &line(0.0, 0.0, 400.0, 0.0), &wheeled(1.0, 0.0)).iter().map(|n| n.geometric_bounds().unwrap().height()).collect();
|
||||
assert!(near(h[0], 12.0, 0.2) && h[h.len() - 1] < 3.0, "{h:?}");
|
||||
// Art width 50 % to 300 % of 4 pt art.
|
||||
let mut ribbon = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut ribbon.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::StylusWheel), Some(300.0));
|
||||
}
|
||||
let out = stroke_pieces(&doc, &ribbon, &bp, &wheeled(1.0, 0.0));
|
||||
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));
|
||||
for st in &others {
|
||||
let h = bounds(&stroke_pieces(&doc, &ribbon, &bp, st)).height();
|
||||
assert!(near(h, 7.0, 1e-6), "{st:?}: {h}");
|
||||
}
|
||||
// A definition keeps the mode by name.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "a", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "stylusWheel", "width_max": 300.0},
|
||||
]));
|
||||
assert!(matches!(&lib[0].kind, BrushKind::Art(a) if a.width_mode == Some(Variation::StylusWheel)));
|
||||
}
|
||||
|
||||
/// A stroke that recorded the pen's tilt (`tilt`: 0 upright to 1 flat), bearing and barrel
|
||||
/// rotation (degrees counter-clockwise), each the same all along it where given.
|
||||
fn posed(tilt: Option<f64>, bearing: Option<f64>, rotation: Option<f64>) -> StrokeLayer {
|
||||
@@ -1611,7 +1710,7 @@ fn bearing_and_rotation_turn_the_nib() {
|
||||
#[test]
|
||||
fn pen_modes_without_a_recording_draw_the_value_itself() {
|
||||
let horizontal = line(0.0, 0.0, 100.0, 0.0);
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] {
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] {
|
||||
let c = Calligraphic { angle: 90.0, roundness: 50.0, size: 10.0, variation: [90.0, 50.0, 6.0], modes: Some([mode; 3]) };
|
||||
let b = Brush { name: "n".into(), kind: BrushKind::Calligraphic(c) };
|
||||
let h = bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, &stroke(1.0))).height();
|
||||
@@ -1658,7 +1757,7 @@ fn a_mouse_stroke_draws_pen_modes_as_pressure_did() {
|
||||
};
|
||||
let (calli_before, scatter_before) = (calli(Variation::Pressure), scattered(Variation::Pressure));
|
||||
assert!(!calli_before.is_empty() && !scatter_before.is_empty());
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] {
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] {
|
||||
assert_eq!(calli(mode), calli_before, "{mode:?}");
|
||||
assert_eq!(scattered(mode), scatter_before, "{mode:?}");
|
||||
}
|
||||
@@ -1726,8 +1825,12 @@ fn brushes_without_modes_vary_randomly_as_before() {
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &old, &bp, &pressed(vec![(0.0, 0.0), (1.0, 1.0)]))
|
||||
);
|
||||
// Modes are saved by name.
|
||||
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation"]));
|
||||
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v)));
|
||||
assert_eq!(
|
||||
serde_json::to_value(Variation::ALL).unwrap(),
|
||||
serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"])
|
||||
);
|
||||
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id()));
|
||||
assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel));
|
||||
}
|
||||
|
||||
/// Junk definitions and pressure never panic and never draw non-finite art.
|
||||
|
||||
@@ -198,14 +198,24 @@ pub fn export(doc: &Document, opts: &HpglOptions) -> Result<HpglOutput, String>
|
||||
Ok(export_regions(doc, opts, &[opts.region])?.pop().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// An error unless a plot can cover `region`: its corners are finite and it has a width and a
|
||||
/// height (either corner may come first).
|
||||
pub fn check_region(region: Rect) -> Result<(), String> {
|
||||
let r = region.abs();
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Err("the export region is empty".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the visible art of `doc` over each of `regions` as an HP-GL plot, one per region, as
|
||||
/// [`export`] does with `opts.region`. The plots share one pen numbering, so a color is the same
|
||||
/// pen in each, and one point budget.
|
||||
pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> Result<Vec<HpglOutput>, String> {
|
||||
let regions: Vec<Rect> = regions.iter().map(|r| r.abs()).collect();
|
||||
if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) {
|
||||
return Err("the export region is empty".into());
|
||||
for r in regions {
|
||||
check_region(*r)?;
|
||||
}
|
||||
let regions: Vec<Rect> = regions.iter().map(|r| r.abs()).collect();
|
||||
if !TOLERANCE_RANGE.contains(&opts.tolerance) {
|
||||
return Err("the curve tolerance must be from 0.01 to 10 points".into());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "vectorcraft-cdr"
|
||||
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer.
|
||||
synth = []
|
||||
|
||||
[dependencies]
|
||||
crc32fast = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
vectorcraft-cdr = { path = ".", features = ["synth"] }
|
||||
@@ -0,0 +1,33 @@
|
||||
The record layouts this crate reads are described in the Kaitai Struct
|
||||
specification `coreldraw_cdr.ksy`
|
||||
(https://github.com/kaitai-io/coreldraw_cdr.ksy, commit
|
||||
9d8e2704b946961f5114115f1a488750a3c86ed0), which is published under the
|
||||
license below. No part of that specification is copied into this crate;
|
||||
`PROVENANCE.md` cites it by line.
|
||||
|
||||
Some layouts are also taken from the fork of that specification by Zach Wolfe
|
||||
(https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, commit
|
||||
2189b68f07e0cafe9afec3dcf699ebc0342144c7), which is published under the same
|
||||
license and copyright notice.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 Kaitai team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,127 @@
|
||||
# Where each layout comes from
|
||||
|
||||
The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and
|
||||
`tests/it/provenance.rs` fails when a cited id has no row here.
|
||||
|
||||
Sources:
|
||||
|
||||
- **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`),
|
||||
https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy
|
||||
- **KF**: the fork of K by Zach Wolfe, `filestar/coreldraw_cdr.ksy`, branch `new_stuff`, under the same
|
||||
MIT license and notice as K (`LICENSE-kaitai.txt`),
|
||||
https://github.com/filestar/coreldraw_cdr.ksy/blob/2189b68f07e0cafe9afec3dcf699ebc0342144c7/coreldraw_cdr.ksy
|
||||
- **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at
|
||||
the same commit as K,
|
||||
https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md
|
||||
and https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/bin/cdr-unpk
|
||||
- **Z**: the PKWARE ZIP specification, APPNOTE.TXT version 6.3.10,
|
||||
https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE),
|
||||
https://www.rfc-editor.org/rfc/rfc1951
|
||||
- **F**: the magic database of the `file` utility (BSD-2-Clause),
|
||||
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and
|
||||
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff
|
||||
- **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0,
|
||||
https://pronom.nationalarchives.gov.uk/fmt/467.xml,
|
||||
https://pronom.nationalarchives.gov.uk/fmt/466.xml and
|
||||
https://pronom.nationalarchives.gov.uk/fmt/465.xml
|
||||
- **S**: own inspection of the bytes of public sample files, checked against the picture each file
|
||||
carries of its drawing where it has one (versions 2 and 4 to 25; files of versions 1 and 3 carry
|
||||
none). The files come from:
|
||||
- **TP**: https://telparia.com/fileFormatSamples/image/cdr/, by file name
|
||||
- **LT**: https://git.libreoffice.org/libcdr-test at commit
|
||||
`dafe4fe53d685d89df20a5c0bb18f318ccefb4a8`, `testset/<version>/<file>`
|
||||
- **UC**: https://svn.code.sf.net/p/uniconvertor/code/formats/CDR/testing%20base/ at revision
|
||||
434, by file name
|
||||
- **TDF**: attachments to The Document Foundation's bug tracker,
|
||||
https://bugs.documentfoundation.org/attachment.cgi?id=<id>
|
||||
- **NR**: Natural Resources Canada's tactile maps,
|
||||
https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/approach-approch/cdr/banff_ap_en.cdr and
|
||||
https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr
|
||||
- **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name
|
||||
- **CX**: the `.cmx` files of https://telparia.com/fileFormatSamples/image/cmx/, by file name. The
|
||||
nine with 32-bit coordinates are `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`,
|
||||
`gold_bar.cmx`, `goldblue.cmx`, `PC.CMX`, `squares.cmx` and `thatch.cmx`; they carry no picture
|
||||
of their drawing.
|
||||
- **CN**: the `.cmx` notes of an MIT OR Apache-2.0 drawing program, which mark each layout
|
||||
"confirmed" when the program's authors found it in sample files,
|
||||
https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md.
|
||||
The same program's `.cmx` reader at that commit,
|
||||
https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs,
|
||||
was read for the order of fields that the notes do not spell out (the table entries, the rendering
|
||||
attributes and the curve body); no code was copied from it
|
||||
|
||||
Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `public-notes` (a layout CN marks
|
||||
confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows;
|
||||
listed so it can be checked against a file, with what the reader does when it is wrong).
|
||||
|
||||
Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as
|
||||
the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the
|
||||
sample files they name.
|
||||
The test inputs are the synthetic files that `src/synth.rs` builds from the rows below; no sample
|
||||
file is committed.
|
||||
|
||||
| Id | What the code relies on | Source | Status |
|
||||
|---|---|---|---|
|
||||
| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01 from the form type alone, whatever its `vrsn` chunk names, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) |
|
||||
| R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec |
|
||||
| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec |
|
||||
| R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec |
|
||||
| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700 | public-spec |
|
||||
| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893 | public-spec |
|
||||
| R7 | Angles: i16 tenths of a degree before version 6, else i32 millionths of a degree | K L2835-L2855 | public-spec |
|
||||
| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834 | public-spec |
|
||||
| R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec |
|
||||
| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec |
|
||||
| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr<version>.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) |
|
||||
| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; a record of id 2 holds a property list laid out as R11's, and the reader takes the outline's color from it when it names a library color; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; KF L1225-L1249 (the id 2 record); S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them; the id 2 record: no sample names a library color in it, and a wrong guess changes only the outline's color) |
|
||||
| R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr<version>.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample |
|
||||
| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) |
|
||||
| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec |
|
||||
| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec |
|
||||
| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) |
|
||||
| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) |
|
||||
| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. On a layer, group or object, bit 0x01 of byte 1 hides it and bit 0x10 of byte 0 locks it. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); KF L1831-L1866 (the hidden and lock bits); S: every grid layer of versions 14 to 25 in the sample files (631) carries byte 1 = 1, and 206 of the 927 of versions 7 to 13 do; desktop layers carry byte 1 = 0 except TDF 114901's [0, 1, 1]; the drawing layers with byte 1 = 1 (TDF 114901, NR `banff_ap_en.cdr` and `symbology_en.cdr`) also carry bit 0x08; of the group and object lists in the sample files, only one object of TDF 60491 (version 14) sets either bit, the lock bit; in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects; bit 0x10 is also the lock bit, so a locked guides layer without a `loda` reads as a grid) |
|
||||
| R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec |
|
||||
| R21 | Page size argument (19130): width and height | K L666-L672 | public-spec |
|
||||
| R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample |
|
||||
| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | S: argument 16000 in NR `ab_en_br.cdr` (9) and TDF 194220 (13); the `guid` chunk of TDF 123971 (7). Pictures do not show guidelines | sample |
|
||||
| R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec |
|
||||
| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec |
|
||||
| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec |
|
||||
| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec |
|
||||
| R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) |
|
||||
| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr<version>.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) |
|
||||
| R30 | Object type 0x25 (version 10 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; S: TDF 78250 (version 15) and UC `shapes_cdr10.cdr`, `shapes_cdr11.cdr`, `shapes_cdr12.cdr` and `shapes_x3.cdr` (versions 10 to 13), whose type bytes start where the counts put them; no sample before version 10 holds the type | public-spec (from version 10: sample) |
|
||||
| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; PR fmt/465; F `riff` L786; S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | public-spec (pages and layers as R19 and R22: sample) |
|
||||
| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | S: the rectangles, curves and text of TP `ARMYSTF1.CDR`, `DALI.CDR` and `FOX.CDR`, which come out whole | sample (ellipse 1 and bitmap 4: unconfirmed, as no sample holds them; a bitmap is left out with a warning) |
|
||||
| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | K L851; S: the matrices of every version 3 file in TP, whose drawings come out whole | sample (envelope type 0x14: unconfirmed, as no sample holds one; it is not applied, with a warning) |
|
||||
| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547 | public-spec |
|
||||
| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; S: the outlines of the version 3 files in TP | public-spec (flag bit: sample; dash unit, and the join, where bytes 32 and 33 of some samples hold 2 and 2: unconfirmed, and a wrong guess changes only how corners, ends and dashes are drawn) |
|
||||
| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; S: model 1 in TP `ARMYSTF1.CDR` (3) and DM `lion1.cdr` (4), model 0 in TP `ARROW5.CDR` (3) and `WI.CDR` (1) | sample (ink 1, and models other than 0 and 1: unconfirmed; an ink of another number opens as a spot color without a look) |
|
||||
| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | sample |
|
||||
| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756 | public-spec |
|
||||
| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 1, 2 and 4, 0 in the others), where K reads the two as one u32 | S: TP `DALI.CDR` (3), DM `headup.cdr` and `lion1.cdr` (4), TP `WI.CDR` (1), `FLAG.CDR` and `MENU.CDR` (2) | sample |
|
||||
| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings, the start and the end of the object records, the start of the trailer and that value minus two. Version 1 has the marker `e` and its settings start at byte 28. Version 2 has the marker `m` or `l`, and its settings start after a 1-bit picture of the drawing, whose header starts where the u32 at byte 28 says. The reader takes these three markers | F `images` L4159-L4172; PR fmt/467, fmt/466; S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`), `MENU.CDR` and `DRINKS.CDR` (`l`) | public-spec (markers `e` and `m`: F and PR; the offsets and the marker `l`: sample) |
|
||||
| R41 | The page's box in a file of version 1 or 2: four i16 two bytes after the start of the settings (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | S: TP `WI.CDR`, `FLAG.CDR` and `MENU.CDR` | sample |
|
||||
| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample |
|
||||
| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample |
|
||||
| R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) |
|
||||
| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u16 before version 6, u32 from it). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables; argument 200 is 2 bytes on all 844 objects of versions 4 and 5 in the sample files that carry it, and 4 bytes on all 18 of version 6 | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) |
|
||||
| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32, a u16 before version 6) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) |
|
||||
| R47 | Argument 8000 marks an object seen through: a lens or a transparency. From version 13 it holds records of a u32 version, a u32 length and a body; a body of version 1300 that is 117 bytes long holds an f64 at byte 61 and a merge mode byte at byte 77, which the reader applies as a uniform transparency. VectorCraft reads the f64 as the transparency in percent (0 opaque, 100 clear) and maps the merge modes 0 normal, 9 multiply, 11 lighten, 12 darken, 14 color, 15 hue, 16 saturation, 17 luminosity, 24 difference, 28 screen, 29 overlay, 30 soft light, 31 hard light, 33 color dodge, 34 color burn and 36 exclusion to its blend modes. Other merge modes, other records (a lens record of version 13 is 84 bytes) and the argument before version 13 are not applied, and the reader names them with lenses in the warnings | K L859 (the argument); KF L707-L798 (the records, the 117-byte body and the merge modes); S: the version 1300 record of LT `square_blackfill_nooutline_transparency50percent` of `testset/15` to `testset/25` is 117 bytes long, with 50.0 at byte 61 and 0 at byte 77; the lens records of UC `corel_lens_test_x3.cdr` (13) are 84 bytes long; of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; the direction of the value: VectorCraft's own reading, as every sample is at 50%, and a wrong reading shows a 25% transparency at 75%; the layout before version 13: unconfirmed, and it is not read) |
|
||||
| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample |
|
||||
| R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample |
|
||||
| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) |
|
||||
| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec |
|
||||
| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) |
|
||||
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
|
||||
| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample |
|
||||
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
|
||||
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
|
||||
| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) |
|
||||
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample |
|
||||
| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) |
|
||||
| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) |
|
||||
| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) |
|
||||
| R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) |
|
||||
| R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample |
|
||||
@@ -0,0 +1,98 @@
|
||||
# vectorcraft-cdr
|
||||
|
||||
A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates).
|
||||
It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its
|
||||
compressed lists, the ZIP packages that versions 14 and later save (with the data streams of
|
||||
versions 16 and later) and the records listed below, and hands the engine a drawing in points,
|
||||
with each object's transform. It does not write `.cdr` files.
|
||||
|
||||
## What is read
|
||||
|
||||
| In the `.cdr` file | Read as |
|
||||
|---|---|
|
||||
| ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it |
|
||||
| Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side |
|
||||
| Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind |
|
||||
| The hidden and locked flags of layers, groups and objects | flags |
|
||||
| Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle |
|
||||
| Groups (`LIST grp `) | groups |
|
||||
| Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips |
|
||||
| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths |
|
||||
| Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius |
|
||||
| Ellipses, arcs and pies | ellipses, and paths for arcs and pies |
|
||||
| Polygons and stars (a base side copied for each side) | paths |
|
||||
| Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints |
|
||||
| The fill's winding flag | the nonzero fill rule, or even-odd |
|
||||
| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags, and from version 13 a library color named in their property list | outlines |
|
||||
| Uniform transparency (version 13 on) and its merge mode | the shape's opacity and blend mode |
|
||||
| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own |
|
||||
|
||||
Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain,
|
||||
pattern, texture and PostScript fills, outline arrowheads, lenses, transparency other than uniform
|
||||
transparency of version 13 and later, and merge modes without a VectorCraft blend mode are not
|
||||
read; the drawing's
|
||||
`warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages
|
||||
that are encrypted, ZIP64 archives or split across files.
|
||||
|
||||
VectorCraft reads a uniform transparency's stored value as the transparency in percent (0 opaque,
|
||||
100 clear), and a winding flag other than 0 as the nonzero fill rule. These are VectorCraft's own
|
||||
readings: no public source states either direction.
|
||||
|
||||
## Versions 1 to 4
|
||||
|
||||
Public specifications cover only parts of these versions, such as the version 3 fill and page
|
||||
settings. For the rest, the reader follows the layouts of public sample files that
|
||||
`PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that
|
||||
`src/synth.rs` builds from those rows.
|
||||
|
||||
| Version | Read | Left out or refused |
|
||||
|---|---|---|
|
||||
| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the reader does not look for; the records after a drawn object of another type, with the unsupported-objects warning |
|
||||
| 3 (RIFF, form type `CDR `) | the page size from the page's corners; pages, layers and groups; rectangles, ellipses, arcs and curves with the matrices of the object and of the groups around it; uniform fills; outlines with their width, color, caps, joins and dashes | text and bitmaps; envelopes, with the envelopes warning (the objects and groups under one keep their outlines and matrices); fountain, pattern and texture fills; arrowheads |
|
||||
| 4 (RIFF, form type `CDR4`) | as version 5, with the colors and the fixed-point transforms of version 4 | as version 5 |
|
||||
|
||||
A file is taken for version 1 or 2 by its content only when, after `WL`, its marker byte is one of
|
||||
`e`, `l` and `m`, the next byte is zero, and the offsets of its header fit the file. The reader
|
||||
reports version 1 for the marker `e` and version 2 for the other two. A RIFF file that names
|
||||
a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as
|
||||
not a `.cdr` drawing.
|
||||
|
||||
## `.cmx` files
|
||||
|
||||
`read_cmx` reads `.cmx` exchange files with 32-bit coordinates (rows R53 to R63) into the same
|
||||
drawing model, with a version of 0. It reads the color, pen, line type, dash, outline and
|
||||
arrowhead tables, then each page's instructions in drawing order:
|
||||
|
||||
| In the `.cmx` file | Read as |
|
||||
|---|---|
|
||||
| Pages, with the size the page gives, or else the size of the drawing's bounds that the page stores | pages; a page sized to the bounds is centered on them |
|
||||
| Layers, by their UTF-16 or 8-bit name | drawing layers, unnamed when the file gives no name; a layer that holds nothing is left out |
|
||||
| Groups | groups |
|
||||
| Curves (moves, lines and cubic curves, as `.cdr` point lists) | paths |
|
||||
| Uniform fills: CMYK in percent or 0 to 255, CMY, RGB, gray, and library colors with their names | colors, spot colors |
|
||||
| Outlines: width, color, caps, joins, dashes, the no-outline, behind-the-fill and scaled-with flags | outlines |
|
||||
|
||||
Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones, outline
|
||||
arrowheads and lenses are not read; the drawing's `warnings` name each kind it held. A clipping
|
||||
path is left out and the objects it clips are read without it. Files in big-endian byte order and
|
||||
files with 16-bit coordinates are refused.
|
||||
|
||||
## Provenance
|
||||
|
||||
`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status.
|
||||
Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row.
|
||||
The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the
|
||||
`synth` feature); no third-party file is committed.
|
||||
|
||||
## Limits
|
||||
|
||||
`Limits` bounds the input size, the bytes inflated from compressed lists and package members, the
|
||||
size of one package member, the number of members, the nesting depth, the chunk count, the
|
||||
objects, the coordinates and the outline dashes of one read. Past a limit the reader stops with an
|
||||
error or leaves the rest out with a warning; it does not recurse and does not panic. Each record
|
||||
of a version 1 or 2 file counts toward the chunk count, and the transform entries of a version 3
|
||||
object are held to the arguments one record may have. A package's
|
||||
data stream is read once however many lines of `content/dataFileList.dat` name it. A redirected
|
||||
list whose bytes overlap those of an earlier redirected list is left out with the damage warning.
|
||||
Other records may share bytes, and the bytes read again may add up to the member limit; past it
|
||||
the records are left out with the limit warning.
|
||||
@@ -0,0 +1,816 @@
|
||||
//! The drawing the chunk index holds: pages, layers, objects and the fills and outlines they name
|
||||
//! (R19 to R23). Records are decoded only when an object refers to them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::bytes::Rd;
|
||||
use crate::geometry;
|
||||
use crate::inline;
|
||||
use crate::layout::{self, Profile};
|
||||
use crate::limits::Budget;
|
||||
use crate::model::{Blend, Color, Drawing, Flags, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape};
|
||||
use crate::records::{self, Loda};
|
||||
use crate::riff::{Chunk, Index, push};
|
||||
use crate::styles::Styles;
|
||||
use crate::{Error, Warning};
|
||||
|
||||
/// Object types (R6).
|
||||
const RECTANGLE: u32 = 1;
|
||||
const ELLIPSE: u32 = 2;
|
||||
const CURVE: u32 = 3;
|
||||
const POLYGON: u32 = 0x14;
|
||||
const GUIDELINE: u32 = 0x16;
|
||||
const PATH: u32 = 0x25;
|
||||
/// Argument types (R6, R20, R21, R33, R52).
|
||||
const ARG_OUTLINE: u32 = 10;
|
||||
const ARG_FILL: u32 = 20;
|
||||
const ARG_COORDS: u32 = 30;
|
||||
const ARG_TRANSFORMS: u32 = 100;
|
||||
const ARG_STYLE: u32 = 200;
|
||||
const ARG_NAME: u32 = 1000;
|
||||
const ARG_LENS: u32 = 8000;
|
||||
const ARG_CONTAINER: u32 = 8005;
|
||||
const ARG_POLYGON: u32 = 11000;
|
||||
const ARG_WINDING: u32 = 14001;
|
||||
const ARG_GUIDE: u32 = 16000;
|
||||
const ARG_PAGE_SIZE: u32 = 19130;
|
||||
|
||||
/// What a RIFF file that names a version before 3 is refused as.
|
||||
const BEFORE_3: &str = "RIFF files of versions before 3";
|
||||
|
||||
/// What one read keeps while mapping.
|
||||
struct Ctx<'a, 'b> {
|
||||
ix: &'b Index<'a>,
|
||||
p: Profile,
|
||||
budget: &'b mut Budget,
|
||||
warn: &'b mut Vec<Warning>,
|
||||
/// Fill and outline records by id, decoded on first use.
|
||||
fill_chunks: HashMap<u32, &'b [u8]>,
|
||||
outline_chunks: HashMap<u32, &'b [u8]>,
|
||||
fills: HashMap<u32, Option<Color>>,
|
||||
outlines: HashMap<u32, Option<Outline>>,
|
||||
/// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't
|
||||
/// parse.
|
||||
styles: Result<Styles, ()>,
|
||||
/// The groups of `LIST clpt` that containers clip, by the id in their `spnd` chunk (R46).
|
||||
clips: HashMap<u32, &'b Chunk>,
|
||||
/// The clipped groups being read, innermost last.
|
||||
open_clips: Vec<u32>,
|
||||
/// Whether the walk of a clipped group stopped at the clipped chunk limit.
|
||||
clip_cut: bool,
|
||||
}
|
||||
|
||||
/// The most clipped groups read one inside another: VectorCraft's own limit.
|
||||
const MAX_CLIP_DEPTH: usize = 64;
|
||||
|
||||
pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Drawing, Error> {
|
||||
let root = ix.root().ok_or(Error::NotCdr)?;
|
||||
let version = ix.version();
|
||||
// A template whose `vrsn` chunk doesn't name a version read (R28).
|
||||
if version == 0 {
|
||||
return Err(Error::NotCdr);
|
||||
}
|
||||
// Versions 1 and 2 are `WL` files (R40); no source shows a RIFF file that names a version
|
||||
// before 3.
|
||||
if version < layout::OLDEST_RIFF {
|
||||
return Err(Error::Unsupported(BEFORE_3));
|
||||
}
|
||||
let p = layout::for_version(version).ok_or(Error::Version(version))?;
|
||||
let mut found = Found::default();
|
||||
collect(ix, root, &mut found);
|
||||
let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p));
|
||||
// Before version 7 a `LIST stlt` holds chunks, not the style table (R4).
|
||||
let styles = match found.stlt {
|
||||
Some(c) if version >= 700 => Styles::read(ix.data(c), version, budget)?.ok_or(()),
|
||||
_ => Ok(Styles::default()),
|
||||
};
|
||||
let mut cx = Ctx {
|
||||
ix,
|
||||
p,
|
||||
budget,
|
||||
warn,
|
||||
fill_chunks: HashMap::new(),
|
||||
outline_chunks: HashMap::new(),
|
||||
fills: HashMap::new(),
|
||||
outlines: HashMap::new(),
|
||||
styles,
|
||||
clips: HashMap::new(),
|
||||
open_clips: Vec::new(),
|
||||
clip_cut: false,
|
||||
};
|
||||
// The `spnd` id is a u16 in files of 16-bit fields (R46).
|
||||
let spnd = |b: &[u8]| if p.short { Rd::new(b).u16().map(u32::from) } else { Rd::new(b).u32() };
|
||||
for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) {
|
||||
if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| spnd(ix.data(c))) {
|
||||
cx.clips.entry(id).or_insert(g);
|
||||
}
|
||||
}
|
||||
for c in &found.fills {
|
||||
if let Some(id) = Rd::new(ix.data(c)).u32() {
|
||||
cx.fill_chunks.entry(id).or_insert(ix.data(c));
|
||||
}
|
||||
}
|
||||
for c in &found.outlines {
|
||||
if let Some(id) = Rd::new(ix.data(c)).u32() {
|
||||
cx.outline_chunks.entry(id).or_insert(ix.data(c));
|
||||
}
|
||||
}
|
||||
let mut guides = found.guid.map(|c| guid_chunk(ix.data(c), &cx.p, cx.budget, cx.warn)).unwrap_or_default();
|
||||
let mut pages = Vec::new();
|
||||
let mut master = Vec::new();
|
||||
for page in &found.pages {
|
||||
let (is_master, read) = cx.page(page);
|
||||
if is_master {
|
||||
// Guidelines on any of the master page's layers show on every page.
|
||||
for mut layer in read.layers {
|
||||
guides.append(&mut layer.guides);
|
||||
if !layer.objects.is_empty() && layer.kind != LayerKind::Grid {
|
||||
master.push(layer);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pages.push(read);
|
||||
}
|
||||
}
|
||||
// A file of only a master page keeps it as its page.
|
||||
if pages.is_empty() && !master.is_empty() {
|
||||
pages.push(Page { size: None, layers: std::mem::take(&mut master) });
|
||||
}
|
||||
Ok(Drawing { version, page_size, pages, master, guides, warnings: std::mem::take(cx.warn) })
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Found<'i> {
|
||||
fills: Vec<&'i Chunk>,
|
||||
outlines: Vec<&'i Chunk>,
|
||||
mcfg: Option<&'i Chunk>,
|
||||
guid: Option<&'i Chunk>,
|
||||
stlt: Option<&'i Chunk>,
|
||||
clpt: Vec<&'i Chunk>,
|
||||
pages: Vec<&'i Chunk>,
|
||||
}
|
||||
|
||||
/// Every fill, outline, `LIST clpt` and page in file order, and the first `mcfg`, `guid` and
|
||||
/// `LIST stlt`; pages are not looked into.
|
||||
fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) {
|
||||
let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect();
|
||||
while let Some(c) = stack.pop() {
|
||||
match &c.id {
|
||||
b"fild" | b"fill" => found.fills.push(c),
|
||||
b"outl" => found.outlines.push(c),
|
||||
b"mcfg" => found.mcfg = found.mcfg.or(Some(c)),
|
||||
b"guid" => found.guid = found.guid.or(Some(c)),
|
||||
// Before version 7 the list holds chunks, which are looked through.
|
||||
_ if c.is_list(b"stlt") => {
|
||||
found.stlt = found.stlt.or(Some(c));
|
||||
stack.extend(ix.children(c).iter().rev());
|
||||
}
|
||||
_ if c.is_list(b"clpt") => found.clpt.push(c),
|
||||
_ if c.is_list(b"page") => found.pages.push(c),
|
||||
_ => stack.extend(ix.children(c).iter().rev()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The page size in `mcfg` (R10); in version 3 the distance between the page's two corners, after
|
||||
/// 2 bytes (R38).
|
||||
fn page_size(b: &[u8], p: &Profile) -> Option<(f64, f64)> {
|
||||
let mut r = Rd::at(b, p.mcfg_skip);
|
||||
if p.mcfg_corners {
|
||||
r.skip(2)?;
|
||||
let (x0, y0, x1, y1) = (records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?);
|
||||
return sane_size(x1 - x0, y1 - y0);
|
||||
}
|
||||
sane_size(records::coord(&mut r, p)?, records::coord(&mut r, p)?)
|
||||
}
|
||||
|
||||
fn sane_size(w: f64, h: f64) -> Option<(f64, f64)> {
|
||||
let (w, h) = (w.abs(), h.abs());
|
||||
(w > 0.0 && h > 0.0).then_some((w, h))
|
||||
}
|
||||
|
||||
/// The version 7 `guid` chunk (R23): two counts, then 40-byte records laid out as argument 16000.
|
||||
/// Each guideline counts toward the objects a read maps; past them the rest are left out.
|
||||
fn guid_chunk(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Vec<Guideline> {
|
||||
let mut r = Rd::new(b);
|
||||
let Some(n) = r.u32() else { return Vec::new() };
|
||||
let _again = r.u32();
|
||||
let fits = r.left() / 40;
|
||||
if n as usize > fits {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let n = (n as usize).min(fits);
|
||||
let mut out = Vec::new();
|
||||
for i in 0..n {
|
||||
if !budget.take_object() {
|
||||
push(warn, Warning::TooDeep);
|
||||
break;
|
||||
}
|
||||
out.extend(b.get(8 + i * 40..8 + (i + 1) * 40).and_then(|g| guideline(g, p)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A guideline record (R23): 12 bytes, the angle in millionths of a degree, then a point.
|
||||
fn guideline(b: &[u8], p: &Profile) -> Option<Guideline> {
|
||||
if p.short {
|
||||
return None;
|
||||
}
|
||||
let mut r = Rd::at(b, 12);
|
||||
let angle = f64::from(r.i32()?) / 1_000_000.0;
|
||||
let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? };
|
||||
Some(Guideline { at, angle, hidden: false })
|
||||
}
|
||||
|
||||
/// Marks the guidelines from `from` on hidden when `flags` hide what holds them.
|
||||
fn hide_guides(guides: &mut [Guideline], from: usize, flags: Flags) {
|
||||
if flags.hidden {
|
||||
for g in guides.iter_mut().skip(from) {
|
||||
g.hidden = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A list's flags (R19): four bytes.
|
||||
fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> {
|
||||
let c = ix.children(list).iter().find(|c| &c.id == b"flgs")?;
|
||||
ix.data(c).get(..4)?.try_into().ok()
|
||||
}
|
||||
|
||||
/// Whether a layer, group or object list is hidden (bit 0x01 of byte 1) or locked (bit 0x10 of
|
||||
/// byte 0) (R19).
|
||||
fn state(ix: &Index, list: &Chunk) -> Flags {
|
||||
flags(ix, list).map_or(Flags::default(), |[b0, b1, _, _]| Flags { hidden: b1 & 0x01 != 0, locked: b0 & 0x10 != 0 })
|
||||
}
|
||||
|
||||
/// `o` with `f` added to its own flags: the objects of a group left ungrouped keep the group's.
|
||||
fn inherit(o: &mut Object, f: Flags) {
|
||||
let own = match o {
|
||||
Object::Shape(s) => &mut s.flags,
|
||||
Object::Group { flags, .. } => flags,
|
||||
Object::Clip { container, .. } => &mut container.flags,
|
||||
};
|
||||
own.hidden |= f.hidden;
|
||||
own.locked |= f.locked;
|
||||
}
|
||||
|
||||
/// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a
|
||||
/// drawing layer. Version 3 counts its types from 0, one less (R32).
|
||||
fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind {
|
||||
match kind.saturating_add(u32::from(types_from_zero)) {
|
||||
11 => LayerKind::Grid,
|
||||
12 => LayerKind::Guides,
|
||||
17 => LayerKind::Desktop,
|
||||
_ => LayerKind::Drawing,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a layer's flags make it, for a layer without an object type of its own (R19). The low
|
||||
/// four bits of byte 0 hold the kind: 0x0a guides, or a grid with bit 0x10 set (versions 7 to 13
|
||||
/// also flag them 0x02); 0x08 the desktop when byte 2 is set, a drawing layer when it is clear.
|
||||
/// Versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set. Bit 0x10
|
||||
/// alone does not make a grid.
|
||||
fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind {
|
||||
let [b0, b1, b2, _] = f;
|
||||
let grid_bit = b0 & 0x10 != 0;
|
||||
match b0 & 0x0f {
|
||||
0x0a if grid_bit => LayerKind::Grid,
|
||||
0x0a => LayerKind::Guides,
|
||||
0x02 if version_below_14 && grid_bit => LayerKind::Grid,
|
||||
0x02 if version_below_14 => LayerKind::Guides,
|
||||
0x08 if b2 != 0 => LayerKind::Desktop,
|
||||
0 if version_below_14 && b1 == 1 && b2 == 1 => LayerKind::Desktop,
|
||||
_ => LayerKind::Drawing,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first chunk of one of `ids` that a page, layer or object keeps for itself: among its own
|
||||
/// chunks, or in its `lgob` list and the `trfl` list there (R22).
|
||||
fn own_chunk<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]]) -> Option<&'i Chunk> {
|
||||
let mut stack: Vec<(&Chunk, u8)> = ix.children(list).iter().rev().map(|c| (c, 0)).collect();
|
||||
while let Some((c, depth)) = stack.pop() {
|
||||
if ids.contains(&&c.id) {
|
||||
return Some(c);
|
||||
}
|
||||
if depth < 2 && (c.is_list(b"lgob") || c.is_list(b"trfl")) {
|
||||
stack.extend(ix.children(c).iter().rev().map(|k| (k, depth + 1)));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `loda` (or `lobj`) a page, layer or object keeps for itself.
|
||||
fn own_loda<'i>(ix: &'i Index, list: &'i Chunk) -> Option<&'i Chunk> {
|
||||
own_chunk(ix, list, &[b"loda", b"lobj"])
|
||||
}
|
||||
|
||||
/// A page's layer lists in file order: its own, and those in the lists it holds, such as the
|
||||
/// `gobj` list of files of versions 7 to 13 (R22).
|
||||
fn page_layers<'i>(ix: &'i Index, page: &'i Chunk) -> Vec<&'i Chunk> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack: Vec<&Chunk> = ix.children(page).iter().rev().collect();
|
||||
while let Some(c) = stack.pop() {
|
||||
if c.is_list(b"layr") {
|
||||
out.push(c);
|
||||
} else if c.id == crate::riff::LIST && !c.is_list(b"lgob") {
|
||||
stack.extend(ix.children(c).iter().rev());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One frame of the object walk: a list's chunks, the next one to look at, and the objects so far.
|
||||
struct Frame<'i> {
|
||||
chunks: &'i [Chunk],
|
||||
next: usize,
|
||||
objects: Vec<Object>,
|
||||
/// Whether its objects form a group in the frame below.
|
||||
group: bool,
|
||||
/// The group's own flags.
|
||||
flags: Flags,
|
||||
/// The first of the guidelines read inside it.
|
||||
guides_from: usize,
|
||||
/// What places its objects after their own transforms: the matrices of the version 3 groups
|
||||
/// around them (R33). The identity in other versions, whose objects hold their whole transform.
|
||||
outer: Matrix,
|
||||
}
|
||||
|
||||
impl<'a, 'b> Ctx<'a, 'b> {
|
||||
/// A page: whether it is the master page, and its layers.
|
||||
fn page(&mut self, page: &Chunk) -> (bool, Page) {
|
||||
let ix = self.ix;
|
||||
let is_master = flags(ix, page).is_some_and(|f| f[2] != 0);
|
||||
let size = own_loda(ix, page)
|
||||
.and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn))
|
||||
.and_then(|l| l.arg(ARG_PAGE_SIZE).and_then(|b| self.size_arg(b)));
|
||||
let mut layers = Vec::new();
|
||||
for l in page_layers(ix, page) {
|
||||
let layer = self.layer(l);
|
||||
let empty = layer.objects.is_empty() && layer.guides.is_empty();
|
||||
// The entries that stand for the master page's layers hold nothing of the page's own.
|
||||
if empty && (is_master || layer.kind != LayerKind::Drawing) {
|
||||
continue;
|
||||
}
|
||||
layers.push(layer);
|
||||
}
|
||||
(is_master, Page { size, layers })
|
||||
}
|
||||
|
||||
fn size_arg(&self, b: &[u8]) -> Option<(f64, f64)> {
|
||||
let mut r = Rd::new(b);
|
||||
sane_size(records::coord(&mut r, &self.p)?, records::coord(&mut r, &self.p)?)
|
||||
}
|
||||
|
||||
fn layer(&mut self, list: &Chunk) -> Layer {
|
||||
let ix = self.ix;
|
||||
let loda = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn));
|
||||
// The layer's own object type says what it is; its flags, only when it has none (R19).
|
||||
let kind = match &loda {
|
||||
Some(l) => layer_kind_of_type(l.kind, self.p.types_from_zero),
|
||||
None => flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)),
|
||||
};
|
||||
let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default();
|
||||
let mut guides = Vec::new();
|
||||
let objects = self.objects(ix.children(list), &mut guides);
|
||||
let flags = state(ix, list);
|
||||
hide_guides(&mut guides, 0, flags);
|
||||
Layer { name, kind, flags, objects, guides }
|
||||
}
|
||||
|
||||
/// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`.
|
||||
fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec<Guideline>) -> Vec<Object> {
|
||||
let ix = self.ix;
|
||||
let mut stack = vec![Frame {
|
||||
chunks,
|
||||
next: 0,
|
||||
objects: Vec::new(),
|
||||
group: false,
|
||||
flags: Flags::default(),
|
||||
guides_from: guides.len(),
|
||||
outer: Matrix::IDENTITY,
|
||||
}];
|
||||
loop {
|
||||
let Some(top) = stack.last_mut() else { return Vec::new() };
|
||||
let (here, outer) = (top.chunks, top.outer);
|
||||
let Some(c) = here.get(top.next) else {
|
||||
let Some(done) = stack.pop() else { return Vec::new() };
|
||||
// A hidden group hides the guidelines inside it.
|
||||
hide_guides(guides, done.guides_from, done.flags);
|
||||
match stack.last_mut() {
|
||||
// A group counts toward the objects a read maps; past them its objects stay,
|
||||
// ungrouped, with the group's flags.
|
||||
Some(parent) if done.group && !done.objects.is_empty() => {
|
||||
if self.budget.take_object() {
|
||||
parent.objects.push(Object::Group { objects: done.objects, flags: done.flags });
|
||||
} else {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
let mut objects = done.objects;
|
||||
for o in &mut objects {
|
||||
inherit(o, done.flags);
|
||||
}
|
||||
parent.objects.extend(objects);
|
||||
}
|
||||
}
|
||||
Some(parent) if !done.group => parent.objects.extend(done.objects),
|
||||
Some(_) => {}
|
||||
None => return done.objects,
|
||||
}
|
||||
continue;
|
||||
};
|
||||
top.next += 1;
|
||||
// Every chunk of a clipped group counts, empty groups included, each time a container
|
||||
// names the group; past the limit the group is left out.
|
||||
if !self.open_clips.is_empty() && !self.budget.take_clipped_chunk() {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
self.clip_cut = true;
|
||||
return Vec::new();
|
||||
}
|
||||
if c.is_list(b"obj ") {
|
||||
if let Some(o) = self.object(c, guides, &outer) {
|
||||
top.objects.push(o);
|
||||
}
|
||||
} else if c.is_list(b"grp ") {
|
||||
let own = self.group_placement(c);
|
||||
let flags = state(ix, c);
|
||||
let guides_from = guides.len();
|
||||
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, flags, guides_from, outer: outer.after(&own) });
|
||||
} else if c.is_list(b"lnkg") {
|
||||
// Linked groups (brush strokes, blends, contours) place their objects with a
|
||||
// matrix of their own, which this reader doesn't apply: they are left out.
|
||||
push(self.warn, Warning::UnsupportedObjects);
|
||||
} else if c.id == crate::riff::LIST && !c.is_list(b"lgob") {
|
||||
// Other lists under a layer are looked through (R22).
|
||||
let guides_from = guides.len();
|
||||
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, flags: Flags::default(), guides_from, outer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The matrix a group places its objects with. Only a version 3 group has one, in the
|
||||
/// transforms argument of its own `lobj` (R33); one that can't be read is damage, and the
|
||||
/// group's objects stay where their own transforms put them.
|
||||
fn group_placement(&mut self, list: &Chunk) -> Matrix {
|
||||
if !self.p.inline_styles {
|
||||
return Matrix::IDENTITY;
|
||||
}
|
||||
let ix = self.ix;
|
||||
let Some(arg) =
|
||||
own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)).and_then(|l| l.arg(ARG_TRANSFORMS))
|
||||
else {
|
||||
return Matrix::IDENTITY;
|
||||
};
|
||||
self.placement(arg)
|
||||
}
|
||||
|
||||
/// The matrices of a transforms argument (R33). An envelope among them is not applied: the
|
||||
/// shapes keep their outlines, placed by the matrices alone, with the envelopes warning.
|
||||
fn placement(&mut self, arg: &[u8]) -> Matrix {
|
||||
match inline::transforms(arg, &self.p, &self.budget.limits, self.warn) {
|
||||
Some(t) => {
|
||||
if t.envelope {
|
||||
push(self.warn, Warning::Envelopes);
|
||||
}
|
||||
t.matrix
|
||||
}
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
Matrix::IDENTITY
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `LIST obj `: a shape placed by its own transform and then by `outer`, or `None` (a
|
||||
/// guideline goes to `guides`).
|
||||
fn object(&mut self, list: &Chunk, guides: &mut Vec<Guideline>, outer: &Matrix) -> Option<Object> {
|
||||
let ix = self.ix;
|
||||
let Some(loda) = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) else {
|
||||
push(self.warn, Warning::Damaged);
|
||||
return None;
|
||||
};
|
||||
// Guidelines count toward the objects a read maps.
|
||||
if !self.budget.take_object() {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
let flags = state(ix, list);
|
||||
if loda.kind == GUIDELINE {
|
||||
guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)).map(|g| Guideline { hidden: flags.hidden, ..g }));
|
||||
return None;
|
||||
}
|
||||
if self.p.inline_styles {
|
||||
return self.inline_object(&loda, outer, flags);
|
||||
}
|
||||
let geometry = self.geometry(&loda)?;
|
||||
// A uniform transparency from version 13 applies (R47); a lens, and a transparency of
|
||||
// another kind or version, is not applied: the shape shows opaque.
|
||||
let (opacity, blend) = match loda.arg(ARG_LENS) {
|
||||
None => (1.0, Blend::Normal),
|
||||
Some(b) => match records::transparency(b).filter(|_| self.p.tagged) {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
push(self.warn, Warning::Lenses);
|
||||
(1.0, Blend::Normal)
|
||||
}
|
||||
},
|
||||
};
|
||||
let nonzero = self.nonzero(&loda);
|
||||
// A transform that is there but can't be read is damage; the shape stays where it is.
|
||||
let matrix = match own_chunk(ix, list, &[b"trfd"]) {
|
||||
None => Matrix::IDENTITY,
|
||||
Some(c) => records::trfd(ix.data(c), &self.p).unwrap_or_else(|| {
|
||||
push(self.warn, Warning::Damaged);
|
||||
Matrix::IDENTITY
|
||||
}),
|
||||
};
|
||||
// Without a fill or outline argument of its own, an object takes its style's (R45). The
|
||||
// style id is a u16 in files of 16-bit fields.
|
||||
let style = loda.arg(ARG_STYLE).and_then(|b| if self.p.short { self.short_id(b) } else { self.id(b) });
|
||||
let fill_id = match loda.arg(ARG_FILL) {
|
||||
Some(b) => self.id(b),
|
||||
None => style.and_then(|s| self.style_entry(s, Styles::fill)),
|
||||
};
|
||||
let outline_id = match loda.arg(ARG_OUTLINE) {
|
||||
Some(b) => self.id(b),
|
||||
None => style.and_then(|s| self.style_entry(s, Styles::outline)),
|
||||
};
|
||||
let fill = fill_id.and_then(|id| self.fill(id));
|
||||
let outline = outline_id.and_then(|id| self.outline(id));
|
||||
let shape = Box::new(Shape { geometry, matrix, fill, outline, nonzero, opacity, blend, flags });
|
||||
// A container clips the group its argument 8005 names (R46).
|
||||
Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) {
|
||||
Some(id) => self.clip(shape, id, guides),
|
||||
None => Object::Shape(shape),
|
||||
})
|
||||
}
|
||||
|
||||
/// `container` and the objects of the clipped group `id`, which keep their own transforms.
|
||||
/// A group that isn't there is damage; one already being read, past the depth limit or past
|
||||
/// the chunks clipped groups may walk is left out with the limit warning, the guidelines it
|
||||
/// holds included. Either way the container stays, as a plain shape.
|
||||
fn clip(&mut self, container: Box<Shape>, id: u32, guides: &mut Vec<Guideline>) -> Object {
|
||||
let Some(&group) = self.clips.get(&id) else {
|
||||
push(self.warn, Warning::Damaged);
|
||||
return Object::Shape(container);
|
||||
};
|
||||
if self.open_clips.contains(&id) || self.open_clips.len() >= MAX_CLIP_DEPTH {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
return Object::Shape(container);
|
||||
}
|
||||
self.open_clips.push(id);
|
||||
let (ix, mark) = (self.ix, guides.len());
|
||||
let objects = self.objects(ix.children(group), guides);
|
||||
self.open_clips.pop();
|
||||
if std::mem::take(&mut self.clip_cut) {
|
||||
guides.truncate(mark);
|
||||
return Object::Shape(container);
|
||||
}
|
||||
// The clipped group's own flags hide or lock the objects it holds; it and the container
|
||||
// hide its guidelines.
|
||||
let flags = state(ix, group);
|
||||
hide_guides(guides, mark, flags);
|
||||
hide_guides(guides, mark, container.flags);
|
||||
if objects.is_empty() {
|
||||
return Object::Shape(container);
|
||||
}
|
||||
let mut objects = objects;
|
||||
for o in &mut objects {
|
||||
inherit(o, flags);
|
||||
}
|
||||
Object::Clip { container, objects }
|
||||
}
|
||||
|
||||
/// The record id that argument `b` names; an argument too short for one is damage.
|
||||
fn id(&mut self, b: &[u8]) -> Option<u32> {
|
||||
let id = id_of(b);
|
||||
if id.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// A u16 id at the start of argument `b`; an argument too short for one is damage.
|
||||
fn short_id(&mut self, b: &[u8]) -> Option<u32> {
|
||||
let id = Rd::new(b).u16().map(u32::from);
|
||||
if id.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Whether the object's fill rule is nonzero: byte 0 of argument 14001 set (R52). Without the
|
||||
/// argument the fill is even-odd; an argument without its byte is damage.
|
||||
fn nonzero(&mut self, loda: &Loda) -> bool {
|
||||
let Some(b) = loda.arg(ARG_WINDING) else { return false };
|
||||
match b.first() {
|
||||
Some(v) => *v != 0,
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill or outline record that style `id` names; a style table that doesn't parse is
|
||||
/// damage, and the object is drawn without it.
|
||||
fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option<u32>) -> Option<u32> {
|
||||
match &self.styles {
|
||||
Ok(s) => entry(s, id),
|
||||
Err(()) => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A version 3 object, whose transforms, fill and outline are arguments of its own record
|
||||
/// (R33, R34, R35). A fill or an outline that is there but can't be read is damage.
|
||||
fn inline_object(&mut self, loda: &Loda, outer: &Matrix, flags: Flags) -> Option<Object> {
|
||||
let own = match loda.arg(ARG_TRANSFORMS) {
|
||||
None => Matrix::IDENTITY,
|
||||
Some(arg) => self.placement(arg),
|
||||
};
|
||||
let geometry = self.geometry(loda)?;
|
||||
let fill = loda.arg(ARG_FILL).and_then(|b| {
|
||||
let read = inline::fill(b, &self.p, self.warn);
|
||||
if read.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
read.flatten()
|
||||
});
|
||||
let outline = loda.arg(ARG_OUTLINE).and_then(|b| {
|
||||
let read = inline::outline(b, &self.p, self.warn);
|
||||
if read.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
read.flatten()
|
||||
});
|
||||
// Past the dashes a read takes, the outline is solid.
|
||||
let outline = outline.map(|mut o| {
|
||||
if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) {
|
||||
o.dashes = Vec::new();
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
o
|
||||
});
|
||||
let nonzero = self.nonzero(loda);
|
||||
let shape = Shape { nonzero, flags, ..Shape::new(geometry, outer.after(&own), fill, outline) };
|
||||
Some(Object::Shape(Box::new(shape)))
|
||||
}
|
||||
|
||||
fn geometry(&mut self, loda: &Loda) -> Option<Geometry> {
|
||||
let coords = loda.arg(ARG_COORDS);
|
||||
// Version 3 counts the first object types from 0, one below the later numbers (R32).
|
||||
let kind = if self.p.types_from_zero && loda.kind <= 4 { loda.kind + 1 } else { loda.kind };
|
||||
// A shape without its coordinates, or a polygon without its sides, is damage like a shape
|
||||
// whose coordinates can't be read; one left out at the coordinate limit is not.
|
||||
self.budget.coordinates_refused();
|
||||
let g = match kind {
|
||||
RECTANGLE => coords.and_then(|c| geometry::rect(c, &self.p)),
|
||||
ELLIPSE => coords.and_then(|c| geometry::ellipse(c, &self.p)),
|
||||
CURVE => coords.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)).map(Geometry::Path),
|
||||
PATH if self.p.paths => coords.and_then(|c| geometry::path_record(c, &self.p, self.budget, self.warn)).map(Geometry::Path),
|
||||
POLYGON => match loda.arg(ARG_POLYGON) {
|
||||
Some(sides) => coords
|
||||
.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn))
|
||||
.and_then(|base| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)),
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
return None;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
push(self.warn, Warning::UnsupportedObjects);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if g.is_none() && !self.budget.coordinates_refused() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
fn fill(&mut self, id: u32) -> Option<Color> {
|
||||
if let Some(f) = self.fills.get(&id) {
|
||||
return f.clone();
|
||||
}
|
||||
// A record that is missing or can't be read is damage, and the shape is drawn without a
|
||||
// fill; id 0 without a record is no fill.
|
||||
if id != 0 && !self.fill_chunks.contains_key(&id) {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
let read = self.fill_chunks.get(&id).and_then(|b| {
|
||||
let read = records::fill(b, &self.p, self.warn);
|
||||
if read.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
read.and_then(|(_, c)| c)
|
||||
});
|
||||
self.fills.insert(id, read.clone());
|
||||
read
|
||||
}
|
||||
|
||||
/// The outline of record `id`. Its dashes count toward the read's dashes for every shape that
|
||||
/// uses it; past them the shape's outline is solid.
|
||||
fn outline(&mut self, id: u32) -> Option<Outline> {
|
||||
if !self.outlines.contains_key(&id) {
|
||||
// A record that is missing is damage, as one that can't be read is; id 0 without a
|
||||
// record is no outline.
|
||||
if id != 0 && !self.outline_chunks.contains_key(&id) {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
let read = self.outline_chunks.get(&id).and_then(|b| {
|
||||
let read = records::outline(b, &self.p, self.warn);
|
||||
if read.is_none() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
read.and_then(|(_, o)| o)
|
||||
});
|
||||
// An outline with more dashes than the read may still take is kept solid.
|
||||
let read = read.map(|mut o| {
|
||||
if o.dashes.len() > self.budget.dashes_left() {
|
||||
o.dashes = Vec::new();
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
o
|
||||
});
|
||||
self.outlines.insert(id, read);
|
||||
}
|
||||
let o = self.outlines.get_mut(&id)?.as_mut()?;
|
||||
// The dashes left only shrink, so an outline refused once is refused for every later
|
||||
// shape: its dashes are dropped from the cache, and later shapes take it solid.
|
||||
if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) {
|
||||
o.dashes = Vec::new();
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
Some(o.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill or outline argument: the record id (R20).
|
||||
fn id_of(b: &[u8]) -> Option<u32> {
|
||||
Rd::new(b).u32()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layer_flags_name_the_kinds() {
|
||||
assert_eq!(layer_kind([0, 0, 0, 0x98], true), LayerKind::Drawing);
|
||||
assert_eq!(layer_kind([0x0a, 0, 0, 0x98], true), LayerKind::Guides);
|
||||
assert_eq!(layer_kind([0x02, 1, 1, 0x98], true), LayerKind::Guides);
|
||||
assert_eq!(layer_kind([0x08, 0, 1, 0x98], true), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0, 1, 1, 0x98], true), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0x1a, 0, 1, 0x98], true), LayerKind::Grid);
|
||||
assert_eq!(layer_kind([0x12, 0, 1, 0x98], true), LayerKind::Grid);
|
||||
// From version 14 the master page flags its layers by byte 0 alone.
|
||||
assert_eq!(layer_kind([0x0a, 0, 1, 0x98], false), LayerKind::Guides);
|
||||
assert_eq!(layer_kind([0x08, 0, 1, 0x98], false), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0x5a, 1, 1, 0x98], false), LayerKind::Grid);
|
||||
assert_eq!(layer_kind([0x02, 1, 1, 0x98], false), LayerKind::Drawing);
|
||||
assert_eq!(layer_kind([0, 1, 1, 0x98], false), LayerKind::Drawing);
|
||||
// Drawing layers flagged 0x10, 0x08, 0x18, 0x40 and 0x58 with byte 2 clear, as sample
|
||||
// files flag them, and desktop and guides layers with bit 0x40 or 0x10 set.
|
||||
for f in [[0x10, 0, 0, 0x98], [0x08, 1, 0, 0x98], [0x18, 1, 0, 0x98], [0x40, 0, 0, 0x98], [0x58, 1, 0, 0x98]] {
|
||||
assert_eq!(layer_kind(f, true), LayerKind::Drawing, "{f:?}");
|
||||
assert_eq!(layer_kind(f, false), LayerKind::Drawing, "{f:?}");
|
||||
}
|
||||
assert_eq!(layer_kind([0x18, 0, 1, 0x98], true), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0x48, 0, 1, 0x98], false), LayerKind::Desktop);
|
||||
assert_eq!(layer_kind([0x4a, 1, 1, 0x98], true), LayerKind::Guides);
|
||||
}
|
||||
|
||||
/// An outline record refused at the dash limit keeps no dashes in the cache, so the shapes
|
||||
/// that use it later copy none.
|
||||
#[test]
|
||||
fn an_outline_past_the_dash_limit_keeps_no_dashes() {
|
||||
let v = crate::synth::V(1100);
|
||||
let pen = crate::synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 };
|
||||
let record = v.outline(1, pen, &crate::synth::color(5, [0, 0, 0, 255]), &[3, 1, 3]);
|
||||
let file = crate::synth::riff(1100, &[]);
|
||||
let mut budget = Budget::new(crate::Limits { dashes: 4, ..crate::Limits::default() });
|
||||
let mut warn = Vec::new();
|
||||
let ix = crate::riff::Index::build(&file, None, &mut budget, &mut warn).unwrap();
|
||||
let mut cx = Ctx {
|
||||
ix: &ix,
|
||||
p: layout::for_version(1100).unwrap(),
|
||||
budget: &mut budget,
|
||||
warn: &mut warn,
|
||||
fill_chunks: HashMap::new(),
|
||||
outline_chunks: HashMap::from([(1, record.as_slice())]),
|
||||
fills: HashMap::new(),
|
||||
outlines: HashMap::new(),
|
||||
styles: Ok(Styles::default()),
|
||||
clips: HashMap::new(),
|
||||
open_clips: Vec::new(),
|
||||
clip_cut: false,
|
||||
};
|
||||
assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(3));
|
||||
for _ in 0..3 {
|
||||
assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(0));
|
||||
assert_eq!(cx.outlines.get(&1).and_then(|o| o.as_ref()).map(|o| o.dashes.len()), Some(0));
|
||||
}
|
||||
assert_eq!(*cx.warn, vec![Warning::TooDeep]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Little-endian reads that fail instead of panicking.
|
||||
|
||||
/// A cursor over one record's bytes. Every read returns `None` past the end.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Rd<'a> {
|
||||
b: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Rd<'a> {
|
||||
pub(crate) fn new(b: &'a [u8]) -> Self {
|
||||
Rd { b, pos: 0 }
|
||||
}
|
||||
|
||||
pub(crate) fn at(b: &'a [u8], pos: usize) -> Self {
|
||||
Rd { b, pos }
|
||||
}
|
||||
|
||||
pub(crate) fn pos(&self) -> usize {
|
||||
self.pos
|
||||
}
|
||||
|
||||
pub(crate) fn left(&self) -> usize {
|
||||
self.b.len().saturating_sub(self.pos)
|
||||
}
|
||||
|
||||
pub(crate) fn skip(&mut self, n: usize) -> Option<()> {
|
||||
let end = self.pos.checked_add(n)?;
|
||||
(end <= self.b.len()).then(|| self.pos = end)
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let end = self.pos.checked_add(n)?;
|
||||
let s = self.b.get(self.pos..end)?;
|
||||
self.pos = end;
|
||||
Some(s)
|
||||
}
|
||||
|
||||
fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
self.bytes(N)?.try_into().ok()
|
||||
}
|
||||
|
||||
pub(crate) fn u8(&mut self) -> Option<u8> {
|
||||
Some(self.array::<1>()?[0])
|
||||
}
|
||||
|
||||
pub(crate) fn u16(&mut self) -> Option<u16> {
|
||||
self.array().map(u16::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn i16(&mut self) -> Option<i16> {
|
||||
self.array().map(i16::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn u32(&mut self) -> Option<u32> {
|
||||
self.array().map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn i32(&mut self) -> Option<i32> {
|
||||
self.array().map(i32::from_le_bytes)
|
||||
}
|
||||
|
||||
/// A finite f64; NaN and the infinities read as `None`.
|
||||
pub(crate) fn f64(&mut self) -> Option<f64> {
|
||||
self.array().map(f64::from_le_bytes).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
pub(crate) fn fourcc(&mut self) -> Option<[u8; 4]> {
|
||||
self.array()
|
||||
}
|
||||
}
|
||||
|
||||
/// The u32 at `pos` of `b`.
|
||||
pub(crate) fn u32_at(b: &[u8], pos: usize) -> Option<u32> {
|
||||
Rd::at(b, pos).u32()
|
||||
}
|
||||
@@ -0,0 +1,651 @@
|
||||
//! Reader for `.cmx` exchange files with 32-bit coordinates: the RIFF form `CMX1` (R53), its
|
||||
//! header (R54), the color, pen, line type, dash, outline and arrowhead tables (R55 to R59) and the
|
||||
//! instructions of each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills
|
||||
//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses
|
||||
//! are left out with a warning.
|
||||
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::geometry::path_of;
|
||||
use crate::layout::{self, Profile};
|
||||
use crate::limits::Budget;
|
||||
use crate::model::{Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape};
|
||||
use crate::records::{name, property_color};
|
||||
use crate::riff::{LIST, push};
|
||||
use crate::{Error, Warning};
|
||||
|
||||
const FORM: [u8; 4] = *b"CMX1";
|
||||
/// Meters per coordinate unit when the header gives no usable value: the 0.1 µm of every sample
|
||||
/// file with 32-bit coordinates (R54).
|
||||
const DEFAULT_UNIT: f64 = 1e-7;
|
||||
/// How far past a chunk that runs short the next chunk id is looked for (R53).
|
||||
const RESYNC: usize = 64;
|
||||
/// The chunks the reader uses (R53 to R60).
|
||||
const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"];
|
||||
/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them.
|
||||
const MAX_NAME_UNITS: usize = 4096;
|
||||
|
||||
// Instruction codes (R60).
|
||||
const BEGIN_PAGE: i16 = 9;
|
||||
const END_PAGE: i16 = 10;
|
||||
const BEGIN_LAYER: i16 = 11;
|
||||
const END_LAYER: i16 = 12;
|
||||
const BEGIN_GROUP: i16 = 13;
|
||||
const END_GROUP: i16 = 14;
|
||||
const BEGIN_TEXT: i16 = 20;
|
||||
const END_TEXT: i16 = 21;
|
||||
const GLYPH_RUN: i16 = 65;
|
||||
const ELLIPSE: i16 = 66;
|
||||
const CURVE: i16 = 67;
|
||||
const RECTANGLE: i16 = 68;
|
||||
const IMAGE: i16 = 69;
|
||||
const ADD_CLIP: i16 = 88;
|
||||
const REMOVE_CLIP: i16 = 89;
|
||||
const JUMP: i16 = 111;
|
||||
|
||||
/// Does `bytes` start as a CMX file: a RIFF or RIFX form of type `CMX1` (R53)?
|
||||
pub(crate) fn is_cmx(bytes: &[u8]) -> bool {
|
||||
matches!(bytes.get(0..4), Some(b"RIFF" | b"RIFX")) && bytes.get(8..12) == Some(FORM.as_slice())
|
||||
}
|
||||
|
||||
/// A chunk outside the `LIST` chunks: its id, its body and where the body starts in the file.
|
||||
struct Chunk<'a> {
|
||||
id: [u8; 4],
|
||||
body: &'a [u8],
|
||||
start: usize,
|
||||
}
|
||||
|
||||
/// The tables that page instructions refer to by 1-based index (R55 to R59).
|
||||
#[derive(Default)]
|
||||
struct Tables {
|
||||
colors: Vec<Option<Color>>,
|
||||
/// Outline widths in points.
|
||||
pens: Vec<Option<f64>>,
|
||||
/// Flags, and the caps and join.
|
||||
line_types: Vec<Option<(u8, u8)>>,
|
||||
dashes: Vec<Vec<u16>>,
|
||||
/// Line type, screen, color, arrowheads, pen and dashes.
|
||||
outlines: Vec<Option<[u16; 6]>>,
|
||||
arrowheads: Vec<(u16, u16)>,
|
||||
}
|
||||
|
||||
pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
|
||||
if !is_cmx(bytes) {
|
||||
return Err(Error::NotCmx);
|
||||
}
|
||||
if bytes.get(0..4) == Some(b"RIFX") {
|
||||
return Err(Error::Unsupported("big-endian CMX files"));
|
||||
}
|
||||
let mut warn = Vec::new();
|
||||
let chunks = chunks(bytes, budget, &mut warn)?;
|
||||
let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?;
|
||||
match cont.get(52) {
|
||||
Some(b'4') => {}
|
||||
Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")),
|
||||
_ => return Err(Error::Damaged("CMX header")),
|
||||
}
|
||||
let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT);
|
||||
let unit = meters / 0.0254 * 72.0;
|
||||
let tables = Tables::read(&chunks, unit, budget, &mut warn)?;
|
||||
let mut pages = Vec::new();
|
||||
for c in chunks.iter().filter(|c| c.id == *b"page") {
|
||||
pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?);
|
||||
}
|
||||
Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
|
||||
}
|
||||
|
||||
/// The chunks of the file in order, those inside `LIST` chunks in place (R53).
|
||||
fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Vec<Chunk<'a>>, Error> {
|
||||
let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len());
|
||||
if declared > b.len() {
|
||||
// The file was cut short of the size its header gives.
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let end = declared.min(b.len());
|
||||
let mut out = Vec::new();
|
||||
// (position, end, depth) of the lists still to walk; a list's children go before the rest of
|
||||
// the list that holds it.
|
||||
let mut stack = vec![(12usize, end, 0usize)];
|
||||
while let Some((mut pos, end, depth)) = stack.pop() {
|
||||
while pos.saturating_add(8) <= end {
|
||||
let Some(id) = Rd::at(b, pos).fourcc() else { break };
|
||||
if !is_id(&id) {
|
||||
match resync(b, pos, end) {
|
||||
Some(next) => {
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
None => {
|
||||
push(warn, Warning::Damaged);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
budget.take_chunk()?;
|
||||
let size = u32_at(b, pos + 4).map_or(0, |s| s as usize);
|
||||
let start = pos + 8;
|
||||
let stop = start.saturating_add(size);
|
||||
if stop > end {
|
||||
// Stray bytes that happen to start with four letters give a length past the list:
|
||||
// look for the next chunk id after them. A chunk the reader uses is kept, cut at
|
||||
// the end of the list.
|
||||
if !READ_IDS.contains(&id)
|
||||
&& let Some(next) = resync(b, pos, end)
|
||||
{
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let stop = stop.min(end);
|
||||
let next = stop.saturating_add(size & 1);
|
||||
if id == LIST {
|
||||
if depth >= budget.limits.depth {
|
||||
push(warn, Warning::TooDeep);
|
||||
pos = next;
|
||||
continue;
|
||||
}
|
||||
stack.push((next, end, depth));
|
||||
stack.push((start + 4, stop, depth + 1));
|
||||
break;
|
||||
}
|
||||
if let Some(body) = b.get(start..stop) {
|
||||
out.push(Chunk { id, body, start });
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Is `t` a chunk id: an ASCII letter, then three ASCII letters, digits or spaces (R53)?
|
||||
fn is_id(t: &[u8]) -> bool {
|
||||
matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' '))
|
||||
}
|
||||
|
||||
/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`]
|
||||
/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list
|
||||
/// that ends at `end` (R53).
|
||||
fn resync(b: &[u8], pos: usize, end: usize) -> Option<usize> {
|
||||
let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end);
|
||||
let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p)));
|
||||
(pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p))
|
||||
}
|
||||
|
||||
/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs
|
||||
/// past it (R55).
|
||||
fn list_end(b: &[u8], mut pos: usize) -> usize {
|
||||
while let Some(&tag) = b.get(pos) {
|
||||
if tag == 0xff {
|
||||
return pos + 1;
|
||||
}
|
||||
match Rd::at(b, pos + 1).u16().map(usize::from).filter(|n| *n >= 3) {
|
||||
Some(n) if pos + n <= b.len() => pos += n,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
/// The data of field `tag` in the field list `b` (R55).
|
||||
fn field(b: &[u8], tag: u8) -> Option<&[u8]> {
|
||||
let mut pos = 0;
|
||||
while let Some(&t) = b.get(pos) {
|
||||
if t == 0xff {
|
||||
return None;
|
||||
}
|
||||
let n = usize::from(Rd::at(b, pos + 1).u16()?);
|
||||
let data = b.get(pos + 3..pos.checked_add(n)?).filter(|_| n >= 3)?;
|
||||
if t == tag {
|
||||
return Some(data);
|
||||
}
|
||||
pos += n;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The field lists of a table: a u16 count, then that many lists (R55). Each entry counts toward
|
||||
/// the chunk limit.
|
||||
fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result<Vec<&'a [u8]>, Error> {
|
||||
let count = Rd::new(d).u16().map_or(0, usize::from);
|
||||
let mut out = Vec::new();
|
||||
let mut pos = 2;
|
||||
for _ in 0..count {
|
||||
if pos >= d.len() {
|
||||
break;
|
||||
}
|
||||
budget.take_chunk()?;
|
||||
let end = list_end(d, pos);
|
||||
out.push(d.get(pos..end).unwrap_or_default());
|
||||
pos = end;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Tables {
|
||||
/// The first chunk of each table; a table that is missing is empty.
|
||||
fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Tables, Error> {
|
||||
let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body);
|
||||
// A color record of field 10 holds a property list as a `.cdr` fill does (R56).
|
||||
let record = layout::for_version(1300);
|
||||
let mut t = Tables::default();
|
||||
for e in entries(first(b"rclr"), budget)? {
|
||||
t.colors.push(color(e, record.as_ref(), warn));
|
||||
}
|
||||
for e in entries(first(b"rpen"), budget)? {
|
||||
t.pens.push(field(e, 1).and_then(|f| Rd::new(f).u32()).map(|w| f64::from(w) * unit));
|
||||
}
|
||||
for e in entries(first(b"rott"), budget)? {
|
||||
t.line_types.push(field(e, 1).and_then(|f| Some((*f.first()?, f.get(1).copied().unwrap_or(0)))));
|
||||
}
|
||||
for e in entries(first(b"rdot"), budget)? {
|
||||
let mut r = Rd::new(field(e, 1).unwrap_or_default());
|
||||
let n = r.u16().map_or(0, usize::from);
|
||||
t.dashes.push((0..n).map_while(|_| r.u16()).collect());
|
||||
}
|
||||
for e in entries(first(b"rotl"), budget)? {
|
||||
t.outlines.push(field(e, 1).and_then(|f| {
|
||||
let mut r = Rd::new(f);
|
||||
Some([r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?])
|
||||
}));
|
||||
}
|
||||
// Arrowhead pairs are plain u16 pairs after the count, not field lists (R59).
|
||||
let mut r = Rd::new(first(b"rota"));
|
||||
let n = r.u16().map_or(0, usize::from);
|
||||
for _ in 0..n {
|
||||
let Some(pair) = r.u16().zip(r.u16()) else { break };
|
||||
budget.take_chunk()?;
|
||||
t.arrowheads.push(pair);
|
||||
}
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
/// Entry `index` (1-based) of `list`, or `None` with a warning when there is none.
|
||||
fn get<T: Clone>(list: &[Option<T>], index: u16, warn: &mut Vec<Warning>) -> Option<T> {
|
||||
let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten();
|
||||
if found.is_none() {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn color(&self, index: u16, warn: &mut Vec<Warning>) -> Color {
|
||||
Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3]))
|
||||
}
|
||||
|
||||
/// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58).
|
||||
fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Outline> {
|
||||
let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?;
|
||||
let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0));
|
||||
if flags & 1 != 0 {
|
||||
return None;
|
||||
}
|
||||
let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0);
|
||||
let mut dashes = Vec::new();
|
||||
if flags & 4 != 0 {
|
||||
let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i));
|
||||
match stored {
|
||||
// A pattern of zero lengths draws as a solid line, as in a `.cdr` outline (R48).
|
||||
Some(d) if d.iter().all(|x| *x == 0) => {}
|
||||
Some(d) if budget.take_dashes(d.len()) => dashes = d.iter().map(|x| f64::from(*x)).collect(),
|
||||
Some(_) => push(warn, Warning::TooDeep),
|
||||
None => push(warn, Warning::Damaged),
|
||||
}
|
||||
}
|
||||
if usize::from(arrows).checked_sub(1).and_then(|i| self.arrowheads.get(i)).is_some_and(|(s, e)| *s != 0 || *e != 0) {
|
||||
push(warn, Warning::Arrowheads);
|
||||
}
|
||||
Some(Outline {
|
||||
width,
|
||||
color: self.color(color, warn),
|
||||
cap: match caps_join & 0x0f {
|
||||
1 => Cap::Round,
|
||||
2 => Cap::Square,
|
||||
_ => Cap::Butt,
|
||||
},
|
||||
join: match caps_join >> 4 {
|
||||
1 => Join::Round,
|
||||
2 => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
},
|
||||
dashes,
|
||||
behind_fill: flags & 8 != 0,
|
||||
scale_with: flags & 16 != 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A color entry (R56): the property list of field 10 when there is one, else the model and
|
||||
/// palette bytes of field 1 and the values of field 2. Colors in other models read as black with a
|
||||
/// warning.
|
||||
fn color(e: &[u8], record: Option<&Profile>, warn: &mut Vec<Warning>) -> Option<Color> {
|
||||
if let (Some(f), Some(p)) = (field(e, 10), record) {
|
||||
let mut r = Rd::new(f);
|
||||
let len = r.u32()? as usize;
|
||||
return property_color(r.bytes(len.min(r.left()))?, p, warn);
|
||||
}
|
||||
let model = *field(e, 1)?.first()?;
|
||||
let v = field(e, 2)?;
|
||||
let byte = |i: usize| v.get(i).map(|b| f32::from(*b));
|
||||
let pct = |i: usize| byte(i).map(|x| (x / 100.0).clamp(0.0, 1.0));
|
||||
let full = |i: usize| byte(i).map(|x| x / 255.0);
|
||||
Some(match model {
|
||||
2 => Color::Cmyk([pct(0)?, pct(1)?, pct(2)?, pct(3)?]),
|
||||
3 => Color::Cmyk([full(0)?, full(1)?, full(2)?, full(3)?]),
|
||||
4 => Color::Cmyk([full(0)?, full(1)?, full(2)?, 0.0]),
|
||||
5 => Color::Rgb([full(0)?, full(1)?, full(2)?]),
|
||||
9 => Color::Gray(1.0 - full(0)?),
|
||||
_ => {
|
||||
push(warn, Warning::UnknownColors);
|
||||
Color::Rgb([0.0; 3])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The objects of one layer while it is read: the layer's own list, then one list for each group
|
||||
/// left open.
|
||||
struct LayerRead {
|
||||
name: String,
|
||||
lists: Vec<Vec<Object>>,
|
||||
}
|
||||
|
||||
impl LayerRead {
|
||||
/// The layer, its open groups closed. Lists are drawn back to front (R60), and the model holds
|
||||
/// them front to back.
|
||||
fn finish(mut self) -> Layer {
|
||||
while self.lists.len() > 1 {
|
||||
close_group(&mut self.lists);
|
||||
}
|
||||
let mut objects = self.lists.pop().unwrap_or_default();
|
||||
objects.reverse();
|
||||
Layer { name: self.name, kind: LayerKind::Drawing, flags: Default::default(), objects, guides: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the innermost open group of `lists` into the one that holds it.
|
||||
fn close_group(lists: &mut Vec<Vec<Object>>) {
|
||||
if lists.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let mut objects = lists.pop().unwrap_or_default();
|
||||
objects.reverse();
|
||||
if let Some(top) = lists.last_mut() {
|
||||
top.push(Object::Group { objects, flags: Default::default() });
|
||||
}
|
||||
}
|
||||
|
||||
/// The reading of one page chunk.
|
||||
struct PageRead<'t, 'b> {
|
||||
tables: &'t Tables,
|
||||
unit: f64,
|
||||
budget: &'b mut Budget,
|
||||
warn: &'b mut Vec<Warning>,
|
||||
size: Option<(f64, f64)>,
|
||||
/// The page's center in the file's coordinates when the page takes its size from the
|
||||
/// drawing's bounds; points are moved by it so the art lies on the page.
|
||||
center: (f64, f64),
|
||||
layers: Vec<Layer>,
|
||||
open: Option<LayerRead>,
|
||||
/// Groups nested past the depth limit that are still open; their content is left out.
|
||||
skipped: usize,
|
||||
}
|
||||
|
||||
impl<'t, 'b> PageRead<'t, 'b> {
|
||||
fn new(tables: &'t Tables, unit: f64, budget: &'b mut Budget, warn: &'b mut Vec<Warning>) -> Self {
|
||||
PageRead { tables, unit, budget, warn, size: None, center: (0.0, 0.0), layers: Vec::new(), open: None, skipped: 0 }
|
||||
}
|
||||
|
||||
/// The instructions of a page chunk: a u16 size counting the whole instruction and an i16 code,
|
||||
/// or 0xFFFF, a u32 size and the code; then the code's field lists (R60).
|
||||
fn read(mut self, c: &Chunk) -> Result<Page, Error> {
|
||||
let d = c.body;
|
||||
let mut pos = 0usize;
|
||||
while pos.saturating_add(4) <= d.len() {
|
||||
self.budget.take_chunk()?;
|
||||
let mut r = Rd::at(d, pos);
|
||||
let (size, code, head) = match r.u16() {
|
||||
Some(0xFFFF) => match (r.u32(), r.i16()) {
|
||||
(Some(size), Some(code)) => (size as usize, code, 8),
|
||||
_ => break,
|
||||
},
|
||||
Some(size) => match r.i16() {
|
||||
Some(code) => (usize::from(size), code, 4),
|
||||
None => break,
|
||||
},
|
||||
None => break,
|
||||
};
|
||||
if size < head {
|
||||
push(self.warn, Warning::Damaged);
|
||||
break;
|
||||
}
|
||||
let end = pos.saturating_add(size);
|
||||
if end > d.len() {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
let body = d.get(pos + head..end.min(d.len())).unwrap_or_default();
|
||||
if code == JUMP {
|
||||
// Field 1 is the file offset the instructions go on from; the bytes passed over
|
||||
// hold the page's images (R60).
|
||||
let target = field(body, 1).and_then(|f| Rd::new(f).u32()).and_then(|t| (t as usize).checked_sub(c.start));
|
||||
pos = target.filter(|t| *t >= end && *t <= d.len()).unwrap_or(end);
|
||||
if pos > end {
|
||||
push(self.warn, Warning::UnsupportedObjects);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.instruction(code, body);
|
||||
pos = end;
|
||||
}
|
||||
if pos < d.len() {
|
||||
// An instruction whose head runs past the page was not read.
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
self.close_layer();
|
||||
// A layer that holds nothing (the special layers every sample file lists empty) is left
|
||||
// out. The file lists layers back to front.
|
||||
let mut layers = self.layers;
|
||||
layers.retain(|l| !l.objects.is_empty());
|
||||
layers.reverse();
|
||||
Ok(Page { size: self.size, layers })
|
||||
}
|
||||
|
||||
fn instruction(&mut self, code: i16, body: &[u8]) {
|
||||
match code {
|
||||
BEGIN_PAGE => {
|
||||
// Field 4: the page's width and height (R61).
|
||||
let mut r = Rd::new(field(body, 4).unwrap_or_default());
|
||||
if let (Some(w), Some(h)) = (r.u32(), r.u32()) {
|
||||
let (w, h) = (f64::from(w) * self.unit, f64::from(h) * self.unit);
|
||||
self.size = (w > 0.0 && h > 0.0).then_some((w, h));
|
||||
}
|
||||
if self.size.is_none() {
|
||||
self.size_from_bounds(field(body, 1).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
BEGIN_LAYER => {
|
||||
self.close_layer();
|
||||
// A layer without a name is left unnamed, as in a `.cdr` drawing.
|
||||
let name = self.layer_name(body).unwrap_or_default();
|
||||
self.open = Some(LayerRead { name, lists: vec![Vec::new()] });
|
||||
}
|
||||
END_LAYER => self.close_layer(),
|
||||
BEGIN_GROUP => {
|
||||
let open = self.layer().lists.len();
|
||||
if self.skipped > 0 || open > self.budget.limits.depth {
|
||||
self.skipped += 1;
|
||||
push(self.warn, Warning::TooDeep);
|
||||
} else if self.budget.take_object() {
|
||||
self.layer().lists.push(Vec::new());
|
||||
} else {
|
||||
// Past the object limit the group's content joins the group that holds it.
|
||||
self.skipped += 1;
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
}
|
||||
END_GROUP => {
|
||||
if self.skipped > 0 {
|
||||
self.skipped -= 1;
|
||||
} else {
|
||||
close_group(&mut self.layer().lists);
|
||||
}
|
||||
}
|
||||
CURVE if self.skipped == 0 => {
|
||||
if let Some(shape) = self.curve(body) {
|
||||
if self.budget.take_object() {
|
||||
if let Some(list) = self.layer().lists.last_mut() {
|
||||
list.push(Object::Shape(Box::new(shape)));
|
||||
}
|
||||
} else {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
}
|
||||
}
|
||||
}
|
||||
BEGIN_TEXT | GLYPH_RUN | ELLIPSE | RECTANGLE | IMAGE | ADD_CLIP => push(self.warn, Warning::UnsupportedObjects),
|
||||
// These and the other codes (text styles and characters, color contexts) draw nothing
|
||||
// on their own.
|
||||
END_PAGE | END_TEXT | REMOVE_CLIP => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A page without a size of its own is sized to the drawing's bounds in field 1 (R61): a u16
|
||||
/// page number, a u32 of flags, then the left, top, right and bottom edges as i32 in
|
||||
/// coordinate units. The page is centered on those bounds.
|
||||
fn size_from_bounds(&mut self, f: &[u8]) {
|
||||
let mut r = Rd::new(f);
|
||||
if r.u16().is_none() || r.u32().is_none() {
|
||||
return;
|
||||
}
|
||||
let (Some(l), Some(t), Some(rt), Some(b)) = (r.i32(), r.i32(), r.i32(), r.i32()) else {
|
||||
return;
|
||||
};
|
||||
let (l, t, rt, b) = (f64::from(l) * self.unit, f64::from(t) * self.unit, f64::from(rt) * self.unit, f64::from(b) * self.unit);
|
||||
let (w, h) = ((rt - l).abs(), (t - b).abs());
|
||||
if w > 0.0 && h > 0.0 {
|
||||
self.size = Some((w, h));
|
||||
self.center = ((l + rt) / 2.0, (t + b) / 2.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The open layer, or a new unnamed one when objects come before any layer begins.
|
||||
fn layer(&mut self) -> &mut LayerRead {
|
||||
self.open.get_or_insert_with(|| LayerRead { name: String::new(), lists: vec![Vec::new()] })
|
||||
}
|
||||
|
||||
fn close_layer(&mut self) {
|
||||
self.skipped = 0;
|
||||
if let Some(l) = self.open.take() {
|
||||
self.layers.push(l.finish());
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer's name: field 4 as a u32 count and UTF-16 units, else field 1 from byte 12 as a
|
||||
/// u16 count and 8-bit characters (R62).
|
||||
fn layer_name(&mut self, body: &[u8]) -> Option<String> {
|
||||
// A field 4 that can't be read leaves the name to field 1.
|
||||
let wide = field(body, 4).and_then(|f| {
|
||||
let mut r = Rd::new(f);
|
||||
let n = (r.u32()? as usize).min(MAX_NAME_UNITS).min(r.left() / 2);
|
||||
Some((r.bytes(n * 2)?, layout::for_version(1200)?))
|
||||
});
|
||||
if let Some((units, l)) = wide {
|
||||
let s = name(units, &l, self.warn);
|
||||
if !s.trim().is_empty() {
|
||||
return Some(s);
|
||||
}
|
||||
}
|
||||
let mut r = Rd::at(field(body, 1)?, 12);
|
||||
let n = usize::from(r.u16()?).min(r.left());
|
||||
let s = name(r.bytes(n)?, &layout::for_version(1100)?, self.warn);
|
||||
(!s.trim().is_empty()).then_some(s)
|
||||
}
|
||||
|
||||
/// A curve (R62): field 1 its rendering attributes, field 2 a u16 point count, the points (i32
|
||||
/// x and y) and one type byte for each. Points are from the page's center, y up.
|
||||
fn curve(&mut self, body: &[u8]) -> Option<Shape> {
|
||||
let mut r = Rd::new(field(body, 2).unwrap_or_default());
|
||||
let Some(count) = r.u16().map(usize::from) else {
|
||||
// A curve without its points is lost.
|
||||
push(self.warn, Warning::Damaged);
|
||||
return None;
|
||||
};
|
||||
// `stored` points are read, so the type bytes are found after all of them, and the first
|
||||
// `n`, those that have a type byte, are kept. When the field holds every point, a short
|
||||
// field has lost type bytes. When it holds whole points and their types for fewer points,
|
||||
// the count is too large. Otherwise the field lost points, and its type bytes can't be
|
||||
// found: the curve is lost.
|
||||
let left = r.left();
|
||||
let (stored, n) = match count.checked_mul(8).filter(|c| *c <= left) {
|
||||
Some(c) => (count, count.min(left - c)),
|
||||
None if left.is_multiple_of(9) => (left / 9, left / 9),
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if n < count {
|
||||
push(self.warn, Warning::Damaged);
|
||||
}
|
||||
if !self.budget.take_coordinates(stored) {
|
||||
push(self.warn, Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
let mut points = Vec::with_capacity(stored);
|
||||
for _ in 0..stored {
|
||||
let (x, y) = (f64::from(r.i32()?) * self.unit, f64::from(r.i32()?) * self.unit);
|
||||
points.push(Pt { x: x - self.center.0, y: y - self.center.1 });
|
||||
}
|
||||
points.truncate(n);
|
||||
let path = path_of(&points, r.bytes(n)?);
|
||||
if path.subpaths.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (fill, outline) = self.attributes(field(body, 1).unwrap_or_default());
|
||||
Some(Shape::new(Geometry::Path(path), Matrix::IDENTITY, fill, outline))
|
||||
}
|
||||
|
||||
/// Rendering attributes (R63): a mask (1 fill, 2 outline, 4 lens), then a field list for the
|
||||
/// fill and one for the outline when the mask names them.
|
||||
fn attributes(&mut self, a: &[u8]) -> (Option<Color>, Option<Outline>) {
|
||||
let Some(&mask) = a.first() else { return (None, None) };
|
||||
let mut pos = 1;
|
||||
let mut fill = None;
|
||||
if mask & 1 != 0 {
|
||||
let end = list_end(a, pos);
|
||||
let list = a.get(pos..end).unwrap_or_default();
|
||||
pos = end;
|
||||
// Field 1: the fill type (u16), then its own field list; type 1, uniform, names its
|
||||
// color in field 1.
|
||||
let v = field(list, 1).unwrap_or_default();
|
||||
match Rd::new(v).u16() {
|
||||
Some(0) | None => {}
|
||||
Some(1) => {
|
||||
let index = field(v.get(2..).unwrap_or_default(), 1).and_then(|c| Rd::new(c).u16());
|
||||
fill = Some(match index {
|
||||
Some(i) => self.tables.color(i, self.warn),
|
||||
None => {
|
||||
push(self.warn, Warning::Damaged);
|
||||
Color::Rgb([0.0; 3])
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(_) => push(self.warn, Warning::UnsupportedFills),
|
||||
}
|
||||
}
|
||||
let mut outline = None;
|
||||
if mask & 2 != 0 {
|
||||
let list = a.get(pos..list_end(a, pos)).unwrap_or_default();
|
||||
match field(list, 1).and_then(|f| Rd::new(f).u16()) {
|
||||
Some(i) => outline = self.tables.outline(i, self.budget, self.warn),
|
||||
None => push(self.warn, Warning::Damaged),
|
||||
}
|
||||
}
|
||||
if mask & 4 != 0 {
|
||||
push(self.warn, Warning::Lenses);
|
||||
}
|
||||
// A canvas (8) or a container (16) is not read.
|
||||
if mask & (8 | 16) != 0 {
|
||||
push(self.warn, Warning::UnsupportedObjects);
|
||||
}
|
||||
(fill, outline)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
//! The coordinates argument (30) of each object type read as geometry: curves (R16), rectangles
|
||||
//! (R15), ellipses and arcs (R17) and polygons (R18).
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
use crate::Warning;
|
||||
use crate::bytes::Rd;
|
||||
use crate::layout::Profile;
|
||||
use crate::limits::Budget;
|
||||
use crate::model::{Geometry, Path, Pt, Segment, SubPath};
|
||||
use crate::records::{angle, coord};
|
||||
use crate::riff::push;
|
||||
|
||||
/// The most sides a polygon record may give (VectorCraft's own bound).
|
||||
const MAX_POLYGON_SIDES: u32 = 1000;
|
||||
/// The base curve of a polygon lies on a circle of 1000 mm (R18), in points.
|
||||
const POLYGON_UNIT_RADIUS: f64 = 1000.0 / 25.4 * 72.0;
|
||||
|
||||
/// What a point type byte asks for (R16): bits 7 and 6.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Op {
|
||||
Move,
|
||||
Line,
|
||||
Curve,
|
||||
Control,
|
||||
}
|
||||
|
||||
fn op(t: u8) -> Op {
|
||||
match t >> 6 {
|
||||
0 => Op::Move,
|
||||
1 => Op::Line,
|
||||
2 => Op::Curve,
|
||||
_ => Op::Control,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bit 3 closes the subpath (R16).
|
||||
const CLOSES: u8 = 0x08;
|
||||
|
||||
/// A point list (R16): the count, the points, then one type byte each. The count is a u32 from
|
||||
/// version 6 and a u16 followed by another u16 before it (R39). It is held to what the bytes hold;
|
||||
/// `None` when the points are past the budget.
|
||||
pub(crate) fn point_list(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
|
||||
let mut r = Rd::new(b);
|
||||
let count = if p.short {
|
||||
let count = usize::from(r.u16()?);
|
||||
r.skip(2)?;
|
||||
count
|
||||
} else {
|
||||
r.u32()? as usize
|
||||
};
|
||||
points(b, r, count, p, budget, warn)
|
||||
}
|
||||
|
||||
/// A path record (object type 0x25, R30): 4 bytes, two u16 counts whose sum is the point count, 16
|
||||
/// bytes, then the points and their type bytes as in a point list.
|
||||
pub(crate) fn path_record(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
|
||||
let mut r = Rd::new(b);
|
||||
r.skip(4)?;
|
||||
let count = usize::from(r.u16()?) + usize::from(r.u16()?);
|
||||
r.skip(16)?;
|
||||
points(b, r, count, p, budget, warn)
|
||||
}
|
||||
|
||||
/// `count` points from `r` over `b`, then their type bytes. A list cut short is read two ways: as
|
||||
/// all `count` points with the type bytes after them, and as the points and type bytes the bytes
|
||||
/// hold split evenly. The reading that keeps more points with a type byte wins, the first on a tie.
|
||||
fn points(b: &[u8], mut r: Rd, count: usize, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
|
||||
let each = 2 * p.word();
|
||||
let left = r.left();
|
||||
let split = (left / (each + 1)).min(count);
|
||||
let whole = count.checked_mul(each).filter(|len| *len <= left).map(|len| (left - len).min(count));
|
||||
let stored = match whole {
|
||||
Some(typed) if typed >= split => count,
|
||||
_ => split,
|
||||
};
|
||||
let types = b.get(r.pos() + stored * each..)?;
|
||||
let n = stored.min(types.len());
|
||||
if count > n {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
if !budget.take_coordinates(n) {
|
||||
push(warn, Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
let mut points = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
points.push(Pt { x: coord(&mut r, p)?, y: coord(&mut r, p)? });
|
||||
}
|
||||
Some(path_of(&points, types))
|
||||
}
|
||||
|
||||
/// The subpaths that points and their type bytes draw.
|
||||
pub(crate) fn path_of(points: &[Pt], types: &[u8]) -> Path {
|
||||
let mut subpaths = Vec::new();
|
||||
let mut cur: Option<SubPath> = None;
|
||||
// The last two control points: a curve end uses only those.
|
||||
let mut controls: Vec<Pt> = Vec::with_capacity(2);
|
||||
for (&pt, &t) in points.iter().zip(types) {
|
||||
let o = op(t);
|
||||
if o == Op::Control {
|
||||
if controls.len() == 2 {
|
||||
controls.remove(0);
|
||||
}
|
||||
controls.push(pt);
|
||||
continue;
|
||||
}
|
||||
if o == Op::Move || cur.is_none() {
|
||||
subpaths.extend(cur.take());
|
||||
cur = Some(SubPath { start: pt, segments: Vec::new(), closed: t & CLOSES != 0 && o == Op::Move });
|
||||
controls.clear();
|
||||
if o == Op::Move {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Some(sp) = cur.as_mut() else { continue };
|
||||
let seg = match (o, controls.as_slice()) {
|
||||
(Op::Curve, [c1, c2]) => Segment::Cubic(*c1, *c2, pt),
|
||||
_ => Segment::Line(pt),
|
||||
};
|
||||
controls.clear();
|
||||
sp.segments.push(seg);
|
||||
if t & CLOSES != 0 {
|
||||
sp.closed = true;
|
||||
}
|
||||
}
|
||||
subpaths.extend(cur);
|
||||
// A closed subpath with no segments, or an open one with none, draws nothing.
|
||||
subpaths.retain(|s| !s.segments.is_empty());
|
||||
Path { subpaths }
|
||||
}
|
||||
|
||||
/// A rectangle record (R15): width, height, then one corner radius for every corner, four from
|
||||
/// version 9.
|
||||
pub(crate) fn rect(b: &[u8], p: &Profile) -> Option<Geometry> {
|
||||
if p.f64_rect {
|
||||
return rect_f64(b, p);
|
||||
}
|
||||
let mut r = Rd::new(b);
|
||||
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let first = coord(&mut r, p)?.abs();
|
||||
let mut radii = [first; 4];
|
||||
if p.four_radii {
|
||||
for slot in radii.iter_mut().skip(1) {
|
||||
*slot = coord(&mut r, p)?.abs();
|
||||
}
|
||||
}
|
||||
Some(Geometry::Rect { w, h, radii })
|
||||
}
|
||||
|
||||
/// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale
|
||||
/// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the
|
||||
/// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter
|
||||
/// side; with it set the radius is in inches. A corner is held to half the shorter side, and
|
||||
/// sizes to the range of the 32-bit coordinates of earlier versions.
|
||||
fn rect_f64(b: &[u8], p: &Profile) -> Option<Geometry> {
|
||||
let mut r = Rd::new(b);
|
||||
let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit());
|
||||
let (w, h) = (size(r.f64()?)?, size(r.f64()?)?);
|
||||
r.skip(8 + 8)?;
|
||||
let inches = r.u8()? != 0;
|
||||
r.skip(7)?;
|
||||
let short = w.abs().min(h.abs());
|
||||
let mut radii = [0.0; 4];
|
||||
for (k, slot) in radii.iter_mut().enumerate() {
|
||||
if k > 0 {
|
||||
r.skip(16)?;
|
||||
}
|
||||
let v = r.f64()?.abs();
|
||||
let radius = if inches { v * 72.0 } else { v * short / 2.0 };
|
||||
*slot = radius.min(short / 2.0);
|
||||
}
|
||||
Some(Geometry::Rect { w, h, radii })
|
||||
}
|
||||
|
||||
/// An ellipse record (R17): the box's width and height, the start and end angles and whether
|
||||
/// the arc closes through the centre. Equal angles make a whole ellipse.
|
||||
pub(crate) fn ellipse(b: &[u8], p: &Profile) -> Option<Geometry> {
|
||||
let mut r = Rd::new(b);
|
||||
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let (a1, a2) = (angle(&mut r, p)?, angle(&mut r, p)?);
|
||||
let pie = if p.short { r.u16()? != 0 } else { r.u32()? != 0 };
|
||||
let sweep = (a2 - a1).rem_euclid(360.0);
|
||||
if sweep.abs() < 1e-9 {
|
||||
return Some(Geometry::Ellipse { w, h });
|
||||
}
|
||||
Some(Geometry::Path(arc(w, h, a1, sweep, pie)))
|
||||
}
|
||||
|
||||
/// The arc of the ellipse in the box from the origin to (`w`, `h`), from `start` degrees through
|
||||
/// `sweep` degrees, in the ellipse's own axes; a pie runs from the centre and closes there. The
|
||||
/// radii are half the size, and a negative width or height points its axis the other way (R17), so
|
||||
/// with a negative height 0 to 180 degrees is the half below the centre.
|
||||
fn arc(w: f64, h: f64, start: f64, sweep: f64, pie: bool) -> Path {
|
||||
let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0);
|
||||
let at = |t: f64| Pt { x: cx + rx * t.cos(), y: cy + ry * t.sin() };
|
||||
let tangent = |t: f64| Pt { x: -rx * t.sin(), y: ry * t.cos() };
|
||||
let pieces = (sweep / 90.0).ceil().max(1.0) as usize;
|
||||
let step = sweep.to_radians() / pieces as f64;
|
||||
let k = 4.0 / 3.0 * (step / 4.0).tan();
|
||||
let t0 = start.to_radians();
|
||||
let mut segments = Vec::with_capacity(pieces + 2);
|
||||
if pie {
|
||||
segments.push(Segment::Line(at(t0)));
|
||||
}
|
||||
for i in 0..pieces {
|
||||
let (a, b) = (t0 + step * i as f64, t0 + step * (i + 1) as f64);
|
||||
let (p0, p1, d0, d1) = (at(a), at(b), tangent(a), tangent(b));
|
||||
segments.push(Segment::Cubic(Pt { x: p0.x + k * d0.x, y: p0.y + k * d0.y }, Pt { x: p1.x - k * d1.x, y: p1.y - k * d1.y }, p1));
|
||||
}
|
||||
let start = if pie { Pt { x: cx, y: cy } } else { at(t0) };
|
||||
Path { subpaths: vec![SubPath { start, segments, closed: pie }] }
|
||||
}
|
||||
|
||||
/// A polygon (R18): its base curve, one side of the outline on a circle of 1000 mm with its top
|
||||
/// vertex first, copied once per side and turned clockwise each time by the vertices the side
|
||||
/// spans, then scaled by (`rx`, `ry`) and moved to the centre the polygon argument (11000) gives.
|
||||
/// A star whose sides skip vertices draws as one outline, or as several when the side count and
|
||||
/// the step share a factor.
|
||||
pub(crate) fn polygon(base: &Path, b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Geometry> {
|
||||
let mut r = Rd::new(b);
|
||||
if !p.tagged {
|
||||
r.skip(4)?;
|
||||
}
|
||||
let sides = r.u32()?;
|
||||
// The next point: the first field, or the second when the first is 0 or 1.
|
||||
let (first, second) = (r.u32()?, r.u32()?);
|
||||
let next = if first > 1 { first } else { second };
|
||||
if p.tagged {
|
||||
r.skip(4)?;
|
||||
}
|
||||
let (rx, ry) = (r.f64()?, r.f64()?);
|
||||
let (cx, cy) = (coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let side = base.subpaths.first()?;
|
||||
if !(1..=MAX_POLYGON_SIDES).contains(&sides) {
|
||||
push(warn, Warning::Damaged);
|
||||
return None;
|
||||
}
|
||||
if !budget.take_coordinates(side.segments.len().saturating_mul(3).saturating_mul(sides as usize)) {
|
||||
push(warn, Warning::TooDeep);
|
||||
return None;
|
||||
}
|
||||
// The base curve's own unit radius, measured from its first point, keeps the scale right
|
||||
// whatever unit the file's coordinates are in.
|
||||
let unit = side.start.x.hypot(side.start.y);
|
||||
let unit = if unit > 0.0 { unit } else { POLYGON_UNIT_RADIUS };
|
||||
let place = |q: Pt, turn: f64| {
|
||||
let (s, c) = turn.sin_cos();
|
||||
let (x, y) = (q.x * c - q.y * s, q.x * s + q.y * c);
|
||||
Pt { x: x / unit * POLYGON_UNIT_RADIUS * rx + cx, y: y / unit * POLYGON_UNIT_RADIUS * ry + cy }
|
||||
};
|
||||
let step = side_step(side, sides, next);
|
||||
let outlines = gcd(sides, step);
|
||||
let each = sides / outlines;
|
||||
let angle = |k: u32| -2.0 * PI * f64::from(k % sides) / f64::from(sides);
|
||||
let mut subpaths = Vec::with_capacity(outlines as usize);
|
||||
for o in 0..outlines {
|
||||
let mut segments = Vec::with_capacity(side.segments.len() * each as usize);
|
||||
for j in 0..each {
|
||||
let turn = angle(o + j * step);
|
||||
segments.extend(side.segments.iter().map(|s| match *s {
|
||||
Segment::Line(a) => Segment::Line(place(a, turn)),
|
||||
Segment::Cubic(a, b, c) => Segment::Cubic(place(a, turn), place(b, turn), place(c, turn)),
|
||||
}));
|
||||
}
|
||||
subpaths.push(SubPath { start: place(side.start, angle(o)), segments, closed: true });
|
||||
}
|
||||
Some(Geometry::Path(Path { subpaths }))
|
||||
}
|
||||
|
||||
/// How many vertices the base side moves on from its first point (R18): the vertex its last
|
||||
/// point lies at, clockwise; else the next-point field when it names one; else 1.
|
||||
fn side_step(side: &SubPath, sides: u32, next: u32) -> u32 {
|
||||
let field = if (1..sides).contains(&next) { next } else { 1 };
|
||||
let Some(end) = side.segments.last().map(|s| match *s {
|
||||
Segment::Line(e) | Segment::Cubic(_, _, e) => e,
|
||||
}) else {
|
||||
return field;
|
||||
};
|
||||
let (r0, r1) = (side.start.x.hypot(side.start.y), end.x.hypot(end.y));
|
||||
if !(r0 > 0.0 && (r1 - r0).abs() <= r0 * 1e-3) {
|
||||
return field;
|
||||
}
|
||||
let turned = (side.start.y.atan2(side.start.x) - end.y.atan2(end.x)) / (2.0 * PI / f64::from(sides));
|
||||
let k = turned.round();
|
||||
if !k.is_finite() || (turned - k).abs() > 1e-3 {
|
||||
return field;
|
||||
}
|
||||
match k.rem_euclid(f64::from(sides)) as u32 {
|
||||
0 => field,
|
||||
k => k,
|
||||
}
|
||||
}
|
||||
|
||||
fn gcd(a: u32, b: u32) -> u32 {
|
||||
let (mut a, mut b) = (a, b);
|
||||
while b != 0 {
|
||||
(a, b) = (b, a % b);
|
||||
}
|
||||
a.max(1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pt(x: f64, y: f64) -> Pt {
|
||||
Pt { x, y }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_bytes_make_moves_lines_curves_and_closes() {
|
||||
let points = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0), pt(20.0, 20.0), pt(30.0, 20.0)];
|
||||
// move (closed), line, control, control, curve end closing; move, line.
|
||||
let types = [0x08, 0x40, 0xC0, 0xC0, 0x88, 0x00, 0x40];
|
||||
let path = path_of(&points, &types);
|
||||
assert_eq!(path.subpaths.len(), 2);
|
||||
let first = &path.subpaths[0];
|
||||
assert!(first.closed);
|
||||
assert_eq!(first.segments, vec![Segment::Line(pt(10.0, 0.0)), Segment::Cubic(pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0))]);
|
||||
assert!(!path.subpaths[1].closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_list_short_of_type_bytes_reads_them_after_all_its_points() {
|
||||
let p = crate::layout::for_version(1300).unwrap_or_else(|| panic!("profile"));
|
||||
// Three points, (0, 0), (1 inch, 0) and (0, 0), and type bytes for the first two only.
|
||||
let mut b = 3u32.to_le_bytes().to_vec();
|
||||
for v in [0i32, 0, 254_000, 0, 0, 0] {
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
b.extend([0x00, 0x40]);
|
||||
let mut warn = vec![];
|
||||
let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path"));
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(72.0, 0.0))]);
|
||||
assert_eq!(warn, vec![Warning::Damaged]);
|
||||
// A count past the points the bytes hold keeps the points that have a type byte.
|
||||
// Eight points and their eight type bytes take the bytes of nine points.
|
||||
let mut b = 9u32.to_le_bytes().to_vec();
|
||||
for i in 0..8 {
|
||||
b.extend((i * 254_000i32).to_le_bytes());
|
||||
b.extend(0i32.to_le_bytes());
|
||||
}
|
||||
b.extend([0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40]);
|
||||
let mut warn = vec![];
|
||||
let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path"));
|
||||
assert_eq!(path.subpaths[0].segments.len(), 7);
|
||||
assert!(matches!(path.subpaths[0].segments[6], Segment::Line(end) if (end.x - 504.0).abs() < 1e-9 && end.y == 0.0));
|
||||
assert_eq!(warn, vec![Warning::Damaged]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_of_control_points_keeps_the_last_two() {
|
||||
let points: Vec<Pt> = (0..7).map(|i| pt(f64::from(i), 0.0)).collect();
|
||||
let path = path_of(&points, &[0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80]);
|
||||
assert_eq!(path.subpaths[0].segments, vec![Segment::Cubic(pt(4.0, 0.0), pt(5.0, 0.0), pt(6.0, 0.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_end_without_two_controls_is_a_line() {
|
||||
let path = path_of(&[pt(0.0, 0.0), pt(1.0, 1.0)], &[0x00, 0x80]);
|
||||
assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(1.0, 1.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quarter_arc_ends_on_the_ellipse() {
|
||||
let p = arc(20.0, 10.0, 0.0, 90.0, false);
|
||||
let sp = &p.subpaths[0];
|
||||
assert_eq!(sp.start, pt(20.0, 5.0));
|
||||
let Some(Segment::Cubic(_, _, end)) = sp.segments.last() else { panic!("no curve") };
|
||||
assert!((end.x - 10.0).abs() < 1e-9 && (end.y - 10.0).abs() < 1e-9);
|
||||
let pie = arc(20.0, 10.0, 0.0, 180.0, true);
|
||||
assert!(pie.subpaths[0].closed && pie.subpaths[0].start == pt(10.0, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_height_turns_the_arc_below_the_centre() {
|
||||
let p = arc(20.0, -10.0, 0.0, 180.0, false);
|
||||
let sp = &p.subpaths[0];
|
||||
assert_eq!(sp.start, pt(20.0, -5.0));
|
||||
let Some(Segment::Cubic(_, _, mid)) = sp.segments.first() else { panic!("no curve") };
|
||||
assert!((mid.x - 10.0).abs() < 1e-9 && (mid.y + 10.0).abs() < 1e-9, "{mid:?}");
|
||||
}
|
||||
|
||||
/// A version 13 polygon argument: `sides`, the two next-point fields, then rx = ry = 1 at the
|
||||
/// origin.
|
||||
fn polygon_arg(sides: u32, first: u32, second: u32) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
for v in [sides, first, second, 0] {
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
b.extend(1.0f64.to_le_bytes());
|
||||
b.extend(1.0f64.to_le_bytes());
|
||||
b.extend([0; 8]);
|
||||
b
|
||||
}
|
||||
|
||||
/// Vertex `k` of `sides`, counted clockwise from the top, on the base circle.
|
||||
fn vertex(k: u32, sides: u32) -> Pt {
|
||||
let a = PI / 2.0 - 2.0 * PI * f64::from(k) / f64::from(sides);
|
||||
pt(POLYGON_UNIT_RADIUS * a.cos(), POLYGON_UNIT_RADIUS * a.sin())
|
||||
}
|
||||
|
||||
fn ends(sp: &SubPath) -> Vec<Pt> {
|
||||
sp.segments
|
||||
.iter()
|
||||
.map(|s| match *s {
|
||||
Segment::Line(e) | Segment::Cubic(_, _, e) => e,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn close(a: &[Pt], b: &[Pt]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.x - q.x).abs() < 1e-6 && (p.y - q.y).abs() < 1e-6)
|
||||
}
|
||||
|
||||
fn star(sides: u32, step: u32, first: u32, second: u32) -> Path {
|
||||
let p = crate::layout::for_version(1300).unwrap();
|
||||
let base = Path { subpaths: vec![SubPath { start: vertex(0, sides), segments: vec![Segment::Line(vertex(step, sides))], closed: false }] };
|
||||
let mut budget = Budget::new(crate::Limits::default());
|
||||
let Some(Geometry::Path(path)) = polygon(&base, &polygon_arg(sides, first, second), &p, &mut budget, &mut vec![]) else {
|
||||
panic!("no polygon")
|
||||
};
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_star_whose_sides_skip_a_vertex_chains_its_points() {
|
||||
// {5/2}: each side runs two vertices on, so the outline visits 2, 4, 1, 3 and 0.
|
||||
let path = star(5, 2, 2, 0);
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
let want: Vec<Pt> = [2, 4, 1, 3, 0].iter().map(|&k| vertex(k, 5)).collect();
|
||||
assert!(close(&ends(&path.subpaths[0]), &want), "{:?}", ends(&path.subpaths[0]));
|
||||
// The base side alone tells the step when the field doesn't.
|
||||
assert!(close(&ends(&star(5, 2, 0, 0).subpaths[0]), &want));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_star_sharing_a_factor_with_its_sides_draws_one_outline_for_each() {
|
||||
// {6/2}: two triangles, 0-2-4 and 1-3-5.
|
||||
let path = star(6, 2, 0, 2);
|
||||
assert_eq!(path.subpaths.len(), 2);
|
||||
assert!(close(&ends(&path.subpaths[0]), &[vertex(2, 6), vertex(4, 6), vertex(0, 6)]));
|
||||
assert!(close(&[path.subpaths[1].start], &[vertex(1, 6)]));
|
||||
assert!(close(&ends(&path.subpaths[1]), &[vertex(3, 6), vertex(5, 6), vertex(1, 6)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_polygon_turns_one_vertex_for_each_side() {
|
||||
let path = star(4, 1, 0, 1);
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert!(close(&ends(&path.subpaths[0]), &[1, 2, 3, 0].map(|k| vertex(k, 4))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
//! What a version 3 object holds as arguments where later versions name records: its transforms
|
||||
//! (argument 100, R33), its fill (argument 20, R34) and its outline (argument 10, R35).
|
||||
|
||||
use crate::bytes::Rd;
|
||||
use crate::layout::Profile;
|
||||
use crate::model::{Cap, Color, Join, Matrix, Outline};
|
||||
use crate::records::{self, angle, coord};
|
||||
use crate::riff::push;
|
||||
use crate::{Limits, Warning};
|
||||
|
||||
/// Transform entry types (R33): a matrix, and an envelope.
|
||||
const MATRIX: u16 = 0x8c;
|
||||
const ENVELOPE: u16 = 0x14;
|
||||
/// The bytes of one transform entry (R33).
|
||||
const ENTRY: usize = 10;
|
||||
/// The bytes an outline keeps for its dashes, one byte each (R35).
|
||||
const DASH_AREA: usize = 10;
|
||||
|
||||
/// The transforms of one object or group.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Placement {
|
||||
/// The matrices composed in file order, in points.
|
||||
pub(crate) matrix: Matrix,
|
||||
/// An envelope bends the shape. The reader doesn't apply envelopes.
|
||||
pub(crate) envelope: bool,
|
||||
}
|
||||
|
||||
/// The transforms argument (R33): a u16, the entry count, then 10-byte entries of a type and, at
|
||||
/// byte 6, where the entry's data starts in the argument. The count is held to the entries the
|
||||
/// argument holds and to the arguments a record may have. Entries of other types are passed over.
|
||||
pub(crate) fn transforms(b: &[u8], p: &Profile, limits: &Limits, warn: &mut Vec<Warning>) -> Option<Placement> {
|
||||
let mut r = Rd::new(b);
|
||||
r.skip(2)?;
|
||||
let stored = usize::from(r.u16()?);
|
||||
let count = stored.min(r.left() / ENTRY).min(limits.arguments);
|
||||
if count < stored {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let mut out = Placement { matrix: Matrix::IDENTITY, envelope: false };
|
||||
for _ in 0..count {
|
||||
let mut e = Rd::new(r.bytes(ENTRY)?);
|
||||
let kind = e.u16()?;
|
||||
e.skip(4)?;
|
||||
let at = usize::from(e.u16()?);
|
||||
match kind {
|
||||
MATRIX => out.matrix = records::fixed_matrix(&mut Rd::at(b, at), p.unit())?.after(&out.matrix),
|
||||
ENVELOPE => out.envelope = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The fill argument (R34): a type byte, 0 for none and 1 for a uniform fill with its color. Fills
|
||||
/// of other types read as none with a warning. The outer `None` is an argument that can't be read.
|
||||
pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Option<Color>> {
|
||||
let mut r = Rd::new(b);
|
||||
match r.u8()? {
|
||||
0 => Some(None),
|
||||
1 => Some(Some(records::color(&mut r, p, warn)?)),
|
||||
_ => {
|
||||
push(warn, Warning::UnsupportedFills);
|
||||
Some(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline argument (R35): a flags byte whose bit 0 is set when the object is outlined, the
|
||||
/// width, the stretch, the nib angle, the color, 7 bytes, the dash count and 10 bytes that hold the
|
||||
/// dashes, the join and the caps (u16 each), then the two arrowhead ids. An argument that ends
|
||||
/// after its color gives a solid line with butt caps and miter joins. The outer `None` is an
|
||||
/// argument that can't be read.
|
||||
pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Option<Outline>> {
|
||||
let mut r = Rd::new(b);
|
||||
if r.u8()? & 1 == 0 {
|
||||
return Some(None);
|
||||
}
|
||||
let width = coord(&mut r, p)?.abs();
|
||||
let _stretch = r.u16()?;
|
||||
let _nib = angle(&mut r, p)?;
|
||||
let color = records::color(&mut r, p, warn)?;
|
||||
let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false };
|
||||
let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) };
|
||||
let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) };
|
||||
if stored > DASH_AREA {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
let dashes: Vec<f64> = area.iter().take(stored).map(|d| f64::from(*d)).collect();
|
||||
if dashes.iter().any(|d| *d > 0.0) {
|
||||
out.dashes = dashes;
|
||||
}
|
||||
out.join = match r.u16() {
|
||||
Some(1) => Join::Round,
|
||||
Some(2) => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
};
|
||||
out.cap = match r.u16() {
|
||||
Some(1) => Cap::Round,
|
||||
Some(2) => Cap::Square,
|
||||
_ => Cap::Butt,
|
||||
};
|
||||
if matches!((r.u32(), r.u32()), (Some(s), Some(e)) if s != 0 || e != 0) {
|
||||
push(warn, Warning::Arrowheads);
|
||||
}
|
||||
Some(Some(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn p3() -> Profile {
|
||||
crate::layout::for_version(300).unwrap()
|
||||
}
|
||||
|
||||
/// A transforms argument of `entries` (type, data offset), then `data` from byte 4 + 10 for
|
||||
/// each entry.
|
||||
fn arg(count: u16, entries: &[(u16, u16)], data: &[i32]) -> Vec<u8> {
|
||||
let mut b = vec![0, 0];
|
||||
b.extend(count.to_le_bytes());
|
||||
for (kind, at) in entries {
|
||||
b.extend(kind.to_le_bytes());
|
||||
b.extend([0; 4]);
|
||||
b.extend(at.to_le_bytes());
|
||||
b.extend([0; 2]);
|
||||
}
|
||||
b.extend(data.iter().flat_map(|v| v.to_le_bytes()));
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrices_compose_in_file_order_and_other_entries_are_passed_over() {
|
||||
// Scale by 2, then move 1 inch right: entry types 0x8c, an unknown one and 0x8c.
|
||||
let scale = [131072, 0, 0, 0, 131072, 0];
|
||||
let shift = [65536, 0, 1000, 0, 65536, 0];
|
||||
let b = arg(3, &[(MATRIX, 34), (0x99, 0), (MATRIX, 58)], &[scale, shift].concat());
|
||||
let mut w = vec![];
|
||||
let t = transforms(&b, &p3(), &Limits::default(), &mut w).unwrap();
|
||||
assert_eq!((t.matrix, t.envelope), (Matrix([2.0, 0.0, 0.0, 2.0, 72.0, 0.0]), false));
|
||||
assert!(w.is_empty());
|
||||
let b = arg(2, &[(MATRIX, 24), (ENVELOPE, 0)], &scale);
|
||||
assert!(transforms(&b, &p3(), &Limits::default(), &mut vec![]).unwrap().envelope);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_transform_arguments_do_not_read_past_their_bytes() {
|
||||
let scale = [131072, 0, 0, 0, 131072, 0];
|
||||
// A count of 65,535 over one entry reads that entry, with the damage warning.
|
||||
let b = arg(u16::MAX, &[(MATRIX, 14)], &scale);
|
||||
let mut w = vec![];
|
||||
assert_eq!(transforms(&b, &p3(), &Limits::default(), &mut w).unwrap().matrix.0[0], 2.0);
|
||||
assert_eq!(w, vec![Warning::Damaged]);
|
||||
// A data offset past the argument, and one that leaves less than a matrix.
|
||||
for at in [5000, 14 + 4] {
|
||||
assert!(transforms(&arg(1, &[(MATRIX, at)], &scale), &p3(), &Limits::default(), &mut vec![]).is_none(), "{at}");
|
||||
}
|
||||
// More entries than a record may have arguments.
|
||||
let many: Vec<(u16, u16)> = vec![(0x99, 0); 100];
|
||||
let limits = Limits { arguments: 8, ..Limits::default() };
|
||||
let mut w = vec![];
|
||||
assert!(transforms(&arg(100, &many, &[]), &p3(), &limits, &mut w).is_some());
|
||||
assert_eq!(w, vec![Warning::Damaged]);
|
||||
for len in 0..4 {
|
||||
assert!(transforms(&b[..len], &p3(), &Limits::default(), &mut vec![]).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// An outline argument: flags, width in 1/1000 inch, black, `dashes`, join, caps, arrowheads.
|
||||
fn outline_arg(flags: u8, count: u8, dashes: &[u8], join: u16, cap: u16, heads: [u32; 2]) -> Vec<u8> {
|
||||
let mut b = vec![flags];
|
||||
b.extend(28i16.to_le_bytes());
|
||||
b.extend([100, 0, 0, 0]);
|
||||
b.extend([1, 0, 0, 0, 100]);
|
||||
b.extend([0; 7]);
|
||||
b.push(count);
|
||||
let mut area = dashes.to_vec();
|
||||
area.resize(DASH_AREA, 0);
|
||||
b.extend(area);
|
||||
b.extend(join.to_le_bytes());
|
||||
b.extend(cap.to_le_bytes());
|
||||
b.extend(heads.iter().flat_map(|h| h.to_le_bytes()));
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outline_reads_its_width_color_dashes_join_and_caps() {
|
||||
let mut w = vec![];
|
||||
let o = outline(&outline_arg(1, 2, &[3, 1], 1, 2, [0, 0]), &p3(), &mut w).unwrap().unwrap();
|
||||
assert!((o.width - 2.016).abs() < 1e-9, "{}", o.width);
|
||||
assert_eq!((o.color, o.join, o.cap, o.dashes), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Join::Round, Cap::Square, vec![3.0, 1.0]));
|
||||
assert!(w.is_empty());
|
||||
// Bit 0 clear: no outline, whatever follows.
|
||||
assert_eq!(outline(&outline_arg(0, 2, &[3, 1], 1, 2, [7, 0]), &p3(), &mut w), Some(None));
|
||||
assert_eq!(outline(&[0], &p3(), &mut w), Some(None));
|
||||
assert!(w.is_empty());
|
||||
outline(&outline_arg(1, 0, &[], 0, 0, [0, 9]), &p3(), &mut w).unwrap().unwrap();
|
||||
assert_eq!(w, vec![Warning::Arrowheads]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dash_count_past_the_dash_bytes_is_held_to_them() {
|
||||
let mut w = vec![];
|
||||
let o = outline(&outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]), &p3(), &mut w).unwrap().unwrap();
|
||||
assert_eq!(o.dashes.len(), DASH_AREA);
|
||||
assert_eq!(w, vec![Warning::Damaged]);
|
||||
// An argument that ends inside the dashes keeps a solid line; one cut before the color is
|
||||
// unreadable.
|
||||
let full = outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]);
|
||||
assert_eq!(outline(&full[..25], &p3(), &mut vec![]).unwrap().unwrap().dashes, Vec::<f64>::new());
|
||||
assert_eq!(outline(&full[..12], &p3(), &mut vec![]).unwrap().unwrap().cap, Cap::Butt);
|
||||
for len in 0..12 {
|
||||
assert!(outline(&full[..len], &p3(), &mut vec![]).is_none(), "{len}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_read_none_uniform_and_other_types() {
|
||||
let mut w = vec![];
|
||||
assert_eq!(fill(&[0], &p3(), &mut w), Some(None));
|
||||
assert_eq!(fill(&[1, 1, 100, 0, 0, 0], &p3(), &mut w), Some(Some(Color::Cmyk([1.0, 0.0, 0.0, 0.0]))));
|
||||
assert!(w.is_empty());
|
||||
for kind in [2, 4, 6, 7, 10] {
|
||||
let mut w = vec![];
|
||||
assert_eq!(fill(&[kind, 0, 0], &p3(), &mut w), Some(None));
|
||||
assert_eq!(w, vec![Warning::UnsupportedFills], "{kind}");
|
||||
}
|
||||
assert_eq!(fill(&[], &p3(), &mut w), None);
|
||||
assert_eq!(fill(&[1, 1, 100], &p3(), &mut w), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//! Where the fields of each record lie, by version: one table, resolved once per file. Each field
|
||||
//! names the `PROVENANCE.md` row it rests on.
|
||||
|
||||
/// The layouts of one range of versions.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Profile {
|
||||
/// Coordinates are i16 in 1/1000 inch, record headers, counts and angles 16-bit (R5, R6, R7).
|
||||
pub(crate) short: bool,
|
||||
/// Bytes before the page size in `mcfg` (R10).
|
||||
pub(crate) mcfg_skip: usize,
|
||||
/// Bytes before a `trfd` entry's type (R8).
|
||||
pub(crate) trfd_head: usize,
|
||||
/// Bytes between a matrix entry's type and its six numbers (R8).
|
||||
pub(crate) matrix_skip: usize,
|
||||
/// Fill and outline records start with tagged records (R11, R12).
|
||||
pub(crate) tagged: bool,
|
||||
/// Outline: bytes after the join, after the stretch, after the nib angle and after the color
|
||||
/// (R12).
|
||||
pub(crate) outl_after_join: usize,
|
||||
pub(crate) outl_after_stretch: usize,
|
||||
pub(crate) outl_after_angle: usize,
|
||||
pub(crate) outl_after_color: usize,
|
||||
/// Where the start marker id lies after the first dash (R13); `None` where no source says.
|
||||
pub(crate) marker_after_dash: Option<usize>,
|
||||
/// Rectangles carry four corner radii, not one (R15).
|
||||
pub(crate) four_radii: bool,
|
||||
/// Rectangles are f64 sizes with radii as shares of half the shorter side (R29).
|
||||
pub(crate) f64_rect: bool,
|
||||
/// The master page flags its guides and desktop layers the way of versions 7 to 13 (R19).
|
||||
pub(crate) old_master_flags: bool,
|
||||
/// Object type 0x25 is a path (R30).
|
||||
pub(crate) paths: bool,
|
||||
/// Names are UTF-16LE, not Windows-1252 (R9).
|
||||
pub(crate) utf16_names: bool,
|
||||
/// An object holds its transform, fill and outline as arguments; there are no `trfd`, `fill`
|
||||
/// or `outl` records (R33, R34, R35).
|
||||
pub(crate) inline_styles: bool,
|
||||
/// Object types count from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4 (R32).
|
||||
pub(crate) types_from_zero: bool,
|
||||
/// How a color is laid out (R14, R36).
|
||||
pub(crate) color: ColorLayout,
|
||||
/// A matrix is six i32 with its factors in 16.16 fixed point, not six f64 (R37).
|
||||
pub(crate) fixed_matrix: bool,
|
||||
/// `mcfg` holds 2 bytes and the page's two corners, not its width and height (R38).
|
||||
pub(crate) mcfg_corners: bool,
|
||||
}
|
||||
|
||||
/// The layouts of a color.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ColorLayout {
|
||||
/// A model byte and four value bytes (R36).
|
||||
Bytes5,
|
||||
/// A model u16, four u16 values and 2 bytes (R36).
|
||||
Words12,
|
||||
/// A model u16, a palette u16, 4 bytes and four value bytes (R14).
|
||||
Record12,
|
||||
}
|
||||
|
||||
const fn profile(from: u16) -> Profile {
|
||||
let short = from < 600;
|
||||
Profile {
|
||||
short,
|
||||
inline_styles: from < 400,
|
||||
types_from_zero: from < 400,
|
||||
color: if from < 400 {
|
||||
ColorLayout::Bytes5
|
||||
} else if from < 500 {
|
||||
ColorLayout::Words12
|
||||
} else {
|
||||
ColorLayout::Record12
|
||||
},
|
||||
fixed_matrix: from < 500,
|
||||
mcfg_corners: from < 400,
|
||||
mcfg_skip: if from >= 1300 {
|
||||
12
|
||||
} else if from >= 900 {
|
||||
4
|
||||
} else if from >= 600 && from < 700 {
|
||||
28
|
||||
} else {
|
||||
0
|
||||
},
|
||||
trfd_head: if from >= 1300 { 8 } else { 0 },
|
||||
matrix_skip: if short { 0 } else { 6 },
|
||||
tagged: from >= 1300,
|
||||
outl_after_join: if from >= 600 && from < 1300 { 2 } else { 0 },
|
||||
outl_after_stretch: if short { 0 } else { 2 },
|
||||
outl_after_angle: if from >= 1300 {
|
||||
46
|
||||
} else if !short {
|
||||
52
|
||||
} else {
|
||||
0
|
||||
},
|
||||
outl_after_color: if short { 10 } else { 16 },
|
||||
marker_after_dash: if from >= 1300 {
|
||||
Some(20)
|
||||
} else if from >= 600 {
|
||||
Some(22)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
four_radii: from >= 900,
|
||||
f64_rect: from >= 1500,
|
||||
old_master_flags: from < 1400,
|
||||
paths: from >= 1000,
|
||||
utf16_names: from >= 1200,
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest version read: 27, as the `vrsn` chunk names it (R1, R2).
|
||||
pub(crate) const NEWEST: u16 = 2799;
|
||||
|
||||
/// The first version of each range, with its layouts. Ranges start where a field moves.
|
||||
const PROFILES: &[(u16, Profile)] = &[
|
||||
(300, profile(300)),
|
||||
(400, profile(400)),
|
||||
(500, profile(500)),
|
||||
(600, profile(600)),
|
||||
(700, profile(700)),
|
||||
(800, profile(800)),
|
||||
(900, profile(900)),
|
||||
(1000, profile(1000)),
|
||||
(1100, profile(1100)),
|
||||
(1200, profile(1200)),
|
||||
(1300, profile(1300)),
|
||||
(1400, profile(1400)),
|
||||
(1500, profile(1500)),
|
||||
(1600, profile(1600)),
|
||||
];
|
||||
|
||||
/// The oldest version of a RIFF file read: 3 (R31). Versions 1 and 2 are not RIFF files (`wl.rs`).
|
||||
pub(crate) const OLDEST_RIFF: u16 = 300;
|
||||
|
||||
/// The layouts of the RIFF file of `version` (hundreds; 801 is the 8.01 variant, 2430 is 24.3), or
|
||||
/// `None` outside 3 to 27.
|
||||
pub(crate) fn for_version(version: u16) -> Option<Profile> {
|
||||
if !(OLDEST_RIFF..=NEWEST).contains(&version) {
|
||||
return None;
|
||||
}
|
||||
PROFILES.iter().rev().find(|(from, _)| *from <= version).map(|(_, p)| *p)
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
/// Points per coordinate unit.
|
||||
pub(crate) fn unit(&self) -> f64 {
|
||||
if self.short { 72.0 / 1000.0 } else { 72.0 / 254_000.0 }
|
||||
}
|
||||
|
||||
/// Bytes of a coordinate, and of header fields and counts.
|
||||
pub(crate) fn word(&self) -> usize {
|
||||
if self.short { 2 } else { 4 }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_version_from_3_to_27_has_one_profile() {
|
||||
assert!(for_version(299).is_none() && for_version(2800).is_none());
|
||||
assert!(for_version(300).is_some_and(|p| p.short && p.inline_styles && p.types_from_zero && p.mcfg_corners && p.fixed_matrix));
|
||||
assert!(for_version(399).is_some_and(|p| p.color == ColorLayout::Bytes5));
|
||||
assert!(for_version(400).is_some_and(|p| p.short && !p.inline_styles && !p.mcfg_corners && p.fixed_matrix));
|
||||
assert!(for_version(499).is_some_and(|p| p.color == ColorLayout::Words12));
|
||||
assert!(for_version(500).is_some_and(|p| !p.fixed_matrix && !p.types_from_zero && p.color == ColorLayout::Record12));
|
||||
assert!(for_version(1300).is_some_and(|p| p.old_master_flags));
|
||||
assert!(for_version(1400).is_some_and(|p| p.tagged && !p.f64_rect && !p.old_master_flags));
|
||||
assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && p.paths));
|
||||
assert!(for_version(2430).is_some_and(|p| p.f64_rect && p.paths && p.utf16_names));
|
||||
assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0 && p.marker_after_dash.is_none()));
|
||||
assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28 && p.marker_after_dash == Some(22)));
|
||||
assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash == Some(22)));
|
||||
assert!(for_version(999).is_some_and(|p| !p.paths && p.marker_after_dash == Some(22)));
|
||||
assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names && p.paths));
|
||||
assert!(for_version(1300).is_some_and(|p| p.tagged && p.trfd_head == 8 && p.outl_after_angle == 46));
|
||||
// The table is in order, so the search finds each range's own row.
|
||||
assert!(PROFILES.windows(2).all(|w| w[0].0 < w[1].0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Reader for `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the `WL` files
|
||||
//! of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, the ZIP
|
||||
//! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups,
|
||||
//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads
|
||||
//! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and
|
||||
//! curves with uniform fills and outlines.
|
||||
//!
|
||||
//! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source
|
||||
//! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not
|
||||
//! panic. Nothing here writes `.cdr` or `.cmx` files.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::fmt;
|
||||
|
||||
mod build;
|
||||
mod bytes;
|
||||
mod cmx;
|
||||
mod geometry;
|
||||
mod inline;
|
||||
mod layout;
|
||||
mod limits;
|
||||
pub mod model;
|
||||
mod package;
|
||||
mod records;
|
||||
mod riff;
|
||||
mod styles;
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
pub mod synth;
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
pub mod synth_cmx;
|
||||
mod wl;
|
||||
mod zip;
|
||||
|
||||
pub use limits::Limits;
|
||||
pub use model::{Drawing, Warning};
|
||||
|
||||
/// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file
|
||||
/// of version 1 or 2 whose header offsets fit the file?
|
||||
pub fn is_cdr(bytes: &[u8]) -> bool {
|
||||
riff::is_cdr_riff(bytes) || package::is_package(bytes) || wl::is_wl(bytes)
|
||||
}
|
||||
|
||||
/// Does `bytes` start as a `.cmx` exchange file: a RIFF form (or its big-endian RIFX form) of type
|
||||
/// `CMX1`?
|
||||
pub fn is_cmx(bytes: &[u8]) -> bool {
|
||||
cmx::is_cmx(bytes)
|
||||
}
|
||||
|
||||
/// Why a file can't be read.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// Not a `.cdr` drawing.
|
||||
NotCdr,
|
||||
/// Not a `.cmx` file.
|
||||
NotCmx,
|
||||
/// A drawing of a version this reader doesn't read (hundreds: 2800 is version 28).
|
||||
Version(u16),
|
||||
/// A container structure that doesn't parse.
|
||||
Damaged(&'static str),
|
||||
/// Past one of the [`Limits`].
|
||||
Limit(&'static str),
|
||||
/// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that
|
||||
/// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates.
|
||||
Unsupported(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Error::NotCdr => write!(f, "not a CDR drawing"),
|
||||
Error::NotCmx => write!(f, "not a CMX file"),
|
||||
Error::Version(v) => write!(f, "version {} drawings are not read", v / 100),
|
||||
Error::Damaged(what) => write!(f, "damaged {what}"),
|
||||
Error::Limit(what) => write!(f, "past the {what} limit"),
|
||||
Error::Unsupported(what) => write!(f, "{what} are not read"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// Read a drawing within `limits`.
|
||||
pub fn read(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
if bytes.len() > limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
let mut budget = limits::Budget::new(limits);
|
||||
// Versions 1 and 2 are not RIFF files (R40).
|
||||
if wl::is_wl(bytes) {
|
||||
return wl::drawing(bytes, &mut budget);
|
||||
}
|
||||
let mut warnings = Vec::new();
|
||||
// Versions 14 on save a ZIP package around the RIFF stream (R24, R25, R26).
|
||||
let (stream, streams) = if zip::is_zip(bytes) { package::open(bytes, &mut budget)? } else { (std::borrow::Cow::Borrowed(bytes), None) };
|
||||
let ix = riff::Index::build(&stream, streams, &mut budget, &mut warnings)?;
|
||||
let mut drawing = build::drawing(&ix, &mut budget, &mut warnings)?;
|
||||
ix.stream_warnings(&mut drawing.warnings);
|
||||
Ok(drawing)
|
||||
}
|
||||
|
||||
/// Read a `.cmx` exchange file within `limits`. Files in big-endian byte order and files with
|
||||
/// 16-bit coordinates are refused with [`Error::Unsupported`]. Its [`Drawing::version`] is 0.
|
||||
pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
if bytes.len() > limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
let mut budget = limits::Budget::new(limits);
|
||||
cmx::drawing(bytes, &mut budget)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! What one read may take. The values are VectorCraft's own; wasm32 gets half the memory limits.
|
||||
|
||||
use crate::Error;
|
||||
|
||||
/// The most a read may take, checked before every allocation and descent.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
/// Bytes of input.
|
||||
pub input: usize,
|
||||
/// Bytes inflated from compressed lists and package members, all of one file together.
|
||||
pub inflated: usize,
|
||||
/// Bytes of one package member.
|
||||
pub member: usize,
|
||||
/// Members of a package.
|
||||
pub members: usize,
|
||||
/// Nested lists below the file's own. Deeper content is left out with a warning.
|
||||
pub depth: usize,
|
||||
/// Chunks in the index, nested ones included, and the entries and styles of the style table;
|
||||
/// in a `.cmx` file, its chunks, table entries and page instructions.
|
||||
pub chunks: usize,
|
||||
/// Objects mapped (shapes, groups and guidelines).
|
||||
pub objects: usize,
|
||||
/// Points of all curves together.
|
||||
pub coordinates: usize,
|
||||
/// Arguments of one `loda` record.
|
||||
pub arguments: usize,
|
||||
/// Dashes of all outlines together, an outline's counted again for every shape that uses it.
|
||||
/// Past them a shape's outline is solid, with a warning.
|
||||
pub dashes: usize,
|
||||
/// Chunks walked inside clipped groups, all containers together, a group's counted again for
|
||||
/// every container that names it. Past them a container's group is left out, with a warning.
|
||||
pub clipped_chunks: usize,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MIB: usize = 1 << 20;
|
||||
|
||||
impl Default for Limits {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
input: 512 * MIB,
|
||||
inflated: 1024 * MIB,
|
||||
member: 512 * MIB,
|
||||
members: 4096,
|
||||
depth: 256,
|
||||
chunks: 2_000_000,
|
||||
objects: 1_000_000,
|
||||
coordinates: 16_000_000,
|
||||
arguments: 64,
|
||||
dashes: 16_000_000,
|
||||
clipped_chunks: 2_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
input: 256 << 20,
|
||||
inflated: 512 << 20,
|
||||
member: 256 << 20,
|
||||
members: 4096,
|
||||
depth: 256,
|
||||
chunks: 2_000_000,
|
||||
objects: 1_000_000,
|
||||
coordinates: 16_000_000,
|
||||
arguments: 64,
|
||||
dashes: 8_000_000,
|
||||
clipped_chunks: 2_000_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The running counters of one read against its [`Limits`].
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Budget {
|
||||
pub(crate) limits: Limits,
|
||||
inflated: usize,
|
||||
chunks: usize,
|
||||
objects: usize,
|
||||
coordinates: usize,
|
||||
dashes: usize,
|
||||
clipped_chunks: usize,
|
||||
/// A request for coordinates was refused since [`Budget::coordinates_refused`] last asked.
|
||||
refused: bool,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
pub(crate) fn new(limits: Limits) -> Self {
|
||||
Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, clipped_chunks: 0, refused: false }
|
||||
}
|
||||
|
||||
/// Whether a request for coordinates was refused since the last call, which tells a shape
|
||||
/// left out at the limit from one whose bytes don't parse.
|
||||
pub(crate) fn coordinates_refused(&mut self) -> bool {
|
||||
std::mem::take(&mut self.refused)
|
||||
}
|
||||
|
||||
/// Bytes an inflate may still produce.
|
||||
pub(crate) fn inflate_left(&self) -> usize {
|
||||
self.limits.inflated.saturating_sub(self.inflated)
|
||||
}
|
||||
|
||||
pub(crate) fn take_inflated(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.inflated = self.inflated.checked_add(n).filter(|&t| t <= self.limits.inflated).ok_or(Error::Limit("inflated size"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn take_chunk(&mut self) -> Result<(), Error> {
|
||||
self.take_chunks(1)
|
||||
}
|
||||
|
||||
/// `n` more chunks or style table entries.
|
||||
pub(crate) fn take_chunks(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.chunks = self.chunks.saturating_add(n);
|
||||
if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// One more object, or `false` when the drawing already holds as many as a read maps.
|
||||
pub(crate) fn take_object(&mut self) -> bool {
|
||||
if self.objects >= self.limits.objects {
|
||||
return false;
|
||||
}
|
||||
self.objects += 1;
|
||||
true
|
||||
}
|
||||
|
||||
/// `n` more curve points, or `false` past the limit (nothing is taken then).
|
||||
pub(crate) fn take_coordinates(&mut self, n: usize) -> bool {
|
||||
match self.coordinates.checked_add(n).filter(|&t| t <= self.limits.coordinates) {
|
||||
Some(t) => {
|
||||
self.coordinates = t;
|
||||
true
|
||||
}
|
||||
None => {
|
||||
self.refused = true;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dashes the read may still take.
|
||||
pub(crate) fn dashes_left(&self) -> usize {
|
||||
self.limits.dashes.saturating_sub(self.dashes)
|
||||
}
|
||||
|
||||
/// `n` more dashes, or `false` past the limit (nothing is taken then).
|
||||
pub(crate) fn take_dashes(&mut self, n: usize) -> bool {
|
||||
match self.dashes.checked_add(n).filter(|&t| t <= self.limits.dashes) {
|
||||
Some(t) => {
|
||||
self.dashes = t;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One more chunk walked inside a clipped group, or `false` past the limit.
|
||||
pub(crate) fn take_clipped_chunk(&mut self) -> bool {
|
||||
if self.clipped_chunks >= self.limits.clipped_chunks {
|
||||
return false;
|
||||
}
|
||||
self.clipped_chunks += 1;
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! What a drawing reads as. Lengths are in points (1/72 inch), from the centre of the page, with y
|
||||
//! pointing up, as the file stores them.
|
||||
|
||||
/// A point in points.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Pt {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
}
|
||||
|
||||
/// An affine map `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Matrix(pub [f64; 6]);
|
||||
|
||||
impl Matrix {
|
||||
pub const IDENTITY: Matrix = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
|
||||
/// `self` after `first`: the map that applies `first`, then `self`.
|
||||
pub fn after(&self, first: &Matrix) -> Matrix {
|
||||
let [a, b, c, d, e, f] = self.0;
|
||||
let [p, q, r, s, t, u] = first.0;
|
||||
Matrix([a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f])
|
||||
}
|
||||
|
||||
pub fn apply(&self, p: Pt) -> Pt {
|
||||
let [a, b, c, d, e, f] = self.0;
|
||||
Pt { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f }
|
||||
}
|
||||
}
|
||||
|
||||
/// One segment after the previous point.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Segment {
|
||||
Line(Pt),
|
||||
/// Two control points, then the end point.
|
||||
Cubic(Pt, Pt, Pt),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SubPath {
|
||||
pub start: Pt,
|
||||
pub segments: Vec<Segment>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Path {
|
||||
pub subpaths: Vec<SubPath>,
|
||||
}
|
||||
|
||||
/// The shape of an object, in its own space ([`Shape::matrix`] places it).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Geometry {
|
||||
Path(Path),
|
||||
/// A rectangle from the origin to (`w`, `h`) (either may be negative). `radii` round its
|
||||
/// corners counterclockwise from the one at (`w`, 0): (`w`, 0), (`w`, `h`), (0, `h`), (0, 0).
|
||||
Rect {
|
||||
w: f64,
|
||||
h: f64,
|
||||
radii: [f64; 4],
|
||||
},
|
||||
/// A whole ellipse in the box from the origin to (`w`, `h`).
|
||||
Ellipse {
|
||||
w: f64,
|
||||
h: f64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Color {
|
||||
Rgb([f32; 3]),
|
||||
Cmyk([f32; 4]),
|
||||
/// Ink: 0 is white, 1 black.
|
||||
Gray(f32),
|
||||
/// Every ink at full strength.
|
||||
Registration,
|
||||
/// A color of a named library, printed on its own plate. `look` is its full-strength color
|
||||
/// when the file stores one (an approximation in sRGB); `tint` is 0 to 1.
|
||||
Spot {
|
||||
name: String,
|
||||
tint: f32,
|
||||
look: Option<[f32; 3]>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Cap {
|
||||
Butt,
|
||||
Round,
|
||||
Square,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Join {
|
||||
Miter,
|
||||
Round,
|
||||
Bevel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Outline {
|
||||
pub width: f64,
|
||||
pub color: Color,
|
||||
pub cap: Cap,
|
||||
pub join: Join,
|
||||
/// Dash and gap lengths, in outline widths; empty for a solid line.
|
||||
pub dashes: Vec<f64>,
|
||||
/// Drawn behind the fill, so that a filled shape shows only the outer half of it.
|
||||
pub behind_fill: bool,
|
||||
/// Scaled with the shape: the shape's matrix scales the width and dashes as it scales the
|
||||
/// geometry.
|
||||
pub scale_with: bool,
|
||||
}
|
||||
|
||||
/// Whether a layer, group or shape is hidden or locked.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Flags {
|
||||
pub hidden: bool,
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
/// How a shape's colors combine with the art below it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Blend {
|
||||
#[default]
|
||||
Normal,
|
||||
Multiply,
|
||||
Screen,
|
||||
Overlay,
|
||||
SoftLight,
|
||||
HardLight,
|
||||
ColorDodge,
|
||||
ColorBurn,
|
||||
Darken,
|
||||
Lighten,
|
||||
Difference,
|
||||
Exclusion,
|
||||
Hue,
|
||||
Saturation,
|
||||
Color,
|
||||
Luminosity,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Shape {
|
||||
pub geometry: Geometry,
|
||||
pub matrix: Matrix,
|
||||
pub fill: Option<Color>,
|
||||
pub outline: Option<Outline>,
|
||||
/// The fill covers every area its subpaths wind around (nonzero); otherwise subpaths that
|
||||
/// overlap leave holes (even-odd).
|
||||
pub nonzero: bool,
|
||||
/// 1 opaque, 0 clear.
|
||||
pub opacity: f32,
|
||||
pub blend: Blend,
|
||||
pub flags: Flags,
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
/// An opaque, shown shape filled even-odd.
|
||||
pub fn new(geometry: Geometry, matrix: Matrix, fill: Option<Color>, outline: Option<Outline>) -> Shape {
|
||||
Shape { geometry, matrix, fill, outline, nonzero: false, opacity: 1.0, blend: Blend::Normal, flags: Flags::default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Object {
|
||||
Shape(Box<Shape>),
|
||||
Group {
|
||||
objects: Vec<Object>,
|
||||
flags: Flags,
|
||||
},
|
||||
/// A clipping container and the objects it clips: `objects` (front to back) show only
|
||||
/// inside the container's shape, with its fill behind them and its outline over them.
|
||||
Clip {
|
||||
container: Box<Shape>,
|
||||
objects: Vec<Object>,
|
||||
},
|
||||
}
|
||||
|
||||
/// A guideline through `at`, at `angle` degrees counterclockwise from horizontal.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Guideline {
|
||||
pub at: Pt,
|
||||
pub angle: f64,
|
||||
/// The guideline, a group around it or its layer is hidden.
|
||||
pub hidden: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LayerKind {
|
||||
Drawing,
|
||||
/// The objects left beside the pages.
|
||||
Desktop,
|
||||
Guides,
|
||||
Grid,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Layer {
|
||||
pub name: String,
|
||||
pub kind: LayerKind,
|
||||
pub flags: Flags,
|
||||
/// Front to back, as the file lists them.
|
||||
pub objects: Vec<Object>,
|
||||
pub guides: Vec<Guideline>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Page {
|
||||
/// Width and height in points, when the page gives its own.
|
||||
pub size: Option<(f64, f64)>,
|
||||
/// Front to back, as the file lists them.
|
||||
pub layers: Vec<Layer>,
|
||||
}
|
||||
|
||||
/// What was left out or changed while reading. Each kind is listed once.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Warning {
|
||||
/// Text, bitmaps, splines and other objects not read yet.
|
||||
UnsupportedObjects,
|
||||
/// Fountain, pattern, texture and PostScript fills.
|
||||
UnsupportedFills,
|
||||
/// Colors in models not read; shown black.
|
||||
UnknownColors,
|
||||
/// Library spot colors whose look the file doesn't store; shown black.
|
||||
SpotLooks,
|
||||
/// Outline arrowheads.
|
||||
Arrowheads,
|
||||
/// Envelopes, which are not applied: the shapes under them keep their outlines.
|
||||
Envelopes,
|
||||
/// Lenses, and object transparency that isn't read, which are not applied: the objects show
|
||||
/// opaque.
|
||||
Lenses,
|
||||
/// Content nested deeper, or past the counts, that a read takes.
|
||||
TooDeep,
|
||||
/// Chunks or records that end early or don't parse.
|
||||
Damaged,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Drawing {
|
||||
/// In hundreds, as a RIFF file stores it: 300 to 2799. A file of version 1 or 2 stores no
|
||||
/// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. A
|
||||
/// `.cmx` file gives 0.
|
||||
pub version: u16,
|
||||
/// Page size from the document settings, in points.
|
||||
pub page_size: Option<(f64, f64)>,
|
||||
pub pages: Vec<Page>,
|
||||
/// Layers every page shows, from the master page.
|
||||
pub master: Vec<Layer>,
|
||||
/// Guidelines every page shows, kept outside any layer.
|
||||
pub guides: Vec<Guideline>,
|
||||
pub warnings: Vec<Warning>,
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! The packages of versions 14 on (R25, R26): a ZIP archive holding the RIFF stream as
|
||||
//! `content/riffData.cdr` (14 and 15), or as `content/root.dat` with its chunk bodies in the data
|
||||
//! streams that `content/dataFileList.dat` names (16 on). A data stream is inflated only when a
|
||||
//! chunk the reader reads, or a list it splits, points into it.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::{Cell, OnceCell};
|
||||
|
||||
use crate::limits::{Budget, Limits};
|
||||
use crate::riff::push;
|
||||
use crate::zip::{self, Archive};
|
||||
use crate::{Error, Warning};
|
||||
|
||||
const RIFF_DATA: &[u8] = b"content/riffData.cdr";
|
||||
const ROOT: &[u8] = b"content/root.dat";
|
||||
const DATA_FILE_LIST: &[u8] = b"content/dataFileList.dat";
|
||||
const DATA_DIR: &[u8] = b"content/data/";
|
||||
|
||||
/// Is `bytes` a ZIP archive with a `.cdr` drawing's root stream?
|
||||
pub(crate) fn is_package(bytes: &[u8]) -> bool {
|
||||
zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| a.find(RIFF_DATA).or_else(|| a.find(ROOT)).is_some())
|
||||
}
|
||||
|
||||
/// The RIFF stream of the package `bytes`, and its data streams when it has them (16 on).
|
||||
pub(crate) fn open<'a>(bytes: &'a [u8], budget: &mut Budget) -> Result<(Cow<'a, [u8]>, Option<Streams<'a>>), Error> {
|
||||
let zip = Archive::open(bytes, budget.limits.members)?;
|
||||
if let Some(i) = zip.find(RIFF_DATA) {
|
||||
return Ok((member(&zip, i, budget)?, None));
|
||||
}
|
||||
let root = zip.find(ROOT).ok_or(Error::NotCdr)?;
|
||||
let root = member(&zip, root, budget)?;
|
||||
let list = match zip.find(DATA_FILE_LIST) {
|
||||
Some(i) => member(&zip, i, budget)?,
|
||||
None => Cow::Borrowed(&[][..]),
|
||||
};
|
||||
// One name for each line; a line feed after the last name ends it.
|
||||
let list = list.strip_suffix(b"\n").unwrap_or(&list);
|
||||
let mut members = Vec::new();
|
||||
if !list.is_empty() {
|
||||
for line in list.split(|&b| b == b'\n') {
|
||||
if members.len() == budget.limits.members {
|
||||
return Err(Error::Limit("package member count"));
|
||||
}
|
||||
let name = line.strip_suffix(b"\r").unwrap_or(line);
|
||||
let found = zip.find(&[DATA_DIR, name].concat());
|
||||
// A data stream that is encrypted or packed some other way refuses the file, as the
|
||||
// root stream does.
|
||||
if let Some(i) = found {
|
||||
zip.check(i)?;
|
||||
}
|
||||
members.push(found);
|
||||
}
|
||||
}
|
||||
let loaded = (0..zip.count()).map(|_| OnceCell::new()).collect();
|
||||
let streams = Streams { zip, members, loaded, member_limit: budget.limits.member, damaged: Cell::new(false) };
|
||||
Ok((root, Some(streams)))
|
||||
}
|
||||
|
||||
/// Member `i` within the member limit and, when deflated, what is left to inflate.
|
||||
fn member<'a>(zip: &Archive<'a>, i: usize, budget: &mut Budget) -> Result<Cow<'a, [u8]>, Error> {
|
||||
let m = zip.read(i, budget.limits.member, budget.inflate_left())?;
|
||||
if let Cow::Owned(v) = &m {
|
||||
budget.take_inflated(v.len())?;
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// What reading one package member gave.
|
||||
#[derive(Debug)]
|
||||
enum Slot<'a> {
|
||||
Read(Cow<'a, [u8]>),
|
||||
Damaged,
|
||||
PastLimit,
|
||||
}
|
||||
|
||||
/// The data streams of a version 16+ package, in `dataFileList.dat` order (R26).
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Streams<'a> {
|
||||
zip: Archive<'a>,
|
||||
/// The member holding each stream; `None` when the archive lacks it.
|
||||
members: Vec<Option<usize>>,
|
||||
/// Each member's bytes once read, so that streams naming one member read it once.
|
||||
loaded: Vec<OnceCell<Slot<'a>>>,
|
||||
member_limit: usize,
|
||||
/// A stream, or a chunk's bytes in one, could not be found.
|
||||
damaged: Cell<bool>,
|
||||
}
|
||||
|
||||
impl<'a> Streams<'a> {
|
||||
/// The member holding stream `s`; `None` when there is no such stream.
|
||||
pub(crate) fn member_of(&self, s: usize) -> Option<usize> {
|
||||
*self.members.get(s)?
|
||||
}
|
||||
|
||||
/// The size the archive gives stream `s`; `None` when there is no such stream.
|
||||
pub(crate) fn size(&self, s: usize) -> Option<usize> {
|
||||
Some(self.zip.size(self.member_of(s)?))
|
||||
}
|
||||
|
||||
/// Stream `s`, its member read on first use within the member limit and, when deflated,
|
||||
/// within `left` more inflated bytes (which it takes from).
|
||||
pub(crate) fn get(&self, s: usize, left: &Cell<usize>) -> Option<&[u8]> {
|
||||
let Some(i) = self.member_of(s) else {
|
||||
self.damaged.set(true);
|
||||
return None;
|
||||
};
|
||||
let slot = self.loaded.get(i)?.get_or_init(|| {
|
||||
let read = self.zip.read(i, self.member_limit, left.get());
|
||||
if !matches!(read, Err(Error::Limit(_))) {
|
||||
left.set(left.get().saturating_sub(self.zip.inflate_cost(i)));
|
||||
}
|
||||
match read {
|
||||
Ok(b) => Slot::Read(b),
|
||||
Err(Error::Limit(_)) => Slot::PastLimit,
|
||||
Err(_) => {
|
||||
self.damaged.set(true);
|
||||
Slot::Damaged
|
||||
}
|
||||
}
|
||||
});
|
||||
match slot {
|
||||
Slot::Read(b) => Some(b.as_ref()),
|
||||
Slot::Damaged | Slot::PastLimit => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Was stream `s` left out because it is past a limit? Chunks in it are then not damage.
|
||||
pub(crate) fn past_limit(&self, s: usize) -> bool {
|
||||
let slot = self.member_of(s).and_then(|i| self.loaded.get(i)).and_then(OnceCell::get);
|
||||
matches!(slot, Some(Slot::PastLimit))
|
||||
}
|
||||
|
||||
/// Mark a chunk whose stream bytes could not be found.
|
||||
pub(crate) fn note_damage(&self) {
|
||||
self.damaged.set(true);
|
||||
}
|
||||
|
||||
/// The warnings for streams that were left out.
|
||||
pub(crate) fn warnings(&self, warn: &mut Vec<Warning>) {
|
||||
if self.damaged.get() {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
if self.loaded.iter().any(|s| matches!(s.get(), Some(Slot::PastLimit))) {
|
||||
push(warn, Warning::TooDeep);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Hand-written decoders of the records a drawing's objects refer to: the `loda` argument table
|
||||
//! (R6), transforms (R8), colors (R14), fills (R11) and outlines (R12, R13).
|
||||
|
||||
use crate::bytes::Rd;
|
||||
use crate::layout::{ColorLayout, Profile};
|
||||
use crate::model::{Blend, Cap, Color, Join, Matrix, Outline};
|
||||
use crate::riff::push;
|
||||
use crate::{Limits, Warning};
|
||||
|
||||
/// The tag of a record's current layout in tagged files (R11, R12).
|
||||
const TAG_1300: u32 = 1300;
|
||||
/// The most tagged records skipped before a fill's own (R11).
|
||||
const MAX_SKIPPED: usize = 4;
|
||||
/// The most records skipped before an outline's own (R12).
|
||||
const MAX_OUTLINE_RECORDS: usize = 16;
|
||||
/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of
|
||||
/// a layer's.
|
||||
const MAX_NAME: usize = 256;
|
||||
|
||||
/// A header field: u16 in short files, u32 otherwise.
|
||||
fn word(r: &mut Rd, p: &Profile) -> Option<usize> {
|
||||
if p.short { r.u16().map(usize::from) } else { r.u32().map(|v| v as usize) }
|
||||
}
|
||||
|
||||
/// A coordinate in points.
|
||||
pub(crate) fn coord(r: &mut Rd, p: &Profile) -> Option<f64> {
|
||||
let raw = if p.short { f64::from(r.i16()?) } else { f64::from(r.i32()?) };
|
||||
Some(raw * p.unit())
|
||||
}
|
||||
|
||||
/// An angle in degrees: tenths in short files, millionths otherwise (R7).
|
||||
pub(crate) fn angle(r: &mut Rd, p: &Profile) -> Option<f64> {
|
||||
if p.short { Some(f64::from(r.i16()?) / 10.0) } else { Some(f64::from(r.i32()?) / 1_000_000.0) }
|
||||
}
|
||||
|
||||
/// A `loda` record (R6): its object type and arguments as (type, bytes).
|
||||
pub(crate) struct Loda<'a> {
|
||||
pub(crate) kind: u32,
|
||||
pub(crate) args: Vec<(u32, &'a [u8])>,
|
||||
}
|
||||
|
||||
impl<'a> Loda<'a> {
|
||||
pub(crate) fn arg(&self, kind: u32) -> Option<&'a [u8]> {
|
||||
self.args.iter().find(|(k, _)| *k == kind).map(|(_, b)| *b)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec<Warning>) -> Option<Loda<'a>> {
|
||||
let mut r = Rd::new(b);
|
||||
let (_len, count, offsets_at, types_at, kind) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?);
|
||||
// The types table is indexed from the stored count, however many arguments are read.
|
||||
let stored = count;
|
||||
let count = if count > limits.arguments {
|
||||
push(warn, Warning::Damaged);
|
||||
limits.arguments
|
||||
} else {
|
||||
count
|
||||
};
|
||||
let mut offsets = Vec::with_capacity(count + 1);
|
||||
let mut ro = Rd::at(b, offsets_at);
|
||||
for _ in 0..=count {
|
||||
offsets.push(word(&mut ro, p)?);
|
||||
}
|
||||
let mut args = Vec::with_capacity(count);
|
||||
for i in 0..count {
|
||||
// The types table runs the other way: offset i pairs with type stored - 1 - i.
|
||||
let kind = word(&mut Rd::at(b, types_at.checked_add((stored - 1 - i).checked_mul(p.word())?)?), p)? as u32;
|
||||
let (start, end) = (*offsets.get(i)?, *offsets.get(i + 1)?);
|
||||
match b.get(start..end) {
|
||||
Some(body) => args.push((kind, body)),
|
||||
None => push(warn, Warning::Damaged),
|
||||
}
|
||||
}
|
||||
Some(Loda { kind: kind as u32, args })
|
||||
}
|
||||
|
||||
/// The matrices of a `trfd` record composed in file order, in points (R8). Each entry ends where
|
||||
/// the next offset points, and the last at the offset after it (R51); an entry too short for its
|
||||
/// matrix makes the record unreadable.
|
||||
pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option<Matrix> {
|
||||
let mut r = Rd::new(b);
|
||||
let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?);
|
||||
let mut m = Matrix::IDENTITY;
|
||||
let k = p.unit();
|
||||
// Each entry takes at least its offset's bytes, which bounds the count by the record's size.
|
||||
for i in 0..count.min(b.len() / p.word()) {
|
||||
let slot = offsets_at.checked_add(i.checked_mul(p.word())?)?;
|
||||
let start = word(&mut Rd::at(b, slot), p)?;
|
||||
// A table that stops before the last entry's end offset leaves that entry the rest of the
|
||||
// record.
|
||||
let end = word(&mut Rd::at(b, slot.checked_add(p.word())?), p).unwrap_or(b.len());
|
||||
let mut e = Rd::at(b.get(start..end)?, p.trfd_head);
|
||||
if e.u16()? != 8 {
|
||||
continue;
|
||||
}
|
||||
e.skip(p.matrix_skip)?;
|
||||
let next = if p.fixed_matrix {
|
||||
fixed_matrix(&mut e, k)?
|
||||
} else {
|
||||
let (a, c, tx, bb, d, ty) = (e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?);
|
||||
Matrix([a, bb, c, d, tx * k, ty * k])
|
||||
};
|
||||
m = next.after(&m);
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// A number in 16.16 fixed point.
|
||||
pub(crate) fn fixed(r: &mut Rd) -> Option<f64> {
|
||||
Some(f64::from(r.i32()?) / 65536.0)
|
||||
}
|
||||
|
||||
/// A matrix of versions 3 and 4 (R37): six i32 `a c tx b d ty`, the factors in 16.16 fixed point
|
||||
/// and `tx` and `ty` in coordinate units of `k` points.
|
||||
pub(crate) fn fixed_matrix(r: &mut Rd, k: f64) -> Option<Matrix> {
|
||||
let (a, c, tx) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?));
|
||||
let (b, d, ty) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?));
|
||||
Some(Matrix([a, b, c, d, tx * k, ty * k]))
|
||||
}
|
||||
|
||||
/// A color in the layout of the file's version (R14, R36). Unknown models read as black with a
|
||||
/// warning.
|
||||
pub(crate) fn color(r: &mut Rd, p: &Profile, warn: &mut Vec<Warning>) -> Option<Color> {
|
||||
match p.color {
|
||||
ColorLayout::Record12 => {
|
||||
let model = r.u16()?;
|
||||
let palette = r.u16()?;
|
||||
r.skip(4)?;
|
||||
let v: [u8; 4] = r.bytes(4)?.try_into().ok()?;
|
||||
Some(model_color(model, palette, v, warn))
|
||||
}
|
||||
ColorLayout::Words12 => {
|
||||
let model = r.u16()?;
|
||||
let w = [r.u16()?, r.u16()?, r.u16()?, r.u16()?];
|
||||
r.skip(2)?;
|
||||
// The models take 8-bit values, as in the other layouts; a larger value reads as 255.
|
||||
Some(early_color(model, w.map(|x| u8::try_from(x).unwrap_or(u8::MAX)), w[0], w[1], warn))
|
||||
}
|
||||
ColorLayout::Bytes5 => Some(color5(r.bytes(5)?.try_into().ok()?, warn)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 5-byte color (R36): a model byte and four value bytes.
|
||||
pub(crate) fn color5(b: [u8; 5], warn: &mut Vec<Warning>) -> Color {
|
||||
let [model, v @ ..] = b;
|
||||
early_color(u16::from(model), v, u16::from_le_bytes([v[0], v[1]]), u16::from_le_bytes([v[2], v[3]]), warn)
|
||||
}
|
||||
|
||||
/// A color of versions 1 to 4 (R36). Model 1 is CMYK in percent. Model 0 is a numbered ink and
|
||||
/// its tint in percent: 0 is black, 1 is white, and other numbers are inks of a library the file
|
||||
/// doesn't store. Other models read as in later versions.
|
||||
fn early_color(model: u16, v: [u8; 4], index: u16, tint: u16, warn: &mut Vec<Warning>) -> Color {
|
||||
let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0);
|
||||
match (model, index) {
|
||||
(1, _) => Color::Cmyk(v.map(|x| pct(f32::from(x)))),
|
||||
(0, 0) => Color::Gray(pct(f32::from(tint))),
|
||||
(0, 1) => Color::Gray(0.0),
|
||||
(0, number) => {
|
||||
push(warn, Warning::SpotLooks);
|
||||
Color::Spot { name: format!("Spot 0:{number}"), tint: pct(f32::from(tint)), look: None }
|
||||
}
|
||||
_ => model_color(model, 0, v, warn),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color of `model` with the four value bytes `v`, from version 5 (R14).
|
||||
fn model_color(model: u16, palette: u16, v: [u8; 4], warn: &mut Vec<Warning>) -> Color {
|
||||
let (v0, v1, v2, v3) = (f32::from(v[0]), f32::from(v[1]), f32::from(v[2]), f32::from(v[3]));
|
||||
let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0);
|
||||
let byte = |x: f32| x / 255.0;
|
||||
match model {
|
||||
2 => Color::Cmyk([pct(v0), pct(v1), pct(v2), pct(v3)]),
|
||||
3 | 17 => Color::Cmyk([byte(v0), byte(v1), byte(v2), byte(v3)]),
|
||||
4 => Color::Cmyk([byte(v0), byte(v1), byte(v2), 0.0]),
|
||||
5 | 21 => Color::Rgb([byte(v2), byte(v1), byte(v0)]),
|
||||
9 => Color::Gray(1.0 - byte(v0)),
|
||||
20 => Color::Registration,
|
||||
1 | 14 | 25 => {
|
||||
let number = u16::from_le_bytes([v[0], v[1]]);
|
||||
let tint = pct(f32::from(u16::from_le_bytes([v[2], v[3]])));
|
||||
push(warn, Warning::SpotLooks);
|
||||
// Each library numbers its own colors: the name holds the palette and the number.
|
||||
Color::Spot { name: format!("Spot {palette}:{number}"), tint, look: None }
|
||||
}
|
||||
_ => {
|
||||
push(warn, Warning::UnknownColors);
|
||||
Color::Rgb([0.0; 3])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A UTF-16 name stored as a character count and its code units. Every shape that uses the color
|
||||
/// gets its own copy of the name: a name longer than [`MAX_NAME`] units keeps its first ones and a
|
||||
/// hash of the whole name, with a warning, so two long names that start alike stay apart.
|
||||
fn counted_utf16(r: &mut Rd, warn: &mut Vec<Warning>) -> Option<String> {
|
||||
let n = r.u32()? as usize;
|
||||
let b = r.bytes(n.checked_mul(2)?)?;
|
||||
// Trailing NULs are padding.
|
||||
let all = b.as_chunks::<2>().0;
|
||||
let all = all.get(..all.iter().rposition(|c| *c != [0, 0]).map_or(0, |i| i + 1)).unwrap_or_default();
|
||||
let units = all.iter().map(|c| u16::from_le_bytes(*c));
|
||||
if all.len() <= MAX_NAME {
|
||||
let units: Vec<u16> = units.collect();
|
||||
return Some(String::from_utf16_lossy(&units));
|
||||
}
|
||||
push(warn, Warning::TooDeep);
|
||||
// FNV-1a over the code units.
|
||||
let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u64::from(u)).wrapping_mul(0x0100_0000_01b3));
|
||||
let kept: Vec<u16> = units.take(MAX_NAME).collect();
|
||||
Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept)))
|
||||
}
|
||||
|
||||
/// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color
|
||||
/// record, named by the library name it carries.
|
||||
pub(crate) fn property_color(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Color> {
|
||||
let mut r = Rd::new(b);
|
||||
let (mut found, mut name) = (None, None);
|
||||
while r.left() >= 5 {
|
||||
let kind = r.u8()?;
|
||||
let len = r.u32()? as usize;
|
||||
if kind == 0 {
|
||||
break;
|
||||
}
|
||||
let body = r.bytes(len)?;
|
||||
let mut br = Rd::new(body);
|
||||
match kind {
|
||||
1 => found = color(&mut br, p, warn),
|
||||
8 => name = br.skip(16).and_then(|_| counted_utf16(&mut br, warn)),
|
||||
3 => name = name.or_else(|| counted_utf16(&mut br, warn)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match (found?, name.filter(|n| !n.is_empty())) {
|
||||
// A library color with its name: the record's sRGB has the tint applied already.
|
||||
(Color::Rgb(rgb), Some(name)) => {
|
||||
let tint = b_tint(b).unwrap_or(1.0);
|
||||
Some(Color::Spot { name, tint, look: Some(untinted(rgb, tint)) })
|
||||
}
|
||||
(c, _) => Some(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tint byte of the first color property of a property list (model 21 keeps it last).
|
||||
fn b_tint(b: &[u8]) -> Option<f32> {
|
||||
let mut r = Rd::new(b);
|
||||
while r.left() >= 5 {
|
||||
let kind = r.u8()?;
|
||||
let len = r.u32()? as usize;
|
||||
let body = r.bytes(len)?;
|
||||
if kind == 1 {
|
||||
let mut c = Rd::new(body);
|
||||
return (c.u16()? == 21).then(|| f32::from(*body.get(11).unwrap_or(&100)) / 100.0).map(|t| t.clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white).
|
||||
fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
|
||||
if tint <= 0.0 {
|
||||
return rgb;
|
||||
}
|
||||
rgb.map(|v| (1.0 - (1.0 - v) / tint).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// A fill record: its id, and its color (`None`: no fill). Fills of other kinds read as none with
|
||||
/// a warning (R11).
|
||||
pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<(u32, Option<Color>)> {
|
||||
let mut r = Rd::new(b);
|
||||
let id = r.u32()?;
|
||||
let body = if p.tagged { tagged_body(&mut r)? } else { r.bytes(r.left())? };
|
||||
let mut r = Rd::new(body);
|
||||
let kind = r.u16()?;
|
||||
let color = match kind {
|
||||
0 => None,
|
||||
1 if p.tagged => {
|
||||
if r.u32()? != TAG_1300 {
|
||||
push(warn, Warning::Damaged);
|
||||
return Some((id, None));
|
||||
}
|
||||
// A uniform fill whose color can't be read is damage, not a fill of none.
|
||||
let len = r.u32()? as usize;
|
||||
Some(property_color(r.bytes(len.min(r.left()))?, p, warn)?)
|
||||
}
|
||||
1 => {
|
||||
r.skip(2)?;
|
||||
Some(color(&mut r, p, warn)?)
|
||||
}
|
||||
_ => {
|
||||
push(warn, Warning::UnsupportedFills);
|
||||
None
|
||||
}
|
||||
};
|
||||
Some((id, color))
|
||||
}
|
||||
|
||||
/// The body of the record tagged 1300 that follows tagged records of later layouts (R11).
|
||||
fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> {
|
||||
for _ in 0..=MAX_SKIPPED {
|
||||
let (tag, len) = (r.u32()?, r.u32()? as usize);
|
||||
let body = r.bytes(len.min(r.left()))?;
|
||||
if tag == TAG_1300 {
|
||||
return Some(body);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// An outline record: its id and the outline (`None`: no outline) (R12, R13).
|
||||
pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<(u32, Option<Outline>)> {
|
||||
let mut r = Rd::new(b);
|
||||
let id = r.u32()?;
|
||||
// A library color named in a record of type 2, with the warnings its read gave.
|
||||
let mut named = None;
|
||||
if p.tagged {
|
||||
let mut found = false;
|
||||
for _ in 0..MAX_OUTLINE_RECORDS {
|
||||
let (rec, len) = (r.u32()?, r.u32()? as usize);
|
||||
if rec == 1 {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
let body = r.bytes(len)?;
|
||||
// Type 2 holds the outline's color as a property list, as a uniform fill does (R12).
|
||||
// Only a library color with its name is taken from it; any other color comes from
|
||||
// the fixed field below.
|
||||
if rec == 2 {
|
||||
let mut w = Vec::new();
|
||||
if let Some(c @ Color::Spot { look: Some(_), .. }) = property_color(body, p, &mut w) {
|
||||
named = Some((c, w));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let (line_type, cap, join) = (r.u16()?, r.u16()?, r.u16()?);
|
||||
r.skip(p.outl_after_join)?;
|
||||
let width = coord(&mut r, p)?.abs();
|
||||
let _stretch = r.u16()?;
|
||||
r.skip(p.outl_after_stretch)?;
|
||||
let _nib = angle(&mut r, p)?;
|
||||
r.skip(p.outl_after_angle)?;
|
||||
let color = match named {
|
||||
Some((named, w)) => {
|
||||
color(&mut r, p, &mut Vec::new())?;
|
||||
for x in w {
|
||||
push(warn, x);
|
||||
}
|
||||
named
|
||||
}
|
||||
None => color(&mut r, p, warn)?,
|
||||
};
|
||||
r.skip(p.outl_after_color)?;
|
||||
let count = usize::from(r.u16()?);
|
||||
let first_dash = r.pos();
|
||||
let fits = r.left() / 2;
|
||||
if count > fits {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
// At most 65,535; the read's dash limit is applied where shapes use them.
|
||||
let dashes: Vec<f64> = (0..count.min(fits)).filter_map(|_| r.u16().map(f64::from)).collect();
|
||||
if let Some(after) = p.marker_after_dash {
|
||||
let mut m = Rd::at(b, first_dash + after);
|
||||
if matches!((m.u32(), m.u32()), (Some(s), Some(e)) if s != 0 || e != 0) {
|
||||
push(warn, Warning::Arrowheads);
|
||||
}
|
||||
}
|
||||
// Bit 0 of the line type: no outline (R13).
|
||||
if line_type & 1 != 0 {
|
||||
return Some((id, None));
|
||||
}
|
||||
let cap = match cap {
|
||||
1 => Cap::Round,
|
||||
2 => Cap::Square,
|
||||
_ => Cap::Butt,
|
||||
};
|
||||
let join = match join {
|
||||
1 => Join::Round,
|
||||
2 => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
};
|
||||
// Bit 2 of the line type marks the outline dashed; without it the dashes stored are not drawn
|
||||
// (R48).
|
||||
let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() };
|
||||
// Bit 4 of the line type: behind the fill (R49).
|
||||
let behind_fill = line_type & 0x10 != 0;
|
||||
// Bit 5 of the line type: scaled with the shape (R50).
|
||||
let scale_with = line_type & 0x20 != 0;
|
||||
Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with })))
|
||||
}
|
||||
|
||||
/// The opacity and blend of argument 8000 from version 13 (R47): records of a u32 version, a u32
|
||||
/// length and a body. A body of version 1300 that is [`UNIFORM_LEN`] bytes long is a uniform
|
||||
/// transparency: an f64 at byte 61 and the merge mode at byte 77. VectorCraft reads the f64 as the
|
||||
/// transparency in percent, 0 opaque and 100 clear. `None` for any other argument, such as a lens,
|
||||
/// and for a value out of range or a merge mode without a VectorCraft blend mode.
|
||||
pub(crate) fn transparency(b: &[u8]) -> Option<(f32, Blend)> {
|
||||
let mut r = Rd::new(b);
|
||||
while r.left() >= 8 {
|
||||
let (since, len) = (r.u32()?, r.u32()? as usize);
|
||||
let body = r.bytes(len)?;
|
||||
if since != TAG_1300 {
|
||||
continue;
|
||||
}
|
||||
if body.len() != UNIFORM_LEN {
|
||||
return None;
|
||||
}
|
||||
let value = Rd::at(body, 61).f64()?;
|
||||
if !(0.0..=100.0).contains(&value) {
|
||||
return None;
|
||||
}
|
||||
return Some(((1.0 - value / 100.0) as f32, blend(*body.get(77)?)?));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The length of a uniform transparency's record body (R47).
|
||||
const UNIFORM_LEN: usize = 117;
|
||||
|
||||
/// The blend mode of a transparency's merge mode byte (R47); `None` for the modes VectorCraft has
|
||||
/// no blend mode for.
|
||||
fn blend(mode: u8) -> Option<Blend> {
|
||||
Some(match mode {
|
||||
0 => Blend::Normal,
|
||||
9 => Blend::Multiply,
|
||||
11 => Blend::Lighten,
|
||||
12 => Blend::Darken,
|
||||
14 => Blend::Color,
|
||||
15 => Blend::Hue,
|
||||
16 => Blend::Saturation,
|
||||
17 => Blend::Luminosity,
|
||||
24 => Blend::Difference,
|
||||
28 => Blend::Screen,
|
||||
29 => Blend::Overlay,
|
||||
30 => Blend::SoftLight,
|
||||
31 => Blend::HardLight,
|
||||
33 => Blend::ColorDodge,
|
||||
34 => Blend::ColorBurn,
|
||||
36 => Blend::Exclusion,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name
|
||||
/// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a
|
||||
/// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does.
|
||||
pub(crate) fn name(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> String {
|
||||
if p.utf16_names {
|
||||
let units = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0);
|
||||
let (mut kept, hash) = capped(units, warn);
|
||||
if hash.is_some() && kept.last().is_some_and(|u| (0xD800..0xDC00).contains(u)) {
|
||||
kept.pop();
|
||||
}
|
||||
with_hash(String::from_utf16_lossy(&kept), hash)
|
||||
} else {
|
||||
let bytes = b.iter().copied().take_while(|c| *c != 0);
|
||||
let (kept, hash) = capped(bytes, warn);
|
||||
with_hash(kept.into_iter().map(windows_1252).collect(), hash)
|
||||
}
|
||||
}
|
||||
|
||||
/// The first [`MAX_NAME`] of `units`, and when there are more, an FNV-1a hash of them all, with a
|
||||
/// warning.
|
||||
fn capped<T: Copy + Into<u64>>(units: impl Iterator<Item = T> + Clone, warn: &mut Vec<Warning>) -> (Vec<T>, Option<u64>) {
|
||||
if units.clone().nth(MAX_NAME).is_none() {
|
||||
return (units.collect(), None);
|
||||
}
|
||||
push(warn, Warning::TooDeep);
|
||||
let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u.into()).wrapping_mul(0x0100_0000_01b3));
|
||||
(units.take(MAX_NAME).collect(), Some(hash))
|
||||
}
|
||||
|
||||
/// `name`, followed by `hash` in hexadecimal when there is one.
|
||||
fn with_hash(name: String, hash: Option<u64>) -> String {
|
||||
match hash {
|
||||
Some(h) => format!("{name} {h:016x}"),
|
||||
None => name,
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes
|
||||
/// are Latin-1.
|
||||
const CP1252_HIGH: [char; 32] = [
|
||||
'€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–',
|
||||
'—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ',
|
||||
];
|
||||
|
||||
fn windows_1252(c: u8) -> char {
|
||||
match c {
|
||||
0x80..=0x9F => CP1252_HIGH.get(usize::from(c - 0x80)).copied().unwrap_or('\u{FFFD}'),
|
||||
_ => char::from(c),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An outline that names an arrowhead says so with a warning, in each version whose arrowhead
|
||||
/// ids have a known place: 22 bytes after the first dash in versions 6 to 12, 20 from 13.
|
||||
#[test]
|
||||
fn arrowheads_are_named_from_version_6() {
|
||||
let pen = crate::synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 };
|
||||
let color = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100];
|
||||
for (version, place) in [
|
||||
(500, None),
|
||||
(600, Some(22)),
|
||||
(700, Some(22)),
|
||||
(800, Some(22)),
|
||||
(900, Some(22)),
|
||||
(1000, Some(22)),
|
||||
(1100, Some(22)),
|
||||
(1200, Some(22)),
|
||||
(1300, Some(20)),
|
||||
(1700, Some(20)),
|
||||
] {
|
||||
let p = crate::layout::for_version(version).unwrap();
|
||||
let plain = crate::synth::V(version).outline(7, pen, &color, &[]);
|
||||
// The record ends with 32 bytes after its dashes, and this one has none.
|
||||
let first_dash = plain.len() - 32;
|
||||
let mut w = vec![];
|
||||
assert!(outline(&plain, &p, &mut w).is_some_and(|(id, o)| id == 7 && o.is_some()), "{version}");
|
||||
assert!(w.is_empty(), "{version}: {w:?}");
|
||||
let Some(place) = place else { continue };
|
||||
let mut arrow = plain.clone();
|
||||
arrow[first_dash + place..first_dash + place + 4].copy_from_slice(&9u32.to_le_bytes());
|
||||
let mut w = vec![];
|
||||
assert!(outline(&arrow, &p, &mut w).is_some(), "{version}");
|
||||
assert_eq!(w, vec![Warning::Arrowheads], "{version}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_byte_names_read_as_windows_1252() {
|
||||
let p = crate::layout::for_version(1100).unwrap();
|
||||
assert_eq!(name(b"Caf\xe9 \x80\x96\0junk", &p, &mut vec![]), "Café €–");
|
||||
let p = crate::layout::for_version(1200).unwrap();
|
||||
assert_eq!(name(&[0x41, 0, 0x42, 0, 0, 0, 0x43, 0], &p, &mut vec![]), "AB");
|
||||
}
|
||||
|
||||
/// A layer name longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones and a hash
|
||||
/// of the whole name, with a warning, in both encodings. A cut never keeps half of a surrogate
|
||||
/// pair.
|
||||
#[test]
|
||||
fn long_layer_names_are_cut_with_a_hash() {
|
||||
for version in [1100, 1200] {
|
||||
let p = crate::layout::for_version(version).unwrap();
|
||||
let bytes =
|
||||
|s: &str| if p.utf16_names { s.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>() } else { s.as_bytes().to_vec() };
|
||||
let mut w = vec![];
|
||||
let a = name(&bytes(&"N".repeat(100_000)), &p, &mut w);
|
||||
let b = name(&bytes(&format!("{}M", "N".repeat(99_999))), &p, &mut vec![]);
|
||||
assert_ne!(a, b, "{version}");
|
||||
assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{version}: {}", a.len());
|
||||
assert_eq!(w, vec![Warning::TooDeep], "{version}");
|
||||
let mut w = vec![];
|
||||
assert_eq!(name(&bytes(&"N".repeat(MAX_NAME)), &p, &mut w), "N".repeat(MAX_NAME), "{version}");
|
||||
assert!(w.is_empty(), "{version}");
|
||||
}
|
||||
let p = crate::layout::for_version(1200).unwrap();
|
||||
let emoji: Vec<u8> = format!("N{}", "\u{1F600}".repeat(200)).encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
let cut = name(&emoji, &p, &mut vec![]);
|
||||
assert!(!cut.contains('\u{FFFD}'), "{cut}");
|
||||
assert_eq!(cut.chars().filter(|c| *c == '\u{1F600}').count(), (MAX_NAME - 1) / 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_read_in_their_models() {
|
||||
let p = crate::layout::for_version(500).unwrap();
|
||||
let rec = |model: u16, v: [u8; 4]| {
|
||||
let mut b = model.to_le_bytes().to_vec();
|
||||
b.extend([0; 6]);
|
||||
b.extend(v);
|
||||
let mut w = vec![];
|
||||
(color(&mut Rd::new(&b), &p, &mut w), w)
|
||||
};
|
||||
assert_eq!(rec(2, [100, 50, 0, 10]).0, Some(Color::Cmyk([1.0, 0.5, 0.0, 0.1])));
|
||||
assert_eq!(rec(5, [255, 0, 0, 0]).0, Some(Color::Rgb([0.0, 0.0, 1.0])));
|
||||
assert_eq!(rec(9, [255, 0, 0, 0]).0, Some(Color::Gray(0.0)));
|
||||
assert_eq!(rec(25, [7, 0, 40, 0]).0, Some(Color::Spot { name: "Spot 0:7".into(), tint: 0.4, look: None }));
|
||||
// The same number in another library is another color.
|
||||
let mut other = 25u16.to_le_bytes().to_vec();
|
||||
other.extend(3u16.to_le_bytes());
|
||||
other.extend([0; 4]);
|
||||
other.extend([7, 0, 40, 0]);
|
||||
assert_eq!(color(&mut Rd::new(&other), &p, &mut vec![]), Some(Color::Spot { name: "Spot 3:7".into(), tint: 0.4, look: None }));
|
||||
let (c, w) = rec(6, [1, 2, 3, 4]);
|
||||
assert_eq!((c, w), (Some(Color::Rgb([0.0; 3])), vec![Warning::UnknownColors]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_of_versions_3_and_4_read_models_0_and_1() {
|
||||
let read = |version: u16, model: u8, v: [u16; 4]| {
|
||||
let p = crate::layout::for_version(version).unwrap();
|
||||
let b: Vec<u8> = if version < 400 {
|
||||
std::iter::once(model).chain(v.map(|x| x as u8)).collect()
|
||||
} else {
|
||||
u16::from(model).to_le_bytes().into_iter().chain(v.iter().flat_map(|x| x.to_le_bytes())).chain([0, 0]).collect()
|
||||
};
|
||||
let mut r = Rd::new(&b);
|
||||
let mut w = vec![];
|
||||
let c = color(&mut r, &p, &mut w);
|
||||
assert_eq!(r.left(), 0, "{version}");
|
||||
(c, w)
|
||||
};
|
||||
for version in [300, 400] {
|
||||
// Model 1 is CMYK in percent, not a library color as from version 5.
|
||||
assert_eq!(read(version, 1, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}");
|
||||
assert_eq!(read(version, 2, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}");
|
||||
}
|
||||
// Model 0: an ink number and a tint. Version 3 stores each as a u16 in its four bytes.
|
||||
assert_eq!(read(300, 0, [0, 0, 60, 0]).0, Some(Color::Gray(0.6)));
|
||||
assert_eq!(read(300, 0, [1, 0, 60, 0]).0, Some(Color::Gray(0.0)));
|
||||
assert_eq!(read(300, 0, [44, 1, 60, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks]));
|
||||
assert_eq!(read(400, 0, [0, 60, 0, 0]).0, Some(Color::Gray(0.6)));
|
||||
assert_eq!(read(400, 0, [1, 60, 0, 0]).0, Some(Color::Gray(0.0)));
|
||||
assert_eq!(read(400, 0, [300, 60, 0, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixed_point_matrix_reads_its_factors_and_offsets() {
|
||||
let raw: Vec<u8> = [65536i32, -32768, 1000, 131072, 16384, -500].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let m = fixed_matrix(&mut Rd::new(&raw), 0.5).unwrap();
|
||||
assert_eq!(m, Matrix([1.0, 2.0, -0.5, 0.25, 500.0, -250.0]));
|
||||
assert!(fixed_matrix(&mut Rd::new(&raw[..23]), 0.5).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_names_that_start_alike_stay_apart() {
|
||||
let read = |name: &str| {
|
||||
let mut b = (name.encode_utf16().count() as u32).to_le_bytes().to_vec();
|
||||
b.extend(name.encode_utf16().flat_map(u16::to_le_bytes));
|
||||
let mut w = vec![];
|
||||
(counted_utf16(&mut Rd::new(&b), &mut w).unwrap(), w)
|
||||
};
|
||||
let (a, w) = read(&"N".repeat(300));
|
||||
let (b, _) = read(&format!("{}M", "N".repeat(299)));
|
||||
assert_ne!(a, b);
|
||||
assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{a}");
|
||||
assert_eq!(w, vec![Warning::TooDeep]);
|
||||
assert_eq!(read("Sky Blue"), ("Sky Blue".to_string(), vec![]));
|
||||
// Padding doesn't count toward the length or the name.
|
||||
let (padded, w) = read(&format!("{}\0\0", "N".repeat(MAX_NAME - 1)));
|
||||
assert_eq!((padded, w), ("N".repeat(MAX_NAME - 1), vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tint_mixes_toward_white_and_comes_off_again() {
|
||||
let shown = [0.6, 0.8, 1.0];
|
||||
let base = untinted(shown, 0.5);
|
||||
assert!((base[0] - 0.2).abs() < 1e-6 && (base[1] - 0.6).abs() < 1e-6 && base[2] == 1.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
//! The chunk index: one flat table of every chunk, a list's children contiguous, built without
|
||||
//! recursion. Payloads are not copied: an entry names a range of the RIFF stream, of the bytes
|
||||
//! inflated from `LIST cmpr`, or of a package's data stream (layouts R1 to R4, R27).
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Read as _;
|
||||
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::layout;
|
||||
use crate::limits::Budget;
|
||||
use crate::package::Streams;
|
||||
use crate::{Error, Warning};
|
||||
|
||||
pub(crate) const LIST: [u8; 4] = *b"LIST";
|
||||
const CMPR: [u8; 4] = *b"cmpr";
|
||||
const CPNG: [u8; 4] = *b"CPng";
|
||||
/// What follows `CPng` before the zlib stream (R3).
|
||||
const CPNG_HEAD: [u8; 4] = [1, 0, 4, 0];
|
||||
/// The size of a redirect record, and the stream number of one that holds its body (R27).
|
||||
const REDIRECT: usize = 16;
|
||||
const INLINE: u32 = u32::MAX;
|
||||
|
||||
/// One chunk: 28 bytes. `start` and `len` give the payload (after a list's form type) in its
|
||||
/// source: 0 is the RIFF stream followed by the inflated bytes, `s + 1` is data stream `s`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Chunk {
|
||||
pub(crate) id: [u8; 4],
|
||||
/// A list's form type; zeros for other chunks.
|
||||
pub(crate) form: [u8; 4],
|
||||
src: u32,
|
||||
start: u32,
|
||||
len: u32,
|
||||
first: u32,
|
||||
count: u32,
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
pub(crate) fn is_list(&self, form: &[u8; 4]) -> bool {
|
||||
self.id == LIST && &self.form == form
|
||||
}
|
||||
}
|
||||
|
||||
/// Every chunk of a file, and the bytes they point into.
|
||||
pub(crate) struct Index<'a> {
|
||||
input: &'a [u8],
|
||||
inflated: Vec<u8>,
|
||||
chunks: Vec<Chunk>,
|
||||
/// The version the form type names: hundreds, as `vrsn` stores it (0 when the `vrsn` chunk
|
||||
/// decides).
|
||||
pub(crate) form_version: u16,
|
||||
/// A version 16+ package's data streams; chunks of 16 bytes are redirect records then.
|
||||
streams: Option<Streams<'a>>,
|
||||
/// Bytes that inflating may still produce.
|
||||
left: Cell<usize>,
|
||||
/// The bytes redirected lists have taken: (package member, start) to end.
|
||||
lists: Cell<BTreeMap<(usize, usize), usize>>,
|
||||
/// The bytes other redirected chunks have taken, the same way.
|
||||
leaves: Cell<BTreeMap<(usize, usize), usize>>,
|
||||
/// Bytes that redirects to bytes another chunk already took may still read.
|
||||
shared_left: Cell<usize>,
|
||||
/// The first `vrsn` chunk among the file's own chunks, once seen, and the version it names
|
||||
/// (`None` when it can't be read) (R2).
|
||||
vrsn: Option<Option<u16>>,
|
||||
}
|
||||
|
||||
/// A list still to be split into its children.
|
||||
struct Pending {
|
||||
entry: usize,
|
||||
src: u32,
|
||||
/// Its children's bytes.
|
||||
start: usize,
|
||||
end: usize,
|
||||
/// The size pool of a compressed list's stream (`start..end` in source 0).
|
||||
pool: Option<(usize, usize)>,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
/// What reading one chunk header gives.
|
||||
enum Read {
|
||||
Chunk(Chunk),
|
||||
/// A redirect record whose body can't be found: the chunk is left out, its list read on.
|
||||
Lost,
|
||||
/// A redirect record into a data stream past a limit: the chunk is left out without the
|
||||
/// damage warning.
|
||||
PastLimit,
|
||||
/// A redirect record to bytes another chunk took, past the shared-bytes limit: the chunk is
|
||||
/// left out with the limit warning.
|
||||
SharedPastLimit,
|
||||
}
|
||||
|
||||
/// The version the RIFF form type names (R1): `CDR5`..`CDR9`, `CDRA` (10) to `CDRH` (17) with `I`
|
||||
/// unused, then `J` (18) on; `CDR ` is version 3. Some files use a lower-case `cdr`, which names
|
||||
/// the same versions except that `cdr8` is the 8.01 variant. Templates of version 21 have the form
|
||||
/// type `CDTQ`; for `CDT` the `vrsn` chunk names the version, so this gives 0 (R28).
|
||||
pub(crate) fn form_version(form: [u8; 4]) -> Option<u16> {
|
||||
let [a, b, c, v] = form;
|
||||
match (&[a, b, c], v) {
|
||||
(b"cdr", b'8') => Some(801),
|
||||
(b"CDR" | b"cdr", b' ') => Some(300),
|
||||
(b"CDR" | b"cdr", b'1'..=b'9') => Some(100 * u16::from(v - b'0')),
|
||||
(b"CDR" | b"cdr", b'A'..=b'H') => Some(100 * u16::from(v - b'A' + 10)),
|
||||
(b"CDR" | b"cdr", b'J'..=b'W') => Some(100 * u16::from(v - b'J' + 18)),
|
||||
(b"CDT", b'A'..=b'Z') => Some(0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `bytes` start like a RIFF `.cdr` drawing (not the `CDRX` exchange variant)?
|
||||
pub(crate) fn is_cdr_riff(bytes: &[u8]) -> bool {
|
||||
bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12).and_then(|f| f.try_into().ok()).and_then(form_version).is_some()
|
||||
}
|
||||
|
||||
impl<'a> Index<'a> {
|
||||
pub(crate) fn build(input: &'a [u8], streams: Option<Streams<'a>>, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Self, Error> {
|
||||
if input.len() > budget.limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
let mut r = Rd::new(input);
|
||||
if r.fourcc() != Some(*b"RIFF") {
|
||||
return Err(Error::NotCdr);
|
||||
}
|
||||
let declared = r.u32().ok_or(Error::NotCdr)? as usize;
|
||||
let form = r.fourcc().ok_or(Error::NotCdr)?;
|
||||
let version = form_version(form).ok_or(Error::NotCdr)?;
|
||||
// A file cut short keeps what it holds: its last chunk is truncated with a warning. A
|
||||
// length that ends inside the form type is damage too, and the chunks after it are read.
|
||||
let end = match declared.checked_add(8) {
|
||||
Some(e) if (12..=input.len()).contains(&e) => e,
|
||||
_ => {
|
||||
push(warn, Warning::Damaged);
|
||||
input.len()
|
||||
}
|
||||
};
|
||||
let left = Cell::new(budget.inflate_left());
|
||||
let mut ix = Index {
|
||||
input,
|
||||
inflated: Vec::new(),
|
||||
chunks: Vec::new(),
|
||||
form_version: version,
|
||||
streams,
|
||||
left,
|
||||
lists: Cell::default(),
|
||||
leaves: Cell::default(),
|
||||
shared_left: Cell::new(budget.limits.member),
|
||||
vrsn: None,
|
||||
};
|
||||
ix.chunks.push(Chunk { id: *b"RIFF", form, src: 0, start: 12, len: 0, first: 0, count: 0 });
|
||||
let mut queue = vec![Pending { entry: 0, src: 0, start: 12, end, pool: None, depth: 0 }];
|
||||
while let Some(p) = queue.pop() {
|
||||
ix.split(p, &mut queue, budget, warn)?;
|
||||
}
|
||||
Ok(ix)
|
||||
}
|
||||
|
||||
/// The bytes `start..end` of source `src`, or `None` when the range crosses its end. A data
|
||||
/// stream is read on first use.
|
||||
fn span(&self, src: u32, start: usize, end: usize) -> Option<&[u8]> {
|
||||
if src > 0 {
|
||||
let s = self.streams.as_ref()?;
|
||||
return s.get(src as usize - 1, &self.left)?.get(start..end);
|
||||
}
|
||||
let n = self.input.len();
|
||||
if end <= n {
|
||||
self.input.get(start..end)
|
||||
} else if start >= n {
|
||||
self.inflated.get(start - n..end - n)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn data(&self, c: &Chunk) -> &[u8] {
|
||||
let start = c.start as usize;
|
||||
match self.span(c.src, start, start + c.len as usize) {
|
||||
Some(b) => b,
|
||||
None => {
|
||||
if let Some(s) = &self.streams
|
||||
&& !self.past_limit(c.src)
|
||||
{
|
||||
s.note_damage();
|
||||
}
|
||||
&[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Was source `src` a data stream left out because it is past a limit? Its chunks are then
|
||||
/// left out with that warning alone.
|
||||
fn past_limit(&self, src: u32) -> bool {
|
||||
src > 0 && self.streams.as_ref().is_some_and(|s| s.past_limit(src as usize - 1))
|
||||
}
|
||||
|
||||
pub(crate) fn children(&self, c: &Chunk) -> &[Chunk] {
|
||||
let first = c.first as usize;
|
||||
self.chunks.get(first..first + c.count as usize).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn root(&self) -> Option<&Chunk> {
|
||||
self.chunks.first()
|
||||
}
|
||||
|
||||
/// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1,
|
||||
/// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names
|
||||
/// (R28). Letters count differently from the version 24 update on (R1), so when both name a
|
||||
/// version after 27 the `vrsn` chunk's is the one refused. The `cdr8` form type alone makes a
|
||||
/// file the 8.01 variant, whatever its `vrsn` chunk names (R1).
|
||||
pub(crate) fn version(&self) -> u16 {
|
||||
match self.vrsn.flatten() {
|
||||
_ if self.form_version == 801 => 801,
|
||||
Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v,
|
||||
Some(v) if self.form_version == 0 => v,
|
||||
Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v,
|
||||
_ => self.form_version,
|
||||
}
|
||||
}
|
||||
|
||||
/// The warnings for data streams that were left out.
|
||||
pub(crate) fn stream_warnings(&self, warn: &mut Vec<Warning>) {
|
||||
if let Some(s) = &self.streams {
|
||||
s.warnings(warn);
|
||||
}
|
||||
}
|
||||
|
||||
/// Split list `p` into its children, appended to the table together; their lists are queued.
|
||||
fn split(&mut self, p: Pending, queue: &mut Vec<Pending>, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<(), Error> {
|
||||
let first = self.chunks.len();
|
||||
let mut at = p.start;
|
||||
let mut lists = Vec::new();
|
||||
while at < p.end {
|
||||
let Some((read, next, cut)) = self.read_chunk(p.src, at, p.end, p.pool) else {
|
||||
push(warn, Warning::Damaged);
|
||||
break;
|
||||
};
|
||||
if cut {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
at = next;
|
||||
// A redirect record whose body can't be found counts as well, so that lists redirected
|
||||
// to again and again can't repeat such records past the limit.
|
||||
budget.take_chunk()?;
|
||||
let chunk = match read {
|
||||
Read::Chunk(chunk) => chunk,
|
||||
Read::Lost => {
|
||||
push(warn, Warning::Damaged);
|
||||
continue;
|
||||
}
|
||||
Read::PastLimit => continue,
|
||||
Read::SharedPastLimit => {
|
||||
push(warn, Warning::TooDeep);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if p.entry == 0 && chunk.id == *b"vrsn" && self.vrsn.is_none() {
|
||||
let at = chunk.start as usize;
|
||||
self.vrsn = Some(self.span(chunk.src, at, at + chunk.len as usize).and_then(|b| Rd::new(b).u16()));
|
||||
}
|
||||
if chunk.id == LIST {
|
||||
lists.push(self.chunks.len());
|
||||
}
|
||||
self.chunks.push(chunk);
|
||||
}
|
||||
let count = (self.chunks.len() - first) as u32;
|
||||
if let Some(parent) = self.chunks.get_mut(p.entry) {
|
||||
parent.first = first as u32;
|
||||
parent.count = count;
|
||||
}
|
||||
for i in lists {
|
||||
let Some(c) = self.chunks.get(i).copied() else { continue };
|
||||
// From version 7 a `LIST stlt` holds the style tables, not chunks (R4); its body is read
|
||||
// whole (R45). Before version 7 it holds chunks. The file's own chunks, its `vrsn`
|
||||
// among them, are all read before this.
|
||||
if c.form == *b"stlt" && self.version() >= 700 {
|
||||
continue;
|
||||
}
|
||||
if p.depth + 1 > budget.limits.depth {
|
||||
push(warn, Warning::TooDeep);
|
||||
continue;
|
||||
}
|
||||
let (start, end) = (c.start as usize, c.start as usize + c.len as usize);
|
||||
if c.form == CMPR && p.pool.is_none() {
|
||||
match self.inflate_cmpr(c.src, start, end) {
|
||||
Ok((s, e, pool)) => queue.push(Pending { entry: i, src: 0, start: s, end: e, pool: Some(pool), depth: p.depth + 1 }),
|
||||
Err(Error::Limit(what)) => return Err(Error::Limit(what)),
|
||||
Err(_) => push(warn, Warning::Damaged),
|
||||
}
|
||||
} else {
|
||||
queue.push(Pending { entry: i, src: c.src, start, end, pool: p.pool, depth: p.depth + 1 });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The chunk at `at` (before `end`) of source `src`, and where the next one starts. In a
|
||||
/// compressed stream the size field is an index into the size pool (R3); in a version 16+
|
||||
/// package a chunk of 16 bytes outside one is a redirect record (R27). The flag is set for a
|
||||
/// list cut short at `end`.
|
||||
fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize, bool)> {
|
||||
let head = self.span(src, at, at.checked_add(8)?.min(end))?;
|
||||
let id: [u8; 4] = head.get(..4)?.try_into().ok()?;
|
||||
let raw = u32_at(head, 4)? as usize;
|
||||
let size = match pool {
|
||||
None => raw,
|
||||
Some((ps, pe)) => {
|
||||
let off = raw.checked_mul(4)?.checked_add(ps)?;
|
||||
(off.checked_add(4)? <= pe).then_some(())?;
|
||||
u32_at(self.span(0, off, off + 4)?, 0)? as usize
|
||||
}
|
||||
};
|
||||
let body = at + 8;
|
||||
// A list cut short by the end of its parent keeps the bytes it has, so the children
|
||||
// before the cut are read; the caller warns that it is damaged. Other chunks are lost.
|
||||
let (size, cut) = match body.checked_add(size) {
|
||||
Some(e) if e <= end => (size, false),
|
||||
_ if id == LIST => (end.checked_sub(body)?, true),
|
||||
_ => return None,
|
||||
};
|
||||
let next = (body + size + (size & 1)).min(end);
|
||||
if cut {
|
||||
return Some((self.chunk(id, src, body, size).map_or(Read::Lost, Read::Chunk), next, true));
|
||||
}
|
||||
if self.streams.is_some() && pool.is_none() && size == REDIRECT {
|
||||
let read = match self.redirect(id, src, body) {
|
||||
Some(read) => read,
|
||||
None if self.redirect_past_limit(src, body) => Read::PastLimit,
|
||||
None => Read::Lost,
|
||||
};
|
||||
return Some((read, next, false));
|
||||
}
|
||||
Some((Read::Chunk(self.chunk(id, src, body, size)?), next, false))
|
||||
}
|
||||
|
||||
/// Chunk `id` whose body is `len` bytes at `body` of source `src`; a list's body starts with
|
||||
/// its form type.
|
||||
fn chunk(&self, id: [u8; 4], src: u32, body: usize, len: usize) -> Option<Chunk> {
|
||||
let (form, start) = if id == LIST {
|
||||
let f: [u8; 4] = self.span(src, body, body.checked_add(4).filter(|_| len >= 4)?)?.try_into().ok()?;
|
||||
(f, body + 4)
|
||||
} else {
|
||||
([0; 4], body)
|
||||
};
|
||||
let len = len - (start - body);
|
||||
Some(Chunk { id, form, src, start: u32::try_from(start).ok()?, len: u32::try_from(len).ok()?, first: 0, count: 0 })
|
||||
}
|
||||
|
||||
/// The chunk the redirect record at `body` of `src` stands for (R27): stream, length, offset
|
||||
/// and a reserved u32. Stream `0xFFFFFFFF` holds at most 8 bytes in the record itself, after
|
||||
/// the length. The body is not read again as a redirect record. `None` when the body can't
|
||||
/// be found.
|
||||
///
|
||||
/// A redirected list whose bytes overlap those of an earlier redirected list, in any stream of
|
||||
/// the same package member, is left out, so that no list is split twice. Other chunks may
|
||||
/// share bytes: each one after the first to read them takes their length from the
|
||||
/// shared-bytes limit (the member limit), so that many redirects to one body can't decode it
|
||||
/// without end.
|
||||
fn redirect(&self, id: [u8; 4], src: u32, body: usize) -> Option<Read> {
|
||||
let mut r = Rd::new(self.span(src, body, body + REDIRECT)?);
|
||||
let stream = r.u32()?;
|
||||
let len = r.u32()? as usize;
|
||||
if stream == INLINE {
|
||||
return (len <= 8).then(|| self.chunk(id, src, body + 8, len).map(Read::Chunk))?;
|
||||
}
|
||||
let off = r.u32()? as usize;
|
||||
let streams = self.streams.as_ref()?;
|
||||
let size = streams.size(stream as usize)?;
|
||||
let end = off.checked_add(len).filter(|&e| e <= size)?;
|
||||
let member = streams.member_of(stream as usize)?;
|
||||
if id == LIST {
|
||||
if !claim(&self.lists, member, off, end) {
|
||||
return None;
|
||||
}
|
||||
} else if !claim(&self.leaves, member, off, end) {
|
||||
let left = self.shared_left.get();
|
||||
if len > left {
|
||||
return Some(Read::SharedPastLimit);
|
||||
}
|
||||
self.shared_left.set(left - len);
|
||||
}
|
||||
// Only a list's form type is read now; other bodies are read when the mapping asks.
|
||||
self.chunk(id, stream.checked_add(1)?, off, len).map(Read::Chunk)
|
||||
}
|
||||
|
||||
/// Does the redirect record at `body` of `src` point into a data stream past a limit?
|
||||
fn redirect_past_limit(&self, src: u32, body: usize) -> bool {
|
||||
let stream = self.span(src, body, body + 4).and_then(|b| u32_at(b, 0));
|
||||
stream.is_some_and(|s| s != INLINE && self.past_limit(s.saturating_add(1)))
|
||||
}
|
||||
|
||||
/// Inflate the two blocks of a `LIST cmpr` body at `start..end` of `src` (R3) → the chunk
|
||||
/// stream and the size pool, as ranges of source 0.
|
||||
fn inflate_cmpr(&mut self, src: u32, start: usize, end: usize) -> Result<(usize, usize, (usize, usize)), Error> {
|
||||
let body = self.span(src, start, end).ok_or(Error::Damaged("compressed list"))?;
|
||||
let mut r = Rd::new(body);
|
||||
let c1 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize;
|
||||
r.skip(4).ok_or(Error::Damaged("compressed list"))?;
|
||||
let c2 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize;
|
||||
let block = |at: usize, len: usize| -> Result<&[u8], Error> {
|
||||
let b = body.get(at..at.checked_add(len).ok_or(Error::Damaged("compressed list"))?).ok_or(Error::Damaged("compressed list"))?;
|
||||
let mut h = Rd::new(b);
|
||||
if h.fourcc() != Some(CPNG) || h.fourcc() != Some(CPNG_HEAD) {
|
||||
return Err(Error::Damaged("compressed block"));
|
||||
}
|
||||
Ok(b.get(8..).unwrap_or_default())
|
||||
};
|
||||
let second_at = c1.checked_add(16).ok_or(Error::Damaged("compressed list"))?;
|
||||
let (first, second) = (block(16, c1)?.to_vec(), block(second_at, c2)?.to_vec());
|
||||
let base = self.input.len();
|
||||
let stream = self.inflate(&first)?;
|
||||
let pool = self.inflate(&second)?;
|
||||
Ok((base + stream.0, base + stream.1, (base + pool.0, base + pool.1)))
|
||||
}
|
||||
|
||||
/// Inflate zlib `data` onto the end of the inflated bytes, within what is left → its range
|
||||
/// there.
|
||||
fn inflate(&mut self, data: &[u8]) -> Result<(usize, usize), Error> {
|
||||
let at = self.inflated.len();
|
||||
let left = self.left.get();
|
||||
let reader = flate2::read::ZlibDecoder::new(data);
|
||||
// One byte past what is left tells a stream that is too long from one that just fits.
|
||||
let got = match reader.take((left as u64).saturating_add(1)).read_to_end(&mut self.inflated) {
|
||||
Ok(n) => n,
|
||||
Err(_) => {
|
||||
// What a stream inflated before it failed counts toward the limit too, so that
|
||||
// streams that fail late can't inflate past it again and again.
|
||||
let produced = self.inflated.len().saturating_sub(at);
|
||||
self.left.set(left.saturating_sub(produced));
|
||||
self.inflated.truncate(at);
|
||||
return Err(Error::Damaged("compressed block"));
|
||||
}
|
||||
};
|
||||
if got > left {
|
||||
self.inflated.truncate(at);
|
||||
return Err(Error::Limit("inflated size"));
|
||||
}
|
||||
self.left.set(left - got);
|
||||
if self.input.len().saturating_add(self.inflated.len()) > u32::MAX as usize {
|
||||
return Err(Error::Limit("inflated size"));
|
||||
}
|
||||
Ok((at, at + got))
|
||||
}
|
||||
}
|
||||
|
||||
/// Take bytes `start..end` of package member `member` in `claimed`, or `false` when an earlier
|
||||
/// redirect there took any of them. Empty ranges take nothing.
|
||||
fn claim(claimed: &Cell<BTreeMap<(usize, usize), usize>>, member: usize, start: usize, end: usize) -> bool {
|
||||
if start == end {
|
||||
return true;
|
||||
}
|
||||
let mut taken = claimed.take();
|
||||
let before = taken.range(..=(member, start)).next_back().is_some_and(|(&(m, _), &e)| m == member && e > start);
|
||||
let after = taken.range((member, start)..).next().is_some_and(|(&(m, s), _)| m == member && s < end);
|
||||
let free = !before && !after;
|
||||
if free {
|
||||
taken.insert((member, start), end);
|
||||
}
|
||||
claimed.set(taken);
|
||||
free
|
||||
}
|
||||
|
||||
/// Add `w` to the warnings once.
|
||||
pub(crate) fn push(warn: &mut Vec<Warning>, w: Warning) {
|
||||
if !warn.contains(&w) {
|
||||
warn.push(w);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! The style table in a `LIST stlt` of versions 7 to 15 (R45): the fill and outline records that a
|
||||
//! style gives the objects that name it and have no fill or outline argument of their own.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::Error;
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::limits::Budget;
|
||||
|
||||
/// One style: its parent, and the fill and outline table entries it names (0: none).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Style {
|
||||
parent: u32,
|
||||
fill: u32,
|
||||
outline: u32,
|
||||
}
|
||||
|
||||
/// The styles of a drawing: for each style id, the fill and outline records it gives, its
|
||||
/// parents' included.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Styles {
|
||||
fills: HashMap<u32, u32>,
|
||||
outlines: HashMap<u32, u32>,
|
||||
}
|
||||
|
||||
impl Styles {
|
||||
/// The style table in body `b` of a `LIST stlt` of `version` (R45), or `None` when it doesn't
|
||||
/// parse to its end. Its fill and outline entries and its styles count toward the chunks a
|
||||
/// read takes.
|
||||
pub(crate) fn read(b: &[u8], version: u16, budget: &mut Budget) -> Result<Option<Styles>, Error> {
|
||||
let mut limit = None;
|
||||
let styles = parse(b, version, &mut |n| match budget.take_chunks(n) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
limit = Some(e);
|
||||
false
|
||||
}
|
||||
});
|
||||
match limit {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(styles),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill record that style `id` gives.
|
||||
pub(crate) fn fill(&self, id: u32) -> Option<u32> {
|
||||
self.fills.get(&id).copied()
|
||||
}
|
||||
|
||||
/// The outline record that style `id` gives.
|
||||
pub(crate) fn outline(&self, id: u32) -> Option<u32> {
|
||||
self.outlines.get(&id).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// The style table in `b`. `take` is asked for each count of entries or styles before they are
|
||||
/// read; a `false` stops the read.
|
||||
fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option<Styles> {
|
||||
let mut r = Rd::new(b);
|
||||
let count = r.u32()? as usize;
|
||||
if count == 0 {
|
||||
return (r.left() == 0).then(Styles::default);
|
||||
}
|
||||
// Fill entries carry 48 more bytes from version 13.
|
||||
let fills = table(&mut r, if version >= 1300 { 60 } else { 12 }, take)?;
|
||||
let outlines = table(&mut r, 12, take)?;
|
||||
// The text style tables: fonts, alignments, spacings, two tables of fixed records, bullets,
|
||||
// indents, hyphenation and drop caps, and from version 8.01 one more.
|
||||
skip_table(&mut r, if version >= 1000 { 60 } else { 44 })?;
|
||||
skip_table(&mut r, 12)?;
|
||||
skip_table(&mut r, 52)?;
|
||||
skip_table(&mut r, 152)?;
|
||||
skip_table(&mut r, 784)?;
|
||||
let bullets = r.u32()?;
|
||||
for _ in 0..bullets {
|
||||
bullet(&mut r, version)?;
|
||||
}
|
||||
skip_table(&mut r, 28)?;
|
||||
skip_table(&mut r, if version >= 1300 { 36 } else { 32 })?;
|
||||
skip_table(&mut r, 28)?;
|
||||
if version >= 801 {
|
||||
skip_table(&mut r, 12)?;
|
||||
}
|
||||
// Each style is at least 32 bytes.
|
||||
if count > r.left() / 32 || !take(count) {
|
||||
return None;
|
||||
}
|
||||
let mut styles = HashMap::new();
|
||||
for _ in 0..count {
|
||||
let (id, s) = style(&mut r, version)?;
|
||||
styles.entry(id).or_insert(s);
|
||||
}
|
||||
if r.left() != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut work = 0;
|
||||
Some(Styles { fills: resolve(&styles, &fills, |s| s.fill, &mut work), outlines: resolve(&styles, &outlines, |s| s.outline, &mut work) })
|
||||
}
|
||||
|
||||
/// For each style, the record of `table` that its own entry names, or the nearest parent's where
|
||||
/// its entry is 0. Each style is resolved once, and each path forgets only the styles on it, so a
|
||||
/// chain of any length takes time in proportion to the styles; a chain that comes back to a style
|
||||
/// on it, or reaches a style that isn't there, gives no record. `work` counts the styles visited
|
||||
/// and forgotten.
|
||||
fn resolve(styles: &HashMap<u32, Style>, table: &HashMap<u32, u32>, entry: impl Fn(&Style) -> u32, work: &mut usize) -> HashMap<u32, u32> {
|
||||
// `None`: resolved to no record.
|
||||
let mut done: HashMap<u32, Option<u32>> = HashMap::new();
|
||||
let mut path = Vec::new();
|
||||
let mut on_path = HashSet::new();
|
||||
for &start in styles.keys() {
|
||||
let mut id = start;
|
||||
let found = loop {
|
||||
*work += 1;
|
||||
if let Some(&known) = done.get(&id) {
|
||||
break known;
|
||||
}
|
||||
let Some(s) = styles.get(&id) else { break None };
|
||||
// Back at a style on this path: a cycle.
|
||||
if !on_path.insert(id) {
|
||||
break None;
|
||||
}
|
||||
path.push(id);
|
||||
match entry(s) {
|
||||
0 => id = s.parent,
|
||||
e => break table.get(&e).copied(),
|
||||
}
|
||||
};
|
||||
for id in path.drain(..) {
|
||||
*work += 1;
|
||||
on_path.remove(&id);
|
||||
done.insert(id, found);
|
||||
}
|
||||
}
|
||||
done.into_iter().filter_map(|(id, r)| Some((id, r?))).collect()
|
||||
}
|
||||
|
||||
/// A table of a u32 count and entries of `size` bytes, each a table id, 4 bytes and a record id.
|
||||
fn table(r: &mut Rd, size: usize, take: &mut dyn FnMut(usize) -> bool) -> Option<HashMap<u32, u32>> {
|
||||
let n = r.u32()? as usize;
|
||||
if n > r.left() / size || !take(n) {
|
||||
return None;
|
||||
}
|
||||
let mut out = HashMap::new();
|
||||
for _ in 0..n {
|
||||
let e = r.bytes(size)?;
|
||||
out.entry(u32_at(e, 0)?).or_insert(u32_at(e, 8)?);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A table of a u32 count and entries of `size` bytes, passed over.
|
||||
fn skip_table(r: &mut Rd, size: usize) -> Option<()> {
|
||||
let n = r.u32()? as usize;
|
||||
r.skip(n.checked_mul(size)?)
|
||||
}
|
||||
|
||||
/// A bullet record, passed over: its length depends on a u32 inside it.
|
||||
fn bullet(r: &mut Rd, version: u16) -> Option<()> {
|
||||
r.skip(40)?;
|
||||
if version >= 1300 {
|
||||
if version >= 1400 {
|
||||
r.skip(4)?;
|
||||
}
|
||||
let more = r.u32()?;
|
||||
return r.skip(if more != 0 { 68 } else { 12 });
|
||||
}
|
||||
r.skip(if version >= 1000 { 28 } else { 20 })?;
|
||||
let more = r.u32()?;
|
||||
if more != 0 {
|
||||
r.skip(8)?;
|
||||
}
|
||||
r.skip(8)
|
||||
}
|
||||
|
||||
/// A style record: its kind (u32), id, parent, 8 bytes, a name length and the name (bytes before
|
||||
/// version 12, UTF-16 units from it), the fill and outline entries, then the entries of text
|
||||
/// styles (kinds 2 and 3).
|
||||
fn style(r: &mut Rd, version: u16) -> Option<(u32, Style)> {
|
||||
let kind = r.u32()?;
|
||||
let (id, parent) = (r.u32()?, r.u32()?);
|
||||
r.skip(8)?;
|
||||
let len = r.u32()? as usize;
|
||||
r.skip(len.checked_mul(if version >= 1200 { 2 } else { 1 })?)?;
|
||||
let (fill, outline) = (r.u32()?, r.u32()?);
|
||||
if kind > 1 {
|
||||
r.skip(if version >= 801 { 20 } else { 16 })?;
|
||||
}
|
||||
if kind > 2 {
|
||||
r.skip(20)?;
|
||||
}
|
||||
Some((id, Style { parent, fill, outline }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Limits;
|
||||
use crate::synth::{self, V};
|
||||
|
||||
fn read(b: &[u8], version: u16) -> Option<Styles> {
|
||||
Styles::read(b, version, &mut Budget::new(Limits::default())).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_that_name_each_other_as_parents_end() {
|
||||
let looped = [synth::Style { id: 0x10, parent: 0x11, fill: 0, outline: 0 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }];
|
||||
let s = read(&synth::stlt_body(V(700), &[(0x100, 1)], &[], &looped, false), 700).unwrap();
|
||||
assert_eq!((s.fill(0x10), s.outline(0x11), s.fill(0x12)), (None, None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_chain_of_parents_reaches_the_style_that_names_an_entry() {
|
||||
let mut chain = vec![synth::Style { id: 1, parent: 0, fill: 0x100, outline: 0 }];
|
||||
chain.extend((2..=500).map(|id| synth::Style { id, parent: id - 1, fill: 0, outline: 0 }));
|
||||
let s = read(&synth::stlt_body(V(1100), &[(0x100, 7)], &[], &chain, false), 1100).unwrap();
|
||||
assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None));
|
||||
}
|
||||
|
||||
/// A loop of 2,000 styles, which every walk into it follows around, leaves the walks of 20,000
|
||||
/// other styles no more work than the styles they visit.
|
||||
#[test]
|
||||
fn one_long_walk_does_not_slow_the_walks_after_it() {
|
||||
let mut styles: HashMap<u32, Style> = (1..=2000).map(|id| (id, Style { parent: id % 2000 + 1, fill: 0, outline: 0 })).collect();
|
||||
styles.extend((10_001..=30_000).map(|id| (id, Style { parent: 0, fill: 0x100, outline: 0 })));
|
||||
let table = HashMap::from([(0x100, 7)]);
|
||||
let mut work = 0;
|
||||
let fills = resolve(&styles, &table, |s| s.fill, &mut work);
|
||||
assert_eq!((fills.get(&1), fills.get(&10_001), fills.len()), (None, Some(&7), 20_000));
|
||||
assert!(work <= 4 * styles.len(), "{work}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_missing_from_its_table_names_no_record() {
|
||||
let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }];
|
||||
let s = read(&synth::stlt_body(V(1300), &[(0x100, 1)], &[(0x200, 2)], &styles, false), 1300).unwrap();
|
||||
assert_eq!((s.fill(0x10), s.outline(0x10)), (None, Some(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_past_the_body_do_not_parse() {
|
||||
let mut b = synth::stlt_body(V(900), &[], &[], &[], false);
|
||||
b[..4].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert!(read(&b, 900).is_none());
|
||||
let empty = 0u32.to_le_bytes();
|
||||
assert!(read(&empty, 900).is_some());
|
||||
assert!(read(&[], 900).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_and_styles_count_toward_the_chunk_limit() {
|
||||
let styles: Vec<_> = (1..=10).map(|id| synth::Style { id, parent: 0, fill: 0x100, outline: 0 }).collect();
|
||||
let b = synth::stlt_body(V(1000), &[(0x100, 1)], &[], &styles, false);
|
||||
let mut budget = Budget::new(Limits { chunks: 10, ..Limits::default() });
|
||||
assert_eq!(Styles::read(&b, 1000, &mut budget).err(), Some(Error::Limit("chunk count")));
|
||||
let mut budget = Budget::new(Limits { chunks: 11, ..Limits::default() });
|
||||
assert!(Styles::read(&b, 1000, &mut budget).is_ok_and(|s| s.is_some()));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,287 @@
|
||||
//! Synthetic `.cmx` files for tests and fuzz seeds, built from the layouts in `PROVENANCE.md` (R53
|
||||
//! to R63). Not a `.cmx` writer: nothing checks that other programs open these files.
|
||||
|
||||
/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53).
|
||||
pub fn chunk(id: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
let mut out = id.to_vec();
|
||||
out.extend((body.len() as u32).to_le_bytes());
|
||||
out.extend(body);
|
||||
if body.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A `LIST` chunk of form `form`.
|
||||
pub fn list(form: &[u8; 4], children: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut body = form.to_vec();
|
||||
body.extend(children.concat());
|
||||
chunk(b"LIST", &body)
|
||||
}
|
||||
|
||||
/// The RIFF form `CMX1` around `children`.
|
||||
pub fn riff(children: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut body = b"CMX1".to_vec();
|
||||
body.extend(children.concat());
|
||||
chunk(b"RIFF", &body)
|
||||
}
|
||||
|
||||
/// The header (R54): `coord` is the coordinate size digit (`b'4'` or `b'2'`) and `meters` the size
|
||||
/// of a coordinate unit. The header string and the system name, which the reader doesn't read,
|
||||
/// are left as zeros.
|
||||
pub fn cont(coord: u8, meters: f64) -> Vec<u8> {
|
||||
let mut c = vec![0u8; 180];
|
||||
c[48] = b'2';
|
||||
c[52] = coord;
|
||||
c[54] = b'2';
|
||||
c[64..72].copy_from_slice(&meters.to_le_bytes());
|
||||
chunk(b"cont", &c)
|
||||
}
|
||||
|
||||
/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55).
|
||||
pub fn field(tag: u8, data: &[u8]) -> Vec<u8> {
|
||||
let mut f = vec![tag];
|
||||
f.extend(((data.len() + 3) as u16).to_le_bytes());
|
||||
f.extend(data);
|
||||
f
|
||||
}
|
||||
|
||||
/// A field list: the fields, then 0xff (R55).
|
||||
pub fn fields(fields: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut l = fields.concat();
|
||||
l.push(0xff);
|
||||
l
|
||||
}
|
||||
|
||||
/// A table chunk: a u16 count, then the entries (field lists) (R55).
|
||||
pub fn table(id: &[u8; 4], entries: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut d = (entries.len() as u16).to_le_bytes().to_vec();
|
||||
d.extend(entries.concat());
|
||||
chunk(id, &d)
|
||||
}
|
||||
|
||||
/// A color entry in the older form: the model and palette bytes in field 1, the values in field 2
|
||||
/// (R56).
|
||||
pub fn color(model: u8, values: &[u8]) -> Vec<u8> {
|
||||
fields(&[field(1, &[model, 5]), field(2, values)])
|
||||
}
|
||||
|
||||
/// A color entry with a property list in field 10 whose color record (part 1) holds `model` and
|
||||
/// the four value bytes `v` (R56).
|
||||
pub fn color_record(model: u16, v: [u8; 4]) -> Vec<u8> {
|
||||
color_record_named(model, v, None)
|
||||
}
|
||||
|
||||
/// A color entry as [`color_record`], with a name part (part 3: a u32 count and UTF-16 units)
|
||||
/// after the color when `name` is given (R56).
|
||||
pub fn color_record_named(model: u16, v: [u8; 4], name: Option<&str>) -> Vec<u8> {
|
||||
let mut part = vec![1u8];
|
||||
part.extend(12u32.to_le_bytes());
|
||||
part.extend(model.to_le_bytes());
|
||||
part.extend(5u16.to_le_bytes());
|
||||
part.extend([0; 4]);
|
||||
part.extend(v);
|
||||
if let Some(name) = name {
|
||||
let units: Vec<u16> = name.encode_utf16().collect();
|
||||
part.push(3);
|
||||
part.extend((4 + 2 * units.len() as u32).to_le_bytes());
|
||||
part.extend((units.len() as u32).to_le_bytes());
|
||||
part.extend(units.iter().flat_map(|u| u.to_le_bytes()));
|
||||
}
|
||||
let mut rec = (part.len() as u32).to_le_bytes().to_vec();
|
||||
rec.extend(part);
|
||||
fields(&[field(10, &rec)])
|
||||
}
|
||||
|
||||
/// A pen entry (R57): the width in coordinate units, an aspect of 100 and no angle, with the
|
||||
/// identity matrix.
|
||||
pub fn pen(width: u32) -> Vec<u8> {
|
||||
let mut d = width.to_le_bytes().to_vec();
|
||||
d.extend(100u16.to_le_bytes());
|
||||
d.extend(0i32.to_le_bytes());
|
||||
d.extend(1u16.to_le_bytes());
|
||||
fields(&[field(1, &d)])
|
||||
}
|
||||
|
||||
/// A line type entry (R57): its flags and the caps (low 4 bits) and join (high 4 bits).
|
||||
pub fn line_type(flags: u8, caps_join: u8) -> Vec<u8> {
|
||||
fields(&[field(1, &[flags, caps_join])])
|
||||
}
|
||||
|
||||
/// A dash pattern entry (R57): the lengths in outline widths.
|
||||
pub fn dashes(lengths: &[u16]) -> Vec<u8> {
|
||||
let mut d = (lengths.len() as u16).to_le_bytes().to_vec();
|
||||
d.extend(lengths.iter().flat_map(|l| l.to_le_bytes()));
|
||||
fields(&[field(1, &d)])
|
||||
}
|
||||
|
||||
/// An outline entry (R58): 1-based indexes of the line type, screen, color, arrowhead pair, pen and
|
||||
/// dash pattern.
|
||||
pub fn outline(parts: [u16; 6]) -> Vec<u8> {
|
||||
fields(&[field(1, &parts.iter().flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())])
|
||||
}
|
||||
|
||||
/// The arrowhead pairs chunk (R59): a u16 count, then start and end (u16 each).
|
||||
pub fn arrowheads(pairs: &[(u16, u16)]) -> Vec<u8> {
|
||||
let mut d = (pairs.len() as u16).to_le_bytes().to_vec();
|
||||
for (s, e) in pairs {
|
||||
d.extend(s.to_le_bytes());
|
||||
d.extend(e.to_le_bytes());
|
||||
}
|
||||
chunk(b"rota", &d)
|
||||
}
|
||||
|
||||
/// An instruction in the short form: a u16 size counting the whole instruction, the code, the
|
||||
/// body (R60).
|
||||
pub fn instr(code: i16, body: &[u8]) -> Vec<u8> {
|
||||
let mut i = ((body.len() + 4) as u16).to_le_bytes().to_vec();
|
||||
i.extend(code.to_le_bytes());
|
||||
i.extend(body);
|
||||
i
|
||||
}
|
||||
|
||||
/// An instruction in the long form: 0xFFFF, a u32 size counting the whole instruction, the code,
|
||||
/// the body (R60).
|
||||
pub fn long_instr(code: i16, body: &[u8]) -> Vec<u8> {
|
||||
let mut i = 0xFFFFu16.to_le_bytes().to_vec();
|
||||
i.extend(((body.len() + 8) as u32).to_le_bytes());
|
||||
i.extend(code.to_le_bytes());
|
||||
i.extend(body);
|
||||
i
|
||||
}
|
||||
|
||||
/// Begin a page (R61), with its width and height in coordinate units in field 4 when given.
|
||||
pub fn begin_page(size: Option<(u32, u32)>) -> Vec<u8> {
|
||||
let mut f = vec![field(1, &[1, 0, 0, 0, 0, 0])];
|
||||
if let Some((w, h)) = size {
|
||||
let mut d = w.to_le_bytes().to_vec();
|
||||
d.extend(h.to_le_bytes());
|
||||
f.push(field(4, &d));
|
||||
}
|
||||
instr(9, &fields(&f))
|
||||
}
|
||||
|
||||
/// Begin a page (R61) without a size of its own, with the drawing's left, top, right and bottom
|
||||
/// edges in field 1.
|
||||
pub fn begin_page_in_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Vec<u8> {
|
||||
let mut d = vec![1, 0, 0, 0, 0, 0];
|
||||
for v in [left, top, right, bottom] {
|
||||
d.extend(v.to_le_bytes());
|
||||
}
|
||||
instr(9, &fields(&[field(1, &d)]))
|
||||
}
|
||||
|
||||
/// Begin a layer (R62) named in 8-bit characters in field 1 from byte 12, and in UTF-16 in
|
||||
/// field 4 when `wide` is given.
|
||||
pub fn begin_layer(name: &str, wide: Option<&str>) -> Vec<u8> {
|
||||
let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
d.extend((name.len() as u16).to_le_bytes());
|
||||
d.extend(name.bytes());
|
||||
let mut f = vec![field(1, &d)];
|
||||
if let Some(w) = wide {
|
||||
let units: Vec<u16> = w.encode_utf16().collect();
|
||||
let mut d = (units.len() as u32).to_le_bytes().to_vec();
|
||||
d.extend(units.iter().flat_map(|u| u.to_le_bytes()));
|
||||
f.push(field(4, &d));
|
||||
}
|
||||
instr(11, &fields(&f))
|
||||
}
|
||||
|
||||
pub fn end_layer() -> Vec<u8> {
|
||||
instr(12, &[])
|
||||
}
|
||||
|
||||
pub fn end_page() -> Vec<u8> {
|
||||
instr(10, &[])
|
||||
}
|
||||
|
||||
pub fn begin_group() -> Vec<u8> {
|
||||
instr(13, &fields(&[field(1, &[0; 26])]))
|
||||
}
|
||||
|
||||
pub fn end_group() -> Vec<u8> {
|
||||
instr(14, &[])
|
||||
}
|
||||
|
||||
/// Rendering attributes (R63): a uniform fill of color `fill` and the outline `outline` (1-based
|
||||
/// indexes; `None` leaves the part out of the mask), and `lens` sets the lens bit.
|
||||
pub fn attrs(fill: Option<u16>, outline: Option<u16>, lens: bool) -> Vec<u8> {
|
||||
let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1) | (u8::from(lens) << 2);
|
||||
let mut a = vec![mask];
|
||||
if let Some(c) = fill {
|
||||
let mut v = 1u16.to_le_bytes().to_vec();
|
||||
let mut uniform = c.to_le_bytes().to_vec();
|
||||
uniform.extend(0u16.to_le_bytes());
|
||||
v.extend(fields(&[field(1, &uniform)]));
|
||||
a.extend(fields(&[field(1, &v)]));
|
||||
}
|
||||
if let Some(o) = outline {
|
||||
a.extend(fields(&[field(1, &o.to_le_bytes())]));
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// Rendering attributes with a fill of type `kind` and no settings of its own.
|
||||
pub fn attrs_fill_type(kind: u16) -> Vec<u8> {
|
||||
let mut a = vec![1u8];
|
||||
a.extend(fields(&[field(1, &kind.to_le_bytes())]));
|
||||
a
|
||||
}
|
||||
|
||||
/// A curve (R62): `attrs`, then a u16 count, the points (i32 x, y) and their type bytes.
|
||||
pub fn curve(attrs: &[u8], points: &[(i32, i32)], types: &[u8]) -> Vec<u8> {
|
||||
let mut g = (points.len() as u16).to_le_bytes().to_vec();
|
||||
for (x, y) in points {
|
||||
g.extend(x.to_le_bytes());
|
||||
g.extend(y.to_le_bytes());
|
||||
}
|
||||
g.extend(types);
|
||||
instr(67, &fields(&[field(1, attrs), field(2, &g), field(3, &[0; 16])]))
|
||||
}
|
||||
|
||||
/// A closed square of side `side` with its lower left corner at (`x`, `y`).
|
||||
pub fn square(attrs: &[u8], x: i32, y: i32, side: i32) -> Vec<u8> {
|
||||
curve(attrs, &[(x, y), (x + side, y), (x + side, y + side), (x, y + side), (x, y)], &[0x0c, 0x44, 0x44, 0x44, 0x48])
|
||||
}
|
||||
|
||||
/// A `page` chunk of `instructions`.
|
||||
pub fn page(instructions: &[Vec<u8>]) -> Vec<u8> {
|
||||
chunk(b"page", &instructions.concat())
|
||||
}
|
||||
|
||||
/// The tables of [`sample`]: colors red (RGB), black (CMYK in percent) and blue (a color record,
|
||||
/// blue, green, red); pens of 0.5 mm and 1 mm; line types solid with round caps and joins, none,
|
||||
/// and dashed behind the fill; one dash pattern; three outlines; one empty arrowhead pair.
|
||||
pub fn tables() -> Vec<Vec<u8>> {
|
||||
vec![
|
||||
table(b"rclr", &[color(5, &[255, 0, 0]), color(2, &[0, 0, 0, 100]), color_record(5, [255, 0, 0, 0])]),
|
||||
table(b"rpen", &[pen(5_000), pen(10_000)]),
|
||||
table(b"rott", &[line_type(2, 0x11), line_type(1, 0), line_type(2 | 4 | 8, 0x02)]),
|
||||
table(b"rdot", &[dashes(&[3, 1])]),
|
||||
table(b"rotl", &[outline([1, 1, 2, 1, 1, 1]), outline([2, 1, 2, 1, 1, 1]), outline([3, 1, 3, 1, 2, 1])]),
|
||||
arrowheads(&[(0, 0)]),
|
||||
]
|
||||
}
|
||||
|
||||
/// One page of 210 x 297 mm with two layers: "Art" holds a red square outlined in black, then a
|
||||
/// group of a square with no outline and a blue one with the dashed outline; "Top" holds a black
|
||||
/// square drawn last. Units are 0.1 µm.
|
||||
pub fn sample() -> Vec<u8> {
|
||||
let p = page(&[
|
||||
begin_page(Some((2_100_000, 2_970_000))),
|
||||
begin_layer("Art", None),
|
||||
square(&attrs(Some(1), Some(1), false), -500_000, -500_000, 1_000_000),
|
||||
begin_group(),
|
||||
square(&attrs(Some(2), Some(2), false), 0, 0, 100_000),
|
||||
square(&attrs(Some(3), Some(3), false), 200_000, 0, 100_000),
|
||||
end_group(),
|
||||
end_layer(),
|
||||
begin_layer("Top", Some("Top")),
|
||||
square(&attrs(Some(2), None, false), 0, 0, 10_000),
|
||||
end_layer(),
|
||||
end_page(),
|
||||
]);
|
||||
let mut children = vec![cont(b'4', 1e-7), p];
|
||||
children.extend(tables());
|
||||
riff(&children)
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Drawings of versions 1 and 2: the file before RIFF, which starts with `WL` (R40 to R44). A
|
||||
//! header of offsets, the settings with the page's box, then one flat list of records: 28 bytes
|
||||
//! for a group or a layer, and a longer record for each drawn object, which holds its matrix, fill,
|
||||
//! outline and shape. The reader maps the rectangles, ellipses and curves onto one page with one
|
||||
//! layer and keeps no groups.
|
||||
|
||||
use crate::bytes::{Rd, u32_at};
|
||||
use crate::geometry;
|
||||
use crate::layout::{self, Profile};
|
||||
use crate::limits::Budget;
|
||||
use crate::model::{Cap, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape};
|
||||
use crate::records::{self, coord, fixed};
|
||||
use crate::riff::push;
|
||||
use crate::{Error, Warning};
|
||||
|
||||
/// The header: the signature, a marker byte, a zero and five u32 offsets (R40).
|
||||
const HEADER: usize = 28;
|
||||
/// The marker bytes read after `WL` (R40): `e` for version 1, `l` and `m` for version 2.
|
||||
const MARKERS: [u8; 3] = *b"elm";
|
||||
/// Where the page's box lies after the start of the settings (R41).
|
||||
const PAGE_BOX: usize = 2;
|
||||
/// The bytes of a group or layer record (R42).
|
||||
const GROUP: usize = 28;
|
||||
/// The u32 that starts every record (R42).
|
||||
const RECORD_START: u32 = 24;
|
||||
/// The flag bit, in byte 26, of a drawn object (R42).
|
||||
const DRAWN: u8 = 0x40;
|
||||
/// The bytes after a drawn object's body size (R42).
|
||||
const AFTER_BODY: usize = 32;
|
||||
/// Where a drawn object's fields lie (R43, R44).
|
||||
const POINT: usize = 32;
|
||||
const KIND: usize = 60;
|
||||
const OUTLINED: usize = 67;
|
||||
const OUTLINE_WIDTH: usize = 68;
|
||||
const OUTLINE_COLOR: usize = 74;
|
||||
|
||||
/// Where a drawn object's fill and shape lie, which differs between the markers (R43, R44).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Fields {
|
||||
fill_kind: usize,
|
||||
shape: usize,
|
||||
}
|
||||
|
||||
impl Fields {
|
||||
fn of(marker: u8) -> Self {
|
||||
if marker == b'e' { Fields { fill_kind: 94, shape: 114 } } else { Fields { fill_kind: 105, shape: 136 } }
|
||||
}
|
||||
|
||||
/// The least a drawn object takes: its fixed fields and the 4 bytes of a shape's size.
|
||||
fn least(self) -> usize {
|
||||
self.shape + 4
|
||||
}
|
||||
}
|
||||
/// Object types (R43).
|
||||
const RECTANGLE: u8 = 0;
|
||||
const ELLIPSE: u8 = 1;
|
||||
const CURVE: u8 = 2;
|
||||
const TEXT: u8 = 3;
|
||||
|
||||
/// Where the settings start, and where the records start and end, when `b` has a `WL` header
|
||||
/// whose offsets fit the file.
|
||||
fn header(b: &[u8]) -> Option<(usize, usize, usize)> {
|
||||
if b.get(..2)? != b"WL" || !MARKERS.contains(b.get(2)?) || *b.get(3)? != 0 {
|
||||
return None;
|
||||
}
|
||||
let (settings, start, end) = (u32_at(b, 4)? as usize, u32_at(b, 8)? as usize, u32_at(b, 12)? as usize);
|
||||
(settings >= HEADER && settings <= start && start <= end && end <= b.len()).then_some((settings, start, end))
|
||||
}
|
||||
|
||||
/// Does `b` start like a drawing of version 1 or 2? The two letters alone are not enough: the
|
||||
/// marker byte, the zero after it and the record offsets must fit too.
|
||||
pub(crate) fn is_wl(b: &[u8]) -> bool {
|
||||
header(b).is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
|
||||
let (settings, start, end) = header(b).ok_or(Error::NotCdr)?;
|
||||
let marker = b.get(2).copied().ok_or(Error::NotCdr)?;
|
||||
let fields = Fields::of(marker);
|
||||
// Lengths are i16 in 1/1000 inch, as in version 3 (R5).
|
||||
let p = layout::for_version(layout::OLDEST_RIFF).ok_or(Error::NotCdr)?;
|
||||
let mut warn = Vec::new();
|
||||
let mut objects = Vec::new();
|
||||
let mut at = start;
|
||||
// Every step takes at least a group record's bytes, so the file's size bounds the steps.
|
||||
while end - at >= GROUP {
|
||||
budget.take_chunk()?;
|
||||
// A record that doesn't start as records do is past one whose length isn't known.
|
||||
if u32_at(b, at) != Some(RECORD_START) {
|
||||
break;
|
||||
}
|
||||
if b.get(at + 26).is_none_or(|flags| flags & DRAWN == 0) {
|
||||
at += GROUP;
|
||||
continue;
|
||||
}
|
||||
// A drawn object of another type than rectangle, ellipse, curve and text doesn't say its
|
||||
// length in the same way, so the records after it can't be found.
|
||||
if b.get(at + KIND).is_none_or(|kind| *kind > TEXT) {
|
||||
push(&mut warn, Warning::UnsupportedObjects);
|
||||
at = end;
|
||||
break;
|
||||
}
|
||||
let len = Rd::at(b, at + 28).u16().map_or(0, |body| usize::from(body) + AFTER_BODY);
|
||||
let Some(rec) = b.get(at..at + len).filter(|_| len >= fields.least() && at + len <= end) else {
|
||||
push(&mut warn, Warning::Damaged);
|
||||
at = end;
|
||||
break;
|
||||
};
|
||||
at += len;
|
||||
if !budget.take_object() {
|
||||
push(&mut warn, Warning::TooDeep);
|
||||
at = end;
|
||||
break;
|
||||
}
|
||||
objects.extend(object(rec, fields, &p, budget, &mut warn));
|
||||
}
|
||||
if at != end {
|
||||
push(&mut warn, Warning::Damaged);
|
||||
}
|
||||
let version = if marker == b'e' { 100 } else { 200 };
|
||||
let layer = Layer { name: String::new(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() };
|
||||
let pages = vec![Page { size: None, layers: vec![layer] }];
|
||||
Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
|
||||
}
|
||||
|
||||
/// The page's size from its box (R41): left, top, right and bottom around the page's centre.
|
||||
fn page_box(b: &[u8], settings: usize, p: &Profile) -> Option<(f64, f64)> {
|
||||
let mut r = Rd::at(b, settings + PAGE_BOX);
|
||||
let (left, top, right, bottom) = (coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let (w, h) = ((right - left).abs(), (top - bottom).abs());
|
||||
(w > 0.0 && h > 0.0).then_some((w, h))
|
||||
}
|
||||
|
||||
/// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object
|
||||
/// of another type and for a shape that can't be read.
|
||||
fn object(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Object> {
|
||||
// A curve left out at the coordinate limit is not damage.
|
||||
budget.coordinates_refused();
|
||||
let read = shape(rec, fields, p, budget, warn);
|
||||
if read.is_none() && !budget.coordinates_refused() {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
read?.map(|s| Object::Shape(Box::new(s)))
|
||||
}
|
||||
|
||||
/// The shape of a record. The outer `None` is a record that can't be read; the inner one an object
|
||||
/// the reader leaves out, with its warning.
|
||||
fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Option<Shape>> {
|
||||
let k = p.unit();
|
||||
let mut r = Rd::at(rec, POINT);
|
||||
let (x, y) = (f64::from(r.i16()?), f64::from(r.i16()?));
|
||||
// x' = a x + b y + tx + x of the point, y' = c x + d y + ty + y of the point.
|
||||
let (a, b, tx, c, d, ty) = (fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?);
|
||||
let matrix = Matrix([a, c, b, d, (tx + x) * k, (ty + y) * k]);
|
||||
let body = rec.get(fields.shape..)?;
|
||||
let geometry = match *rec.get(KIND)? {
|
||||
RECTANGLE => rect(body, p)?,
|
||||
ELLIPSE => {
|
||||
let mut s = Rd::new(body);
|
||||
let (w, h) = (coord(&mut s, p)?, coord(&mut s, p)?);
|
||||
// Two angles follow. No source confirms how they make an arc, so an ellipse whose
|
||||
// angles differ is left out; one whose angles are missing is damage.
|
||||
let (from, to) = (s.i16()?, s.i16()?);
|
||||
if from != to {
|
||||
push(warn, Warning::UnsupportedObjects);
|
||||
return Some(None);
|
||||
}
|
||||
Geometry::Ellipse { w, h }
|
||||
}
|
||||
CURVE => Geometry::Path(geometry::point_list(body, p, budget, warn)?),
|
||||
_ => {
|
||||
push(warn, Warning::UnsupportedObjects);
|
||||
return Some(None);
|
||||
}
|
||||
};
|
||||
let color_at = |at: usize, warn: &mut Vec<Warning>| Some(records::color5(rec.get(at..at + 5)?.try_into().ok()?, warn));
|
||||
let fill = match *rec.get(fields.fill_kind)? {
|
||||
0 => None,
|
||||
1 => Some(color_at(fields.fill_kind + 1, warn)?),
|
||||
_ => {
|
||||
push(warn, Warning::UnsupportedFills);
|
||||
None
|
||||
}
|
||||
};
|
||||
let outline = if *rec.get(OUTLINED)? != 0 {
|
||||
let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k;
|
||||
Some(Outline {
|
||||
width,
|
||||
color: color_at(OUTLINE_COLOR, warn)?,
|
||||
cap: Cap::Butt,
|
||||
join: Join::Miter,
|
||||
dashes: Vec::new(),
|
||||
behind_fill: false,
|
||||
scale_with: false,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(Some(Shape::new(geometry, matrix, fill, outline)))
|
||||
}
|
||||
|
||||
/// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most
|
||||
/// half the shorter side.
|
||||
fn rect(body: &[u8], p: &Profile) -> Option<Geometry> {
|
||||
let mut r = Rd::new(body);
|
||||
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
|
||||
let radius = coord(&mut r, p).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0);
|
||||
Some(Geometry::Rect { w, h, radii: [radius; 4] })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Limits;
|
||||
use crate::model::Color;
|
||||
use crate::synth::{self, WlShape};
|
||||
|
||||
fn read(b: &[u8]) -> Result<Drawing, Error> {
|
||||
drawing(b, &mut Budget::new(Limits::default()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_header_is_taken_only_when_its_offsets_fit() {
|
||||
let file = synth::wl_file(b'e', (612.0, 792.0), &[synth::wl_group()]);
|
||||
assert!(is_wl(&file));
|
||||
// The two letters, a marker and a zero are not enough.
|
||||
assert!(!is_wl(b"WLe\0"));
|
||||
assert!(!is_wl(b"WLe\0 and then some text that is long enough to hold offsets"));
|
||||
let with = |at: usize, v: u32| {
|
||||
let mut f = file.clone();
|
||||
f[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||||
f
|
||||
};
|
||||
// Records that start inside the header, start after their end, or end past the file.
|
||||
assert!(!is_wl(&with(8, 27)));
|
||||
assert!(!is_wl(&with(8, file.len() as u32)));
|
||||
assert!(!is_wl(&with(12, file.len() as u32 + 1)));
|
||||
// Settings that start inside the header or after the records.
|
||||
assert!(!is_wl(&with(4, 27)));
|
||||
assert!(!is_wl(&with(4, 65)));
|
||||
let mut other = file.clone();
|
||||
other[2] = b'x';
|
||||
assert!(!is_wl(&other));
|
||||
// No sample shows the marker `d`, so it is not taken.
|
||||
other[2] = b'd';
|
||||
assert!(!is_wl(&other));
|
||||
for marker in *b"lm" {
|
||||
assert!(is_wl(&synth::wl_file(marker, (612.0, 792.0), &[synth::wl_group()])));
|
||||
}
|
||||
other[2] = b'e';
|
||||
other[3] = 1;
|
||||
assert!(!is_wl(&other));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_2_file_keeps_its_page_box_fill_and_shape_where_that_version_puts_them() {
|
||||
let (red, black) = ([1, 0, 100, 100, 0], [1, 0, 0, 0, 100]);
|
||||
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 9.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(red), Some((2.0, black)));
|
||||
for marker in *b"elm" {
|
||||
let file = synth::wl_file(marker, (720.0, 504.0), std::slice::from_ref(&rect));
|
||||
// Version 2 files start their settings after a picture, not after the header.
|
||||
assert_eq!(u32_at(&file, 4) == Some(28), marker == b'e');
|
||||
let d = read(&file).unwrap();
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 0.02;
|
||||
assert_eq!((d.version, d.warnings.clone()), (if marker == b'e' { 100 } else { 200 }, vec![]));
|
||||
assert!(d.page_size.is_some_and(|(w, h)| near(w, 720.0) && near(h, 504.0)), "{:?}", d.page_size);
|
||||
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
|
||||
assert!(
|
||||
matches!(s.geometry, Geometry::Rect { w, h, radii } if near(w, 72.0) && near(h, 36.0) && near(radii[0], 9.0)),
|
||||
"{}",
|
||||
marker as char
|
||||
);
|
||||
assert_eq!(s.fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0])), "{}", marker as char);
|
||||
assert!(s.outline.as_ref().is_some_and(|o| near(o.width, 2.0) && o.color == Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{}", marker as char);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawn_object_is_marked_by_its_flag_bit() {
|
||||
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], None, None);
|
||||
let mut file = synth::wl_file(b'l', (612.0, 792.0), &[rect]);
|
||||
// Files with the marker `l` set another flag bit beside it.
|
||||
file[64 + 26] = 0xc0;
|
||||
let d = read(&file).unwrap();
|
||||
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walk_stops_where_records_can_no_longer_be_found() {
|
||||
let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
let rect = || synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, unit, None, None);
|
||||
// An object of another type doesn't give its length in the same way.
|
||||
let mut other = rect();
|
||||
other[KIND] = 0xff;
|
||||
let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[rect(), other, rect()])).unwrap();
|
||||
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::UnsupportedObjects]));
|
||||
// A record that doesn't start as records do.
|
||||
let mut lost = rect();
|
||||
lost[0] = 0x84;
|
||||
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), lost, rect()])).unwrap();
|
||||
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::Damaged]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangle_keeps_a_radius_of_at_most_half_its_shorter_side() {
|
||||
let p = layout::for_version(300).unwrap();
|
||||
let body = |radius: i16| [1000i16, 500, radius].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>();
|
||||
let radius_of = |b: &[u8]| match rect(b, &p) {
|
||||
Some(Geometry::Rect { w, h, radii }) if (w - 72.0).abs() < 1e-9 && (h - 36.0).abs() < 1e-9 => radii[0],
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert!((radius_of(&body(200)) - 14.4).abs() < 1e-9);
|
||||
for radius in [300, -5, 0] {
|
||||
assert_eq!(radius_of(&body(radius)), 0.0, "{radius}");
|
||||
}
|
||||
// A record that ends after the size has square corners.
|
||||
assert_eq!(radius_of(&body(200)[..4]), 0.0);
|
||||
assert_eq!(rect(&body(200)[..3], &p), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_shorter_than_its_fields_ends_the_walk_as_damage() {
|
||||
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None);
|
||||
let mut short = rect.clone();
|
||||
// A body size that leaves less than the fixed fields.
|
||||
short[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY - 1) as u16).to_le_bytes());
|
||||
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect.clone(), short, rect])).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
assert_eq!(d.warnings, vec![Warning::Damaged]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ellipse_without_its_angles_is_damage() {
|
||||
let ellipse =
|
||||
synth::wl_object(WlShape::Ellipse { w: 72.0, h: 36.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None);
|
||||
let mut cut = ellipse.clone();
|
||||
// A body size that ends the record after the ellipse's width and height.
|
||||
cut[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY) as u16).to_le_bytes());
|
||||
cut.truncate(Fields::of(b'e').least());
|
||||
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[ellipse, cut])).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
assert_eq!(d.warnings, vec![Warning::Damaged]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_types_other_than_uniform_and_unknown_inks_are_named() {
|
||||
let mut textured =
|
||||
synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([0, 9, 0, 50, 0]), None);
|
||||
let d = read(&synth::wl_file(b'm', (612.0, 792.0), std::slice::from_ref(&textured))).unwrap();
|
||||
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
|
||||
assert_eq!(s.fill, Some(Color::Spot { name: "Spot 0:9".into(), tint: 0.5, look: None }));
|
||||
assert_eq!((d.version, d.warnings), (200, vec![Warning::SpotLooks]));
|
||||
textured[Fields::of(b'e').fill_kind] = 5;
|
||||
let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[textured])).unwrap();
|
||||
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
|
||||
assert_eq!((s.fill.clone(), d.warnings), (None, vec![Warning::UnsupportedFills]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! The ZIP archives of `.cdr` drawings from version 14 on (R24): the central directory, then stored
|
||||
//! and deflated members read on request. Archives that span disks, ZIP64 archives and encrypted
|
||||
//! members are refused; so are directories whose members overlap or repeat a name.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::io::Read as _;
|
||||
|
||||
use crate::Error;
|
||||
use crate::bytes::Rd;
|
||||
|
||||
/// End of central directory record: signature and fixed length.
|
||||
const END: u32 = 0x0605_4b50;
|
||||
const END_LEN: usize = 22;
|
||||
/// The longest archive comment, which the end record may be followed by.
|
||||
const MAX_COMMENT: usize = 0xFFFF;
|
||||
/// ZIP64 end of central directory locator, 20 bytes before the end record when present.
|
||||
const ZIP64_LOCATOR: u32 = 0x0706_4b50;
|
||||
/// Central directory header: signature and fixed length.
|
||||
const CENTRAL: u32 = 0x0201_4b50;
|
||||
const CENTRAL_LEN: usize = 46;
|
||||
/// Local file header: signature and fixed length.
|
||||
const LOCAL: u32 = 0x0403_4b50;
|
||||
const LOCAL_LEN: usize = 30;
|
||||
/// General purpose flag bit 0: the member is encrypted.
|
||||
const ENCRYPTED: u16 = 1;
|
||||
const STORED: u16 = 0;
|
||||
const DEFLATED: u16 = 8;
|
||||
/// What members packed by another method are refused as.
|
||||
const OTHER_METHODS: &str = "package compression methods other than storing and deflate";
|
||||
|
||||
/// One member, as the central directory and its local header give it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Entry<'a> {
|
||||
name: &'a [u8],
|
||||
flags: u16,
|
||||
method: u16,
|
||||
crc: u32,
|
||||
packed: usize,
|
||||
size: usize,
|
||||
/// Where its local header starts and where its packed bytes start.
|
||||
header: usize,
|
||||
data: usize,
|
||||
}
|
||||
|
||||
/// An archive's directory over its bytes.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Archive<'a> {
|
||||
bytes: &'a [u8],
|
||||
entries: Vec<Entry<'a>>,
|
||||
/// The entries in name order, for lookups.
|
||||
by_name: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Does `bytes` start with a local file header?
|
||||
pub(crate) fn is_zip(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(b"PK\x03\x04")
|
||||
}
|
||||
|
||||
impl<'a> Archive<'a> {
|
||||
/// The directory of `bytes`, holding at most `max_entries` members.
|
||||
pub(crate) fn open(bytes: &'a [u8], max_entries: usize) -> Result<Self, Error> {
|
||||
let end = find_end(bytes).ok_or(Error::Damaged("package directory"))?;
|
||||
if end >= 20 && Rd::at(bytes, end - 20).u32() == Some(ZIP64_LOCATOR) {
|
||||
return Err(Error::Unsupported("ZIP64 packages"));
|
||||
}
|
||||
let mut r = Rd::at(bytes, end + 4);
|
||||
let dir = || Error::Damaged("package directory");
|
||||
let (disk, dir_disk) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?);
|
||||
let (on_disk, total) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?);
|
||||
let (dir_len, dir_at) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?);
|
||||
if total == u16::MAX || dir_len == u32::MAX || dir_at == u32::MAX {
|
||||
return Err(Error::Unsupported("ZIP64 packages"));
|
||||
}
|
||||
if disk != 0 || dir_disk != 0 || on_disk != total {
|
||||
return Err(Error::Unsupported("packages split across files"));
|
||||
}
|
||||
let total = usize::from(total);
|
||||
if total > max_entries {
|
||||
return Err(Error::Limit("package member count"));
|
||||
}
|
||||
let (dir_at, dir_len) = (dir_at as usize, dir_len as usize);
|
||||
let dir_end = dir_at.checked_add(dir_len).filter(|&e| e <= end).ok_or_else(dir)?;
|
||||
let mut r = Rd::at(bytes, dir_at);
|
||||
let mut entries = Vec::with_capacity(total);
|
||||
for _ in 0..total {
|
||||
let e = central_entry(bytes, &mut r, dir_end)?;
|
||||
entries.push(e);
|
||||
}
|
||||
// Each member's bytes end before the next member's header and before the directory.
|
||||
let mut order: Vec<&Entry> = entries.iter().collect();
|
||||
order.sort_unstable_by_key(|e| e.header);
|
||||
for (i, e) in order.iter().enumerate() {
|
||||
let stop = order.get(i + 1).map_or(dir_at, |n| n.header);
|
||||
if e.data.checked_add(e.packed).is_none_or(|x| x > stop) {
|
||||
return Err(Error::Damaged("package members overlap"));
|
||||
}
|
||||
}
|
||||
let mut by_name: Vec<usize> = (0..entries.len()).collect();
|
||||
by_name.sort_unstable_by_key(|&i| entries.get(i).map(|e| e.name));
|
||||
let name = |i: &usize| entries.get(*i).map(|e| e.name);
|
||||
if by_name.windows(2).any(|w| name(&w[0]) == name(&w[1])) {
|
||||
return Err(Error::Damaged("package member named twice"));
|
||||
}
|
||||
Ok(Archive { bytes, entries, by_name })
|
||||
}
|
||||
|
||||
/// The member named `name`.
|
||||
pub(crate) fn find(&self, name: &[u8]) -> Option<usize> {
|
||||
let at = self.by_name.binary_search_by(|&i| self.entries.get(i).map(|e| e.name).cmp(&Some(name))).ok()?;
|
||||
self.by_name.get(at).copied()
|
||||
}
|
||||
|
||||
/// The size member `i`'s directory entry gives.
|
||||
pub(crate) fn size(&self, i: usize) -> usize {
|
||||
self.entries.get(i).map_or(0, |e| e.size)
|
||||
}
|
||||
|
||||
/// How many members the archive holds.
|
||||
pub(crate) fn count(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
/// The bytes reading member `i` may inflate: its stated size when it is deflated, else 0.
|
||||
pub(crate) fn inflate_cost(&self, i: usize) -> usize {
|
||||
self.entries.get(i).filter(|e| e.method == DEFLATED).map_or(0, |e| e.size)
|
||||
}
|
||||
|
||||
/// An error when member `i` is encrypted or packed by a method other than storing or deflate.
|
||||
pub(crate) fn check(&self, i: usize) -> Result<(), Error> {
|
||||
let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?;
|
||||
if e.flags & ENCRYPTED != 0 {
|
||||
return Err(Error::Unsupported("encrypted packages"));
|
||||
}
|
||||
if e.method != STORED && e.method != DEFLATED {
|
||||
return Err(Error::Unsupported(OTHER_METHODS));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Member `i`'s bytes when they come to at most `limit`, and a deflated member's when they
|
||||
/// also come to at most `inflate_left`. A stored member is borrowed; a deflated one inflates to
|
||||
/// at most its stated size plus one byte, so a member that inflates past what it states stops
|
||||
/// there. The length and CRC-32 must match the directory's.
|
||||
pub(crate) fn read(&self, i: usize, limit: usize, inflate_left: usize) -> Result<Cow<'a, [u8]>, Error> {
|
||||
self.check(i)?;
|
||||
let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?;
|
||||
if e.size > limit {
|
||||
return Err(Error::Limit("package member size"));
|
||||
}
|
||||
if e.method == DEFLATED && e.size > inflate_left {
|
||||
return Err(Error::Limit("inflated size"));
|
||||
}
|
||||
let packed = self.bytes.get(e.data..e.data + e.packed).ok_or(Error::Damaged("package member"))?;
|
||||
let out: Cow<'a, [u8]> = match e.method {
|
||||
STORED if e.packed == e.size => Cow::Borrowed(packed),
|
||||
STORED => return Err(Error::Damaged("package member")),
|
||||
DEFLATED => {
|
||||
let mut out = Vec::new();
|
||||
let got = flate2::read::DeflateDecoder::new(packed)
|
||||
.take(e.size as u64 + 1)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|_| Error::Damaged("package member"))?;
|
||||
if got != e.size {
|
||||
return Err(Error::Damaged("package member"));
|
||||
}
|
||||
Cow::Owned(out)
|
||||
}
|
||||
_ => return Err(Error::Unsupported(OTHER_METHODS)),
|
||||
};
|
||||
if crc32fast::hash(&out) != e.crc {
|
||||
return Err(Error::Damaged("package member"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the end of central directory record starts: searched back from the end over at most the
|
||||
/// longest comment, among the records whose comment reaches exactly to the end the first that
|
||||
/// names members in a directory before it, else the first. A comment or a member may hold bytes
|
||||
/// that look like an empty archive's end record.
|
||||
fn find_end(bytes: &[u8]) -> Option<usize> {
|
||||
let last = bytes.len().checked_sub(END_LEN)?;
|
||||
let first = last.saturating_sub(MAX_COMMENT);
|
||||
let mut found = None;
|
||||
for at in (first..=last).rev() {
|
||||
let mut r = Rd::at(bytes, at);
|
||||
if r.u32() != Some(END) || r.skip(6).is_none() {
|
||||
continue;
|
||||
}
|
||||
let (total, dir_len, dir_at, comment) = (r.u16(), r.u32(), r.u32(), r.u16());
|
||||
if !comment.is_some_and(|c| at + END_LEN + usize::from(c) == bytes.len()) {
|
||||
continue;
|
||||
}
|
||||
let names_members = total.is_some_and(|t| t > 0)
|
||||
&& dir_len.zip(dir_at).is_some_and(|(len, dir)| {
|
||||
(dir as usize).checked_add(len as usize).is_some_and(|e| e <= at) && Rd::at(bytes, dir as usize).u32() == Some(CENTRAL)
|
||||
});
|
||||
if names_members {
|
||||
return Some(at);
|
||||
}
|
||||
found = found.or(Some(at));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The central directory entry at `r` (before `dir_end`) and its local header.
|
||||
fn central_entry<'a>(bytes: &'a [u8], r: &mut Rd<'a>, dir_end: usize) -> Result<Entry<'a>, Error> {
|
||||
let dir = || Error::Damaged("package directory");
|
||||
if r.pos().checked_add(CENTRAL_LEN).is_none_or(|e| e > dir_end) || r.u32() != Some(CENTRAL) {
|
||||
return Err(dir());
|
||||
}
|
||||
r.skip(4).ok_or_else(dir)?;
|
||||
let flags = r.u16().ok_or_else(dir)?;
|
||||
let method = r.u16().ok_or_else(dir)?;
|
||||
r.skip(4).ok_or_else(dir)?;
|
||||
let crc = r.u32().ok_or_else(dir)?;
|
||||
let (packed, size) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?);
|
||||
let name_len = usize::from(r.u16().ok_or_else(dir)?);
|
||||
let extra_len = usize::from(r.u16().ok_or_else(dir)?);
|
||||
let comment_len = usize::from(r.u16().ok_or_else(dir)?);
|
||||
let disk = r.u16().ok_or_else(dir)?;
|
||||
r.skip(6).ok_or_else(dir)?;
|
||||
let header = r.u32().ok_or_else(dir)?;
|
||||
if packed == u32::MAX || size == u32::MAX || header == u32::MAX {
|
||||
return Err(Error::Unsupported("ZIP64 packages"));
|
||||
}
|
||||
if disk != 0 {
|
||||
return Err(Error::Unsupported("packages split across files"));
|
||||
}
|
||||
let name = r.bytes(name_len).ok_or_else(dir)?;
|
||||
r.skip(extra_len).and_then(|()| r.skip(comment_len)).ok_or_else(dir)?;
|
||||
if r.pos() > dir_end {
|
||||
return Err(dir());
|
||||
}
|
||||
// The local header repeats the name; its own extra field may differ in length.
|
||||
let header = header as usize;
|
||||
let mut l = Rd::at(bytes, header);
|
||||
let local = || Error::Damaged("package member header");
|
||||
if l.u32() != Some(LOCAL) {
|
||||
return Err(local());
|
||||
}
|
||||
// The signature, 22 bytes, then the name and extra field lengths.
|
||||
l.skip(LOCAL_LEN - 8).ok_or_else(local)?;
|
||||
let (local_name, local_extra) = (usize::from(l.u16().ok_or_else(local)?), usize::from(l.u16().ok_or_else(local)?));
|
||||
if l.bytes(local_name) != Some(name) {
|
||||
return Err(local());
|
||||
}
|
||||
l.skip(local_extra).ok_or_else(local)?;
|
||||
Ok(Entry { name, flags, method, crc, packed: packed as usize, size: size as usize, header, data: l.pos() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::synth::{Member, zip};
|
||||
|
||||
fn stored(name: &str, data: &[u8]) -> Member {
|
||||
Member { name: name.into(), data: data.to_vec(), deflate: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_and_deflated_members_read_back() {
|
||||
let bytes = zip(&[stored("a", b"hello"), Member { name: "b".into(), data: vec![7; 5000], deflate: true }], b"");
|
||||
let a = Archive::open(&bytes, 10).unwrap();
|
||||
assert!(matches!(a.read(a.find(b"a").unwrap(), 100, 100).unwrap(), Cow::Borrowed(b"hello")));
|
||||
assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 5000).unwrap().as_ref(), &[7; 5000][..]);
|
||||
assert_eq!(a.read(a.find(b"b").unwrap(), 4999, 5000), Err(Error::Limit("package member size")));
|
||||
assert_eq!(a.find(b"c"), None);
|
||||
// What is left to inflate holds back deflated members only.
|
||||
assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 4999), Err(Error::Limit("inflated size")));
|
||||
assert!(a.read(a.find(b"a").unwrap(), 100, 0).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_record_is_found_behind_a_comment() {
|
||||
let bytes = zip(&[stored("a", b"x")], &[b'c'; 300]);
|
||||
assert!(Archive::open(&bytes, 10).is_ok());
|
||||
// A comment longer than the record says leaves no end record to find.
|
||||
let mut cut = bytes.clone();
|
||||
cut.push(0);
|
||||
assert_eq!(Archive::open(&cut, 10).unwrap_err(), Error::Damaged("package directory"));
|
||||
// A comment that ends in bytes like an empty archive's end record: the record that names
|
||||
// members in a directory is the archive's.
|
||||
let mut fake = END.to_le_bytes().to_vec();
|
||||
fake.resize(END_LEN, 0);
|
||||
let bytes = zip(&[stored("a", b"x")], &fake);
|
||||
let a = Archive::open(&bytes, 10).unwrap();
|
||||
assert_eq!(a.count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_whose_crc_or_length_is_wrong_is_damage() {
|
||||
let bytes = zip(&[Member { name: "a".into(), data: vec![1; 64], deflate: true }], b"");
|
||||
let a = Archive::open(&bytes, 10).unwrap();
|
||||
// The directory's CRC-32 sits 16 bytes into its entry.
|
||||
let dir_at = bytes.windows(4).position(|w| w == CENTRAL.to_le_bytes()).unwrap();
|
||||
let mut bad = bytes.clone();
|
||||
bad[dir_at + 16] ^= 1;
|
||||
let b = Archive::open(&bad, 10).unwrap();
|
||||
assert_eq!(b.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member"));
|
||||
// A stated size one short: the inflate runs past it.
|
||||
let mut short = bytes.clone();
|
||||
short[dir_at + 24] -= 1;
|
||||
let s = Archive::open(&short, 10).unwrap();
|
||||
assert_eq!(s.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member"));
|
||||
assert!(a.read(0, 1000, 1000).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Read time of a large synthetic drawing. Run with
|
||||
//! `cargo test --release -p vectorcraft-cdr --test it bench -- --ignored --nocapture`.
|
||||
|
||||
use vectorcraft_cdr::synth::{self, V, chunk, list};
|
||||
use vectorcraft_cdr::{Limits, read};
|
||||
|
||||
/// A version 13 drawing of `n` curves of 22 points each, filled and outlined, compressed when
|
||||
/// `compress`.
|
||||
fn many_curves(n: usize, compress: bool) -> Vec<u8> {
|
||||
let v = V(1300);
|
||||
let red = synth::color(5, [0, 0, 255, 0]);
|
||||
let black = synth::color(2, [0, 0, 0, 100]);
|
||||
let styles = list(
|
||||
b"doc ",
|
||||
vec![
|
||||
synth::mcfg(v, 612.0, 792.0),
|
||||
list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]),
|
||||
list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &black, &[]))]),
|
||||
],
|
||||
);
|
||||
let objects: Vec<_> = (0..n)
|
||||
.map(|i| {
|
||||
let o = (i % 500) as f64;
|
||||
// A move, then curves of two control points and an end point each.
|
||||
let kind = |k: i32| {
|
||||
if k == 0 {
|
||||
0x08
|
||||
} else if k % 3 == 0 {
|
||||
0x80
|
||||
} else {
|
||||
0xC0
|
||||
}
|
||||
};
|
||||
let pts: Vec<(f64, f64, u8)> = (0..22).map(|k| (o + f64::from(k), o + f64::from(k % 5), kind(k))).collect();
|
||||
let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, 2u32.to_le_bytes().to_vec()), (30, v.points(&pts))];
|
||||
synth::object(v, 3, &args, Some([1.0, 0.0, 0.0, 1.0, o, -o]))
|
||||
})
|
||||
.collect();
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", objects)]);
|
||||
let body = vec![styles, page];
|
||||
let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())];
|
||||
if compress {
|
||||
kids.push(synth::cmpr(&body));
|
||||
} else {
|
||||
kids.extend(body);
|
||||
}
|
||||
synth::riff(1300, &kids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn read_a_large_drawing() {
|
||||
for compress in [false, true] {
|
||||
let file = many_curves(50_000, compress);
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let t = std::time::Instant::now();
|
||||
let d = read(&file, Limits::default()).unwrap();
|
||||
times.push(t.elapsed().as_secs_f64() * 1000.0);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
println!("compress={compress} bytes={} median_ms={:.1} min_ms={:.1}", file.len(), times[2], times[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and
|
||||
//! hostile ones.
|
||||
|
||||
use proptest::prelude::*;
|
||||
use vectorcraft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape};
|
||||
use vectorcraft_cdr::synth_cmx::*;
|
||||
use vectorcraft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx};
|
||||
|
||||
fn shape(o: &Object) -> &Shape {
|
||||
match o {
|
||||
Object::Shape(s) => s,
|
||||
other => panic!("not a shape: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The (x, y) bounds of a shape's path.
|
||||
fn bounds(s: &Shape) -> (f64, f64, f64, f64) {
|
||||
let Geometry::Path(p) = &s.geometry else { panic!("not a path") };
|
||||
let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
|
||||
for sp in &p.subpaths {
|
||||
for pt in std::iter::once(sp.start).chain(sp.segments.iter().map(|s| match s {
|
||||
vectorcraft_cdr::model::Segment::Line(p) | vectorcraft_cdr::model::Segment::Cubic(_, _, p) => *p,
|
||||
})) {
|
||||
b = (b.0.min(pt.x), b.1.min(pt.y), b.2.max(pt.x), b.3.max(pt.y));
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// The file with `children` after a 32-bit header and the sample tables.
|
||||
fn file(pages: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.extend(pages.iter().cloned());
|
||||
children.extend(tables());
|
||||
riff(&children)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmx_file_is_told_from_a_cdr_drawing() {
|
||||
let f = sample();
|
||||
assert!(is_cmx(&f) && !is_cdr(&f));
|
||||
let mut rifx = f.clone();
|
||||
rifx[..4].copy_from_slice(b"RIFX");
|
||||
assert!(is_cmx(&rifx));
|
||||
assert!(!is_cmx(b"RIFF\0\0\0\0CDR9"));
|
||||
assert_eq!(read_cmx(b"RIFF\0\0\0\0CDR9", Limits::default()), Err(Error::NotCmx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_layers_groups_and_curves() {
|
||||
let d = read_cmx(&sample(), Limits::default()).unwrap();
|
||||
assert_eq!(d.version, 0);
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
let page = &d.pages[0];
|
||||
// 2,100,000 units of 0.1 µm are 210 mm.
|
||||
let (w, h) = page.size.unwrap();
|
||||
assert!(near(w, 210.0 / 25.4 * 72.0) && near(h, 297.0 / 25.4 * 72.0), "{w} {h}");
|
||||
// The layer drawn last is in front: the model lists layers front to back.
|
||||
let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["Top", "Art"]);
|
||||
let art = &page.layers[1].objects;
|
||||
assert_eq!(art.len(), 2);
|
||||
// The group, drawn after the red square, is in front of it.
|
||||
let Object::Group { objects: kids, .. } = &art[0] else { panic!("{:?}", art[0]) };
|
||||
assert_eq!(kids.len(), 2);
|
||||
let red = shape(&art[1]);
|
||||
assert_eq!(red.fill, Some(Color::Rgb([1.0, 0.0, 0.0])));
|
||||
// 1,000,000 units are 100 mm; the square's corner is 50 mm left of and below the center.
|
||||
let mm = 72.0 / 25.4;
|
||||
let b = bounds(red);
|
||||
assert!(near(b.0, -50.0 * mm) && near(b.1, -50.0 * mm) && near(b.2, 50.0 * mm) && near(b.3, 50.0 * mm), "{b:?}");
|
||||
let Geometry::Path(p) = &red.geometry else { panic!() };
|
||||
assert!(p.subpaths.len() == 1 && p.subpaths[0].closed && p.subpaths[0].segments.len() == 4);
|
||||
let o = red.outline.as_ref().unwrap();
|
||||
assert!(near(o.width, 0.5 * mm));
|
||||
assert_eq!((o.color.clone(), o.cap, o.join), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Round, Join::Round));
|
||||
assert!(o.dashes.is_empty() && !o.behind_fill && !o.scale_with);
|
||||
// Line type 1 draws no outline.
|
||||
let blue = shape(&kids[0]);
|
||||
let black = shape(&kids[1]);
|
||||
assert!(black.outline.is_none());
|
||||
assert_eq!(black.fill, Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0])));
|
||||
// The color record's values are blue, green and red.
|
||||
assert_eq!(blue.fill, Some(Color::Rgb([0.0, 0.0, 1.0])));
|
||||
let o = blue.outline.as_ref().unwrap();
|
||||
assert!(near(o.width, 1.0 * mm));
|
||||
assert_eq!((o.dashes.clone(), o.behind_fill, o.cap, o.join), (vec![3.0, 1.0], true, Cap::Square, Join::Miter));
|
||||
assert_eq!(page.layers[0].name, "Top");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_names_and_layers_without_objects() {
|
||||
let p = page(&[
|
||||
begin_page(None),
|
||||
begin_layer("Ebene 1", Some("Слой 1")),
|
||||
square(&attrs(Some(1), None, false), 0, 0, 1000),
|
||||
end_layer(),
|
||||
begin_layer("Gitter", None),
|
||||
end_layer(),
|
||||
begin_layer("Caf\u{e9}", None),
|
||||
square(&attrs(Some(1), None, false), 0, 0, 1000),
|
||||
end_layer(),
|
||||
end_page(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let page = &d.pages[0];
|
||||
assert_eq!(page.size, None);
|
||||
// The empty layer is left out, and the UTF-16 name wins over the 8-bit one.
|
||||
let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["Caf\u{c3}\u{a9}", "Слой 1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_before_any_layer_get_one() {
|
||||
let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages[0].layers.len(), 1);
|
||||
// The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place.
|
||||
assert_eq!(d.pages[0].layers[0].name, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_without_a_size_takes_the_drawings_bounds() {
|
||||
// A square of 100 mm whose bounds lie off the file's origin, above and to the right.
|
||||
let p = page(&[
|
||||
begin_page_in_bounds(1_000_000, 3_000_000, 2_000_000, 2_000_000),
|
||||
begin_layer("L", None),
|
||||
square(&attrs(Some(1), None, false), 1_000_000, 2_000_000, 1_000_000),
|
||||
end_layer(),
|
||||
end_page(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let page = &d.pages[0];
|
||||
let side = 100.0 / 25.4 * 72.0;
|
||||
let (w, h) = page.size.unwrap();
|
||||
assert!(near(w, side) && near(h, side), "{w} x {h}");
|
||||
// The page is centered on the bounds, so the square fills it.
|
||||
let (x0, y0, x1, y1) = bounds(shape(&page.layers[0].objects[0]));
|
||||
assert!(near(x0, -side / 2.0) && near(x1, side / 2.0) && near(y0, -side / 2.0) && near(y1, side / 2.0), "{x0} {y0} {x1} {y1}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curves_and_open_groups() {
|
||||
let c =
|
||||
curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]);
|
||||
// A group the layer leaves open closes with it.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") };
|
||||
let s = shape(&kids[0]);
|
||||
assert!(s.fill.is_none());
|
||||
let Geometry::Path(p) = &s.geometry else { panic!() };
|
||||
assert_eq!(p.subpaths.len(), 2);
|
||||
assert!(matches!(p.subpaths[0].segments[..], [vectorcraft_cdr::model::Segment::Cubic(..)]));
|
||||
assert!(!p.subpaths[1].closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_without_its_points_is_reported() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() {
|
||||
let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0];
|
||||
d.extend(b"Art");
|
||||
let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])]));
|
||||
let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].name, "Art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_read_is_reported() {
|
||||
let other = |code: i16| instr(code, &fields(&[field(1, &[0; 8])]));
|
||||
let p = page(&[
|
||||
begin_page(None),
|
||||
begin_layer("L", None),
|
||||
other(66),
|
||||
other(68),
|
||||
other(20),
|
||||
other(88),
|
||||
square(&attrs_fill_type(2), 0, 0, 1000),
|
||||
square(&attrs(Some(1), None, true), 0, 0, 1000),
|
||||
end_layer(),
|
||||
]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] {
|
||||
assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings);
|
||||
}
|
||||
// A fill of another type leaves the curve unfilled; the curve is still read.
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
assert_eq!(objects.len(), 2);
|
||||
assert!(shape(&objects[1]).fill.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_of_other_models_and_missing_entries() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[
|
||||
begin_page(None),
|
||||
begin_layer("L", None),
|
||||
square(&attrs(Some(1), None, false), 0, 0, 1000),
|
||||
square(&attrs(Some(9), None, false), 0, 0, 1000),
|
||||
square(&attrs(Some(2), None, false), 0, 0, 1000),
|
||||
]));
|
||||
children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0])));
|
||||
assert_eq!(shape(&objects[1]).fill, Some(Color::Rgb([0.0; 3])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray_cmy_and_rgb_colors_of_the_older_fields() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[
|
||||
begin_page(None),
|
||||
begin_layer("L", None),
|
||||
square(&attrs(Some(1), None, false), 0, 0, 1000),
|
||||
square(&attrs(Some(2), None, false), 0, 0, 1000),
|
||||
square(&attrs(Some(3), None, false), 0, 0, 1000),
|
||||
]));
|
||||
children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
// The model holds objects front to back: the RGB square, the CMY one, then the gray one.
|
||||
assert_eq!(shape(&objects[0]).fill, Some(Color::Rgb([1.0, 0.0, 0.0])));
|
||||
match (shape(&objects[1]).fill.clone(), shape(&objects[2]).fill.clone()) {
|
||||
(Some(Color::Cmyk([c, m, y, k])), Some(Color::Gray(g))) => {
|
||||
assert!((c - 1.0).abs() < 1e-6 && m == 0.0 && (y - 0.2).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}");
|
||||
assert!((g - 0.8).abs() < 1e-6, "{g}");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_arrowheads_are_reported() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)]));
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota")));
|
||||
children.push(arrowheads(&[(0, 2)]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.warnings, vec![Warning::Arrowheads]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_instruction_and_a_jump_over_image_bytes() {
|
||||
// The jump's target counts from the start of the file: header, `cont`, then the page body.
|
||||
let before = riff(&[cont(b'4', 1e-7), page(&[])]).len() - 8;
|
||||
let head = [begin_page(None), begin_layer("L", None)].concat();
|
||||
let jump_len = 4 + 1 + 3 + 4;
|
||||
let image = vec![0xEEu8; 37];
|
||||
let target = (before + 8 + head.len() + jump_len + image.len()) as u32;
|
||||
let jump = instr(111, &fields(&[field(1, &target.to_le_bytes())]));
|
||||
assert_eq!(jump.len(), jump_len);
|
||||
let body = [
|
||||
head,
|
||||
jump,
|
||||
image,
|
||||
long_instr(67, &curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48])[4..]),
|
||||
end_layer(),
|
||||
]
|
||||
.concat();
|
||||
let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
// The images jumped over are not read, and the warning says so.
|
||||
assert_eq!(d.warnings, [Warning::UnsupportedObjects]);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_after_a_chunk_that_runs_short_are_passed_over() {
|
||||
let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff];
|
||||
let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_byte_orders_and_coordinate_sizes_are_refused() {
|
||||
let mut f = sample();
|
||||
f[..4].copy_from_slice(b"RIFX");
|
||||
assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files")));
|
||||
let mut children = vec![cont(b'2', 1e-3)];
|
||||
children.extend(tables());
|
||||
assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates")));
|
||||
assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header")));
|
||||
assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_without_a_usable_unit_reads_0_1_micrometers() {
|
||||
for meters in [0.0, -1.0, f64::NAN, 2.0] {
|
||||
let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
let (w, _) = d.pages[0].size.unwrap();
|
||||
assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_past_the_depth_limit_are_left_out() {
|
||||
let mut ins = vec![begin_page(None), begin_layer("L", None)];
|
||||
for _ in 0..6 {
|
||||
ins.push(begin_group());
|
||||
}
|
||||
ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000));
|
||||
for _ in 0..6 {
|
||||
ins.push(end_group());
|
||||
}
|
||||
ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000));
|
||||
let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::TooDeep));
|
||||
// The square after the groups is still read, beside the three groups kept.
|
||||
let objects = &d.pages[0].layers[0].objects;
|
||||
assert_eq!(objects.len(), 2);
|
||||
let mut depth = 0;
|
||||
let mut o = &objects[1];
|
||||
while let Object::Group { objects: kids, .. } = o {
|
||||
depth += 1;
|
||||
match kids.first() {
|
||||
Some(k) => o = k,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
assert_eq!(depth, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_past_the_limits_are_bounded() {
|
||||
let ins: Vec<Vec<u8>> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect();
|
||||
let f = file(&[page(&ins)]);
|
||||
let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 10);
|
||||
assert!(d.warnings.contains(&Warning::TooDeep));
|
||||
let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap();
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 2);
|
||||
assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count")));
|
||||
assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size")));
|
||||
let dashed = |n: u16| {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)]));
|
||||
children.extend(tables());
|
||||
read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap()
|
||||
};
|
||||
let d = dashed(3);
|
||||
let o: Vec<usize> = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect();
|
||||
assert_eq!(o, [0, 2]);
|
||||
assert!(d.warnings.contains(&Warning::TooDeep));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_cut_short_keeps_the_points_it_holds() {
|
||||
let mut c = curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48]);
|
||||
// Claim 9 points where 3 are stored: the field's own length still covers only 3.
|
||||
let at = c.windows(2).position(|w| w == [3, 0]).unwrap();
|
||||
c[at] = 9;
|
||||
let p = page(&[begin_page(None), c]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged));
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_that_lost_type_bytes_keeps_its_first_points() {
|
||||
// Three whole points and only two of their type bytes.
|
||||
let mut g = 3u16.to_le_bytes().to_vec();
|
||||
for (x, y) in [(0i32, 0i32), (1_000_000, 0), (1_000_000, 1_000_000)] {
|
||||
g.extend(x.to_le_bytes());
|
||||
g.extend(y.to_le_bytes());
|
||||
}
|
||||
g.extend([0x0c, 0x44]);
|
||||
let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)]));
|
||||
let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() };
|
||||
let side = 100.0 / 25.4 * 72.0;
|
||||
assert!(near(p.subpaths[0].start.x, 0.0) && near(p.subpaths[0].start.y, 0.0));
|
||||
match p.subpaths[0].segments[..] {
|
||||
[vectorcraft_cdr::model::Segment::Line(e)] => assert!(near(e.x, side) && near(e.y, 0.0), "{e:?}"),
|
||||
ref other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_cut_short_of_its_declared_size_is_reported() {
|
||||
let mut f = file(&[]);
|
||||
let declared = (f.len() as u32 - 8 + 100).to_le_bytes();
|
||||
f[4..8].copy_from_slice(&declared);
|
||||
let d = read_cmx(&f, Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_that_ends_inside_an_instruction_is_reported() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_64_bytes_past_stray_bytes_is_found() {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stray_letters_with_a_length_past_the_file_are_passed_over() {
|
||||
let mut stray = b"abcd".to_vec();
|
||||
stray.extend(0xFFFF_FF00u32.to_le_bytes());
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)]));
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl")));
|
||||
children.push(table(b"rdot", &[dashes(&[0, 0])]));
|
||||
children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap();
|
||||
assert!(o.dashes.is_empty(), "{:?}", o.dashes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_field_that_lost_points_is_left_out() {
|
||||
// Three points claimed, two whole points stored and the third cut inside its y: the type
|
||||
// bytes can't be found, so no node types are read from coordinates.
|
||||
let mut g = 3u16.to_le_bytes().to_vec();
|
||||
for (x, y) in [(0i32, 0i32), (1_000_000, 0)] {
|
||||
g.extend(x.to_le_bytes());
|
||||
g.extend(y.to_le_bytes());
|
||||
}
|
||||
g.extend(1_000_000i32.to_le_bytes());
|
||||
g.extend([0x40, 0x42]);
|
||||
let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)]));
|
||||
let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap();
|
||||
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
|
||||
assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() {
|
||||
// Stray bytes, a chunk the reader passes over whose id ends in a digit, then the page.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 6];
|
||||
b.extend(chunk(b"inf1", &[0; 70]));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() {
|
||||
// After stray bytes, four spaces with a small length, or letters with a length past the list,
|
||||
// come before the page: neither is taken for a chunk, so the page is found.
|
||||
for filler in [b" \x08\x00\x00\x00".to_vec(), b"junk\x40\x42\x0f\x00".to_vec()] {
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(filler);
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() {
|
||||
// Stray bytes, then a chunk the reader passes over whose body starts with the letters of a
|
||||
// page chunk, then the page: only the page is read.
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
|
||||
let mut inner = b"page".to_vec();
|
||||
inner.extend(4u32.to_le_bytes());
|
||||
inner.extend([0; 10]);
|
||||
let mut b = vec![1u8; 2];
|
||||
b.extend(chunk(b"inf1", &inner));
|
||||
b.extend(p);
|
||||
let mut children = vec![cont(b'4', 1e-7), b];
|
||||
children.extend(tables());
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canvas_or_a_container_is_reported() {
|
||||
for bit in [8u8, 16] {
|
||||
let mut a = attrs(Some(1), None, false);
|
||||
a[0] |= bit;
|
||||
let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]);
|
||||
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
|
||||
assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}");
|
||||
assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_color_with_its_name_reads_as_a_spot_color() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]));
|
||||
children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))]));
|
||||
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
|
||||
match shape(&d.pages[0].layers[0].objects[0]).fill.clone() {
|
||||
Some(Color::Spot { name, tint, look }) => {
|
||||
assert_eq!((name.as_str(), tint), ("Brick 12", 1.0));
|
||||
assert!(look.is_some());
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||
|
||||
#[test]
|
||||
fn never_panics_on_garbage(bytes in prop::collection::vec(any::<u8>(), 0..2048)) {
|
||||
let mut b = b"RIFF\0\0\0\0CMX1".to_vec();
|
||||
b.extend(bytes);
|
||||
let _ = read_cmx(&b, Limits::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_panics_on_mutated_samples(edits in prop::collection::vec((any::<usize>(), any::<u8>()), 1..24)) {
|
||||
let mut b = sample();
|
||||
let n = b.len();
|
||||
for (at, v) in edits {
|
||||
b[at % n] = v;
|
||||
}
|
||||
let _ = read_cmx(&b, Limits::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Integration tests: one test binary for the crate, one module per area.
|
||||
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
mod bench;
|
||||
mod cmx;
|
||||
mod provenance;
|
||||
mod read;
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Every layout id the code cites (`R1` ...) has a row in `PROVENANCE.md`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// The ids `R<n>` in `text`.
|
||||
fn ids(text: &str) -> BTreeSet<u32> {
|
||||
let b = text.as_bytes();
|
||||
let mut out = BTreeSet::new();
|
||||
for (i, c) in b.iter().enumerate() {
|
||||
let starts = *c == b'R' && (i == 0 || !b[i - 1].is_ascii_alphanumeric());
|
||||
if !starts {
|
||||
continue;
|
||||
}
|
||||
let digits: String = b[i + 1..].iter().take_while(|d| d.is_ascii_digit()).map(|d| *d as char).collect();
|
||||
let ends = b.get(i + 1 + digits.len()).is_none_or(|d| !d.is_ascii_alphanumeric());
|
||||
if !digits.is_empty() && ends {
|
||||
out.insert(digits.parse().unwrap());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_cited_layout_has_a_row() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let table = std::fs::read_to_string(dir.join("PROVENANCE.md")).unwrap();
|
||||
let rows: BTreeSet<u32> = table.lines().filter_map(|l| l.strip_prefix("| R")).filter_map(|l| l.split(' ').next()?.parse().ok()).collect();
|
||||
let mut cited = BTreeSet::new();
|
||||
for entry in std::fs::read_dir(dir.join("src")).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_some_and(|e| e == "rs") {
|
||||
cited.extend(ids(&std::fs::read_to_string(&path).unwrap()));
|
||||
}
|
||||
}
|
||||
assert!(!cited.is_empty());
|
||||
let missing: Vec<_> = cited.difference(&rows).collect();
|
||||
assert!(missing.is_empty(), "cited without a PROVENANCE.md row: {missing:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_found_only_as_whole_words() {
|
||||
assert_eq!(ids("(R1, R12) RIFF R3x xR4 R"), BTreeSet::from([1, 12]));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+25
-5
@@ -185,6 +185,15 @@ pub struct ColorSettings {
|
||||
/// The color management policy for CMYK profiles. Settings saved without one take the default.
|
||||
#[serde(default)]
|
||||
pub cmyk_policy: Policy,
|
||||
/// Profile Mismatches: Ask When Opening. Off by default, as in settings saved without it.
|
||||
#[serde(default)]
|
||||
pub ask_mismatch_open: bool,
|
||||
/// Profile Mismatches: Ask When Pasting.
|
||||
#[serde(default)]
|
||||
pub ask_mismatch_paste: bool,
|
||||
/// Missing Profiles: Ask When Opening.
|
||||
#[serde(default)]
|
||||
pub ask_missing_open: bool,
|
||||
}
|
||||
|
||||
impl Default for ColorSettings {
|
||||
@@ -196,6 +205,9 @@ impl Default for ColorSettings {
|
||||
bpc: true,
|
||||
rgb_policy: Policy::default(),
|
||||
cmyk_policy: Policy::default(),
|
||||
ask_mismatch_open: false,
|
||||
ask_mismatch_paste: false,
|
||||
ask_missing_open: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -589,10 +601,11 @@ impl Cms {
|
||||
|
||||
/// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s
|
||||
/// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to
|
||||
/// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded
|
||||
/// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's
|
||||
/// black-point compensation; CMYK goes through Lab when either space is built in. Grey and
|
||||
/// Lab colours stay as they are.
|
||||
/// Working Space). RGB converts directly from profile to profile, with this context's
|
||||
/// black-point compensation. CMYK converts between two loaded profiles through ProPhoto RGB
|
||||
/// ([`IccProfile::to_same_model_of`]), and through Lab when either space is built in: the Lab it
|
||||
/// displays as ([`Self::cmyk_display_lab`]), or for Absolute Colorimetric its absolute Lab. Grey
|
||||
/// and Lab colours stay as they are.
|
||||
pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => {
|
||||
@@ -612,9 +625,16 @@ impl Cms {
|
||||
(CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc),
|
||||
_ => None,
|
||||
};
|
||||
// Absolute colorimetry starts from the inks' absolute Lab, paper color included and
|
||||
// without black-point compensation; the other intents from the Lab they display as.
|
||||
let source_lab = || match (&self.cmyk, intent) {
|
||||
(CmykSpace::Generic(g), Intent::AbsoluteColorimetric) => g.to_lab_abs(inks),
|
||||
(_, Intent::AbsoluteColorimetric) => lab::srgb_to_lab(self.cmyk_to_srgb(inks, true)),
|
||||
_ => self.cmyk_display_lab(inks),
|
||||
};
|
||||
let [c, m, y, k] = match direct.as_deref() {
|
||||
Some(&[c, m, y, k]) => [c, m, y, k],
|
||||
_ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent),
|
||||
_ => dest.lab_to_cmyk(source_lab(), intent),
|
||||
};
|
||||
Color::Cmyk { c, m, y, k }
|
||||
}
|
||||
|
||||
@@ -459,6 +459,23 @@ fn policies_parse_and_default_in_saved_settings() {
|
||||
assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers")));
|
||||
}
|
||||
|
||||
/// The three Ask boxes are off by default and in settings saved before they existed, and save
|
||||
/// under their own keys.
|
||||
#[test]
|
||||
fn ask_boxes_default_off_and_save() {
|
||||
let old: ColorSettings =
|
||||
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
|
||||
assert!(!old.ask_mismatch_open && !old.ask_mismatch_paste && !old.ask_missing_open);
|
||||
let st = ColorSettings::default();
|
||||
assert!(!st.ask_mismatch_open && !st.ask_mismatch_paste && !st.ask_missing_open);
|
||||
let saved = serde_json::to_value(ColorSettings { ask_mismatch_paste: true, ..Default::default() }).unwrap();
|
||||
assert_eq!(saved["askMismatchOpen"], false);
|
||||
assert_eq!(saved["askMismatchPaste"], true);
|
||||
assert_eq!(saved["askMissingOpen"], false);
|
||||
let back: ColorSettings = serde_json::from_value(saved).unwrap();
|
||||
assert!(back.ask_mismatch_paste);
|
||||
}
|
||||
|
||||
/// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into
|
||||
/// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and
|
||||
/// Lab colors stay as they are.
|
||||
@@ -478,3 +495,48 @@ fn convert_into_keeps_the_appearance() {
|
||||
assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c);
|
||||
}
|
||||
}
|
||||
|
||||
/// With black-point compensation on, Generic CMYK displays its press black as black, so dark inks
|
||||
/// converted out of it keep that appearance: into Device CMYK, and into another document whose
|
||||
/// CMYK space is also Generic CMYK.
|
||||
#[test]
|
||||
fn convert_into_keeps_compensated_dark_inks() {
|
||||
let generic = cms();
|
||||
let device = Cms::new(&ColorSettings { cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap();
|
||||
let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
|
||||
for ink in [
|
||||
Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 },
|
||||
Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 1.0 },
|
||||
Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 },
|
||||
] {
|
||||
for dest in [&device, &other_generic] {
|
||||
let moved = generic.convert_into(dest, &ink, Intent::RelativeColorimetric);
|
||||
assert!(matches!(moved, Color::Cmyk { .. }), "{ink:?} → {moved:?}");
|
||||
let d = delta_e2000(generic.lab(&ink), dest.lab(&moved));
|
||||
assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Absolute Colorimetric converts CMYK out of Generic CMYK from the inks' absolute Lab (paper color
|
||||
/// included, no black-point compensation): into another document whose CMYK space is also Generic
|
||||
/// CMYK, the paper, dark inks and mid tones keep their absolute appearance.
|
||||
#[test]
|
||||
fn absolute_cmyk_conversion_keeps_the_absolute_appearance() {
|
||||
let generic = cms();
|
||||
let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
|
||||
let absolute = |c: &Cms, ink: &Color| match (&c.cmyk, ink) {
|
||||
(CmykSpace::Generic(g), Color::Cmyk { c, m, y, k }) => g.to_lab_abs([*c, *m, *y, *k]),
|
||||
_ => panic!("Generic CMYK inks expected, not {ink:?}"),
|
||||
};
|
||||
for ink in [
|
||||
Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 },
|
||||
Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 },
|
||||
Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 },
|
||||
Color::Cmyk { c: 0.4, m: 0.1, y: 0.6, k: 0.1 },
|
||||
] {
|
||||
let moved = generic.convert_into(&other_generic, &ink, Intent::AbsoluteColorimetric);
|
||||
let d = delta_e2000(absolute(&generic, &ink), absolute(&other_generic, &moved));
|
||||
assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}");
|
||||
}
|
||||
}
|
||||
@@ -176,18 +176,33 @@ impl Harmony {
|
||||
|
||||
/// The rule's colours in the base colour's model, the base colour itself first.
|
||||
pub fn apply(self, base: Color) -> Vec<Color> {
|
||||
let [h, s, v] = base.to_hsb();
|
||||
std::iter::once(base)
|
||||
.chain(self.tones()[1..].iter().map(|tone| {
|
||||
let rest = self.apply_hsb(base.to_hsb()).into_iter().skip(1);
|
||||
std::iter::once(base).chain(rest.map(|[h, s, v]| keep_model(base, Color::from_hsb(h, s, v)))).collect()
|
||||
}
|
||||
|
||||
/// The rule's colours as HSB from base HSB `hsb`, the base first: hue in degrees from 0 to 360,
|
||||
/// saturation and brightness from 0 to 1. A gray base keeps its hue, so the colours keep their
|
||||
/// places around a hue wheel.
|
||||
pub fn apply_hsb(self, [h, s, v]: [f32; 3]) -> Vec<[f32; 3]> {
|
||||
self.tones()
|
||||
.iter()
|
||||
.map(|tone| {
|
||||
let b = match tone.bright {
|
||||
Bright::Times(f) => v * f,
|
||||
Bright::Contrast => contrast(v),
|
||||
};
|
||||
keep_model(base, Color::from_hsb(h + tone.turn, (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)))
|
||||
}))
|
||||
[(h + tone.turn).rem_euclid(360.0), (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether every colour of the rule has a hue of its own (Triad, but not Triad 2 or
|
||||
/// Monochromatic), so that each can sit on a hue ring apart from the others.
|
||||
pub fn hues_differ(self) -> bool {
|
||||
let turns: Vec<f32> = self.tones().iter().map(|t| t.turn.rem_euclid(360.0)).collect();
|
||||
turns.iter().enumerate().all(|(i, a)| turns[..i].iter().all(|b| a != b))
|
||||
}
|
||||
|
||||
/// A [`THEME_SIZE`]-colour theme from `base`: the rule's colours, each followed by the lighter or
|
||||
/// darker variations of it that fill the remaining places (the rule's first colours get them
|
||||
/// first). The base colour comes first, every colour in its model.
|
||||
@@ -409,6 +424,34 @@ mod tests {
|
||||
assert_eq!(Harmony::parse("square"), None);
|
||||
}
|
||||
|
||||
/// A rule's HSB colours match the colours `apply` gives, and a gray base keeps its hue, so its
|
||||
/// colours turn around the hue ring from it.
|
||||
#[test]
|
||||
fn hsb_colours_match_and_keep_a_grays_hue() {
|
||||
for h in Harmony::ALL {
|
||||
let base = Color::rgb8(230, 120, 40);
|
||||
let hsb = h.apply_hsb(base.to_hsb());
|
||||
let colors = h.apply(base);
|
||||
assert_eq!(hsb.len(), colors.len(), "{}", h.label());
|
||||
for (a, c) in hsb.iter().zip(&colors).skip(1) {
|
||||
assert_eq!(Color::from_hsb(a[0], a[1], a[2]).to_hex(), c.to_hex(), "{}", h.label());
|
||||
}
|
||||
}
|
||||
let gray = Harmony::Triad.apply_hsb([40.0, 0.0, 0.5]);
|
||||
assert_eq!(gray.iter().map(|c| c[0]).collect::<Vec<_>>(), [40.0, 160.0, 280.0]);
|
||||
assert_eq!(Harmony::Analogous.apply_hsb([10.0, 1.0, 1.0])[2][0], 340.0, "hues wrap to 0..360");
|
||||
}
|
||||
|
||||
/// Fifteen rules give every colour its own hue; the six that repeat a hue are left out.
|
||||
#[test]
|
||||
fn rules_whose_colours_all_have_their_own_hue() {
|
||||
let differ: Vec<Harmony> = Harmony::ALL.into_iter().filter(|h| h.hues_differ()).collect();
|
||||
assert_eq!(differ.len(), 15);
|
||||
for h in [Harmony::Complementary2, Harmony::Monochromatic, Harmony::Shades, Harmony::Triad2, Harmony::Triad3, Harmony::HighContrast2] {
|
||||
assert!(!h.hues_differ(), "{}", h.label());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_contrast_flips_brightness() {
|
||||
let light = Harmony::HighContrast.apply(Color::rgb(0.9, 0.8, 0.2));
|
||||
|
||||
@@ -127,8 +127,8 @@ impl Appearance {
|
||||
pub fn stroke_mut(&mut self) -> Option<&mut StrokeLayer> {
|
||||
self.items.iter_mut().rev().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None })
|
||||
}
|
||||
/// This appearance for other art: the pen pressure, tilt, bearing and rotation its strokes
|
||||
/// were drawn with stay with them.
|
||||
/// This appearance for other art: the pen pressure, tilt, bearing, rotation and wheel its
|
||||
/// strokes were drawn with stay with them.
|
||||
pub fn without_pressure(mut self) -> Self {
|
||||
for it in &mut self.items {
|
||||
if let AppearanceItem::Stroke(s) = it {
|
||||
@@ -136,6 +136,7 @@ impl Appearance {
|
||||
s.tilt = None;
|
||||
s.bearing = None;
|
||||
s.rotation = None;
|
||||
s.wheel = None;
|
||||
}
|
||||
}
|
||||
self
|
||||
|
||||
@@ -113,6 +113,11 @@ pub struct StrokeLayer {
|
||||
/// pressure, it stays with this path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub rotation: Option<AngleProfile>,
|
||||
/// Where the finger wheel of an airbrush pen was set along the stroke: 0 at one end of its
|
||||
/// travel to 1 at the other. Brushes with Stylus Wheel variation vary with it. Like the
|
||||
/// pressure, it stays with this path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub wheel: Option<PressureProfile>,
|
||||
}
|
||||
|
||||
/// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant
|
||||
@@ -187,6 +192,7 @@ impl StrokeLayer {
|
||||
tilt: None,
|
||||
bearing: None,
|
||||
rotation: None,
|
||||
wheel: None,
|
||||
}
|
||||
}
|
||||
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
|
||||
|
||||
@@ -130,8 +130,9 @@ impl WidthProfile {
|
||||
|
||||
/// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1
|
||||
/// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s
|
||||
/// are. The pen's tilt is kept the same way ([`StrokeLayer::tilt`]). Calligraphic and Scatter
|
||||
/// brushes with Pressure or Tilt variation read them; everything else ignores them.
|
||||
/// are. The pen's tilt and an airbrush pen's finger wheel are kept the same way
|
||||
/// ([`StrokeLayer::tilt`], [`StrokeLayer::wheel`]). Brushes with Pressure, Tilt or Stylus Wheel
|
||||
/// variation read them; everything else ignores them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PressureProfile {
|
||||
pub points: Vec<(f64, f64)>,
|
||||
|
||||
@@ -188,7 +188,7 @@ fn angle_profiles_join_samples_the_shorter_way_round() {
|
||||
#[test]
|
||||
fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap();
|
||||
for key in ["pressure", "tilt", "bearing", "rotation"] {
|
||||
for key in ["pressure", "tilt", "bearing", "rotation", "wheel"] {
|
||||
assert!(json.get(key).is_none(), "{key}");
|
||||
}
|
||||
let st: StrokeLayer = serde_json::from_value(json).unwrap();
|
||||
@@ -199,19 +199,21 @@ fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample());
|
||||
assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None);
|
||||
// The pen's tilt, bearing and rotation load, save and stay behind the same way.
|
||||
// The pen's tilt, bearing, rotation and wheel load, save and stay behind the same way.
|
||||
let posed = StrokeLayer {
|
||||
tilt: Some(PressureProfile::sample()),
|
||||
bearing: Some(AngleProfile::sample()),
|
||||
rotation: Some(AngleProfile { points: vec![(0.0, -45.0)] }),
|
||||
wheel: Some(PressureProfile { points: vec![(0.0, 0.25), (1.0, 0.75)] }),
|
||||
..back
|
||||
};
|
||||
assert_eq!(serde_json::to_value(&posed).unwrap()["wheel"], serde_json::json!({"points": [[0.0, 0.25], [1.0, 0.75]]}));
|
||||
let again: StrokeLayer = serde_json::from_value(serde_json::to_value(&posed).unwrap()).unwrap();
|
||||
assert_eq!(again, posed);
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
*ap.stroke_mut().unwrap() = posed;
|
||||
let st = ap.without_pressure().stroke().cloned().unwrap();
|
||||
assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation), (None, None, None, None));
|
||||
assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation, st.wheel), (None, None, None, None, None));
|
||||
}
|
||||
|
||||
/// The Lens profile's widths at its middle, a quarter of the way along and past its end.
|
||||
|
||||
+52
-9
@@ -6,7 +6,7 @@
|
||||
//! tool clicked.
|
||||
//! - **Paint**: colours, gradients (stops resampled to a common set when their counts differ),
|
||||
//! opacity, stroke weight, dashes, miter limit, width profiles and the pen pressure, tilt,
|
||||
//! bearing and rotation that brushes read interpolate; what can't
|
||||
//! bearing, rotation and wheel that brushes read interpolate; what can't
|
||||
//! (caps, joins, brushes, fonts, symbols, text content) switches halfway.
|
||||
//! - **Groups** pair their children in stacking order; the children one group has more of grow
|
||||
//! out of the other group's centre. Compound paths stay compound paths.
|
||||
@@ -429,8 +429,8 @@ fn lerp_angle(x: Option<&AngleProfile>, y: Option<&AngleProfile>, t: f64) -> Opt
|
||||
}
|
||||
|
||||
/// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale, width
|
||||
/// profile and the pen pressure, tilt, bearing and rotation its brush reads into `o` (a copy of
|
||||
/// the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway).
|
||||
/// profile and the pen pressure, tilt, bearing, rotation and wheel its brush reads into `o` (a
|
||||
/// copy of the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway).
|
||||
fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) {
|
||||
let tf = t as f32;
|
||||
o.paint = lerp_paint(&x.paint, &y.paint, tf);
|
||||
@@ -444,6 +444,7 @@ fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) {
|
||||
o.tilt = lerp_pressure(x.tilt.as_ref(), y.tilt.as_ref(), t);
|
||||
o.bearing = lerp_angle(x.bearing.as_ref(), y.bearing.as_ref(), t);
|
||||
o.rotation = lerp_angle(x.rotation.as_ref(), y.rotation.as_ref(), t);
|
||||
o.wheel = lerp_pressure(x.wheel.as_ref(), y.wheel.as_ref(), t);
|
||||
}
|
||||
|
||||
/// Interpolate appearance stacks: item by item when their structure matches, else the top fill
|
||||
@@ -755,9 +756,9 @@ fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) {
|
||||
}
|
||||
|
||||
/// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width
|
||||
/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes,
|
||||
/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as
|
||||
/// they are.
|
||||
/// profile (whose sides swap when reversed), pen pressure, tilt, bearing, rotation and wheel, its
|
||||
/// dashes, a gradient along the path or across it (whose sides swap when reversed). Its arrowheads
|
||||
/// stay as they are.
|
||||
fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) {
|
||||
if o.is_identity() {
|
||||
return;
|
||||
@@ -805,7 +806,7 @@ fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) {
|
||||
let out = reoriented(&pts, o, |f| p.at(f), |v| v, |(l, r)| (r, l));
|
||||
p.points = out.into_iter().map(|(t, (l, r))| (t, l, r)).collect();
|
||||
}
|
||||
for p in [&mut s.pressure, &mut s.tilt].into_iter().flatten() {
|
||||
for p in [&mut s.pressure, &mut s.tilt, &mut s.wheel].into_iter().flatten() {
|
||||
let out = reoriented(&p.points, o, |f| p.at(f), same, same);
|
||||
p.points = out;
|
||||
}
|
||||
@@ -842,8 +843,8 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
|
||||
|
||||
/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths
|
||||
/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its
|
||||
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and
|
||||
/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are
|
||||
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing,
|
||||
/// rotation and wheel then run the new way, so the stroke draws as it did. A compound path's subpaths are
|
||||
/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns
|
||||
/// only when all of them turn alike. Arrowheads stay at the path's start and end.
|
||||
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
|
||||
@@ -3014,6 +3015,48 @@ mod tests {
|
||||
assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stylus_wheel_recording_turns_with_the_gradient_and_dashes_of_its_stroke() {
|
||||
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
|
||||
let mut ap = Appearance::default();
|
||||
ap.set_stroke(Paint::solid(Color::BLACK));
|
||||
if let Some(s) = ap.stroke_mut() {
|
||||
edit(s);
|
||||
}
|
||||
Node::path(NodeId(1), path, ap)
|
||||
};
|
||||
let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
|
||||
let wheel = |s: &StrokeLayer, f: f64| s.wheel.as_ref().map_or(PressureProfile::MID, |p| p.at(f));
|
||||
let light = |s: &StrokeLayer, u: f32| match &s.paint {
|
||||
Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::<f32>(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
let recorded = |s: &mut StrokeLayer| {
|
||||
s.wheel = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] });
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false });
|
||||
};
|
||||
// An open key clicked at its last anchor: the wheel runs the other way with the gradient
|
||||
// along it, and the dashes are read from its end.
|
||||
let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false));
|
||||
let key = keyed(line(100.0), &recorded);
|
||||
let s = stroke(&Lerp::new(&keyed(line(0.0), &|_| {}), &key, (None, Some(1))).at(1.0));
|
||||
assert!((wheel(&s, 0.0) - 1.0).abs() < 1e-9 && wheel(&s, 1.0).abs() < 1e-9, "{:?}", s.wheel);
|
||||
assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{:?}", s.paint);
|
||||
assert_ne!(s.dash, stroke(&key).dash, "the dashes turn too");
|
||||
// A closed key started half way round starts its wheel recording there, stepping where its
|
||||
// own start was, as its gradient does.
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
let key = keyed(square(100.0), &recorded);
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0));
|
||||
assert!((wheel(&s, 0.25) - 0.75).abs() < 1e-9 && (wheel(&s, 0.75) - 0.25).abs() < 1e-9, "{:?}", s.wheel);
|
||||
assert!((light(&s, 0.25) - 0.75).abs() < 0.02 && (light(&s, 0.75) - 2.25).abs() < 0.02, "{:?}", s.paint);
|
||||
// Half way through, a key without a recording counts as the wheel half way.
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(0.5));
|
||||
assert!((wheel(&s, 0.25) - 0.625).abs() < 1e-9, "{:?}", s.wheel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() {
|
||||
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
|
||||
|
||||
@@ -35,6 +35,7 @@ impl Document {
|
||||
char_styles,
|
||||
para_styles,
|
||||
composite_fonts,
|
||||
kinsoku_sets,
|
||||
text_threads,
|
||||
symbols,
|
||||
graph_designs,
|
||||
@@ -96,6 +97,7 @@ impl Document {
|
||||
&& *char_styles == other.char_styles
|
||||
&& *para_styles == other.para_styles
|
||||
&& *composite_fonts == other.composite_fonts
|
||||
&& *kinsoku_sets == other.kinsoku_sets
|
||||
&& *text_threads == other.text_threads
|
||||
&& symbols.len() == other.symbols.len()
|
||||
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
@@ -221,6 +223,7 @@ impl Document {
|
||||
char_styles: Default::default(),
|
||||
para_styles: Default::default(),
|
||||
composite_fonts: Default::default(),
|
||||
kinsoku_sets: Default::default(),
|
||||
text_threads: vec![],
|
||||
symbols: vec![],
|
||||
graph_designs: vec![],
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
//! Flare objects: the settings a flare group was drawn with (the Flare tool, `shape.flare`). Its
|
||||
//! children are ordinary paths for every renderer and exporter; the settings let it be drawn again.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Vec2, shapes};
|
||||
|
||||
use crate::Appearance;
|
||||
use crate::node::{Node, NodeId, NodeKind};
|
||||
|
||||
/// The seed of the sizes a flare's rays and rings take when its settings give none.
|
||||
pub const DEFAULT_SEED: u64 = 0x2545_f491_4f6c_dd1d;
|
||||
|
||||
/// One part of a flare: its name, outline, fill and opacity.
|
||||
pub type Part = (&'static str, PathData, Paint, f32);
|
||||
|
||||
/// The number `key` of the settings `v`, or `default`.
|
||||
fn number(v: &Value, key: &str, default: f64) -> f64 {
|
||||
v.get(key).and_then(Value::as_f64).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// The parts of a flare with the settings `v` (`shape.flare`'s params, each one given): a bright
|
||||
/// center, a halo ring, rays of varying length and rings along the path to the end point.
|
||||
pub fn parts(v: &Value) -> Vec<Part> {
|
||||
let c = Point::new(number(v, "cx", 0.0), number(v, "cy", 0.0));
|
||||
let end = Point::new(number(v, "x2", c.x), number(v, "y2", c.y));
|
||||
let pct = |k: &str| (number(v, k, 0.0) / 100.0).clamp(0.0, 10.0);
|
||||
let r = (number(v, "diameter", 100.0) / 2.0).max(0.5);
|
||||
let opacity = pct("opacity").min(1.0) as f32;
|
||||
let brightness = pct("brightness").min(1.0) as f32;
|
||||
let growth = pct("growth");
|
||||
let fuzz = pct("fuzziness").min(1.0);
|
||||
let rays = v.get("rays").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
|
||||
let longest = pct("longest");
|
||||
let ray_fuzz = pct("rayFuzziness").min(1.0);
|
||||
let ray_turn = number(v, "rotation", 0.0).to_radians();
|
||||
let rings = v.get("rings").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
|
||||
let largest = pct("largest");
|
||||
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
|
||||
// along the path from a sequence of its own; their count and sizes and the other parts stay.
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
};
|
||||
let mut rnd = random(v.get("seed").and_then(Value::as_u64).unwrap_or(DEFAULT_SEED) | 1);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
|
||||
let mut ring_at = v.get("ringSeed").and_then(Value::as_u64).filter(|r| *r < 1 << 53).map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
g.geom = Some(GradientGeom { start: centre, end: centre + Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
|
||||
let mut parts: Vec<Part> = vec![];
|
||||
// Halo: a soft ring just outside the centre.
|
||||
let halo_r = r * (1.0 + growth) * 1.6;
|
||||
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
|
||||
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
|
||||
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
|
||||
// `rotation` turns them clockwise about the center.
|
||||
if rays > 0 {
|
||||
let mut bp = BezPath::new();
|
||||
let mut reach: f64 = 0.0;
|
||||
for i in 0..rays {
|
||||
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
|
||||
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
|
||||
reach = reach.max(len);
|
||||
let w = r * 0.035;
|
||||
let dir = Vec2::new(a.cos(), a.sin());
|
||||
let n = Vec2::new(-dir.y, dir.x) * w;
|
||||
bp.move_to(c + n);
|
||||
bp.line_to(c + dir * len);
|
||||
bp.line_to(c - n);
|
||||
bp.line_to(c - dir * (w * 4.0));
|
||||
bp.close_path();
|
||||
}
|
||||
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
|
||||
}
|
||||
// Centre: bright core fading to transparent.
|
||||
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
|
||||
// Rings along the path to the end point (Largest = % of the average ring size).
|
||||
for _ in 0..rings {
|
||||
let t = rnd();
|
||||
let t = ring_at.as_mut().map_or(t, |next| next());
|
||||
let at = c + (end - c) * t;
|
||||
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
|
||||
let solid = rnd() < 0.5;
|
||||
let stops = if solid {
|
||||
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
|
||||
} else {
|
||||
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
|
||||
};
|
||||
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Part `part` of a flare as the object `id`, transformed by `xf` (the transform its flare has had
|
||||
/// since it was drawn), with the pixel-aligned property when `aligned`.
|
||||
pub fn part_node(id: NodeId, part: Part, xf: Affine, aligned: bool) -> Node {
|
||||
let (name, pd, paint, op) = part;
|
||||
let mut n = Node::path(id, pd, Appearance::basic(paint, Paint::None, 0.0));
|
||||
n.name = Some(name.into());
|
||||
n.blend = BlendMode::Screen;
|
||||
n.opacity = op;
|
||||
if aligned {
|
||||
n.extras_mut().pixel_aligned = true;
|
||||
}
|
||||
if xf != Affine::IDENTITY {
|
||||
n.transform(xf, false);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The ellipse of a radial gradient's placement `geom` as the symmetric matrix `[xx, xy, yy]` that
|
||||
/// maps it to the unit circle's: the same for every end point and aspect that give that ellipse
|
||||
/// (transforms applied one by one and all at once can put the end on different axes of it).
|
||||
fn ellipse(geom: &GradientGeom) -> [f64; 3] {
|
||||
let u = geom.end - geom.start;
|
||||
let w = Vec2::new(-u.y, u.x) * geom.aspect;
|
||||
[u.x * u.x + w.x * w.x, u.x * u.y + w.x * w.y, u.y * u.y + w.y * w.y]
|
||||
}
|
||||
|
||||
/// The ellipse `[xx, xy, yy]` ([`ellipse`]) as its size, the length of its longer half-axis, and
|
||||
/// its shape: the ratio of its shorter axis to its longer one, then the cosine and sine of twice
|
||||
/// the longer axis's angle, each times one minus that ratio (0 for a circle). Each number is a
|
||||
/// length or a ratio of lengths, never a squared length that a tiny flare or a narrow gradient
|
||||
/// makes smaller than the tolerance.
|
||||
fn ellipse_size_and_shape(geom: &GradientGeom) -> (f64, [f64; 3]) {
|
||||
let [xx, xy, yy] = ellipse(geom);
|
||||
let half_diff = (xx - yy) / 2.0;
|
||||
let d = half_diff.hypot(xy);
|
||||
let longer = (xx + yy) / 2.0 + d;
|
||||
if longer.is_nan() || longer <= 0.0 {
|
||||
return (0.0, [0.0; 3]);
|
||||
}
|
||||
// The product of the half-axes is the area factor of the map from the unit circle, `u` across
|
||||
// `w` as [`ellipse`] builds them: a sum of squares times the aspect, without the cancellation
|
||||
// of `xx * yy - xy * xy` for a narrow ellipse.
|
||||
let u = geom.end - geom.start;
|
||||
let w = Vec2::new(-u.y, u.x) * geom.aspect;
|
||||
let ratio = ((u.x * w.y - u.y * w.x).abs() / longer).min(1.0);
|
||||
let (cos, sin) = if d > 0.0 { (half_diff / d, xy / d) } else { (0.0, 0.0) };
|
||||
(longer.sqrt(), [ratio, (1.0 - ratio) * cos, (1.0 - ratio) * sin])
|
||||
}
|
||||
|
||||
/// `n` as JSON without what depends on how its transforms were applied: its id, the angle of its
|
||||
/// bounding box, and which axis of a gradient's ellipse its end point is on (the ellipse stays: its
|
||||
/// size in the placement, and its shape beside the placement, out of reach of a pixel-aligned
|
||||
/// part's snap allowance, which is a length).
|
||||
fn comparable(n: &Node) -> Value {
|
||||
fn strip(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
for key in ["id", "bbox_angle"] {
|
||||
m.remove(key);
|
||||
}
|
||||
if let Some(geom) = m.get_mut("geom")
|
||||
&& let Ok(g) = serde_json::from_value::<GradientGeom>(geom.clone())
|
||||
&& let Value::Object(geom) = geom
|
||||
{
|
||||
let (size, shape) = ellipse_size_and_shape(&g);
|
||||
geom.remove("end");
|
||||
geom.remove("aspect");
|
||||
geom.insert("ellipse".into(), serde_json::json!(size));
|
||||
m.insert("ellipseShape".into(), serde_json::json!(shape));
|
||||
}
|
||||
m.values_mut().for_each(strip);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(strip),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut v = serde_json::to_value(n).unwrap_or(Value::Null);
|
||||
strip(&mut v);
|
||||
v
|
||||
}
|
||||
|
||||
/// How close, relative to its size, a number in an outline or a gradient's placement must be to the
|
||||
/// one its transforms give: a few thousandths of a point near the edge of the canvas.
|
||||
const GEOMETRY_TOL: f64 = 1e-9;
|
||||
|
||||
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size; each
|
||||
/// number in an outline (`path`) or a gradient's placement (`geom`) is within [`GEOMETRY_TOL`]
|
||||
/// relative to its size (or `tol`, when smaller), and `snap` points as well.
|
||||
fn close(a: &Value, b: &Value, tol: f64, snap: f64, geometry: bool) -> bool {
|
||||
match (a, b) {
|
||||
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
|
||||
(Some(x), Some(y)) => {
|
||||
let (snap, tol) = if geometry { (snap, tol.min(GEOMETRY_TOL)) } else { (0.0, tol) };
|
||||
(x - y).abs() <= snap + tol * (1.0 + x.abs().max(y.abs()))
|
||||
}
|
||||
_ => x == y,
|
||||
},
|
||||
(Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| close(x, y, tol, snap, geometry)),
|
||||
(Value::Object(x), Value::Object(y)) => {
|
||||
x.len() == y.len()
|
||||
&& x.iter().all(|(k, v)| {
|
||||
// A gradient's shape is ratios: compared as closely as geometry, without the snap.
|
||||
let snap = if k == "ellipseShape" { 0.0 } else { snap };
|
||||
y.get(k).is_some_and(|w| close(v, w, tol, snap, geometry || k == "path" || k == "geom" || k == "ellipseShape"))
|
||||
})
|
||||
}
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size.
|
||||
pub fn json_close(a: &Value, b: &Value, tol: f64) -> bool {
|
||||
close(a, b, tol, 0.0, false)
|
||||
}
|
||||
|
||||
/// How far a pixel-aligned object's points may be from where its transforms put them: snapping to
|
||||
/// the pixel grid moves each by up to a pixel.
|
||||
const PIXEL_SNAP: f64 = 1.0;
|
||||
|
||||
/// The settings of a flare group ([`crate::NodeExtras::flare`]).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FlareSpec {
|
||||
/// `shape.flare`'s params the flare was drawn with, each one given: the center (`cx`, `cy`) and
|
||||
/// the rings' end point (`x2`, `y2`) are in the coordinates it was drawn in.
|
||||
pub params: serde_json::Value,
|
||||
/// The transform its art has had since it was drawn (moves, scales, rotations, reflections and
|
||||
/// shears).
|
||||
#[serde(default = "identity", skip_serializing_if = "is_identity")]
|
||||
pub transform: Affine,
|
||||
}
|
||||
|
||||
fn identity() -> Affine {
|
||||
Affine::IDENTITY
|
||||
}
|
||||
|
||||
fn is_identity(a: &Affine) -> bool {
|
||||
*a == Affine::IDENTITY
|
||||
}
|
||||
|
||||
impl FlareSpec {
|
||||
/// The settings of a flare drawn with `params`, not transformed since.
|
||||
pub fn new(params: serde_json::Value) -> Self {
|
||||
Self { params, transform: Affine::IDENTITY }
|
||||
}
|
||||
|
||||
/// The point `key_x`, `key_y` of the params, where it is in the document now.
|
||||
fn point(&self, key_x: &str, key_y: &str) -> Option<Point> {
|
||||
let x = self.params.get(key_x)?.as_f64()?;
|
||||
let y = self.params.get(key_y)?.as_f64()?;
|
||||
Some(self.transform * Point::new(x, y)).filter(|p| p.x.is_finite() && p.y.is_finite())
|
||||
}
|
||||
|
||||
/// The flare's center, where it is in the document now.
|
||||
pub fn center(&self) -> Option<Point> {
|
||||
self.point("cx", "cy")
|
||||
}
|
||||
|
||||
/// The rings' end point, where it is in the document now.
|
||||
pub fn end(&self) -> Option<Point> {
|
||||
self.point("x2", "y2")
|
||||
}
|
||||
|
||||
/// Its art transformed by `a`.
|
||||
pub fn transform(&mut self, a: Affine) {
|
||||
self.transform = a * self.transform;
|
||||
}
|
||||
|
||||
/// Whether `group`'s parts are still the ones these settings draw, in place: none was edited,
|
||||
/// distorted, removed or added, and the transform can be undone. The parts are compared where
|
||||
/// they are in the document, at any scale.
|
||||
pub fn draws(&self, group: &Node) -> bool {
|
||||
let NodeKind::Group { children, .. } = &group.kind else { return false };
|
||||
if !self.transform.is_finite() || self.transform.determinant() == 0.0 || !self.transform.inverse().is_finite() {
|
||||
return false;
|
||||
}
|
||||
let expected = parts(&self.params);
|
||||
expected.len() == children.len()
|
||||
&& expected.into_iter().zip(children).all(|(part, child)| {
|
||||
let aligned = child.extras().pixel_aligned;
|
||||
let snap = if aligned { PIXEL_SNAP } else { 0.0 };
|
||||
close(&comparable(&part_node(child.id, part, self.transform, aligned)), &comparable(child), 1e-6, snap, false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// A flare's center and end point follow its art through a transform, and a save and reload
|
||||
/// keeps its settings.
|
||||
#[test]
|
||||
fn a_flare_keeps_its_settings_through_a_transform_and_a_save() {
|
||||
let mut g = Node::group(NodeId(1), vec![std::sync::Arc::new(Node::path(NodeId(2), PathData::default(), Default::default()))]);
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec::new(json!({ "cx": 10.0, "cy": 20.0, "x2": 110.0, "y2": 20.0, "seed": 7 }))));
|
||||
g.transform(Affine::translate((5.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2), false);
|
||||
let spec = g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
|
||||
let c = spec.center().unwrap_or_else(|| panic!("no center"));
|
||||
let e = spec.end().unwrap_or_else(|| panic!("no end"));
|
||||
assert!((c.x - -15.0).abs() < 1e-9 && (c.y - 10.0).abs() < 1e-9, "{c:?}");
|
||||
assert!((e.x - -15.0).abs() < 1e-9 && (e.y - 110.0).abs() < 1e-9, "{e:?}");
|
||||
let text = serde_json::to_string(&g).unwrap_or_else(|e| panic!("{e}"));
|
||||
let back: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(back.extras().flare.as_deref(), Some(&spec));
|
||||
// A flare that was not transformed writes no transform.
|
||||
let plain = FlareSpec::new(json!({ "cx": 1.0 }));
|
||||
assert_eq!(serde_json::to_value(&plain).unwrap_or_default(), json!({ "params": { "cx": 1.0 } }));
|
||||
}
|
||||
|
||||
/// A flare group draws its settings until a part's gradient, opacity or outline is edited; a
|
||||
/// pixel-aligned part may sit up to a pixel from where its transforms put it, but only in its
|
||||
/// outline and its gradient's placement.
|
||||
#[test]
|
||||
fn a_flare_with_an_edited_part_no_longer_draws_its_settings() {
|
||||
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0,
|
||||
"opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0,
|
||||
"rotation": 0.0, "largest": 50.0 });
|
||||
let flare = |aligned: bool| {
|
||||
let xf = Affine::rotate(0.3) * Affine::scale_non_uniform(1.5, 0.75);
|
||||
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
|
||||
let mut g = Node::group(NodeId(1), children.collect());
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
|
||||
g
|
||||
};
|
||||
let spec = |g: &Node| g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
|
||||
let edit = |g: &mut Node, f: &dyn Fn(&mut Node)| {
|
||||
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
|
||||
// The center, drawn at half opacity.
|
||||
f(std::sync::Arc::make_mut(&mut children[2]));
|
||||
};
|
||||
for aligned in [false, true] {
|
||||
let g = flare(aligned);
|
||||
assert!(spec(&g).draws(&g), "aligned {aligned}");
|
||||
let mut moved = g.clone();
|
||||
edit(&mut moved, &|n| n.transform(Affine::translate((0.4, 0.0)), false));
|
||||
assert_eq!(spec(&moved).draws(&moved), aligned, "a fraction of a pixel, aligned {aligned}");
|
||||
let mut faded = g.clone();
|
||||
edit(&mut faded, &|n| n.opacity *= 0.8);
|
||||
assert!(!spec(&faded).draws(&faded), "opacity, aligned {aligned}");
|
||||
let mut shifted = g.clone();
|
||||
edit(&mut shifted, &|n| {
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
geom.start.x += 20.0;
|
||||
}
|
||||
});
|
||||
assert!(!spec(&shifted).draws(&shifted), "gradient placement, aligned {aligned}");
|
||||
let mut squashed = g.clone();
|
||||
edit(&mut squashed, &|n| {
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
geom.aspect *= 0.5;
|
||||
}
|
||||
});
|
||||
assert!(!spec(&squashed).draws(&squashed), "gradient shape, aligned {aligned}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An ellipse's size and shape are the same whichever axis its end point is on, and a narrow
|
||||
/// gradient made narrower, or turned, changes its shape by more than [`GEOMETRY_TOL`].
|
||||
#[test]
|
||||
fn an_ellipse_shape_tells_narrow_gradients_apart() {
|
||||
let geom = |end: (f64, f64), aspect: f64| GradientGeom { start: Point::new(1.0, 2.0), end: Point::new(end.0, end.1), aspect, focal: None };
|
||||
let of = ellipse_size_and_shape;
|
||||
let (size, shape) = of(&geom((11.0, 2.0), 0.5));
|
||||
// The same ellipse with its end point on the other axis.
|
||||
let (size2, shape2) = of(&geom((1.0, 7.0), 2.0));
|
||||
assert!((size - size2).abs() < 1e-12 && shape.iter().zip(shape2).all(|(a, b)| (a - b).abs() < 1e-12), "{shape:?} {shape2:?}");
|
||||
// A very narrow ellipse, given both ways, keeps its shape to within the tolerance.
|
||||
let (thin, thin2) = (of(&geom((11.0, 2.0), 1e-8)).1, of(&geom((1.0, 2.0 + 1e-7), 1e8)).1);
|
||||
assert!(thin.iter().zip(thin2).all(|(a, b)| (a - b).abs() < GEOMETRY_TOL), "{thin:?} {thin2:?}");
|
||||
let narrow = of(&geom((11.0, 2.0), 1e-4)).1;
|
||||
for other in [of(&geom((11.0, 2.0), 5e-5)).1, of(&geom((1.0, 12.0), 1e-4)).1] {
|
||||
assert!(narrow.iter().zip(other).any(|(a, b)| (a - b).abs() > 1e3 * GEOMETRY_TOL), "{narrow:?} {other:?}");
|
||||
}
|
||||
assert_eq!(of(&geom((1.0, 2.0), 1.0)), (0.0, [0.0; 3]));
|
||||
}
|
||||
|
||||
/// A flare scaled far down, in one direction or in all, anywhere on the canvas, still draws its
|
||||
/// settings, and a part's gradient whose shape was edited is still told apart; a flattened flare
|
||||
/// does not draw its settings.
|
||||
#[test]
|
||||
fn a_flare_scaled_far_down_still_draws_its_settings() {
|
||||
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0 });
|
||||
let flare_aligned = |xf: Affine, aligned: bool| {
|
||||
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
|
||||
let mut g = Node::group(NodeId(1), children.collect());
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
|
||||
g
|
||||
};
|
||||
let flare = |xf: Affine| flare_aligned(xf, false);
|
||||
// The center's gradient placement, to edit.
|
||||
let center_geom = |g: &mut Node, f: &dyn Fn(&mut GradientGeom)| {
|
||||
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = std::sync::Arc::make_mut(&mut children[2]).appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
f(geom);
|
||||
} else {
|
||||
panic!("the center has no gradient fill");
|
||||
}
|
||||
};
|
||||
let draws = |g: &Node| g.extras().flare.as_deref().is_some_and(|spec| spec.draws(g));
|
||||
assert!(draws(&flare(Affine::scale(1e-7))), "scaled to 0.00001%");
|
||||
assert!(draws(&flare(Affine::rotate(0.3) * Affine::scale_non_uniform(1.0, 1e-10))), "shrunk far on one axis");
|
||||
assert!(draws(&flare(Affine::translate((crate::MAX_COORD - 1000.0, 0.0)) * Affine::scale(0.5))), "near the edge of the canvas");
|
||||
assert!(draws(&flare(Affine::translate((1000.0, 0.0)) * Affine::scale(1e-5))), "scaled to 0.001% and moved away");
|
||||
assert!(!draws(&flare(Affine::scale_non_uniform(1.0, 0.0))), "flattened");
|
||||
// At that size a part whose gradient's shape was edited no longer draws the settings.
|
||||
let mut squashed = flare(Affine::scale(1e-6));
|
||||
assert!(draws(&squashed), "scaled to 0.0001%");
|
||||
center_geom(&mut squashed, &|geom| geom.aspect *= 0.5);
|
||||
assert!(!draws(&squashed), "gradient shape at 0.0001%");
|
||||
// A pixel-aligned part may sit up to a pixel off, but its gradient's shape may not change,
|
||||
// even when the ellipse keeps its size.
|
||||
let mut reshaped = flare_aligned(Affine::IDENTITY, true);
|
||||
assert!(draws(&reshaped), "aligned");
|
||||
center_geom(&mut reshaped, &|geom| {
|
||||
let a = geom.aspect;
|
||||
geom.aspect = a * 0.5;
|
||||
geom.end = geom.start + (geom.end - geom.start) * ((1.0 + a * a) / (1.0 + a * a / 4.0)).sqrt();
|
||||
});
|
||||
assert!(!draws(&reshaped), "gradient shape of the same size, aligned");
|
||||
}
|
||||
}
|
||||
+108
-43
@@ -74,11 +74,24 @@ pub struct HitOptions {
|
||||
/// its edge. Off for the tools that act on what is drawn (sampling, type, gradients…);
|
||||
/// [`hit_test_visible`] never does it.
|
||||
pub clip_outlines: bool,
|
||||
/// The Type tool: area type is hit anywhere inside its frame, where a click places the caret.
|
||||
/// Off, the empty part of the frame (away from its edge and its lines of type) takes no
|
||||
/// clicks, so they reach the art behind (#7274).
|
||||
pub area_type_interior: bool,
|
||||
}
|
||||
|
||||
impl Default for HitOptions {
|
||||
fn default() -> Self {
|
||||
Self { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: false, scope: None }
|
||||
Self {
|
||||
tol: 3.0,
|
||||
outline: false,
|
||||
path_only: false,
|
||||
type_path_only: false,
|
||||
skip_guides: false,
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
scope: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1507,7 +1520,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
hit_painted(n, p, opt, symbols)
|
||||
}
|
||||
NodeKind::Text(_) | NodeKind::PlacedDocument(_) => {
|
||||
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
|
||||
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p))?;
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) if !opt.area_type_interior => in_area_type_art(n, t, p, opt.tol).unwrap_or(true).then_some(HitKind::Bounds),
|
||||
_ => Some(HitKind::Bounds),
|
||||
}
|
||||
}
|
||||
// A symbol instance is hit within its bounds, and outside them where its art paints
|
||||
// ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape
|
||||
@@ -1577,6 +1594,30 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool {
|
||||
stroke_contains(&path.to_bezpath(), 0.0, tol, p)
|
||||
}
|
||||
|
||||
/// Is `p` on area type `t` (in `n`) where it is drawn: within `tol` of its frame's edge or inside
|
||||
/// its laid-out lines ([`crate::TextObject::cached_bounds`], with the characters' strokes)? The
|
||||
/// rest of the frame is empty and takes no clicks (#7274). `None` when that is not known: other
|
||||
/// type, type in perspective, or area type not laid out yet, which are hit within their bounds.
|
||||
fn in_area_type_art(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> Option<bool> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let crate::TextKind::Area { frame } = &t.kind else { return None };
|
||||
if n.projection().is_some() {
|
||||
return None;
|
||||
}
|
||||
if stroke_contains(&frame.transformed(t.xf).to_bezpath(), 0.0, tol, p) {
|
||||
return Some(true);
|
||||
}
|
||||
let lines = t.cached_bounds?;
|
||||
// No lines (empty type): only the frame's edge.
|
||||
if lines.width() <= 0.0 && lines.height() <= 0.0 {
|
||||
return Some(false);
|
||||
}
|
||||
let mut lines = lines.to_path(0.1);
|
||||
lines.apply_affine(t.xf);
|
||||
let reach = tol + t.char_stroke_outset();
|
||||
Some(fill_contains(&lines, FillRule::NonZero, p) || stroke_contains(&lines, 0.0, reach, p))
|
||||
}
|
||||
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art
|
||||
/// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and
|
||||
/// nothing more is tested once the limit is used up.
|
||||
@@ -2106,20 +2147,39 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// the members of a group or layer with geometry effects of its own, are touched where the art those
|
||||
/// effects draw lies ([`set_drawn_art`]), as clicks hit them.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, false)
|
||||
marquee_with(doc, r, scope, leaves, false, false, false)
|
||||
}
|
||||
|
||||
/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer
|
||||
/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as
|
||||
/// the clicks of [`HitOptions::outline`] do.
|
||||
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, outline)
|
||||
/// the clicks of [`HitOptions::outline`] do. With `skip_guides` (Lock Guides is on or the guides
|
||||
/// are hidden, as [`HitOptions::skip_guides`]), the paths made into guides are not touched, at the
|
||||
/// top or inside a group, so a group is not taken for a guide in it (#8538).
|
||||
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool, skip_guides: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, outline, skip_guides)
|
||||
}
|
||||
|
||||
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
|
||||
/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint.
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true, outline)
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool, skip_guides: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true, outline, skip_guides)
|
||||
}
|
||||
|
||||
/// What a marquee ([`marquee_with`]) takes, besides where it is: whether a compound path is
|
||||
/// touched by every path it paints (`whole_compounds`, for an enclosing loop's candidates), and
|
||||
/// whether the paths made into guides are left out (`skip_guides`: Lock Guides is on or the
|
||||
/// guides are hidden, [`HitOptions::skip_guides`] for the marquee).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Rules {
|
||||
whole_compounds: bool,
|
||||
skip_guides: bool,
|
||||
}
|
||||
|
||||
impl Rules {
|
||||
/// Is `n` a path made into a guide that the marquee leaves out?
|
||||
fn skips(self, n: &Node) -> bool {
|
||||
self.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
|
||||
@@ -2127,8 +2187,17 @@ fn previews_off(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Layer { preview: false, .. })
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
fn marquee_with(
|
||||
doc: &Document,
|
||||
r: Rect,
|
||||
scope: Option<NodeId>,
|
||||
leaves: bool,
|
||||
whole_compounds: bool,
|
||||
outline: bool,
|
||||
skip_guides: bool,
|
||||
) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let rules = Rules { whole_compounds, skip_guides };
|
||||
let mut out = Vec::new();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
@@ -2142,7 +2211,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
Some(c) => {
|
||||
// In an isolated clip group, its members by their own geometry, as clicks take
|
||||
// them ([`edits_inside`]).
|
||||
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) };
|
||||
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, rules, outline || previews_off(s)) };
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
@@ -2164,7 +2233,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
|
||||
.flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None))
|
||||
.flat_map(|l| layer_objects(l, &symbols, r, outline, rules, None))
|
||||
.collect(),
|
||||
};
|
||||
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
|
||||
@@ -2173,17 +2242,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object
|
||||
/// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around
|
||||
/// `l` has such effects.
|
||||
fn layer_objects<'a>(
|
||||
l: &'a Node,
|
||||
s: &SymbolBoxes,
|
||||
r: Rect,
|
||||
outline: bool,
|
||||
whole_compounds: bool,
|
||||
drawn: Option<Rc<HashSet<NodeId>>>,
|
||||
) -> Vec<Top<'a>> {
|
||||
fn layer_objects<'a>(l: &'a Node, s: &SymbolBoxes, r: Rect, outline: bool, rules: Rules, drawn: Option<Rc<HashSet<NodeId>>>) -> Vec<Top<'a>> {
|
||||
let mut out = vec![];
|
||||
let outline = outline || previews_off(l);
|
||||
let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline));
|
||||
let drawn = drawn.or_else(|| touched_in_art(l, s, r, rules, outline));
|
||||
let inner = marquee_in_parent(l, r, outline);
|
||||
for (i, c) in l.children().into_iter().flatten().enumerate() {
|
||||
if c.is_layer() {
|
||||
@@ -2192,7 +2254,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
&& !c.locked
|
||||
&& !c.is_template()
|
||||
{
|
||||
out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone()));
|
||||
out.extend(layer_objects(c, s, inner, outline, rules, drawn.clone()));
|
||||
}
|
||||
} else if !c.is_ruler_guide() {
|
||||
if drawn.is_some() {
|
||||
@@ -2209,12 +2271,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// The ids of the objects of the art that group or layer `n` draws with its own geometry
|
||||
/// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them.
|
||||
/// `None` in outline and when it has no such effects.
|
||||
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
|
||||
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
|
||||
let art = drawn_art(s, n, outline)?;
|
||||
let _off = DrawnOff::set();
|
||||
let mut ids = vec![];
|
||||
for a in art.iter().filter(|a| a.visible) {
|
||||
collect_leaves(a, s, r, None, whole_compounds, false, &mut ids);
|
||||
collect_leaves(a, s, r, None, rules, false, &mut ids);
|
||||
}
|
||||
Some(Rc::new(ids.into_iter().collect()))
|
||||
}
|
||||
@@ -2271,12 +2333,16 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping
|
||||
/// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region
|
||||
/// ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, rules: Rules, outline: bool) -> bool {
|
||||
// Locked or hidden guides are not touched ([`Rules::skips`]).
|
||||
if rules.skips(n) {
|
||||
return false;
|
||||
}
|
||||
// A path or compound path whose geometry effects reshape it, or a group or layer whose own
|
||||
// geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]).
|
||||
if let Some(art) = drawn_art(s, n, outline || previews_off(n)) {
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false));
|
||||
return art.iter().any(|a| a.visible && touches(a, s, r, None, rules, false));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
|
||||
@@ -2287,25 +2353,26 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
c.visible
|
||||
&& !shaper_hides(n, i, scope)
|
||||
&& if i == 0 && n.clips() {
|
||||
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)))
|
||||
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, rules, outline)))
|
||||
|| clip_edge_touches(c, r, outline)
|
||||
} else {
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, rules, outline))
|
||||
}
|
||||
})
|
||||
}
|
||||
NodeKind::Compound { children, .. } if whole_compounds => {
|
||||
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
|
||||
NodeKind::Compound { children, .. } if rules.whole_compounds => {
|
||||
// Guide contours left out ([`Rules::skips`]) don't make the compound a candidate.
|
||||
children.iter().filter(|c| !rules.skips(c)).filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
|
||||
}
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, rules, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, rules, outline)),
|
||||
// A symbol instance is touched by its box, and outside it where the live geometry
|
||||
// effects of a clipping path in its art show the art, or where the geometry effects of
|
||||
// its active fill or stroke reshape the art ([`painted_touches`]). In the art of another
|
||||
// instance walked outside that instance's box, it is touched only by its own art
|
||||
// ([`ArtOnly`]) and those shapes.
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
!ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, whole_compounds) || painted_touches(n, s, r))
|
||||
!ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, rules) || painted_touches(n, s, r))
|
||||
}
|
||||
// An image is touched by its box, and outside it where its own fills and strokes paint.
|
||||
NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r),
|
||||
@@ -2334,7 +2401,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the
|
||||
/// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's
|
||||
/// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows.
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules) -> bool {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) {
|
||||
@@ -2351,15 +2418,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
#[cfg(test)]
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
let _art_only = ArtOnly::set();
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, rules, false))
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, rules: Rules, outline: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
let outline = outline || previews_off(n);
|
||||
// The members that the art its own geometry effects draw touches, and a group whose
|
||||
// own fills and strokes that art paints, as clicks hit it ([`member_chain`]).
|
||||
if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) {
|
||||
if let Some(drawn) = touched_in_art(n, s, r, rules, outline) {
|
||||
if drawn.contains(&n.id) && !n.is_layer() {
|
||||
out.push(n.id);
|
||||
}
|
||||
@@ -2374,18 +2441,18 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if i == 0 && n.clips() {
|
||||
let before = out.len();
|
||||
if let Some(r) = mask_marquee(n, r) {
|
||||
plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out));
|
||||
plain(true, || collect_leaves(c, s, r, scope, rules, outline, out));
|
||||
}
|
||||
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
|
||||
out.push(c.id);
|
||||
}
|
||||
} else if let Some(r) = inner {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
collect_leaves(c, s, r, scope, rules, outline, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if touches(n, s, r, scope, whole_compounds, outline) {
|
||||
if touches(n, s, r, scope, rules, outline) {
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
@@ -2420,14 +2487,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if leaves {
|
||||
let before = out.len();
|
||||
if let Some(r) = r {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
|
||||
collect_leaves(t, &symbols, r, scope, rules, outline, &mut out);
|
||||
}
|
||||
if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) {
|
||||
out.push(t.id);
|
||||
}
|
||||
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline))
|
||||
|| edge.is_some_and(|e| clip_edge_touches(t, e, outline))
|
||||
{
|
||||
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, rules, outline)) || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) {
|
||||
out.push(t.id);
|
||||
}
|
||||
}
|
||||
|
||||
+112
-7
@@ -164,8 +164,8 @@ fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_chang
|
||||
// So with a marquee across the art's left edge: in the view, only in Outline view. The
|
||||
// clipping path's own left edge lies there too, and counts in both.
|
||||
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, false, false), [mask_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, true, false), [mask_id, art_id]);
|
||||
// `marquee_in` measures by the plain shapes, as its callers clip by them.
|
||||
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
|
||||
// Hidden, the effect no longer moves the region.
|
||||
@@ -489,8 +489,8 @@ fn a_marquee_touches_a_paths_shifted_art_not_its_source() {
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn");
|
||||
assert!(marquee(&d, own, None, leaves).is_empty(), "its own place");
|
||||
assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art");
|
||||
assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place");
|
||||
assert!(marquee_in_view(&d, drawn, None, leaves, true, false).is_empty(), "outline: no drawn art");
|
||||
assert_eq!(marquee_in_view(&d, own, None, leaves, true, false), [a], "outline: its own place");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -870,6 +870,68 @@ fn a_selected_guide_hidden_by_a_mask_counts_only_while_guides_can_be_clicked() {
|
||||
assert_eq!(selected_hidden_at(&d, hidden, HitOptions { skip_guides: true, ..opt }, &[guide_id]), None);
|
||||
}
|
||||
|
||||
/// #8538: while guides are locked or hidden (`skip_guides`), a marquee touches no guide path, at
|
||||
/// the top of a layer or in a group (the group is not taken for it), nor in a group in a group,
|
||||
/// with leaves or without. The group's other members still take it, and with the guides unlocked
|
||||
/// the guide does.
|
||||
#[test]
|
||||
fn a_marquee_skips_guide_paths_in_groups_while_guides_are_locked() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let guide = |d: &mut Document, r: Rect| {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
n
|
||||
};
|
||||
let top = guide(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0));
|
||||
let inner = guide(&mut d, Rect::new(100.0, 0.0, 120.0, 20.0));
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(200.0, 0.0, 220.0, 20.0)), Appearance::default_art());
|
||||
let (top_id, inner_id, art_id) = (top.id, inner.id, art.id);
|
||||
let (outer_id, nested_id) = (d.alloc_id(), d.alloc_id());
|
||||
let nested = Node::group(nested_id, vec![Arc::new(inner)]);
|
||||
d.insert(Some(l), 0, top).unwrap();
|
||||
d.insert(Some(l), 1, Node::group(outer_id, vec![Arc::new(nested), Arc::new(art)])).unwrap();
|
||||
let (on_top, on_inner, on_art) = (Rect::new(-5.0, 5.0, 5.0, 10.0), Rect::new(95.0, 5.0, 105.0, 10.0), Rect::new(195.0, 5.0, 205.0, 10.0));
|
||||
for leaves in [false, true] {
|
||||
let m = |r: Rect, skip: bool| marquee_in_view(&d, r, None, leaves, false, skip);
|
||||
assert!(m(on_top, true).is_empty(), "a guide at the top, leaves {leaves}");
|
||||
assert!(m(on_inner, true).is_empty(), "a guide in a group in a group, leaves {leaves}");
|
||||
assert!(m(Rect::new(0.0, 0.0, 300.0, 200.0), true).iter().all(|id| ![top_id, inner_id].contains(id)), "all, leaves {leaves}");
|
||||
assert_eq!(m(on_art, true), [if leaves { art_id } else { outer_id }], "the group's art, leaves {leaves}");
|
||||
// Unlocked: the guides are touched.
|
||||
assert_eq!(m(on_top, false), [top_id], "unlocked, leaves {leaves}");
|
||||
assert_eq!(m(on_inner, false), [if leaves { inner_id } else { outer_id }], "unlocked, leaves {leaves}");
|
||||
}
|
||||
// An enclosing loop's candidates leave them out alike.
|
||||
assert!(enclosure_candidates(&d, on_inner, None, false, true).is_empty());
|
||||
assert_eq!(enclosure_candidates(&d, on_inner, None, false, false), [inner_id]);
|
||||
}
|
||||
|
||||
/// #8538: an enclosing loop's candidates leave out a compound path whose touched contours are all
|
||||
/// locked or hidden guides, as the marquee does.
|
||||
#[test]
|
||||
fn guide_contours_do_not_make_a_compound_an_enclosure_candidate() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let part = |d: &mut Document, r: Rect| {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
Arc::new(n)
|
||||
};
|
||||
let (a, b) = (part(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0)), part(&mut d, Rect::new(20.0, 20.0, 40.0, 40.0)));
|
||||
let id = d.alloc_id();
|
||||
let mut compound = Node::group(id, vec![]);
|
||||
compound.kind = NodeKind::Compound { children: vec![a, b], rule: Default::default() };
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let r = Rect::new(0.0, 0.0, 60.0, 60.0);
|
||||
assert!(enclosure_candidates(&d, r, None, false, true).is_empty(), "locked or hidden");
|
||||
assert_eq!(enclosure_candidates(&d, r, None, false, false), [id], "shown and unlocked");
|
||||
}
|
||||
|
||||
/// A selected path in a Shaper group's original shapes, where an outer mask hides it, counts only
|
||||
/// while those shapes can be clicked (Construction mode, with them isolated), however deep it
|
||||
/// lies in them.
|
||||
@@ -1393,8 +1455,16 @@ fn masked_square(layer: bool) -> (Document, NodeId, NodeId, NodeId) {
|
||||
}
|
||||
}
|
||||
|
||||
const SELECTING: HitOptions =
|
||||
HitOptions { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: true, scope: None };
|
||||
const SELECTING: HitOptions = HitOptions {
|
||||
tol: 3.0,
|
||||
outline: false,
|
||||
path_only: false,
|
||||
type_path_only: false,
|
||||
skip_guides: false,
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
/// For the selection tools a clip group's clipping path is hit on its outline, within the
|
||||
/// tolerance, before the art it clips and just outside it too; inside, the art is hit.
|
||||
@@ -1688,6 +1758,41 @@ fn type_path_only_picks_type_on_its_path() {
|
||||
assert_eq!(hit(Point::new(60.0, 339.5), path_only), Some((on_path, HitKind::Outline)), "type on a path: its path");
|
||||
}
|
||||
|
||||
/// Area type is hit on its frame's edge and where its lines are laid out, not in the empty rest of
|
||||
/// its frame: a click there reaches the art behind, in Preview and in Outline mode (#7274). The
|
||||
/// Type tool still finds the type anywhere inside its frame.
|
||||
#[test]
|
||||
fn area_type_passes_clicks_through_its_empty_frame() {
|
||||
use crate::{CharStyle, TextKind, TextObject};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
// A filled square behind the type, its edge at x = 150 inside the frame.
|
||||
let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 150.0, 350.0, 350.0)), Appearance::default_art());
|
||||
let square_id = square.id;
|
||||
d.insert(Some(l), 9, square).unwrap();
|
||||
// Area type at (100, 100): a 200 × 200 frame with one 80 wide line at its top.
|
||||
let mut area = TextObject::point(Point::new(100.0, 100.0), "Area", CharStyle { size: 20.0, ..CharStyle::default() });
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)) };
|
||||
area.cached_bounds = Some(Rect::new(0.0, 0.0, 80.0, 24.0));
|
||||
area.cached_baselines = vec![(Point::new(0.0, 18.0), Point::new(80.0, 18.0))];
|
||||
let area_id = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::new(area_id, NodeKind::Text(Box::new(area)))).unwrap();
|
||||
let outline = HitOptions { outline: true, ..Default::default() };
|
||||
for (opt, mode) in [(HitOptions::default(), "preview"), (outline, "outline")] {
|
||||
let hit = |p: Point| hit_test(&d, p, opt).map(|h| h.leaf);
|
||||
assert_eq!(hit(Point::new(140.0, 110.0)), Some(area_id), "{mode}: on the line of type");
|
||||
assert_eq!(hit(Point::new(200.0, 100.5)), Some(area_id), "{mode}: on the frame's top edge");
|
||||
assert_eq!(hit(Point::new(299.0, 250.0)), Some(area_id), "{mode}: on the frame's right edge");
|
||||
assert_eq!(hit(Point::new(220.0, 130.0)), None, "{mode}: the empty frame, nothing behind");
|
||||
assert_eq!(hit(Point::new(120.0, 250.0)), None, "{mode}: the empty frame, nothing behind");
|
||||
assert_eq!(hit(Point::new(150.0, 250.0)), Some(square_id), "{mode}: the square's edge behind the empty frame");
|
||||
}
|
||||
assert_eq!(hit_test(&d, Point::new(250.0, 250.0), HitOptions::default()).map(|h| h.leaf), Some(square_id), "the square's fill");
|
||||
// The Type tool: anywhere inside the frame.
|
||||
let typing = HitOptions { area_type_interior: true, ..Default::default() };
|
||||
assert_eq!(hit_test(&d, Point::new(250.0, 250.0), typing).map(|h| h.leaf), Some(area_id), "type tool: inside the frame");
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only with the layout's baselines: every line's for point type,
|
||||
/// area type's besides its frame, a vertical column's centre line, and type in perspective
|
||||
/// where it is drawn.
|
||||
@@ -2674,7 +2779,7 @@ fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art
|
||||
assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}");
|
||||
assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}");
|
||||
assert!(marquee(&d, past, None, false).is_empty());
|
||||
assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view");
|
||||
assert!(marquee_in_view(&d, edge, None, false, true, false).is_empty(), "Outline view");
|
||||
}
|
||||
// Preview off for the layer the instance is on.
|
||||
let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false);
|
||||
|
||||
@@ -17,6 +17,7 @@ pub mod corners;
|
||||
pub mod decode;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
pub mod flare;
|
||||
pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
@@ -137,7 +138,7 @@ pub use text::{
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
@@ -170,7 +171,7 @@ use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use stored_art::{StoredPlace, StoredRoot};
|
||||
pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number};
|
||||
pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
@@ -217,6 +218,10 @@ pub struct Document {
|
||||
/// Type › Composite Fonts…: the composite fonts defined in the document, by name.
|
||||
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
|
||||
pub composite_fonts: Shared<Vec<CompositeFont>>,
|
||||
/// Type › Kinsoku Shori Settings…: the custom Kinsoku Shori sets defined in the document, by
|
||||
/// name. A paragraph using one holds a copy of it ([`ParaStyle::kinsoku_set`]).
|
||||
#[serde(default, skip_serializing_if = "skip::is_empty_vec", deserialize_with = "text::read_kinsoku_sets")]
|
||||
pub kinsoku_sets: Shared<Vec<KinsokuSet>>,
|
||||
/// Threaded text: area-type frames one story flows through, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub text_threads: Vec<Vec<NodeId>>,
|
||||
|
||||
+37
-1
@@ -113,6 +113,19 @@ impl Document {
|
||||
.map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>() + custom(f))
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.kinsoku_sets, &newer.kinsoku_sets, |k| {
|
||||
vec_bytes(k)
|
||||
+ k.iter()
|
||||
.map(|s: &crate::KinsokuSet| {
|
||||
s.name.capacity()
|
||||
+ vec_bytes(&s.cannot_start)
|
||||
+ vec_bytes(&s.cannot_end)
|
||||
+ vec_bytes(&s.hanging)
|
||||
+ vec_bytes(&s.inseparable)
|
||||
+ s.inseparable.iter().map(String::capacity).sum::<usize>()
|
||||
})
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
|
||||
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
|
||||
});
|
||||
@@ -271,6 +284,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
.as_deref()
|
||||
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
|
||||
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
|
||||
b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::<crate::flare::FlareSpec>() + json_bytes(&f.params));
|
||||
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
|
||||
if e.intertwine_tiers.capacity() > 0 {
|
||||
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
|
||||
@@ -353,7 +367,8 @@ pub fn appearance_heap_bytes(a: &Appearance) -> usize {
|
||||
AppearanceItem::Stroke(s) => {
|
||||
s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern))
|
||||
+ s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points))
|
||||
+ s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points))
|
||||
+ [&s.pressure, &s.tilt, &s.wheel].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::<usize>()
|
||||
+ [&s.bearing, &s.rotation].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::<usize>()
|
||||
+ s.brush.as_ref().map_or(0, String::capacity)
|
||||
}
|
||||
_ => 0,
|
||||
@@ -424,6 +439,27 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pen_recording_of_a_stroke_counts() {
|
||||
use crate::{AngleProfile, PressureProfile};
|
||||
let plain = Appearance::default_art();
|
||||
let base = appearance_heap_bytes(&plain);
|
||||
let ramp = || PressureProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 0.5)).collect() };
|
||||
let turn = || AngleProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 10.0)).collect() };
|
||||
for i in 0..5 {
|
||||
let mut a = plain.clone();
|
||||
let s = a.stroke_mut().unwrap();
|
||||
match i {
|
||||
0 => s.pressure = Some(ramp()),
|
||||
1 => s.tilt = Some(ramp()),
|
||||
2 => s.bearing = Some(turn()),
|
||||
3 => s.rotation = Some(turn()),
|
||||
_ => s.wheel = Some(ramp()),
|
||||
}
|
||||
assert!(appearance_heap_bytes(&a) >= base + 100 * size_of::<(f64, f64)>(), "recording {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_copy_keeps_nothing_of_its_own() {
|
||||
let d = doc_with_rects(10);
|
||||
|
||||
@@ -10,8 +10,9 @@ use super::{Node, PathData};
|
||||
pub struct NodeExtras {
|
||||
/// Opacity mask (Transparency panel). Its art lives here, outside the layer tree.
|
||||
pub mask: Option<Box<OpacityMask>>,
|
||||
/// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows
|
||||
/// them; `view` is its [`crate::TraceView`] id, absent for the tracing result).
|
||||
/// Image Trace object: `{preset, params, view?, split?}` it was traced with (the Image Trace
|
||||
/// panel shows them; `view` is its [`crate::TraceView`] id, absent for the tracing result, and
|
||||
/// `split` the Split view's divider, [`crate::TraceView::split_of`]).
|
||||
pub trace: Option<Box<serde_json::Value>>,
|
||||
/// Object → Text Wrap: area type below this object (in the same layer) flows around it.
|
||||
pub wrap: Option<crate::text::TextWrap>,
|
||||
@@ -41,6 +42,9 @@ pub struct NodeExtras {
|
||||
/// Dimension object: the live measurement it draws; its ordinary group children hold its
|
||||
/// exportable appearance (Object › Dimensions, the Dimension tool).
|
||||
pub dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
/// Flare object: the settings its group was drawn with (the Flare tool); its ordinary group
|
||||
/// children hold its art.
|
||||
pub flare: Option<Box<crate::flare::FlareSpec>>,
|
||||
/// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates,
|
||||
/// filled non-zero) where this object is drawn over the group's other members.
|
||||
pub intertwine: Option<Box<PathData>>,
|
||||
@@ -100,6 +104,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
slice: None,
|
||||
perspective: None,
|
||||
dimension: None,
|
||||
flare: None,
|
||||
intertwine: None,
|
||||
intertwine_tiers: Vec::new(),
|
||||
live_paint_gaps: None,
|
||||
|
||||
@@ -90,6 +90,42 @@ impl Node {
|
||||
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// This object without the paths made into guides among the members of its groups, layers,
|
||||
/// Intertwine groups and compound paths, at any depth, for measuring the art around them while
|
||||
/// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or
|
||||
/// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps
|
||||
/// its structure. `None` when it holds no such guide.
|
||||
pub fn without_guides(&self) -> Option<Node> {
|
||||
let (NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Intertwine { children }
|
||||
| NodeKind::Compound { children, .. }) = &self.kind
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let keep = usize::from(self.clips() || self.extras().shaper.is_some());
|
||||
let mut changed = false;
|
||||
let mut out = Vec::with_capacity(children.len());
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
changed = true;
|
||||
} else if let Some(stripped) = c.without_guides() {
|
||||
changed = true;
|
||||
out.push(Arc::new(stripped));
|
||||
} else {
|
||||
out.push(c.clone());
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
let mut n = self.clone();
|
||||
if let Some(c) = n.children_mut() {
|
||||
*c = out;
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// A template layer (Layer Options → Template).
|
||||
pub fn is_template(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
@@ -484,6 +520,12 @@ impl Node {
|
||||
{
|
||||
dimension.transform(a);
|
||||
}
|
||||
// So does a flare's center and end point.
|
||||
if let Some(e) = self.extras_if_any()
|
||||
&& let Some(flare) = &mut e.flare
|
||||
{
|
||||
flare.transform(a);
|
||||
}
|
||||
// The path the objects are attached to, before it is transformed.
|
||||
let on_path_before = self.on_path_data().cloned();
|
||||
if !self.is_layer() {
|
||||
|
||||
@@ -45,6 +45,7 @@ impl Serialize for Node {
|
||||
is_default(&self.bbox_angle),
|
||||
e.perspective.is_none(),
|
||||
e.dimension.is_none(),
|
||||
e.flare.is_none(),
|
||||
e.intertwine.is_none(),
|
||||
e.intertwine_tiers.is_empty(),
|
||||
e.live_paint_gaps.is_none(),
|
||||
@@ -91,6 +92,7 @@ impl Serialize for Node {
|
||||
field!("bbox_angle", &self.bbox_angle);
|
||||
field!("perspective", &e.perspective);
|
||||
field!("dimension", &e.dimension);
|
||||
field!("flare", &e.flare);
|
||||
field!("intertwine", &e.intertwine);
|
||||
field!("intertwine_tiers", &e.intertwine_tiers);
|
||||
field!("live_paint_gaps", &e.live_paint_gaps);
|
||||
@@ -228,6 +230,8 @@ pub(super) struct NodeWire {
|
||||
#[serde(default)]
|
||||
dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
#[serde(default)]
|
||||
flare: Option<Box<crate::flare::FlareSpec>>,
|
||||
#[serde(default)]
|
||||
intertwine: Option<Box<PathData>>,
|
||||
#[serde(default, deserialize_with = "counted_list")]
|
||||
intertwine_tiers: Vec<PathData>,
|
||||
@@ -271,6 +275,7 @@ impl From<NodeWire> for Node {
|
||||
slice: w.slice,
|
||||
perspective: w.perspective,
|
||||
dimension: w.dimension,
|
||||
flare: w.flare,
|
||||
intertwine: w.intertwine,
|
||||
intertwine_tiers: w.intertwine_tiers,
|
||||
live_paint_gaps: w.live_paint_gaps,
|
||||
|
||||
@@ -157,6 +157,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
|
||||
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: "paper-cutouts", name: "Paper Cutouts", make: paper_cutouts },
|
||||
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 },
|
||||
@@ -384,6 +385,25 @@ fn painted_sketched() -> Vec<GraphicStyle> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Paper Cutouts: original layered paper colors with visible cut edges and crisp cast shadows.
|
||||
fn paper_cutouts() -> Vec<GraphicStyle> {
|
||||
let cutout = |name: &str, face: &str, edge: &str, rim: &str, shadow: &str, x: f64, y: f64| {
|
||||
style(
|
||||
name,
|
||||
vec![F(fill(face)), S(stroke(edge, 7.0)), S(stroke(rim, 2.0))],
|
||||
vec![fx("stylize.dropShadow", json!({"mode": "normal", "opacity": 100.0, "x": x, "y": y, "blur": 0.0, "color": shadow}))],
|
||||
)
|
||||
};
|
||||
vec![
|
||||
cutout("Coral Layers", "#ff6b6b", "#f9c74f", "#fff4e6", "#6d597a", 5.0, 5.0),
|
||||
cutout("Mint Layers", "#80cbc4", "#2a9d8f", "#e9f5db", "#355070", 4.0, 6.0),
|
||||
cutout("Midnight Layers", "#3d5a80", "#ee6c4d", "#e0fbfc", "#1b263b", 6.0, 4.0),
|
||||
cutout("Sunflower Sheet", "#ffbe0b", "#fb5607", "#fff3b0", "#6a4c93", 3.0, 6.0),
|
||||
cutout("Rose Layers", "#f28482", "#84a59d", "#f7ede2", "#4a4e69", 6.0, 3.0),
|
||||
cutout("Monochrome Stack", "#f5f5f5", "#444444", "#ffffff", "#222222", 5.0, 5.0),
|
||||
]
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -702,6 +722,26 @@ mod tests {
|
||||
assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paper_cutouts_have_layered_edges_and_crisp_shadows() {
|
||||
let lib = builtin_style_library("paper-cutouts").unwrap();
|
||||
assert_eq!(lib.name, "Paper Cutouts");
|
||||
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(names, ["Coral Layers", "Mint Layers", "Midnight Layers", "Sunflower Sheet", "Rose Layers", "Monochrome Stack"]);
|
||||
for g in &lib.styles {
|
||||
assert_eq!(g.appearance.items.len(), 3, "{} has a face and two cut edges", g.name);
|
||||
assert!(matches!(g.appearance.items[0], AppearanceItem::Fill(_)));
|
||||
assert!(matches!(g.appearance.items[1], AppearanceItem::Stroke(_)));
|
||||
assert!(matches!(g.appearance.items[2], AppearanceItem::Stroke(_)));
|
||||
assert_eq!(g.appearance.effects.len(), 1);
|
||||
let shadow = &g.appearance.effects[0];
|
||||
assert_eq!(shadow.id, "stylize.dropShadow");
|
||||
assert_eq!(shadow.params["blur"], 0.0);
|
||||
assert_eq!(shadow.params["opacity"], 100.0);
|
||||
}
|
||||
assert_eq!(read(&write(&lib), "Fallback").unwrap(), *lib);
|
||||
}
|
||||
|
||||
/// The built-in styles' Warps draw with the map a new Warp takes.
|
||||
#[test]
|
||||
fn builtin_warp_styles_take_the_nets_map() {
|
||||
|
||||
@@ -94,11 +94,59 @@ fn a_very_long_expression_reads_as_nothing() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `x`, `X` and `×` multiply as `*` does (#8435), units and percentages included; a lowercase `x`
|
||||
/// right after a `p` stays the `px` unit.
|
||||
#[test]
|
||||
fn x_is_a_multiplication_sign() {
|
||||
let (mm, cm) = (72.0 / 25.4, 72.0 / 2.54);
|
||||
for (u, s, want) in [
|
||||
(Unit::Points, "10x2", 20.0),
|
||||
(Unit::Points, "10 x 2", 20.0),
|
||||
(Unit::Points, "10X2", 20.0),
|
||||
(Unit::Points, "10×2", 20.0),
|
||||
(Unit::Points, "10x-2", -20.0),
|
||||
(Unit::Points, "10/2x5", 25.0),
|
||||
(Unit::Points, "1+2x3", 7.0),
|
||||
(Unit::Millimeters, "2x3 mm", 6.0 * mm),
|
||||
(Unit::Points, "2x3mm", 6.0 * mm),
|
||||
(Unit::Points, "3mm x 2", 6.0 * mm),
|
||||
(Unit::Centimeters, "3cmx50%", 1.5 * cm),
|
||||
(Unit::Points, "2p x 2", 48.0),
|
||||
(Unit::Points, "10px", 10.0),
|
||||
(Unit::Points, "2px x 3", 6.0),
|
||||
(Unit::Points, "2pxx3", 6.0),
|
||||
(Unit::Millimeters, "4x3 px", 12.0),
|
||||
// Only a lowercase x after a p is the px suffix.
|
||||
(Unit::Points, "2pX3", 72.0),
|
||||
(Unit::Points, "2p×3", 72.0),
|
||||
// Text that used to be refused now reads as a product.
|
||||
(Unit::Points, "8.5x11 in", 93.5 * 72.0),
|
||||
(Unit::Points, "0x10", 0.0),
|
||||
] {
|
||||
let got = u.parse(s).unwrap_or_else(|| panic!("{u:?} can't read `{s}`"));
|
||||
assert!((got - want).abs() < 1e-9, "{u:?}: `{s}` → {got}, want {want}");
|
||||
}
|
||||
for s in ["x", "x2", "5x", "5 x x 2", "xx", "2px3"] {
|
||||
assert_eq!(Unit::Points.parse(s), None, "{s}");
|
||||
}
|
||||
assert_eq!(crate::parse_number("45x2"), Some(90.0));
|
||||
assert_eq!(crate::parse_number(" 45 X 2 "), Some(90.0));
|
||||
assert_eq!(crate::parse_number("45×2"), Some(90.0));
|
||||
assert_eq!(crate::parse_number("90x-1"), Some(-90.0));
|
||||
assert_eq!(crate::parse_number("x"), None);
|
||||
// Each sign counts toward the 128-sign limit as a `*` would.
|
||||
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(128))), Some(1.0));
|
||||
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(129))), None);
|
||||
assert_eq!(crate::parse_number(&format!("1{}", "×1".repeat(129))), None);
|
||||
assert_eq!(crate::arithmetic_signs("1+2x3X4×5*6/7-8"), 7);
|
||||
assert_eq!(crate::arithmetic_signs("2px x 3"), 1);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
|
||||
/// or as nothing and does not panic.
|
||||
#[test]
|
||||
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxinmcfyd-]{0,24}") {
|
||||
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxXinmcfyd×-]{0,24}") {
|
||||
for u in Unit::ALL {
|
||||
if let Some(v) = u.parse(&s) {
|
||||
prop_assert!(v.is_finite(), "{u:?}: `{s}` → {v}");
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
|
||||
mod area;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod kinsoku_set;
|
||||
mod object;
|
||||
mod para_style;
|
||||
mod runs;
|
||||
@@ -25,6 +26,8 @@ pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
|
||||
};
|
||||
pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets;
|
||||
pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
|
||||
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
//! Type › Kinsoku Shori Settings…: a custom Kinsoku Shori set, saved with the document. Its four
|
||||
//! categories hold the characters that may not start a line, those that may not end one, the
|
||||
//! hanging punctuation that Burasagari lets stand outside a line, and the inseparable sequences
|
||||
//! that Bunri-Kinshi keeps on one line. A paragraph that uses a set holds a copy of it
|
||||
//! ([`super::ParaStyle::kinsoku_set`]).
|
||||
//!
|
||||
//! Behavior reference: the help page
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-kinsoku-for-japanese-line-breaking.html>.
|
||||
//! The name rules and the limits are VectorCraft's own.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The longest set name, in characters.
|
||||
pub const KINSOKU_NAME_MAX: usize = 128;
|
||||
/// The most custom sets a document keeps.
|
||||
pub const KINSOKU_SETS_MAX: usize = 256;
|
||||
/// The most characters one category holds (an inseparable sequence counts each of its characters).
|
||||
pub const KINSOKU_CATEGORY_MAX: usize = 4096;
|
||||
/// The fewest and most characters of an inseparable sequence.
|
||||
pub const KINSOKU_SEQUENCE: std::ops::RangeInclusive<usize> = 2..=16;
|
||||
/// The names of the built-in sets, which no custom set may take (in any case).
|
||||
pub const KINSOKU_BUILT_IN: [&str; 3] = ["None", "Hard", "Soft"];
|
||||
|
||||
/// A custom Kinsoku Shori set. Each list of characters is sorted and holds each character once;
|
||||
/// the inseparable sequences are sorted and unique.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(from = "KinsokuSetFile", into = "KinsokuSetFile")]
|
||||
pub struct KinsokuSet {
|
||||
pub name: String,
|
||||
/// Cannot Start Line: characters that never start a line.
|
||||
pub cannot_start: Vec<char>,
|
||||
/// Cannot End Line: characters that never end a line.
|
||||
pub cannot_end: Vec<char>,
|
||||
/// Hanging Punctuation: characters that Burasagari lets hang outside a line's end.
|
||||
pub hanging: Vec<char>,
|
||||
/// Bunri-Kinshi: sequences of characters that a line never breaks inside while Bunri-Kinshi is
|
||||
/// on.
|
||||
pub inseparable: Vec<String>,
|
||||
}
|
||||
|
||||
/// [`KinsokuSet`] as saved: each category of single characters as one string.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct KinsokuSetFile {
|
||||
#[serde(default, deserialize_with = "read_name")]
|
||||
name: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
cannot_start: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
cannot_end: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
hanging: String,
|
||||
#[serde(default, deserialize_with = "read_sequences")]
|
||||
inseparable: Vec<String>,
|
||||
}
|
||||
|
||||
/// The most characters of a name read from a file, spaces around it included; a longer name is
|
||||
/// not read.
|
||||
const NAME_READ_MAX: usize = KINSOKU_CATEGORY_MAX;
|
||||
/// The most characters of a category read from a file, before control and space characters are
|
||||
/// left out.
|
||||
const CATEGORY_READ_MAX: usize = KINSOKU_CATEGORY_MAX * 4;
|
||||
/// The longest inseparable sequence, as a constant for [`Capped`].
|
||||
const SEQUENCE_MAX: usize = *KINSOKU_SEQUENCE.end();
|
||||
|
||||
/// Text read from a file, copied up to `N` characters: a longer text keeps its first `N + 1`, which
|
||||
/// no rule that allows `N` takes, and is not copied whole.
|
||||
struct Capped<const N: usize>(String);
|
||||
|
||||
impl<'de, const N: usize> Deserialize<'de> for Capped<N> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct Text<const N: usize>;
|
||||
impl<const N: usize> serde::de::Visitor<'_> for Text<N> {
|
||||
type Value = Capped<N>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("text")
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Capped<N>, E> {
|
||||
Ok(Capped(v.chars().take(N + 1).collect()))
|
||||
}
|
||||
}
|
||||
d.deserialize_str(Text::<N>)
|
||||
}
|
||||
}
|
||||
|
||||
/// A set's name as read from a file: empty, so not read, when it is longer than [`NAME_READ_MAX`].
|
||||
fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
let Capped(name) = Capped::<NAME_READ_MAX>::deserialize(d)?;
|
||||
Ok(if name.chars().count() > NAME_READ_MAX { String::new() } else { name })
|
||||
}
|
||||
|
||||
/// A category of a set as read from a file: its first [`CATEGORY_READ_MAX`] characters.
|
||||
fn read_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
let Capped(text) = Capped::<CATEGORY_READ_MAX>::deserialize(d)?;
|
||||
Ok(text.chars().take(CATEGORY_READ_MAX).collect())
|
||||
}
|
||||
|
||||
/// Reads a list, keeping the items `keep` keeps up to `max` of them and skipping the rest of a
|
||||
/// longer list without storing it.
|
||||
struct Kept<T, F>(usize, F, std::marker::PhantomData<T>);
|
||||
|
||||
impl<'de, T: Deserialize<'de>, F: FnMut(&T) -> bool> serde::de::Visitor<'de> for Kept<T, F> {
|
||||
type Value = Vec<T>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a list")
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(mut self, mut seq: A) -> Result<Vec<T>, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while out.len() < self.0 {
|
||||
match seq.next_element::<T>()? {
|
||||
Some(item) if (self.1)(&item) => out.push(item),
|
||||
Some(_) => {}
|
||||
None => return Ok(out),
|
||||
}
|
||||
}
|
||||
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// A set's inseparable sequences as read from a file: those [`KinsokuSet::takes_sequence`] takes,
|
||||
/// at most [`KINSOKU_CATEGORY_MAX`]. A text longer than a sequence is not copied whole.
|
||||
fn read_sequences<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
|
||||
let keep = |s: &Capped<SEQUENCE_MAX>| KinsokuSet::takes_sequence(&s.0);
|
||||
let kept = d.deserialize_seq(Kept(KINSOKU_CATEGORY_MAX, keep, std::marker::PhantomData))?;
|
||||
Ok(kept.into_iter().map(|Capped(s)| s).collect())
|
||||
}
|
||||
|
||||
impl From<KinsokuSet> for KinsokuSetFile {
|
||||
fn from(s: KinsokuSet) -> Self {
|
||||
Self {
|
||||
name: s.name,
|
||||
cannot_start: s.cannot_start.into_iter().collect(),
|
||||
cannot_end: s.cannot_end.into_iter().collect(),
|
||||
hanging: s.hanging.into_iter().collect(),
|
||||
inseparable: s.inseparable,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<KinsokuSetFile> for KinsokuSet {
|
||||
/// A set read from a file keeps what a set can hold: its name trimmed, or no name when
|
||||
/// [`KinsokuSet::clean_name`] refuses it; each category's characters sorted and unique, without
|
||||
/// control or space characters, up to [`KINSOKU_CATEGORY_MAX`]; and the inseparable sequences of
|
||||
/// [`KINSOKU_SEQUENCE`] characters, up to the same count of characters.
|
||||
fn from(f: KinsokuSetFile) -> Self {
|
||||
let chars = |s: &str| s.chars().filter(|&c| KinsokuSet::takes_char(c)).take(KINSOKU_CATEGORY_MAX * 4).collect::<Vec<char>>();
|
||||
let mut set = KinsokuSet {
|
||||
name: KinsokuSet::clean_name(&f.name).unwrap_or_default(),
|
||||
cannot_start: chars(&f.cannot_start),
|
||||
cannot_end: chars(&f.cannot_end),
|
||||
hanging: chars(&f.hanging),
|
||||
inseparable: f.inseparable,
|
||||
};
|
||||
set.normalize();
|
||||
set.cannot_start.truncate(KINSOKU_CATEGORY_MAX);
|
||||
set.cannot_end.truncate(KINSOKU_CATEGORY_MAX);
|
||||
set.hanging.truncate(KINSOKU_CATEGORY_MAX);
|
||||
let mut total = 0;
|
||||
set.inseparable.retain(|s| {
|
||||
total += s.chars().count();
|
||||
total <= KINSOKU_CATEGORY_MAX
|
||||
});
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's custom sets as read from a file: each set with a name, the first set of each name
|
||||
/// (in any case), at most [`KINSOKU_SETS_MAX`]; the sets past those are skipped without being
|
||||
/// stored.
|
||||
pub(crate) fn read_sets<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::Shared<Vec<KinsokuSet>>, D::Error> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let keep = move |s: &KinsokuSet| !s.name.is_empty() && seen.insert(s.name.to_lowercase());
|
||||
Ok(crate::Shared::new(d.deserialize_seq(Kept(KINSOKU_SETS_MAX, keep, std::marker::PhantomData))?))
|
||||
}
|
||||
|
||||
impl KinsokuSet {
|
||||
/// Do `a` and `b` name the same set: equal in any case?
|
||||
pub fn same_name(a: &str, b: &str) -> bool {
|
||||
a == b || a.to_lowercase() == b.to_lowercase()
|
||||
}
|
||||
|
||||
/// The set of `sets` (a document's custom sets) named `name`, in any case.
|
||||
pub fn named<'a>(sets: &'a [KinsokuSet], name: &str) -> Option<&'a KinsokuSet> {
|
||||
sets.iter().find(|s| Self::same_name(&s.name, name))
|
||||
}
|
||||
|
||||
/// `name` trimmed, when it can name a custom set: not empty, at most [`KINSOKU_NAME_MAX`]
|
||||
/// characters, without control characters, and none of [`KINSOKU_BUILT_IN`] in any case.
|
||||
pub fn clean_name(name: &str) -> Option<String> {
|
||||
let name = name.trim();
|
||||
let ok = !name.is_empty()
|
||||
&& name.chars().count() <= KINSOKU_NAME_MAX
|
||||
&& !name.chars().any(char::is_control)
|
||||
&& !KINSOKU_BUILT_IN.iter().any(|b| Self::same_name(b, name));
|
||||
ok.then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// Can a category hold character `c`: not a control character nor a space?
|
||||
pub fn takes_char(c: char) -> bool {
|
||||
!c.is_control() && !c.is_whitespace()
|
||||
}
|
||||
|
||||
/// Can `s` be an inseparable sequence: [`KINSOKU_SEQUENCE`] characters that
|
||||
/// [`Self::takes_char`] takes?
|
||||
pub fn takes_sequence(s: &str) -> bool {
|
||||
KINSOKU_SEQUENCE.contains(&s.chars().count()) && s.chars().all(Self::takes_char)
|
||||
}
|
||||
|
||||
/// Sort each category and keep each character or sequence once.
|
||||
pub fn normalize(&mut self) {
|
||||
for list in [&mut self.cannot_start, &mut self.cannot_end, &mut self.hanging] {
|
||||
list.sort_unstable();
|
||||
list.dedup();
|
||||
}
|
||||
self.inseparable.sort_unstable();
|
||||
self.inseparable.dedup();
|
||||
}
|
||||
|
||||
/// Why this set can't be used, if it can't: a name [`Self::clean_name`] refuses, a character
|
||||
/// [`Self::takes_char`] refuses, a sequence [`Self::takes_sequence`] refuses, or a category of
|
||||
/// more than [`KINSOKU_CATEGORY_MAX`] characters.
|
||||
pub fn check(&self) -> Result<(), String> {
|
||||
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
|
||||
return Err(format!(
|
||||
"`{}` can't name a Kinsoku set (1 to {KINSOKU_NAME_MAX} characters, no control characters, not None, Hard or Soft)",
|
||||
self.name
|
||||
));
|
||||
}
|
||||
for (key, list) in [("cannotStart", &self.cannot_start), ("cannotEnd", &self.cannot_end), ("hanging", &self.hanging)] {
|
||||
if list.len() > KINSOKU_CATEGORY_MAX {
|
||||
return Err(format!("{key}: at most {KINSOKU_CATEGORY_MAX} characters"));
|
||||
}
|
||||
if let Some(c) = list.iter().find(|&&c| !Self::takes_char(c)) {
|
||||
return Err(format!("{key}: U+{:04X} is a control or space character", u32::from(*c)));
|
||||
}
|
||||
}
|
||||
if let Some(s) = self.inseparable.iter().find(|s| !Self::takes_sequence(s)) {
|
||||
return Err(format!(
|
||||
"inseparable: `{s}` must be {} to {} characters, none of them control or space characters",
|
||||
KINSOKU_SEQUENCE.start(),
|
||||
KINSOKU_SEQUENCE.end()
|
||||
));
|
||||
}
|
||||
if self.inseparable.iter().map(|s| s.chars().count()).sum::<usize>() > KINSOKU_CATEGORY_MAX {
|
||||
return Err(format!("inseparable: at most {KINSOKU_CATEGORY_MAX} characters in all"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// May `c` not start a line?
|
||||
pub fn cannot_start(&self, c: char) -> bool {
|
||||
self.cannot_start.binary_search(&c).is_ok()
|
||||
}
|
||||
|
||||
/// May `c` not end a line?
|
||||
pub fn cannot_end(&self, c: char) -> bool {
|
||||
self.cannot_end.binary_search(&c).is_ok()
|
||||
}
|
||||
|
||||
/// May `c` hang outside a line's end (Burasagari)?
|
||||
pub fn hangs(&self, c: char) -> bool {
|
||||
self.hanging.binary_search(&c).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::text::{Kinsoku, ParaStyle};
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A set is saved with each category as one string and read back as it was; a paragraph saves
|
||||
/// its copy of the set beside Hard, and a paragraph saved without one reads with none.
|
||||
#[test]
|
||||
fn kinsoku_sets_are_saved_with_the_paragraphs_that_use_them() {
|
||||
let mut set = KinsokuSet {
|
||||
name: "Tight".into(),
|
||||
cannot_start: "」。、".chars().collect(),
|
||||
cannot_end: vec!['「'],
|
||||
hanging: vec!['、', '。'],
|
||||
inseparable: vec!["——".into(), "あいう".into()],
|
||||
};
|
||||
set.normalize();
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!(saved, json!({"name": "Tight", "cannotStart": "、。」", "cannotEnd": "「", "hanging": "、。", "inseparable": ["——", "あいう"]}));
|
||||
assert_eq!(serde_json::from_value::<KinsokuSet>(saved).unwrap(), set);
|
||||
let p = ParaStyle { kinsoku_set: Some(Arc::new(set.clone())), ..ParaStyle::default() };
|
||||
let v = serde_json::to_value(&p).unwrap();
|
||||
assert_eq!(v["kinsoku_set"]["name"], "Tight");
|
||||
assert!(v.get("kinsoku").is_none(), "Hard, the default, is left out");
|
||||
let back: ParaStyle = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(back.kinsoku_set.as_deref(), Some(&set));
|
||||
assert_eq!((back.kinsoku, back.kinsoku_name(), back.kinsoku_on()), (Kinsoku::Hard, "Tight", true));
|
||||
let old: ParaStyle = serde_json::from_value(json!({"justify": "Left", "kinsoku": "soft"})).unwrap();
|
||||
assert_eq!((old.kinsoku_set, old.kinsoku), (None, Kinsoku::Soft));
|
||||
assert!(serde_json::to_value(ParaStyle::default()).unwrap().get("kinsoku_set").is_none());
|
||||
}
|
||||
|
||||
/// A set read from a file keeps only what a set can hold: each character once, sorted, without
|
||||
/// control or space characters, at most 4096 to a category, and sequences of 2 to 16
|
||||
/// characters; a category left out is empty. Only the start of a longer text is read.
|
||||
#[test]
|
||||
fn kinsoku_sets_read_from_a_file_keep_what_a_set_can_hold() {
|
||||
let long: String = (0x4E00..0x4E00 + 5000).filter_map(char::from_u32).collect();
|
||||
let v = json!({
|
||||
"name": "Odd",
|
||||
"cannotStart": "ccba \t\u{0}a",
|
||||
"cannotEnd": long,
|
||||
"inseparable": ["a", "ab", "ab", "a b", "abcdefghijklmnopq", "abcdefghijklmnop"],
|
||||
});
|
||||
let set: KinsokuSet = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(set.cannot_start, ['a', 'b', 'c']);
|
||||
assert_eq!(set.cannot_end.len(), KINSOKU_CATEGORY_MAX);
|
||||
assert!(set.hanging.is_empty());
|
||||
assert_eq!(set.inseparable, ["ab", "abcdefghijklmnop"]);
|
||||
assert!(set.check().is_ok());
|
||||
let empty: KinsokuSet = serde_json::from_value(json!({})).unwrap();
|
||||
assert!(empty.check().is_err(), "a set needs a name");
|
||||
// Only the start of a long text is read: a category's first 16384 characters, a name of at
|
||||
// most 4096 characters, spaces included, and a sequence's first 17.
|
||||
let spaces = " ".repeat(CATEGORY_READ_MAX);
|
||||
let text = format!(
|
||||
r#"{{"name": "{}Tight", "hanging": "{spaces}、", "cannotEnd": "、", "inseparable": ["{}あ"]}}"#,
|
||||
" ".repeat(NAME_READ_MAX),
|
||||
"あ".repeat(100)
|
||||
);
|
||||
let set: KinsokuSet = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!((set.name.as_str(), set.hanging.len(), set.cannot_end.len(), set.inseparable.len()), ("", 0, 1, 0));
|
||||
let set: KinsokuSet = serde_json::from_str(&format!(r#"{{"name": "{}Tight"}}"#, " ".repeat(NAME_READ_MAX - 5))).unwrap();
|
||||
assert_eq!(set.name, "Tight");
|
||||
}
|
||||
|
||||
/// A set read from a file under a name a custom set can't take (a built-in name, a blank one)
|
||||
/// is not read: a paragraph holding it keeps its Kinsoku Set, so it doesn't show as Hard while
|
||||
/// composing by other characters, and a document's list drops it. The list also keeps the
|
||||
/// first set of each name in any case, and a name read with spaces around it is trimmed. A
|
||||
/// paragraph's set read beside None or Soft is not read either.
|
||||
#[test]
|
||||
fn kinsoku_sets_read_under_names_a_set_cannot_take_are_dropped() {
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": "Hard", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!((p.kinsoku_set, p.kinsoku), (None, Kinsoku::Hard));
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku": "none", "kinsoku_set": {"name": "Tight", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!((p.kinsoku_set.is_none(), p.kinsoku_name()), (true, "None"));
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": " Tight ", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!(p.kinsoku_name(), "Tight");
|
||||
let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap();
|
||||
v["kinsoku_sets"] = json!([{"name": "soft"}, {"name": " "}, {"name": "Tight", "cannotEnd": "「"}, {"name": "TIGHT"}, {"name": "Loose"}]);
|
||||
let d: crate::Document = serde_json::from_value(v).unwrap();
|
||||
let names: Vec<&str> = d.kinsoku_sets.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["Tight", "Loose"]);
|
||||
assert_eq!(d.kinsoku_sets[0].cannot_end, ['「']);
|
||||
let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap();
|
||||
// The sets past the limit are skipped unread: one that isn't a set at all doesn't fail the
|
||||
// file.
|
||||
let mut list: Vec<serde_json::Value> = (0..KINSOKU_SETS_MAX + 5).map(|i| json!({"name": format!("S{i}")})).collect();
|
||||
list.push(json!("not a set"));
|
||||
v["kinsoku_sets"] = json!(list);
|
||||
let d: crate::Document = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(d.kinsoku_sets.len(), KINSOKU_SETS_MAX);
|
||||
let past: Vec<String> = (0..KINSOKU_CATEGORY_MAX + 1).map(|i| format!("あ{i}")).chain(["x".to_string()]).collect();
|
||||
let mut seqs: Vec<serde_json::Value> = past.iter().map(|s| json!(s)).collect();
|
||||
seqs.push(json!(7));
|
||||
let set: KinsokuSet = serde_json::from_value(json!({"name": "Long", "inseparable": seqs})).unwrap();
|
||||
assert!(set.check().is_ok());
|
||||
}
|
||||
|
||||
/// A name is trimmed, 1 to 128 characters without control characters, and never None, Hard or
|
||||
/// Soft in any case; names match in any case.
|
||||
#[test]
|
||||
fn kinsoku_set_names_are_checked() {
|
||||
assert_eq!(KinsokuSet::clean_name(" Tight "), Some("Tight".into()));
|
||||
for bad in ["", " ", "hard", "SOFT", "None", "a\u{7}b", &"x".repeat(KINSOKU_NAME_MAX + 1)] {
|
||||
assert_eq!(KinsokuSet::clean_name(bad), None, "{bad:?}");
|
||||
}
|
||||
assert!(KinsokuSet::clean_name(&"漢".repeat(KINSOKU_NAME_MAX)).is_some());
|
||||
assert!(KinsokuSet::same_name("Tight", "tIGHT"));
|
||||
let sets = [KinsokuSet { name: "Tight".into(), ..Default::default() }];
|
||||
assert!(KinsokuSet::named(&sets, "TIGHT").is_some() && KinsokuSet::named(&sets, "Loose").is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::char_style::CharStyle;
|
||||
use super::kinsoku_set::KinsokuSet;
|
||||
use super::tabs_lists::{ParaList, TabStop};
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
@@ -256,14 +259,18 @@ pub struct ParaStyle {
|
||||
/// How leading is measured (Paragraph panel menu): from baseline to baseline, or from the top
|
||||
/// of one line's ideographic em box to the next.
|
||||
pub leading_model: LeadingModel,
|
||||
/// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line
|
||||
/// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
|
||||
/// Hanging punctuation (Paragraph panel menu › Burasagari): the Kinsoku Set's hanging
|
||||
/// punctuation ending a line may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
|
||||
/// it and imported text keep [`Burasagari::None`], except legacy `.ai` type with binding
|
||||
/// punctuation on, which opens with [`Burasagari::Forced`].
|
||||
pub burasagari: Burasagari,
|
||||
/// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a
|
||||
/// line.
|
||||
pub kinsoku: Kinsoku,
|
||||
/// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) chosen in Kinsoku Set: a copy of
|
||||
/// the document's set of that name, which takes the place of [`Self::kinsoku`]. A paragraph
|
||||
/// with one keeps [`Kinsoku::Hard`] in `kinsoku`, which builds without custom sets read.
|
||||
pub kinsoku_set: Option<Arc<KinsokuSet>>,
|
||||
/// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start
|
||||
/// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku.
|
||||
pub kinsoku_type: KinsokuShoriType,
|
||||
@@ -310,6 +317,21 @@ impl ParaStyle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does kinsoku apply: a custom set, or a Kinsoku Set other than None?
|
||||
pub fn kinsoku_on(&self) -> bool {
|
||||
self.kinsoku_set.is_some() || self.kinsoku != Kinsoku::None
|
||||
}
|
||||
|
||||
/// The name Kinsoku Set shows: the custom set's, or None, Hard or Soft.
|
||||
pub fn kinsoku_name(&self) -> &str {
|
||||
match (&self.kinsoku_set, self.kinsoku) {
|
||||
(Some(set), _) => &set.name,
|
||||
(None, Kinsoku::None) => "None",
|
||||
(None, Kinsoku::Hard) => "Hard",
|
||||
(None, Kinsoku::Soft) => "Soft",
|
||||
}
|
||||
}
|
||||
|
||||
/// The left indent the layout sets the paragraph at: its left indent, and for a paragraph in a
|
||||
/// list at a level past the first, [`ParaList::level_indent`] more.
|
||||
pub fn laid_out_left_indent(&self) -> f64 {
|
||||
@@ -373,6 +395,8 @@ struct ParaStyleFile {
|
||||
burasagari: Burasagari,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku: Kinsoku,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
kinsoku_set: Option<Arc<KinsokuSet>>,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -415,6 +439,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -443,6 +468,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -475,6 +501,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -483,6 +510,11 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
korean_line_break_anywhere,
|
||||
..
|
||||
} = f;
|
||||
// A set whose saved name can't name a custom set (None, Hard or Soft, say) is read as no set:
|
||||
// the paragraph keeps its Kinsoku Set. A paragraph with a custom set keeps Hard, so one read
|
||||
// with None or Soft (a paragraph style written before custom sets, applied over one) has no
|
||||
// custom set.
|
||||
let kinsoku_set = kinsoku_set.filter(|s| !s.name.is_empty() && kinsoku == Kinsoku::Hard);
|
||||
Self {
|
||||
justify,
|
||||
left_indent,
|
||||
@@ -502,6 +534,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -604,19 +637,21 @@ pub enum KinsokuShoriType {
|
||||
PushOutOnly,
|
||||
}
|
||||
|
||||
/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。)
|
||||
/// stands outside the line's measure, in the space its punctuation spacing gives it (half width
|
||||
/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown
|
||||
/// as None / Regular / Force.
|
||||
/// Hanging punctuation (burasagari): hanging punctuation ending a line stands outside the line's
|
||||
/// measure, in the space its punctuation spacing gives it (half width with Line-end Punctuation
|
||||
/// Half Width). With the built-in Kinsoku Sets that is an East Asian comma or full stop
|
||||
/// (、。,.、。), and closing brackets and Latin punctuation don't hang; a custom Kinsoku Set hangs
|
||||
/// the characters in its hanging category. Shown as None / Regular / Force.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Burasagari {
|
||||
/// A comma or full stop that doesn't fit goes to the next line with the character before it.
|
||||
#[default]
|
||||
None,
|
||||
/// A comma or full stop that doesn't fit hangs outside the line; one that fits stays inside.
|
||||
/// Hanging punctuation that doesn't fit hangs outside the line; punctuation that fits stays
|
||||
/// inside.
|
||||
Standard,
|
||||
/// A comma or full stop ending a line always hangs, and the rest of the line fills the measure.
|
||||
/// Hanging punctuation ending a line always hangs, and the rest of the line fills the measure.
|
||||
Forced,
|
||||
}
|
||||
|
||||
|
||||
+54
-6
@@ -20,11 +20,18 @@ pub enum TraceView {
|
||||
OutlinesWithSource,
|
||||
/// Only the source image.
|
||||
Source,
|
||||
/// The source image on the part of the image left of a divider across it, and the traced
|
||||
/// shapes everywhere else ([`TraceView::split_of`]).
|
||||
Split,
|
||||
}
|
||||
|
||||
/// Where the Split view's divider is when the `trace` settings name no valid position: across the
|
||||
/// middle of the source image.
|
||||
pub const DEFAULT_TRACE_SPLIT: f64 = 0.5;
|
||||
|
||||
impl TraceView {
|
||||
/// Panel order.
|
||||
pub const ALL: [Self; 5] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source];
|
||||
pub const ALL: [Self; 6] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source, Self::Split];
|
||||
|
||||
/// The id used in command params and in the saved `trace` object.
|
||||
pub fn id(self) -> &'static str {
|
||||
@@ -34,6 +41,7 @@ impl TraceView {
|
||||
Self::Outlines => "outlines",
|
||||
Self::OutlinesWithSource => "outlinesWithSourceImage",
|
||||
Self::Source => "sourceImage",
|
||||
Self::Split => "split",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,14 +56,21 @@ impl TraceView {
|
||||
trace.get("view").and_then(serde_json::Value::as_str).and_then(Self::from_id).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the source image shows.
|
||||
pub fn shows_source(self) -> bool {
|
||||
matches!(self, Self::OutlinesWithSource | Self::Source)
|
||||
/// The Split view's divider in `trace` settings: the fraction of the source image's width, from
|
||||
/// its left edge in its own pixels, that shows the source image ([`DEFAULT_TRACE_SPLIT`] when
|
||||
/// `split` is missing, not a number or outside 0 to 1).
|
||||
pub fn split_of(trace: &serde_json::Value) -> f64 {
|
||||
trace.get("split").and_then(serde_json::Value::as_f64).filter(|f| (0.0..=1.0).contains(f)).unwrap_or(DEFAULT_TRACE_SPLIT)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes show filled.
|
||||
/// Whether the source image shows (in the Split view, on one side of the divider).
|
||||
pub fn shows_source(self) -> bool {
|
||||
matches!(self, Self::OutlinesWithSource | Self::Source | Self::Split)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes show filled (in the Split view, on one side of the divider).
|
||||
pub fn shows_result(self) -> bool {
|
||||
matches!(self, Self::Result | Self::ResultWithOutlines)
|
||||
matches!(self, Self::Result | Self::ResultWithOutlines | Self::Split)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes' outlines show.
|
||||
@@ -69,6 +84,12 @@ impl Node {
|
||||
pub fn trace_view(&self) -> TraceView {
|
||||
self.extras().trace.as_deref().map(TraceView::of).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The Split view's divider of an Image Trace object ([`TraceView::split_of`];
|
||||
/// [`DEFAULT_TRACE_SPLIT`] for anything else).
|
||||
pub fn trace_split(&self) -> f64 {
|
||||
self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -89,6 +110,26 @@ mod tests {
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "sepia"})));
|
||||
assert_eq!(g.trace_view(), TraceView::Result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() {
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
assert_eq!(g.trace_split(), DEFAULT_TRACE_SPLIT);
|
||||
assert_eq!(TraceView::from_id("Split"), Some(TraceView::Split));
|
||||
assert!(TraceView::Split.shows_source() && TraceView::Split.shows_result() && !TraceView::Split.shows_outlines());
|
||||
for (split, want) in [
|
||||
(serde_json::json!(0.25), 0.25),
|
||||
(serde_json::json!(0), 0.0),
|
||||
(serde_json::json!(1), 1.0),
|
||||
(serde_json::json!(-0.1), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::json!(1.5), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::json!("0.3"), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::Value::Null, DEFAULT_TRACE_SPLIT),
|
||||
] {
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split})));
|
||||
assert_eq!(g.trace_split(), want, "{split}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle() {
|
||||
use crate::{Appearance, Document, ImageObject, NodeId, NodeKind};
|
||||
@@ -132,6 +173,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The Split view measures the whole image wherever the divider is, so the selection box
|
||||
// stays put while the divider moves.
|
||||
for split in [0.0, 0.01, 1.0] {
|
||||
let want = Rect::new(0.0, 0.0, 200.0, 200.0);
|
||||
group.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split})));
|
||||
assert_eq!((group.geometric_bounds(), group.visual_bounds()), (Some(want), Some(want)), "split {split}");
|
||||
}
|
||||
group.extras_mut().trace = None;
|
||||
assert_eq!(
|
||||
group.geometric_bounds(),
|
||||
|
||||
+66
-5
@@ -81,6 +81,21 @@ impl Unit {
|
||||
Unit::Ha => "H",
|
||||
}
|
||||
}
|
||||
/// Whether this unit is a physical measurement unit (not points or pixels).
|
||||
pub fn is_physical(self) -> bool {
|
||||
self.svg_suffix().is_some() || matches!(self, Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet | Unit::Q | Unit::Ha)
|
||||
}
|
||||
/// The standard SVG length unit suffix, if this unit is a physical unit supported in SVG
|
||||
/// (`mm`, `cm`, `in`, `pc`).
|
||||
pub fn svg_suffix(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Unit::Millimeters => Some("mm"),
|
||||
Unit::Centimeters => Some("cm"),
|
||||
Unit::Inches => Some("in"),
|
||||
Unit::Picas => Some("pc"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Unit::Points => "Points",
|
||||
@@ -157,12 +172,17 @@ impl Unit {
|
||||
/// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A
|
||||
/// percentage on its own (`50%`) reads as nothing.
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs reads as nothing.
|
||||
/// `x`, `X` and `×` multiply as `*` does (`10x2` is 20, `2x3 mm` is 6 mm), except a lowercase
|
||||
/// `x` right after a `p`, which is the `px` suffix (`2px x 3` is 6 px, and `2px3` reads as
|
||||
/// nothing; write `2p x 3` for picas). `X` and `×` after a `p` multiply (`2pX3` is 6 picas).
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs ([`arithmetic_signs`], a multiplication sign counted
|
||||
/// as `*`) reads as nothing.
|
||||
pub fn parse(self, s: &str) -> Option<f64> {
|
||||
if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS {
|
||||
if arithmetic_signs(s) > MAX_MEASURE_OPERATORS {
|
||||
return None;
|
||||
}
|
||||
parse_measure(s, self).filter(|v| v.is_finite())
|
||||
parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
@@ -215,6 +235,46 @@ impl Unit {
|
||||
/// The most `+ - * /` signs [`Unit::parse`] reads in one text.
|
||||
const MAX_MEASURE_OPERATORS: usize = 128;
|
||||
|
||||
/// The number of `+ - * /` signs in `s`, each multiplication sign typed as `x`, `X` or `×`
|
||||
/// ([`Unit::parse`]) counted as a `*`.
|
||||
pub fn arithmetic_signs(s: &str) -> usize {
|
||||
let mut prev = None;
|
||||
s.chars()
|
||||
.filter(|&c| {
|
||||
let sign = matches!(c, '+' | '-' | '*' | '/') || is_times(c, prev);
|
||||
prev = Some(c);
|
||||
sign
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Is `c`, after `prev`, a multiplication sign typed as `x`, `X` or `×`? A lowercase `x` right
|
||||
/// after a `p` is the `px` suffix (`2px x 3`), also where a number follows it (`2px3`).
|
||||
fn is_times(c: char, prev: Option<char>) -> bool {
|
||||
matches!(c, 'X' | '×') || (c == 'x' && prev != Some('p'))
|
||||
}
|
||||
|
||||
/// `s` with each multiplication sign ([`is_times`]) written as `*` (`10 x 2` is `10 * 2`); text
|
||||
/// without one is not copied.
|
||||
fn times_as_asterisks(s: &str) -> std::borrow::Cow<'_, str> {
|
||||
let mut prev = None;
|
||||
let any = s.chars().any(|c| {
|
||||
let times = is_times(c, prev);
|
||||
prev = Some(c);
|
||||
times
|
||||
});
|
||||
if !any {
|
||||
return s.into();
|
||||
}
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut prev = None;
|
||||
for c in s.chars() {
|
||||
out.push(if is_times(c, prev) { '*' } else { c });
|
||||
prev = Some(c);
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
|
||||
fn parse_measure(s: &str, default: Unit) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
// Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2").
|
||||
@@ -348,9 +408,10 @@ pub fn finite_in_every_unit(pt: f64) -> bool {
|
||||
}
|
||||
|
||||
/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as
|
||||
/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing.
|
||||
/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as
|
||||
/// nothing.
|
||||
pub fn parse_number(s: &str) -> Option<f64> {
|
||||
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/".contains(c)) {
|
||||
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) {
|
||||
return None;
|
||||
}
|
||||
// A leading `+` is a sign (`+5`), as a plain number read it.
|
||||
|
||||
@@ -210,15 +210,15 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
CLASSIC_EXTRUDE,
|
||||
"Extrude & Bevel (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{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|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), 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","preserveSpotColors":false,"drawHiddenFaces":false}),
|
||||
"{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|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. 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, the surface numbering and the limits 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","preserveSpotColors":false,"drawHiddenFaces":false,"mapArt":[],"mapShade":false,"mapInvisible":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 and a partial sweep's cut sides 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|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. 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","preserveSpotColors":false}),
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides 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|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (the swept side is surface 1, the only one; in a group, the side of the member with the longest profile; a map of another surface draws nothing), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the middle of the side unrolled flat, around the axis), y: pt (-1000000..1000000, 0; along the profile), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the art wraps around the side and is drawn where its outside faces the viewer; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. 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, the surface numbering and the limits 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","preserveSpotColors":false,"mapArt":[],"mapShade":false,"mapInvisible":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_ROTATE,
|
||||
|
||||
@@ -312,6 +312,36 @@ impl Carry {
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo the actual maps of already placed gradients. Failure only changes this temporary
|
||||
/// appearance; callers retain the stored row unchanged when a map cannot be inverted.
|
||||
pub(crate) fn unapply_placed(&self, ap: &mut Appearance) -> Option<()> {
|
||||
for step in self.0.iter().rev() {
|
||||
for item in &mut ap.items {
|
||||
if !matches!(item.paint(), vectorcraft_doc::color::Paint::Gradient(_)) {
|
||||
continue;
|
||||
}
|
||||
let map = match *step {
|
||||
CarryStep::Affine { m, .. } => m,
|
||||
CarryStep::Boxes { from, to } => match item {
|
||||
AppearanceItem::Fill(_) => crate::reshape::box_map(from, to),
|
||||
AppearanceItem::Stroke(s) => crate::reshape::box_map(s.paint_bounds(from), s.paint_bounds(to)),
|
||||
},
|
||||
};
|
||||
if vectorcraft_doc::node::flattens(map) {
|
||||
return None;
|
||||
}
|
||||
let inverse = map.inverse();
|
||||
if !inverse.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if let vectorcraft_doc::color::Paint::Gradient(g) = item.paint_mut() {
|
||||
g.transform(inverse);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
pub(crate) fn push(&mut self, more: Carry) {
|
||||
self.0.extend(more.0);
|
||||
self.1.extend(more.1);
|
||||
|
||||
+79
-25
@@ -846,23 +846,19 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl
|
||||
take_held_guides(n, held, out, false, false);
|
||||
}
|
||||
|
||||
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
|
||||
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
|
||||
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
|
||||
/// the members (after a clipping path) or above them, as its contents slot says. Its
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
|
||||
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
|
||||
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
|
||||
/// it gives each copy those raster effects ([`copied_container`]).
|
||||
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
struct PreparedContainer {
|
||||
m: Node,
|
||||
guides: Vec<Arc<Node>>,
|
||||
paint: bool,
|
||||
carry: crate::Carry,
|
||||
}
|
||||
|
||||
/// The existing container pass up to its own rows becoming art. Keep its carried appearance for
|
||||
/// rendering, and retain the same Carry for freezing only missing stored placements separately.
|
||||
fn prepare_container(doc: Option<&Document>, n: &Node) -> Option<PreparedContainer> {
|
||||
if !is_container(n) {
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
|
||||
return Some(copied_container(doc, n, t));
|
||||
}
|
||||
let pathfinder = has_pathfinder(n);
|
||||
let fx = crate::reshape::geometry_effects(n);
|
||||
let paint = has_own_paint(n);
|
||||
@@ -870,6 +866,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
return None;
|
||||
}
|
||||
let mut m = n.clone();
|
||||
let mut carry = crate::Carry::default();
|
||||
// Its ruler guides take no part: they go back above the evaluated art at the end. With effects
|
||||
// that replace or copy the art, so do its guides among the art and those in its sublayers and
|
||||
// groups, which would otherwise go with that art: they stay on `n`, in order, hidden and
|
||||
@@ -896,7 +893,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut m);
|
||||
}
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
if paint && carry.moves(&m.appearance) {
|
||||
@@ -905,6 +902,27 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
|
||||
Some(PreparedContainer { m, guides, paint, carry })
|
||||
}
|
||||
|
||||
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
|
||||
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
|
||||
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
|
||||
/// the members (after a clipping path) or above them, as its contents slot says. Its
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
|
||||
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
|
||||
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
|
||||
/// it gives each copy those raster effects ([`copied_container`]).
|
||||
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if !is_container(n) {
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
|
||||
return Some(copied_container(doc, n, t));
|
||||
}
|
||||
let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?;
|
||||
if paint {
|
||||
// A clip group whose clipping type paints strokes is now a group of a clip group and those
|
||||
// strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
|
||||
@@ -931,16 +949,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
|
||||
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
|
||||
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
|
||||
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
|
||||
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
|
||||
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
|
||||
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
|
||||
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
|
||||
/// and locked as their containers were.
|
||||
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
/// The exact pre-copy source shared by rendering and stored gradient placement.
|
||||
fn copied_container_source(doc: Option<&Document>, n: &Node, t: usize) -> (Node, Vec<Arc<Node>>, Node) {
|
||||
let mut m = n.clone();
|
||||
let mut guides = vec![];
|
||||
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
|
||||
@@ -955,6 +965,20 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut source);
|
||||
}
|
||||
(m, guides, source)
|
||||
}
|
||||
|
||||
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
|
||||
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
|
||||
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
|
||||
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
|
||||
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
|
||||
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
|
||||
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
|
||||
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
|
||||
/// and locked as their containers were.
|
||||
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
let (mut m, guides, source) = copied_container_source(doc, n, t);
|
||||
let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| {
|
||||
let mut p = source.clone();
|
||||
p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects);
|
||||
@@ -988,6 +1012,36 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
m
|
||||
}
|
||||
|
||||
/// Freeze representable fitted own paints to the box the container pass gives them, retaining
|
||||
/// every live effect and already explicit placement. Hidden-only containers the pass does not
|
||||
/// evaluate stay unchanged; this does not add a different fallback to `evaluate_container`.
|
||||
pub fn pinned_container_appearance(doc: &Document, n: &Node) -> Option<Appearance> {
|
||||
if !n.appearance.has_unplaced_gradient() {
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
|
||||
let (_, _, source) = copied_container_source(Some(doc), n, t);
|
||||
let pinned = pinned_container_appearance(doc, &source)?;
|
||||
let mut out = (*n.appearance).clone();
|
||||
out.items = pinned.items;
|
||||
return Some(out);
|
||||
}
|
||||
let PreparedContainer { m, carry, .. } = prepare_container(Some(doc), n)?;
|
||||
let bounds = m.geometric_bounds()?;
|
||||
let mut out = (*n.appearance).clone();
|
||||
let mut changed = false;
|
||||
for (item, original) in out.items.iter_mut().zip(&n.appearance.items) {
|
||||
if paints(original)
|
||||
&& matches!(original.paint(), Paint::Gradient(g) if !g.is_placed())
|
||||
&& let Some(pinned) = crate::pinned_gradient_item(original, bounds, &[&carry])
|
||||
{
|
||||
*item = pinned;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed.then_some(out)
|
||||
}
|
||||
|
||||
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
|
||||
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
|
||||
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
|
||||
|
||||
@@ -45,6 +45,7 @@ mod lighting_presets;
|
||||
mod live;
|
||||
mod marks;
|
||||
pub mod pixel;
|
||||
mod placement;
|
||||
pub mod preview;
|
||||
mod raster;
|
||||
mod reshape;
|
||||
@@ -75,12 +76,13 @@ pub use bake::{
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
|
||||
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art,
|
||||
};
|
||||
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use placement::pinned_gradient_item;
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
|
||||
without_geometry,
|
||||
@@ -106,6 +108,10 @@ pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale,
|
||||
graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol,
|
||||
};
|
||||
pub use solids::{
|
||||
MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, MapSurface, SurfaceKind, SurfaceMap, map_surfaces_at,
|
||||
map_surfaces_with, surface_maps, takes_map_art, with_surface_map,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
pub use trap::TRAP;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Conservative stored placements for gradients fitted by the existing effects passes.
|
||||
|
||||
use vectorcraft_doc::color::{GradientKind, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::Carry;
|
||||
|
||||
/// Freeze one fitted gradient at the evaluated row's geometric bounds, before its live effects.
|
||||
/// `carries` are the actual object and item passes, in rendering order. Only missing placement
|
||||
/// fields are returned; explicit coordinates and the row's other data stay unchanged. A map or
|
||||
/// model that cannot reproduce the original resolved row returns `None`, leaving it fitted.
|
||||
pub fn pinned_gradient_item(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Option<AppearanceItem> {
|
||||
if gradient(item)?.is_placed() {
|
||||
return Some(item.clone());
|
||||
}
|
||||
if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let resolved = resolve(item, bounds, carries);
|
||||
if !finite_placement(resolved.items.first()?) {
|
||||
return None;
|
||||
}
|
||||
let mut stored = resolved.clone();
|
||||
for carry in carries.iter().rev() {
|
||||
carry.unapply_placed(&mut stored)?;
|
||||
}
|
||||
if !finite_placement(stored.items.first()?) {
|
||||
return None;
|
||||
}
|
||||
let candidate = missing_placement(item, stored.items.first()?)?;
|
||||
let replayed = resolve(&candidate, bounds, carries);
|
||||
(finite_placement(replayed.items.first()?) && replayed.approx_eq(&resolved)).then_some(candidate)
|
||||
}
|
||||
|
||||
fn gradient(item: &AppearanceItem) -> Option<&GradientPaint> {
|
||||
match item.paint() {
|
||||
Paint::Gradient(g) => Some(g),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Appearance {
|
||||
let mut ap = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
for carry in carries {
|
||||
carry.apply(&mut ap);
|
||||
}
|
||||
ap.pin_gradients(bounds);
|
||||
ap
|
||||
}
|
||||
|
||||
fn missing_placement(item: &AppearanceItem, placed: &AppearanceItem) -> Option<AppearanceItem> {
|
||||
let original = gradient(item)?;
|
||||
let placed = gradient(placed)?;
|
||||
let mut out = item.clone();
|
||||
let Paint::Gradient(g) = out.paint_mut() else { return None };
|
||||
if original.geom.is_none() {
|
||||
g.geom = placed.geom;
|
||||
}
|
||||
if original.gradient.kind == GradientKind::Freeform && !original.has_freeform_points() {
|
||||
let freeform = placed.freeform.as_ref()?;
|
||||
match &mut g.freeform {
|
||||
Some(f) => f.points.clone_from(&freeform.points),
|
||||
None => g.freeform = Some(freeform.clone()),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn finite_placement(item: &AppearanceItem) -> bool {
|
||||
let Some(g) = gradient(item) else { return false };
|
||||
g.geom.is_none_or(|v| v.start.is_finite() && v.end.is_finite() && v.aspect.is_finite() && v.focal.is_none_or(|p| p.is_finite()))
|
||||
&& g.freeform.as_ref().is_none_or(|f| f.points.iter().all(|p| p.at.is_finite()))
|
||||
}
|
||||
@@ -3505,7 +3505,7 @@ pub(crate) fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) {
|
||||
|
||||
/// The map that takes box `from` onto box `to` along each axis (along an axis `from` has no extent
|
||||
/// on, a move from its center to `to`'s).
|
||||
fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
|
||||
pub(crate) fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
|
||||
let axis = |a0: f64, a1: f64, b0: f64, b1: f64| {
|
||||
if (a1 - a0).abs() > 1e-12 {
|
||||
let s = (b1 - b0) / (a1 - a0);
|
||||
|
||||
+149
-32
@@ -113,7 +113,7 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
|
||||
/// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with
|
||||
/// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them.
|
||||
fn options_of(id: &str, p: &Value) -> Revolve {
|
||||
pub(crate) fn options_of(id: &str, p: &Value) -> Revolve {
|
||||
if id == CLASSIC_REVOLVE {
|
||||
classic::options(p)
|
||||
} else {
|
||||
@@ -141,6 +141,7 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul
|
||||
/// [`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)?;
|
||||
validate_map_symbols(doc, 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.
|
||||
@@ -215,7 +216,7 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op
|
||||
|
||||
/// The member of a group whose side takes the group's graphics: the first with the longest
|
||||
/// profile among those with a fill or stroke.
|
||||
fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option<usize> {
|
||||
pub(crate) fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option<usize> {
|
||||
shapes
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -237,6 +238,20 @@ 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` ([`validate_item_of`]).
|
||||
/// An error when the symbols that Revolve (Classic)'s Map Art in `p` places, with the symbols of
|
||||
/// `doc`, are past the limits of a graphic's art, as on Extrude & Bevel (Classic), or past the
|
||||
/// limits of art unrolled onto its side, its only surface.
|
||||
fn validate_map_symbols(doc: Option<&Document>, id: &str, p: &Value) -> Result<(), String> {
|
||||
match doc.filter(|_| id == CLASSIC_REVOLVE) {
|
||||
Some(doc) => {
|
||||
crate::solids::graphics::validate_symbols(doc, p)?;
|
||||
// The side is surface 1, laid out about the origin; a map past it draws nothing.
|
||||
crate::solids::graphics::validate_unrolled_symbols(doc, p, &|surface| (surface == 1).then_some(Point::ZERO))
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> {
|
||||
validate_item_of(None, n, REVOLVE, p, target, index)
|
||||
@@ -252,6 +267,7 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V
|
||||
return validate_in(doc, n, id, p);
|
||||
}
|
||||
validate_params_of(id, p)?;
|
||||
validate_map_symbols(doc, 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) {
|
||||
@@ -334,7 +350,7 @@ fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&Appea
|
||||
|
||||
/// `options` with one number of samples for every curve of `shapes`, the members of one group: the
|
||||
/// members share Revolve's limits.
|
||||
fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, String> {
|
||||
pub(crate) fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, String> {
|
||||
let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?;
|
||||
Ok(Revolve { curve_samples: Some(samples), ..options })
|
||||
}
|
||||
@@ -463,10 +479,12 @@ fn group_shadow(
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
|
||||
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
|
||||
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last
|
||||
/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them
|
||||
/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). With
|
||||
/// `hide`, a Revolve (Classic) surface without mapped art leaves its faces out, as Invisible
|
||||
/// Geometry does ([`crate::solids::classic::surface`]). The last two values are whether the faces
|
||||
/// go over an underlay of themselves ([`seals`]): the caller seals them ([`sealed_surface`],
|
||||
/// [`sealed_runs`]) in the order it draws them; and whether the faces were left out.
|
||||
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
|
||||
fn surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
@@ -480,7 +498,8 @@ fn surface(
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
cast: bool,
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>, bool)> {
|
||||
hide: bool,
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>, bool, bool)> {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
@@ -500,7 +519,23 @@ fn surface(
|
||||
let drawn =
|
||||
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false));
|
||||
// Mapped art goes on the side, the surface's one numbered surface. Its paints' copies
|
||||
// count with the graphics', and art past the limits is left out.
|
||||
let map_art = crate::solids::graphics::map_art::MapArt::of(doc, &fx.id, &p);
|
||||
let layout = map_art.as_ref().and_then(|_| {
|
||||
let (width, height) = vectorcraft_three_d::revolve_surface_size(path, b, options)?;
|
||||
let side = vectorcraft_three_d::SolidSurface { kind: vectorcraft_three_d::SurfaceKind::Side, width, height, center: None };
|
||||
Some(crate::solids::graphics::map_art::SolidLayout { first: 0, surfaces: vec![side], ends: None })
|
||||
});
|
||||
let mut budget = crate::solids::graphics::map_art::MapBudget::default();
|
||||
let mapped = map_art.as_ref().zip(layout.as_ref()).map(|(art, layout)| crate::solids::classic::Mapped {
|
||||
art,
|
||||
layout,
|
||||
budget: &mut budget,
|
||||
copies: &mut copies.graphics,
|
||||
});
|
||||
let (art, hidden, _) = crate::solids::classic::surface(n, &facets, &paint, (opacity, blend), &p, mapped, hide);
|
||||
return Some((drawn, art, kept, false, hidden));
|
||||
}
|
||||
let colored = colored(&options);
|
||||
let (faces, kept) = if cast {
|
||||
@@ -632,7 +667,7 @@ fn surface(
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
Some((keys, group, kept, seal))
|
||||
Some((keys, group, kept, seal, false))
|
||||
}
|
||||
|
||||
/// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal`
|
||||
@@ -722,8 +757,8 @@ fn object_surface(
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let cast = casts(fx, opacity);
|
||||
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast)
|
||||
.map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept))
|
||||
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast, false)
|
||||
.map(|(_, art, kept, seal, _)| (sealed_surface(n.id, art, seal), kept))
|
||||
}
|
||||
|
||||
/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides
|
||||
@@ -797,11 +832,12 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
}
|
||||
let (path, rule) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> {
|
||||
let mut keep = |out: &mut Vec<crate::SolidMesh>, path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<(), 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, fx_options(fx))?;
|
||||
Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity)))
|
||||
surface_meshes(path, rule, b, fx, fx_options(fx), (&paint, opacity, 1.0), true)?
|
||||
.into_iter()
|
||||
.try_for_each(|m| crate::solids::keep_mesh(out, total, m, limit))
|
||||
};
|
||||
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();
|
||||
@@ -810,7 +846,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let mut out = vec![];
|
||||
crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?;
|
||||
keep(&mut out, &path, fx, item)?;
|
||||
return Ok(out);
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
@@ -820,12 +856,69 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
&& let Some(fx) = item.effects().get(index)
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
crate::solids::keep_mesh(&mut out, total, mesh(&p, fx, item)?, limit)?;
|
||||
keep(&mut out, &p, fx, item)?;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The surface Revolve `fx` sweeps from `path` (filled under `rule`) about the axis of `b` with
|
||||
/// `options`, painted `paint` at `opacity` in a group member of opacity `member` (1 for an object
|
||||
/// of its own), as meshes. When `graphics` and `fx` maps graphics onto the side, the side's
|
||||
/// triangles are a mesh of their own with the point of the unrolled side surface each corner shows
|
||||
/// ([`crate::MeshGraphics`]), the points the canvas places the graphics by
|
||||
/// ([`crate::solids::graphics::surface_parts`]), after a mesh of the rest (the end caps and the cut
|
||||
/// sides). As on the canvas, the graphics take `opacity`, and `member` applies to the side and its
|
||||
/// graphics together. Otherwise the surface is one plain mesh.
|
||||
fn surface_meshes(
|
||||
path: &PathData,
|
||||
rule: FillRule,
|
||||
b: Rect,
|
||||
fx: &Effect,
|
||||
options: Revolve,
|
||||
(paint, opacity, member): (&Paint, f32, f32),
|
||||
graphics: bool,
|
||||
) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let color = crate::solids::mesh_color(paint, opacity * member);
|
||||
let list: Vec<crate::MappedGraphic> = if graphics && fx.id == REVOLVE && options.map_surface {
|
||||
crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).into_iter().filter(|g| g.face == crate::PlanarFace::Front).collect()
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
if list.is_empty() {
|
||||
return Ok(vec![crate::SolidMesh::plain(vectorcraft_three_d::revolve_mesh(path, rule, b, options)?, color)]);
|
||||
}
|
||||
let (mesh, on) = vectorcraft_three_d::revolve_mesh_surface(path, rule, b, options)?;
|
||||
let (mut side, mut rest, mut art) = (vectorcraft_three_d::Mesh::default(), vectorcraft_three_d::Mesh::default(), vec![]);
|
||||
for (t, points) in mesh.triangles.iter().zip(&on) {
|
||||
let corner = |i: u32| mesh.positions.get(i as usize).copied().zip(mesh.normals.get(i as usize).copied());
|
||||
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
|
||||
let into = match points {
|
||||
Some(points) => {
|
||||
art.extend(points);
|
||||
&mut side
|
||||
}
|
||||
None => &mut rest,
|
||||
};
|
||||
let base = into.positions.len() as u32;
|
||||
for (p, n) in corners {
|
||||
into.positions.push(p);
|
||||
into.normals.push(n);
|
||||
}
|
||||
into.triangles.push([base, base + 1, base + 2]);
|
||||
}
|
||||
let mut out = vec![];
|
||||
if !rest.is_empty() {
|
||||
out.push(crate::SolidMesh::plain(rest, color));
|
||||
}
|
||||
if !side.is_empty() {
|
||||
let graphics =
|
||||
crate::MeshGraphics { face: crate::PlanarFace::Front, graphics: list, center: Point::ZERO, art, opacity, object: member.clamp(0.0, 1.0) };
|
||||
out.push(crate::SolidMesh { mesh: side, color, graphics: Some(graphics) });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol
|
||||
/// instances, blends and clipping groups already resolved), in document coordinates: with the
|
||||
/// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of
|
||||
@@ -919,12 +1012,15 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
|
||||
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, fx_options(fx))?;
|
||||
// The graphics go on the side of the member with the longest profile, as the canvas draws them.
|
||||
let longest = if options.map_surface { graphics_member(&shapes, b, options) } else { None };
|
||||
let mut out = vec![];
|
||||
for s in &shapes {
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
|
||||
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity * s.opacity)), limit)?;
|
||||
for mesh in surface_meshes(&s.path, s.rule, b, fx, options, (&paint, opacity, s.opacity), longest == Some(k))? {
|
||||
crate::solids::keep_mesh(&mut out, total, mesh, limit)?;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -1155,22 +1251,42 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let mut opaque = true;
|
||||
// The graphics go once, on the side of the member with the longest profile. Without graphics
|
||||
// no member is measured for them.
|
||||
let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty();
|
||||
// Revolve (Classic)'s mapped art goes on that member's side too.
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
let mapped = (fx.id == REVOLVE && !crate::solids::mapped_graphics(&p).is_empty())
|
||||
|| (fx.id == CLASSIC_REVOLVE && !crate::solids::surface_maps(&p).is_empty());
|
||||
let longest = if mapped { graphics_member(&shapes, b, options) } else { None };
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let Some(item) = surface_item(&s.items) else {
|
||||
kept.push(None);
|
||||
continue;
|
||||
};
|
||||
// Member `k`'s surface, its faces left out with `hide`, with its opacity and blending mode;
|
||||
// `None` for a member with no fill or stroke.
|
||||
let member = |k: usize, s: &Profile, hide: bool, copies: &mut Copies| {
|
||||
let item = surface_item(&s.items)?;
|
||||
// The opacity and blending of the member and the groups it is in apply through its scopes.
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
|
||||
// A member with transparency of its own keeps every face, as a transparent object does.
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let doc = doc.filter(|_| longest == Some(k));
|
||||
let cast = casts(fx, opacity * s.opacity);
|
||||
let options = Revolve { fill_rule: s.rule, ..options };
|
||||
let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
Some((opacity, blend, surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, copies, cast, hide)))
|
||||
};
|
||||
// With Invisible Geometry the other members leave their faces out too, once the mapped art on
|
||||
// the longest member's side has left that member's faces out, so it is built first.
|
||||
let invisible = fx.id == CLASSIC_REVOLVE && doc.is_some() && p.get(crate::solids::MAP_INVISIBLE).and_then(Value::as_bool).unwrap_or(false);
|
||||
let mut first = None;
|
||||
if let Some(l) = longest.filter(|_| invisible)
|
||||
&& let Some(s) = shapes.get(l)
|
||||
{
|
||||
first = member(l, s, false, &mut copies);
|
||||
}
|
||||
let hide = matches!(first, Some((_, _, Some((_, _, _, _, true)))));
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let built = if longest == Some(k) && first.is_some() { first.take() } else { member(k, s, hide, &mut copies) };
|
||||
let Some((opacity, blend, built)) = built else {
|
||||
kept.push(None);
|
||||
continue;
|
||||
};
|
||||
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
|
||||
let (depths, art, faces, seal, _) = built?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
kept.push(faces);
|
||||
seals.push(seal);
|
||||
@@ -1870,8 +1986,9 @@ mod tests {
|
||||
let path = n.path_data().unwrap();
|
||||
let fx = n.appearance.effects.first().unwrap();
|
||||
let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap());
|
||||
let (_, art, _, seal) =
|
||||
surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap();
|
||||
let (_, art, _, seal, _) =
|
||||
surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false, false)
|
||||
.unwrap();
|
||||
(art, seal)
|
||||
}
|
||||
|
||||
@@ -2129,7 +2246,7 @@ mod tests {
|
||||
.map(|s| {
|
||||
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
|
||||
let cast = casts(&fx, opacity * s.opacity);
|
||||
surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
|
||||
surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2
|
||||
})
|
||||
.collect();
|
||||
assert!(kept.iter().all(Option::is_some), "{id} {params}");
|
||||
@@ -2165,7 +2282,7 @@ mod tests {
|
||||
.map(|s| {
|
||||
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
|
||||
let cast = casts(&fx, opacity * s.opacity);
|
||||
surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
|
||||
surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2
|
||||
})
|
||||
.collect();
|
||||
[group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()]
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
use serde_json::Value;
|
||||
use vectorcraft_three_d::Revolve;
|
||||
|
||||
use crate::solids::graphics::map_art;
|
||||
|
||||
pub const CLASSIC_REVOLVE: &str = "threeD.classicRevolve";
|
||||
|
||||
/// The numeric parameters: (key, lowest, highest, whole numbers only).
|
||||
@@ -23,19 +25,28 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"];
|
||||
const FLAGS: [&str; 5] = ["cap", "lightBehind", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE];
|
||||
|
||||
/// 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.
|
||||
/// rotation and perspective, built unshaded, since the classic surfaces light its faces. With
|
||||
/// mapped art its side is laid out for it.
|
||||
pub(crate) fn options(p: &Value) -> Revolve {
|
||||
Revolve { shade: false, smooth_shading: false, lights: None, light_color: [1.0; 3], ..super::revolve_options(p) }
|
||||
Revolve {
|
||||
shade: false,
|
||||
smooth_shading: false,
|
||||
lights: None,
|
||||
light_color: [1.0; 3],
|
||||
map_surface: !map_art::surface_maps(p).is_empty(),
|
||||
..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.
|
||||
/// the surface and shading color are named, and `mapArt` holds valid maps.
|
||||
pub(crate) fn validate(p: &Value) -> Result<(), String> {
|
||||
crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS)
|
||||
crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS)?;
|
||||
map_art::validate(CLASSIC_REVOLVE, p)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+238
-29
@@ -24,6 +24,10 @@ mod source;
|
||||
pub(crate) use source::{resolve, resolve_for};
|
||||
|
||||
pub(crate) mod graphics;
|
||||
pub use graphics::map_art::{
|
||||
MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, SurfaceMap, surface_maps, takes_map_art, with_surface_map,
|
||||
};
|
||||
use graphics::map_art::{MapArt, MapBudget, SolidLayout};
|
||||
pub use graphics::{
|
||||
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
|
||||
@@ -32,6 +36,7 @@ pub use graphics::{
|
||||
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
|
||||
fitting as graphic_fitting_scale, rename_appearance_graphic_symbol,
|
||||
};
|
||||
pub use vectorcraft_three_d::SurfaceKind;
|
||||
|
||||
pub(crate) mod shadow;
|
||||
|
||||
@@ -182,6 +187,7 @@ pub fn extrude_options(p: &Value) -> Extrude {
|
||||
both_sides: flag(p, "bevelBothSides", false),
|
||||
}),
|
||||
hidden: false,
|
||||
map_surfaces: false,
|
||||
map_surface: false,
|
||||
}
|
||||
}
|
||||
@@ -461,11 +467,22 @@ fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value
|
||||
/// ([`side_carrier`]): their art, or the parts they draw on its pieces
|
||||
/// ([`graphics::surface_parts`]), or when the object `n`'s surfaces can't be built at all. They are
|
||||
/// built as the art builds them ([`surfaces_with`]), so its pieces are the ones the art draws, cuts
|
||||
/// included. Without `doc` nothing is drawn, and nothing is checked.
|
||||
/// included. On Extrude & Bevel (Classic), the art Map Art places on walls and bevels must also fit
|
||||
/// ([`graphics::validate_unrolled_symbols`]). Without `doc` nothing is drawn, and nothing is checked.
|
||||
fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
let Some(doc) = doc else { return Ok(()) };
|
||||
let Some(b) = union_bounds(shapes) else { return Ok(()) };
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
// Map Art unrolls its art onto walls and bevels; the caps draw it as it is.
|
||||
if id == CLASSIC_EXTRUDE && !surface_maps(p).is_empty() {
|
||||
let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(p) };
|
||||
let unrolled: Vec<Option<Point>> = parts
|
||||
.iter()
|
||||
.flat_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default())
|
||||
.map(|s| (!matches!(s.kind, SurfaceKind::End(_))).then(|| graphics::map_art::flat_center(&s)))
|
||||
.collect();
|
||||
graphics::validate_unrolled_symbols(doc, p, &|surface| surface.checked_sub(1).and_then(|k| unrolled.get(k).copied().flatten()))?;
|
||||
}
|
||||
if side_carrier(id, p, &parts, bounds).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -2003,8 +2020,11 @@ fn surfaces_with(
|
||||
filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) });
|
||||
}
|
||||
}
|
||||
let art =
|
||||
if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored, false) };
|
||||
let art = if classic {
|
||||
classic::surface(n, &f, &paint, (opacity, blend), &p, None, false).0
|
||||
} else {
|
||||
surface(n, f, &paint, opacity, blend, colored, false)
|
||||
};
|
||||
out.push((s.scopes.as_slice(), Arc::new(art)));
|
||||
}
|
||||
}
|
||||
@@ -2018,15 +2038,28 @@ fn surfaces_with(
|
||||
let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None };
|
||||
let mut solids = vec![];
|
||||
let mut built = vec![];
|
||||
// With mapped art, each solid's place among the object's numbered surfaces: the surfaces are
|
||||
// counted through the parts in order, those of a part whose solid is left out too.
|
||||
let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE);
|
||||
let mut layouts: Vec<SolidLayout> = vec![];
|
||||
let mut surfaces_before = 0usize;
|
||||
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier);
|
||||
for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() {
|
||||
for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() {
|
||||
let item: &AppearanceItem = item;
|
||||
let layout = map_art.as_ref().map(|_| {
|
||||
let options = classic_extrude_options(&p);
|
||||
let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default();
|
||||
let first = surfaces_before;
|
||||
surfaces_before += surfaces.len();
|
||||
SolidLayout { first, surfaces, ends: Some((bounds, options, view_options(&p))) }
|
||||
});
|
||||
match f {
|
||||
Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
|
||||
return None;
|
||||
}
|
||||
Ok(Some((f, faces))) => {
|
||||
solids.push((item, *opacity, *scopes, f, *member));
|
||||
layouts.extend(layout);
|
||||
built.push(faces);
|
||||
}
|
||||
// A stroke's outline past the limits is left out; the fill's solid still draws. Built
|
||||
@@ -2115,6 +2148,34 @@ fn surfaces_with(
|
||||
let split =
|
||||
split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::<usize>() <= MAX_FACE_COMPOSITES;
|
||||
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
|
||||
// The classic surfaces of the solids, with mapped art when the effect has maps. When the art of
|
||||
// any solid is past the limits the object's maps share, every solid draws without mapped art.
|
||||
let mut classic_arts = if classic {
|
||||
let draw = |with_art: bool, copies: &mut usize| {
|
||||
let mut budget = MapBudget::default();
|
||||
let mut dropped = false;
|
||||
let mut arts = Vec::with_capacity(solids.len());
|
||||
for (k, (item, member, _, f, _)) in solids.iter().enumerate() {
|
||||
let (paint, opacity, blend) = paint_of(item, *member);
|
||||
let mapped = map_art.as_ref().filter(|_| with_art).zip(layouts.get(k)).map(|(art, layout)| classic::Mapped {
|
||||
art,
|
||||
layout,
|
||||
budget: &mut budget,
|
||||
copies: &mut *copies,
|
||||
});
|
||||
let (art, _, left_out) = classic::surface(n, f, &paint, (opacity, blend), &p, mapped, false);
|
||||
dropped |= left_out;
|
||||
arts.push(art);
|
||||
}
|
||||
(arts, dropped)
|
||||
};
|
||||
let mut used = paint_bytes;
|
||||
let (arts, dropped) = draw(map_art.is_some(), &mut used);
|
||||
if dropped { draw(false, &mut paint_bytes).0 } else { arts }
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
.into_iter();
|
||||
// Which surfaces lie over an underlay of their facets, in one order or whole
|
||||
// ([`in_one_order`], [`underlaid_surface`]).
|
||||
let seals: Vec<bool> = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect();
|
||||
@@ -2150,7 +2211,7 @@ fn surfaces_with(
|
||||
};
|
||||
let drawn = parts.iter().any(|p| !p.is_empty());
|
||||
let art = if classic {
|
||||
classic::surface(n, f, &paint, opacity, blend, &p)
|
||||
classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![]))
|
||||
} else {
|
||||
let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false));
|
||||
with_surface_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts)
|
||||
@@ -2481,28 +2542,7 @@ pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option<usize>,
|
||||
/// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from.
|
||||
fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<(Effect, Vec<Profile>)> {
|
||||
let n = &*resolve(doc, n, "").ok()?;
|
||||
let (fx, shapes) = if is_container(n) {
|
||||
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
(fx, shapes)
|
||||
} else {
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
match item {
|
||||
None => {
|
||||
let (index, fx) = pick(&n.appearance.effects)?;
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
(fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }])
|
||||
}
|
||||
Some(k) => {
|
||||
let it = n.appearance.items.get(k)?;
|
||||
let (index, fx) = pick(it.effects())?;
|
||||
let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it));
|
||||
(fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }])
|
||||
}
|
||||
}
|
||||
};
|
||||
let (fx, shapes) = picked(n, item, pick)?;
|
||||
Some((fx.clone(), shapes))
|
||||
}
|
||||
|
||||
@@ -2560,6 +2600,175 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
|
||||
})
|
||||
}
|
||||
|
||||
/// One numbered surface of a 3D object that takes Map Art: what it is, its size laid out flat in
|
||||
/// points, whether the viewer sees any of it, and the edges of its outline on the page.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MapSurface {
|
||||
pub kind: SurfaceKind,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
pub visible: bool,
|
||||
pub outline: Vec<[Point; 2]>,
|
||||
}
|
||||
|
||||
/// The numbered surfaces of the 3D effect at `index` of the effects of `n` (on the object itself
|
||||
/// with `item` `None`, else on its fill or stroke `item`), which must be an Extrude & Bevel
|
||||
/// (Classic) or Revolve (Classic), shown or hidden, in the order Map Art numbers them from 1.
|
||||
/// `None` for any other effect, and when the object's art can't be built.
|
||||
pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<Vec<MapSurface>> {
|
||||
let n = &*resolve(doc, n, "").ok()?;
|
||||
let (fx, shapes) = picked(n, item, &|fx: &[Effect]| fx.get(index).filter(|e| takes_map_art(&e.id)).map(|e| (index, e)))?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let b = union_bounds(&shapes)?;
|
||||
// The edges of `facets` on each local surface of `surfaces`, in one pass over the facets: every
|
||||
// edge of an end, and the edges of the cells that lie along the sides of the flat surface.
|
||||
let seen = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet]| -> Vec<Vec<[Point; 2]>> {
|
||||
let mut edges: Vec<Vec<[Point; 2]>> = vec![vec![]; surfaces.len()];
|
||||
// Each surface laid out flat, and how near a point must be to its side to lie along it.
|
||||
let frames: Vec<(Rect, f64)> = surfaces
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let flat = match s.kind {
|
||||
SurfaceKind::Side => Rect::new(-s.width / 2.0, -s.height / 2.0, s.width / 2.0, s.height / 2.0),
|
||||
_ => Rect::new(0.0, 0.0, s.width, s.height),
|
||||
};
|
||||
(flat, (s.width.max(s.height) * 1e-6).max(1e-9))
|
||||
})
|
||||
.collect();
|
||||
let ends: Vec<(usize, PlanarFace)> = surfaces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(k, s)| match s.kind {
|
||||
SurfaceKind::End(end) => Some((k, end)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for f in facets.iter().filter(|f| !f.away) {
|
||||
if let Some(at) = f.end {
|
||||
for &(k, end) in &ends {
|
||||
if end == at
|
||||
&& let Some(out) = edges.get_mut(k)
|
||||
{
|
||||
for c in &f.contours {
|
||||
out.extend(c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| [*a, *b]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(cell) = f.cell.as_deref().filter(|c| c.uv.len() == c.page.len()) else { continue };
|
||||
let k = cell.surface;
|
||||
// A facet of an end adds to an end's surface only its own edges, above.
|
||||
if f.end.is_some() && surfaces.get(k).is_some_and(|s| matches!(s.kind, SurfaceKind::End(_))) {
|
||||
continue;
|
||||
}
|
||||
let (Some(&(flat, near)), Some(out)) = (frames.get(k), edges.get_mut(k)) else { continue };
|
||||
let count = cell.uv.len();
|
||||
for i in 0..count {
|
||||
let j = (i + 1) % count;
|
||||
let (Some(a), Some(c)) = (cell.uv.get(i), cell.uv.get(j)) else { continue };
|
||||
let along = |at: f64, of: fn(&Point) -> f64| (of(a) - at).abs() <= near && (of(c) - at).abs() <= near;
|
||||
let on_side = along(flat.x0, |p| p.x) || along(flat.x1, |p| p.x) || along(flat.y0, |p| p.y) || along(flat.y1, |p| p.y);
|
||||
if let (true, Some(from), Some(to)) = (on_side, cell.page.get(i), cell.page.get(j)) {
|
||||
out.push([*from, *to]);
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
};
|
||||
let listed = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet], out: &mut Vec<MapSurface>| {
|
||||
for (s, outline) in surfaces.iter().zip(seen(surfaces, facets)) {
|
||||
out.push(MapSurface { kind: s.kind, width: s.width, height: s.height, visible: !outline.is_empty(), outline });
|
||||
}
|
||||
};
|
||||
let mut out = vec![];
|
||||
if fx.id == crate::CLASSIC_REVOLVE {
|
||||
// Revolve (Classic) has one surface: its side, in a group that of the member with the
|
||||
// longest profile. A group's members share one sampling of their curves, and a group past
|
||||
// those shared limits has no surface.
|
||||
let mut options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(&fx.id, &p) };
|
||||
if is_container(n) {
|
||||
options = crate::revolve::shared_options(&shapes, options).ok()?;
|
||||
}
|
||||
let shape = shapes.get(crate::revolve::graphics_member(&shapes, b, options)?)?;
|
||||
let (width, height) = vectorcraft_three_d::revolve_surface_size(&shape.path, b, options)?;
|
||||
let surfaces = [vectorcraft_three_d::SolidSurface { kind: SurfaceKind::Side, width, height, center: None }];
|
||||
let facets = vectorcraft_three_d::revolve_facets(&shape.path, b, options).unwrap_or_default();
|
||||
listed(&surfaces, &facets, &mut out);
|
||||
return Some(out);
|
||||
}
|
||||
let (parts, bounds) = solid_parts(&shapes, b);
|
||||
let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(&p) };
|
||||
let view = view_options(&p);
|
||||
// The faces of the solids count together against the limit the art draws within.
|
||||
let mut kept = 0usize;
|
||||
for (_, _, area, rule, _, _) in &parts {
|
||||
let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default();
|
||||
let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default();
|
||||
kept = kept.saturating_add(facets.len());
|
||||
if kept > MAX_OBJECT_FACES {
|
||||
return None;
|
||||
}
|
||||
listed(&surfaces, &facets, &mut out);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// [`map_surfaces_at`] for `n` as it is with 3D effect `id` and parameters `p` among the effects of
|
||||
/// the object itself (`item` `None`) or of its fill or stroke `item`: in place of the effect at
|
||||
/// `index` when that is an effect `id`, else of the last effect `id` there, or after those effects
|
||||
/// when there is none. A dialog lists the surfaces of the effect it edits with this, whether or not
|
||||
/// its preview has changed the object.
|
||||
pub fn map_surfaces_with(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
(item, index): (Option<usize>, Option<usize>),
|
||||
id: &str,
|
||||
p: &Value,
|
||||
) -> Option<Vec<MapSurface>> {
|
||||
let mut n = n.clone();
|
||||
let effects = n.appearance.effects_mut(item)?;
|
||||
let at = index.filter(|&k| effects.get(k).is_some_and(|e| e.id == id)).or_else(|| effects.iter().rposition(|e| e.id == id));
|
||||
let index = match at {
|
||||
Some(index) => {
|
||||
effects.get_mut(index)?.params = p.clone();
|
||||
index
|
||||
}
|
||||
None => {
|
||||
effects.push(crate::new_effect(id, p)?);
|
||||
effects.len() - 1
|
||||
}
|
||||
};
|
||||
map_surfaces_at(doc, &n, item, index)
|
||||
}
|
||||
|
||||
/// The 3D effect `pick` finds in the effects of `n` (resolved) or of its `item`, with the shapes
|
||||
/// it builds from: the members of a group or layer, or the object's own profile after the geometry
|
||||
/// effects before the 3D effect.
|
||||
fn picked<'n>(n: &'n Node, item: Option<usize>, pick: &Pick<'_>) -> Option<(&'n Effect, Vec<Profile>)> {
|
||||
Some(if is_container(n) {
|
||||
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
(fx, shapes)
|
||||
} else {
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
match item {
|
||||
None => {
|
||||
let (index, fx) = pick(&n.appearance.effects)?;
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
(fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }])
|
||||
}
|
||||
Some(k) => {
|
||||
let it = n.appearance.items.get(k)?;
|
||||
let (index, fx) = pick(it.effects())?;
|
||||
let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it));
|
||||
(fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
|
||||
pub fn graphic_bounds(doc: &Document, name: &str) -> Option<Rect> {
|
||||
graphics::art_bounds(doc, name)
|
||||
@@ -2602,8 +2811,8 @@ impl SolidMesh {
|
||||
/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted
|
||||
/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude &
|
||||
/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each
|
||||
/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its
|
||||
/// mesh, stays plain.
|
||||
/// corner ([`MeshGraphics`]), then the rest. Revolve's meshes are split by their side instead
|
||||
/// (`revolve::surface_meshes`), so a Revolve's mesh stays plain here.
|
||||
fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec<SolidMesh> {
|
||||
let list = graphics::mapped_graphics(p);
|
||||
if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE {
|
||||
|
||||
@@ -9,6 +9,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light};
|
||||
|
||||
use super::graphics::map_art::{self, MapArt, MapBudget, SolidLayout};
|
||||
use crate::util::{flag, num, text};
|
||||
|
||||
pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude";
|
||||
@@ -51,10 +52,21 @@ pub fn classic_extrude_options(p: &Value) -> Extrude {
|
||||
..Bevel::default()
|
||||
}),
|
||||
hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe,
|
||||
// The numbered surfaces are laid out only for an effect that maps art onto them.
|
||||
map_surfaces: !map_art::surface_maps(p).is_empty(),
|
||||
..Extrude::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The mapped art of one solid for [`surface`]: the effect's maps, the solid's place among the
|
||||
/// object's numbered surfaces, and the limits the object's mapped art shares.
|
||||
pub(crate) struct Mapped<'a, 'd> {
|
||||
pub(crate) art: &'a MapArt<'d>,
|
||||
pub(crate) layout: &'a SolidLayout,
|
||||
pub(crate) budget: &'a mut MapBudget,
|
||||
pub(crate) copies: &'a mut usize,
|
||||
}
|
||||
|
||||
/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces
|
||||
/// keep their paint and only the highlight lightens them).
|
||||
fn shading_color(p: &Value) -> Option<Color> {
|
||||
@@ -102,13 +114,15 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"];
|
||||
const FLAGS: [&str; 7] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE];
|
||||
|
||||
/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of
|
||||
/// 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.
|
||||
/// its parameters, numbers are in range, flags are true or false, `surface`, `shadingColor` and
|
||||
/// `shadingCustom` name a surface, a shading color and a #rrggbb color, and `mapArt` holds valid
|
||||
/// maps.
|
||||
pub fn validate(p: &Value) -> Result<(), String> {
|
||||
validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)
|
||||
validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)?;
|
||||
map_art::validate(CLASSIC_EXTRUDE, p)
|
||||
}
|
||||
|
||||
/// Rotate (Classic)'s numeric parameters: (key, lowest, highest, whole numbers only).
|
||||
@@ -261,66 +275,67 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's
|
||||
/// coverage; without a placement of its own, it is placed once on all the faces
|
||||
/// ([`crate::lighting::opaque_surface_paint`]).
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
///
|
||||
/// With `mapped`, a face that carries mapped art is a group of the face and that art, which the
|
||||
/// surface's opacity mask covers too. Shade Artwork gives the art its face's tone and highlight,
|
||||
/// and Invisible Geometry leaves the faces out: a face is then a group of its art alone. Wireframe
|
||||
/// draws no mapped art. Without `mapped`, `hide` leaves the faces out the same way, for a solid
|
||||
/// that shares Invisible Geometry with another solid's mapped art; Wireframe still draws.
|
||||
///
|
||||
/// Returns the group, whether its faces were left out, and whether `mapped` art was left out past
|
||||
/// the limits.
|
||||
pub(crate) fn surface(
|
||||
n: &Node,
|
||||
facets: &[Facet],
|
||||
source: &Paint,
|
||||
(opacity, blend): (f32, BlendMode),
|
||||
p: &Value,
|
||||
mapped: Option<Mapped<'_, '_>>,
|
||||
hide: bool,
|
||||
) -> (Node, bool, bool) {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
let shade = shading_color(p);
|
||||
let preserve = preserves_spot_colors(p);
|
||||
let overprint = black_overprint(p);
|
||||
let wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) };
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(facets)) };
|
||||
let paint = &paint;
|
||||
// The mapped art of each facet, and whether the faces themselves are left out. Art past the
|
||||
// limits is left out, and the faces draw; the copies and the points of art left out do not
|
||||
// count against the art of later solids.
|
||||
let (mut parts, invisible, dropped) = match mapped.filter(|_| !wire) {
|
||||
Some(m) => {
|
||||
let shaded_as = |f: &Facet, c: Color| {
|
||||
let (tone, spec) = shading.tone(f.normal, &lights);
|
||||
shaded(c, tone, spec, shade)
|
||||
};
|
||||
let (mut used, mut budget) = (*m.copies, m.budget.clone());
|
||||
match m.art.parts(n.id, facets, m.layout, &shaded_as, &mut budget, &mut used) {
|
||||
Some(parts) => {
|
||||
(*m.copies, *m.budget) = (used, budget);
|
||||
(parts, m.art.invisible, false)
|
||||
}
|
||||
None => (vec![], false, true),
|
||||
}
|
||||
}
|
||||
None => (vec![], hide && !wire, false),
|
||||
};
|
||||
let children = facets
|
||||
.into_iter()
|
||||
.map(|face| {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, face)| {
|
||||
let art = parts.get_mut(k).map(std::mem::take).unwrap_or_default();
|
||||
if !art.is_empty() || invisible {
|
||||
let drawn = (!invisible).then(|| Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint)));
|
||||
return Arc::new(Node::group(n.id, drawn.into_iter().chain(art).collect()));
|
||||
}
|
||||
if wire {
|
||||
// A wire edge is drawn as a seam is: a round-joined stroke of the paint.
|
||||
let edge = crate::lighting::seam_stroke(paint.clone(), WIRE);
|
||||
return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() }));
|
||||
}
|
||||
let (tone, spec) = shading.tone(face.normal, &lights);
|
||||
// A narrow stroke of the face's own paint closes the hairline seams between faces.
|
||||
let seam = super::seam_width(&face);
|
||||
if overprint {
|
||||
let items = overprinted_face(paint, tone, seam);
|
||||
return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }));
|
||||
}
|
||||
let items = match paint.color() {
|
||||
// Unshaded (No Shading, no shading color, or a face in full light) with no
|
||||
// highlight: the paint itself, its color space and swatch kept.
|
||||
Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => {
|
||||
vec![
|
||||
AppearanceItem::Fill(FillLayer::new(paint.clone())),
|
||||
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
|
||||
]
|
||||
}
|
||||
// Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch.
|
||||
Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => {
|
||||
linked_face(paint, tone, spec, shade, seam)
|
||||
}
|
||||
Some(c) => {
|
||||
let fill = Paint::solid(shaded(c, tone, spec, shade));
|
||||
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]
|
||||
}
|
||||
// Gradients and patterns keep their paint, darkened by a layer of the shading color
|
||||
// and lightened by one of white. As with the other 3D effects' pattern shadow, the
|
||||
// layers cover the whole face, transparent pattern cells included.
|
||||
None => {
|
||||
let mut items = vec![
|
||||
AppearanceItem::Fill(FillLayer::new(paint.clone())),
|
||||
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
|
||||
];
|
||||
for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] {
|
||||
if let Some(color) = color.filter(|_| share > 0.0) {
|
||||
let mut layer = FillLayer::new(Paint::solid(color));
|
||||
layer.opacity = share as f32;
|
||||
items.push(AppearanceItem::Fill(layer));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
};
|
||||
Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }))
|
||||
Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint))
|
||||
})
|
||||
.collect();
|
||||
let mut group = Node::group(n.id, children);
|
||||
@@ -331,5 +346,61 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
|
||||
let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0));
|
||||
group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true)));
|
||||
}
|
||||
group
|
||||
(group, invisible, dropped)
|
||||
}
|
||||
|
||||
/// One face of a solid in paint `paint` (opaque: [`surface`] masks a gradient's transparency),
|
||||
/// filled in the paint shaded by the face's tone and highlight under `lights`, toward shading
|
||||
/// color `shade`. With `preserve` (Preserve Spot Colors), a color linked to a swatch is drawn as
|
||||
/// [`linked_face`] draws it. With `overprint` (Black Overprint), the face is drawn as
|
||||
/// [`overprinted_face`] draws it.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn shaded_face(
|
||||
n: &Node,
|
||||
face: &Facet,
|
||||
paint: &Paint,
|
||||
shading: &ClassicShading,
|
||||
lights: &[([f64; 3], f64)],
|
||||
shade: Option<Color>,
|
||||
preserve: bool,
|
||||
overprint: bool,
|
||||
) -> Node {
|
||||
let (tone, spec) = shading.tone(face.normal, lights);
|
||||
// A narrow stroke of the face's own paint closes the hairline seams between faces.
|
||||
let seam = super::seam_width(face);
|
||||
if overprint {
|
||||
let items = overprinted_face(paint, tone, seam);
|
||||
return Node::path(n.id, face.path(), Appearance { items, ..Default::default() });
|
||||
}
|
||||
let items = match paint.color() {
|
||||
// Unshaded (No Shading, no shading color, or a face in full light) with no
|
||||
// highlight: the paint itself, its color space and swatch kept.
|
||||
Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => {
|
||||
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]
|
||||
}
|
||||
// Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch.
|
||||
Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => {
|
||||
linked_face(paint, tone, spec, shade, seam)
|
||||
}
|
||||
Some(c) => {
|
||||
let fill = Paint::solid(shaded(c, tone, spec, shade));
|
||||
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]
|
||||
}
|
||||
// Gradients and patterns keep their paint, darkened by a layer of the shading color
|
||||
// and lightened by one of white. As with the other 3D effects' pattern shadow, the
|
||||
// layers cover the whole face, transparent pattern cells included.
|
||||
None => {
|
||||
let mut items =
|
||||
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))];
|
||||
for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] {
|
||||
if let Some(color) = color.filter(|_| share > 0.0) {
|
||||
let mut layer = FillLayer::new(Paint::solid(color));
|
||||
layer.opacity = share as f32;
|
||||
items.push(AppearanceItem::Fill(layer));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
};
|
||||
Node::path(n.id, face.path(), Appearance { items, ..Default::default() })
|
||||
}
|
||||
@@ -177,6 +177,8 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
|
||||
/// Revolve and Inflate take graphics; a plane has only a front, and Revolve's graphics go on its
|
||||
/// side, named the front. Only Extrude & Bevel takes graphics on its side.
|
||||
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
// Map Art's maps are checked with the graphics: an effect that takes none refuses them.
|
||||
map_art::validate(id, p)?;
|
||||
let list = match p.get(GRAPHICS) {
|
||||
None => return Ok(()),
|
||||
Some(Value::Array(list)) => list,
|
||||
@@ -210,21 +212,23 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
/// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol
|
||||
/// was deleted may stay.
|
||||
pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option<String> {
|
||||
let kept = old.map(mapped_graphics).unwrap_or_default();
|
||||
mapped_graphics(p)
|
||||
.into_iter()
|
||||
.map(|g| g.symbol)
|
||||
.find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name))
|
||||
let names = |p: &Value| -> Vec<String> {
|
||||
mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)).collect()
|
||||
};
|
||||
let kept = old.map(names).unwrap_or_default();
|
||||
names(p).into_iter().find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.contains(name))
|
||||
}
|
||||
|
||||
/// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol
|
||||
/// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as
|
||||
/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once.
|
||||
/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. The symbols Map
|
||||
/// Art places count with the graphics.
|
||||
pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> {
|
||||
let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 };
|
||||
let mut elements = 0usize;
|
||||
for g in mapped_graphics(p) {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
|
||||
let names = mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol));
|
||||
for name in names {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == name) else { continue };
|
||||
let pieces = pieces_of(doc, symbol)?;
|
||||
elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum());
|
||||
if elements > MAX_ELEMENTS {
|
||||
@@ -234,6 +238,30 @@ pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Does the art Map Art in `p` places on the surfaces that `unrolled` gives a flat center for (by
|
||||
/// number, from 1; [`map_art::flat_center`]), with the symbols of `doc`, fit the limits as a wall, a
|
||||
/// bevel or Revolve's side draws it: each map's art placed about that center at its scale, cut into
|
||||
/// straight pieces, at most [`MAX_ELEMENTS`] points together and within reach? A map whose symbol
|
||||
/// `doc` does not have is not counted.
|
||||
pub fn validate_unrolled_symbols(doc: &Document, p: &Value, unrolled: &dyn Fn(usize) -> Option<Point>) -> Result<(), String> {
|
||||
const TOO_COMPLEX: &str = "The graphics are too complex: simplify the symbols' art";
|
||||
let mut points = 0usize;
|
||||
for m in map_art::surface_maps(p) {
|
||||
let Some(center) = unrolled(m.surface) else { continue };
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == m.symbol) else { continue };
|
||||
let pieces = pieces_of(doc, symbol)?;
|
||||
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
|
||||
let place = m.placement(bounds, center, false);
|
||||
for piece in &pieces {
|
||||
straight_pieces(&(place * piece.path.to_bezpath()), &mut points).ok_or(TOO_COMPLEX)?;
|
||||
}
|
||||
if points > MAX_ELEMENTS {
|
||||
return Err(TOO_COMPLEX.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The path elements `path` draws when each curve draws `curve` elements, before curves near the
|
||||
/// eye are split further: one for each straight line, move and close.
|
||||
fn drawn_elements(path: &PathData, curve: usize) -> usize {
|
||||
@@ -886,7 +914,12 @@ pub(crate) fn surface_parts<F: SurfaceFace>(
|
||||
for k in near {
|
||||
let Some(piece) = pieces.get(k) else { continue };
|
||||
let mut path = BezPath::new();
|
||||
// Each contour is cut only where its own bounds reach the triangle.
|
||||
// Each contour is cut only where its own bounds reach the triangle. Each bounds test
|
||||
// counts as one point cut, whether or not the contour reaches it.
|
||||
cut_points = cut_points.saturating_add(piece.boxes.len());
|
||||
if cut_points > MAX_SURFACE_CUTS {
|
||||
return None;
|
||||
}
|
||||
for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) {
|
||||
if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 {
|
||||
continue;
|
||||
@@ -1411,9 +1444,11 @@ pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec<String> {
|
||||
std::iter::once(&appearance.effects)
|
||||
.chain(appearance.items.iter().map(AppearanceItem::effects))
|
||||
.flatten()
|
||||
.filter(|e| takes_graphics(&e.id))
|
||||
.flat_map(|e| mapped_graphics(&e.params))
|
||||
.map(|g| g.symbol)
|
||||
.filter(|e| takes_graphics(&e.id) || map_art::takes_map_art(&e.id))
|
||||
.flat_map(|e| {
|
||||
let graphics = mapped_graphics(&e.params).into_iter().map(|g| g.symbol).filter(|_| takes_graphics(&e.id));
|
||||
graphics.chain(map_art::surface_maps(&e.params).into_iter().map(|m| m.symbol).filter(|_| map_art::takes_map_art(&e.id)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1433,8 +1468,15 @@ pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str,
|
||||
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
|
||||
lists.push(effects);
|
||||
lists.extend(items.iter_mut().map(AppearanceItem::effects_mut));
|
||||
for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) {
|
||||
if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) {
|
||||
for e in lists.into_iter().flatten() {
|
||||
let key = if takes_graphics(&e.id) {
|
||||
GRAPHICS
|
||||
} else if map_art::takes_map_art(&e.id) {
|
||||
map_art::MAP_ART
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if let Some(Value::Array(list)) = e.params.get_mut(key) {
|
||||
for g in list.iter_mut() {
|
||||
if g.get("symbol").and_then(Value::as_str) == Some(from) {
|
||||
g["symbol"] = json!(to);
|
||||
@@ -1480,6 +1522,9 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
#[path = "map_art.rs"]
|
||||
pub(crate) mod map_art;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests_graphics.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,781 @@
|
||||
//! Map Art: the art of a document symbol mapped onto the numbered surfaces of Extrude & Bevel
|
||||
//! (Classic) and Revolve (Classic).
|
||||
//!
|
||||
//! The effect keeps its maps in its `mapArt` parameter, each `{surface, symbol, x, y, scaleX,
|
||||
//! scaleY, rotation}`: the surface's number (from 1), the symbol's name, the offset of the art's
|
||||
//! center from the center of the surface laid out flat (points, x to the right and y down as the
|
||||
//! surface is seen from outside the solid), its size as a share of the symbol's own, and its turn
|
||||
//! (degrees, counterclockwise). `mapShade` shades the mapped art with its surface, and
|
||||
//! `mapInvisible` draws the mapped art without the solid's faces.
|
||||
//!
|
||||
//! The surfaces of Extrude & Bevel (Classic) are numbered through its solids in the order they are
|
||||
//! built, each solid's as [`vectorcraft_three_d::extrude_surfaces`] lists them. Revolve (Classic)
|
||||
//! has one surface, its swept side (in a group, the side of the member with the longest profile).
|
||||
//! A map whose number is past the object's surfaces draws nothing.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect};
|
||||
use vectorcraft_three_d::{Extrude, FaceMap, Facet, MapCell, PlanarFace, SolidSurface, SurfaceKind, View};
|
||||
|
||||
use super::{
|
||||
MAX_ELEMENTS, MAX_SURFACE_CUTS, MAX_SURFACE_POINTS, NotMapped, SURFACE_SEAM, SURFACE_TOLERANCE, Unrolled, counterclockwise, map_path, pieces_of,
|
||||
straight_pieces, takes_seam, triangle_map,
|
||||
};
|
||||
|
||||
/// The effect parameter that holds the maps.
|
||||
pub const MAP_ART: &str = "mapArt";
|
||||
|
||||
/// The effect parameter of Shade Artwork.
|
||||
pub const MAP_SHADE: &str = "mapShade";
|
||||
|
||||
/// The effect parameter of Invisible Geometry.
|
||||
pub const MAP_INVISIBLE: &str = "mapInvisible";
|
||||
|
||||
/// The most surfaces of one 3D effect that carry a map.
|
||||
pub const MAX_MAPS: usize = 64;
|
||||
|
||||
/// The highest surface number a map may name.
|
||||
pub const MAX_MAP_SURFACE: usize = 100_000;
|
||||
|
||||
/// The error for maps on a 3D effect that takes none.
|
||||
pub const MAP_ART_NOT_TAKEN: &str = "Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)";
|
||||
|
||||
/// The symbol mapped onto one numbered surface of a 3D object.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SurfaceMap {
|
||||
/// The surface's number, from 1.
|
||||
pub surface: usize,
|
||||
pub symbol: String,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
/// Percent of the symbol's own width.
|
||||
pub scale_x: f64,
|
||||
/// Percent of the symbol's own height.
|
||||
pub scale_y: f64,
|
||||
/// Degrees, counterclockwise.
|
||||
pub rotation: f64,
|
||||
}
|
||||
|
||||
impl SurfaceMap {
|
||||
pub fn to_value(&self) -> Value {
|
||||
json!({
|
||||
"surface": self.surface,
|
||||
"symbol": self.symbol,
|
||||
"x": self.x,
|
||||
"y": self.y,
|
||||
"scaleX": self.scale_x,
|
||||
"scaleY": self.scale_y,
|
||||
"rotation": self.rotation,
|
||||
})
|
||||
}
|
||||
|
||||
/// The map `v` describes. `surface` and `symbol` are required: the offsets and the rotation
|
||||
/// default to 0 and the scales to 100.
|
||||
pub fn from_value(v: &Value) -> Result<Self, String> {
|
||||
let Value::Object(m) = v else { return Err(format!("each of `{MAP_ART}` must be an object")) };
|
||||
if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "surface" | "symbol" | "x" | "y" | "scaleX" | "scaleY" | "rotation")) {
|
||||
return Err(format!("`{MAP_ART}` entries take surface, symbol, x, y, scaleX, scaleY and rotation, not `{k}`"));
|
||||
}
|
||||
let surface = m
|
||||
.get("surface")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| usize::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_MAP_SURFACE).contains(n))
|
||||
.ok_or_else(|| format!("each of `{MAP_ART}` needs `surface`, a whole number from 1 to {MAX_MAP_SURFACE}"))?;
|
||||
let symbol = match m.get("symbol") {
|
||||
Some(Value::String(s)) if !s.trim().is_empty() => s.clone(),
|
||||
_ => return Err(format!("each of `{MAP_ART}` needs `symbol`, the name of a symbol")),
|
||||
};
|
||||
let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> {
|
||||
match m.get(key) {
|
||||
None => Ok(default),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && (lo..=hi).contains(n))
|
||||
.ok_or_else(|| format!("`{MAP_ART}` {key} must be a number from {lo} to {hi}")),
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
surface,
|
||||
symbol,
|
||||
x: number("x", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?,
|
||||
y: number("y", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?,
|
||||
scale_x: number("scaleX", 100.0, super::SCALE_RANGE)?,
|
||||
scale_y: number("scaleY", 100.0, super::SCALE_RANGE)?,
|
||||
rotation: number("rotation", 0.0, (-360.0, 360.0))?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the symbol's art goes on the flat surface, for art whose bounds are `art` on a
|
||||
/// surface with center `center`. With `mirrored` (the back cap) x runs to the right as the
|
||||
/// surface is seen from behind the solid.
|
||||
pub fn placement(&self, art: Rect, center: Point, mirrored: bool) -> Affine {
|
||||
let place = Affine::translate((center.x + self.x, center.y + self.y))
|
||||
* Affine::rotate(-self.rotation.to_radians())
|
||||
* Affine::scale_non_uniform(self.scale_x / 100.0, self.scale_y / 100.0)
|
||||
* Affine::translate(-art.center().to_vec2());
|
||||
if mirrored {
|
||||
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
|
||||
} else {
|
||||
place
|
||||
}
|
||||
}
|
||||
|
||||
/// The scales (percent) at which art with bounds `art`, turned by the map's rotation, fills a
|
||||
/// surface `width` by `height` points: Scale to Fit. `None` for art or a surface with no area.
|
||||
pub fn fitting_scales(&self, art: Rect, (width, height): (f64, f64)) -> Option<(f64, f64)> {
|
||||
let (w, h) = (art.width(), art.height());
|
||||
if w <= 0.0 || h <= 0.0 || width <= 0.0 || height <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// The box of the art turned by the rotation, at its own size.
|
||||
let (sin, cos) = self.rotation.to_radians().sin_cos();
|
||||
let (bw, bh) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs());
|
||||
let clamp = |v: f64| v.clamp(super::SCALE_RANGE.0, super::SCALE_RANGE.1);
|
||||
if sin.abs() < 1e-9 || cos.abs() < 1e-9 {
|
||||
// Square to the surface, each side takes its own scale.
|
||||
let (sx, sy) = if cos.abs() >= 0.5 { (width / w, height / h) } else { (height / w, width / h) };
|
||||
return Some((clamp(sx * 100.0), clamp(sy * 100.0)));
|
||||
}
|
||||
let fit = (width / bw).min(height / bh);
|
||||
Some((clamp(fit * 100.0), clamp(fit * 100.0)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D effects that take Map Art: Extrude & Bevel (Classic) and Revolve (Classic).
|
||||
pub fn takes_map_art(id: &str) -> bool {
|
||||
id == super::super::CLASSIC_EXTRUDE || id == crate::CLASSIC_REVOLVE
|
||||
}
|
||||
|
||||
/// The maps in parameters `p`, leaving out entries that are not valid and, of two maps of one
|
||||
/// surface, the later one (a file may hold anything; commands check every entry with
|
||||
/// [`validate`]).
|
||||
pub fn surface_maps(p: &Value) -> Vec<SurfaceMap> {
|
||||
let Some(Value::Array(list)) = p.get(MAP_ART) else { return vec![] };
|
||||
let mut seen = HashSet::new();
|
||||
list.iter().filter_map(|v| SurfaceMap::from_value(v).ok()).filter(|m| seen.insert(m.surface)).take(MAX_MAPS).collect()
|
||||
}
|
||||
|
||||
/// Are the maps in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel (Classic) and
|
||||
/// Revolve (Classic) take maps, at most [`MAX_MAPS`] of them, one for a surface.
|
||||
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
let list = match p.get(MAP_ART) {
|
||||
None => return Ok(()),
|
||||
Some(Value::Array(list)) => list,
|
||||
Some(_) => return Err(format!("`{MAP_ART}` must be an array")),
|
||||
};
|
||||
if list.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if !takes_map_art(id) {
|
||||
return Err(MAP_ART_NOT_TAKEN.into());
|
||||
}
|
||||
if list.len() > MAX_MAPS {
|
||||
return Err(format!("`{MAP_ART}` takes at most {MAX_MAPS} maps"));
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
for v in list {
|
||||
let m = SurfaceMap::from_value(v)?;
|
||||
if !seen.insert(m.surface) {
|
||||
return Err(format!("`{MAP_ART}` maps surface {} more than once", m.surface));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `p` with the map of surface `surface` replaced by `map`, or removed with `None`. The maps stay
|
||||
/// in the order of their surfaces.
|
||||
pub fn with_surface_map(p: &Value, surface: usize, map: Option<&SurfaceMap>) -> Value {
|
||||
let mut maps: Vec<SurfaceMap> = surface_maps(p).into_iter().filter(|m| m.surface != surface).collect();
|
||||
maps.extend(map.cloned());
|
||||
maps.sort_by_key(|m| m.surface);
|
||||
let mut out = p.as_object().cloned().unwrap_or_else(Map::new);
|
||||
out.insert(MAP_ART.into(), Value::Array(maps.iter().map(SurfaceMap::to_value).collect()));
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// One solid's place among its object's numbered surfaces: the index of its first surface, its
|
||||
/// surfaces, and for a solid with planar ends the bounds, options and view it was built with.
|
||||
pub(crate) struct SolidLayout {
|
||||
pub(crate) first: usize,
|
||||
pub(crate) surfaces: Vec<SolidSurface>,
|
||||
pub(crate) ends: Option<(Rect, Extrude, View)>,
|
||||
}
|
||||
|
||||
/// What the mapped art of one object has drawn so far, against the limits its maps share.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct MapBudget {
|
||||
elements: usize,
|
||||
/// The points of the maps' symbols cut into straight pieces, against [`MAX_ELEMENTS`].
|
||||
input: usize,
|
||||
/// The points the maps' art draws on the faces, against [`MAX_SURFACE_POINTS`].
|
||||
points: usize,
|
||||
cuts: usize,
|
||||
}
|
||||
|
||||
/// The maps of one 3D effect, with the document whose symbols they place.
|
||||
pub(crate) struct MapArt<'a> {
|
||||
doc: &'a Document,
|
||||
maps: Vec<SurfaceMap>,
|
||||
/// Shade Artwork: the mapped art takes the shading of its surface.
|
||||
pub(crate) shade: bool,
|
||||
/// Invisible Geometry: only the mapped art is drawn.
|
||||
pub(crate) invisible: bool,
|
||||
}
|
||||
|
||||
impl<'a> MapArt<'a> {
|
||||
/// The maps of 3D effect `id` with parameters `p`. `None` without a document, for an effect
|
||||
/// that takes no maps and for one that has none.
|
||||
pub(crate) fn of(doc: Option<&'a Document>, id: &str, p: &Value) -> Option<Self> {
|
||||
let maps = surface_maps(p);
|
||||
let flag = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false);
|
||||
(takes_map_art(id) && !maps.is_empty()).then_some(Self { doc: doc?, maps, shade: flag(MAP_SHADE), invisible: flag(MAP_INVISIBLE) })
|
||||
}
|
||||
|
||||
fn map_of(&self, index: usize) -> Option<&SurfaceMap> {
|
||||
self.maps.iter().find(|m| m.surface == index + 1)
|
||||
}
|
||||
|
||||
/// The mapped art that falls on each of `facets`, one solid's facets in drawing order, for an
|
||||
/// object with id `id`: for each facet, the nodes to draw right after it. Only facets turned
|
||||
/// toward the viewer carry art. `shade` gives a color as its facet shades it, for Shade
|
||||
/// Artwork. A map whose symbol the document does not have, or whose art is past the limits of
|
||||
/// a graphic's art, draws nothing. `None` when the art is past the limits the maps of one
|
||||
/// object share, or the copies of its paints take `copies` past the object's allowance: the
|
||||
/// solid then draws without mapped art.
|
||||
pub(crate) fn parts(
|
||||
&self,
|
||||
id: NodeId,
|
||||
facets: &[Facet],
|
||||
layout: &SolidLayout,
|
||||
shade: &dyn Fn(&Facet, Color) -> Color,
|
||||
budget: &mut MapBudget,
|
||||
copies: &mut usize,
|
||||
) -> Option<Vec<Vec<Arc<Node>>>> {
|
||||
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; facets.len()];
|
||||
let mut flat: HashMap<usize, Vec<Unrolled>> = HashMap::new();
|
||||
for (f, parts) in facets.iter().zip(out.iter_mut()) {
|
||||
if f.away {
|
||||
continue;
|
||||
}
|
||||
let recolor = |c: Color| if self.shade { shade(f, c) } else { c };
|
||||
if let Some(end) = f.end {
|
||||
let Some(local) = layout.surfaces.iter().position(|s| s.kind == SurfaceKind::End(end)) else { continue };
|
||||
let (Some(m), Some(center)) = (self.map_of(layout.first + local), layout.surfaces.get(local).and_then(|s| s.center)) else {
|
||||
continue;
|
||||
};
|
||||
let Some((bounds, options, view)) = layout.ends else { continue };
|
||||
let Some(map) = vectorcraft_three_d::extrude_face_map(bounds, options, view, end) else { continue };
|
||||
parts.extend(self.end_art(id, m, (end, &map), center, f, &recolor, budget, copies)?);
|
||||
} else if let Some(cell) = f.cell.as_deref() {
|
||||
let (Some(m), Some(surface)) = (self.map_of(layout.first + cell.surface), layout.surfaces.get(cell.surface)) else { continue };
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = flat.entry(cell.surface) {
|
||||
e.insert(self.unrolled(m, surface, budget)?);
|
||||
}
|
||||
let Some(pieces) = flat.get(&cell.surface) else { continue };
|
||||
parts.extend(cell_art(id, pieces, cell, f, &recolor, budget, copies)?);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The art of map `m` on planar end `end` of a solid, drawn on its facet `f` through `map`,
|
||||
/// for an end whose bounds have center `center`: one clipping group, as a graphic on a cap is
|
||||
/// drawn. `None` past the limits.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn end_art(
|
||||
&self,
|
||||
id: NodeId,
|
||||
m: &SurfaceMap,
|
||||
(end, map): (PlanarFace, &FaceMap),
|
||||
center: Point,
|
||||
f: &Facet,
|
||||
recolor: &dyn Fn(Color) -> Color,
|
||||
budget: &mut MapBudget,
|
||||
copies: &mut usize,
|
||||
) -> Option<Vec<Arc<Node>>> {
|
||||
let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) };
|
||||
let Ok(pieces) = pieces_of(self.doc, symbol) else { return Some(vec![]) };
|
||||
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) };
|
||||
let place = m.placement(bounds, center, end == PlanarFace::Back);
|
||||
let affine = map.local_affine(center).filter(|_| map.is_affine());
|
||||
// Gradients follow the end's map as it is near the art's center, or near the middle of the
|
||||
// part in front of the eye when the center is not.
|
||||
let local = map.local_affine(place * bounds.center()).or_else(|| {
|
||||
let part = map.mapped_part(place.transform_rect_bbox(bounds))?;
|
||||
let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2());
|
||||
map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64))
|
||||
});
|
||||
let Some(local) = local else { return Some(vec![]) };
|
||||
let gradient_map = local * place;
|
||||
let mut children = vec![];
|
||||
for piece in pieces {
|
||||
let placed = piece.path.transformed(place);
|
||||
let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum();
|
||||
let before = budget.elements;
|
||||
if before.saturating_add(least) > MAX_ELEMENTS {
|
||||
return None;
|
||||
}
|
||||
let room = MAX_ELEMENTS - before;
|
||||
let mut rule = piece.rule;
|
||||
let mapped = match map_path(&placed, map, affine, room) {
|
||||
Err(NotMapped::Behind) => {
|
||||
// Part of it is at or behind the eye: the part in front is drawn.
|
||||
let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue };
|
||||
let Some(&first) = part.first() else { continue };
|
||||
let mut front = BezPath::new();
|
||||
front.move_to(first);
|
||||
part.iter().skip(1).for_each(|p| front.line_to(*p));
|
||||
front.close_path();
|
||||
let cut = vectorcraft_pathops::boolean(
|
||||
&placed,
|
||||
piece.rule,
|
||||
&PathData::from_bezpath(&front),
|
||||
FillRule::NonZero,
|
||||
vectorcraft_pathops::BoolOp::Intersect,
|
||||
);
|
||||
rule = FillRule::NonZero;
|
||||
map_path(&cut, map, affine, room)
|
||||
}
|
||||
done => done,
|
||||
};
|
||||
let mapped = match mapped {
|
||||
Ok(mapped) => mapped,
|
||||
Err(NotMapped::Full) => return None,
|
||||
Err(NotMapped::Behind) => continue,
|
||||
};
|
||||
budget.elements = before.saturating_add(mapped.elements().len());
|
||||
if !crate::revolve::paint_copies_add(copies, 1, &piece.paint) {
|
||||
return None;
|
||||
}
|
||||
children.push(Arc::new(piece_node(id, piece.paint, (piece.opacity, piece.blend), (mapped, rule), gradient_map, recolor, None)));
|
||||
}
|
||||
if children.is_empty() {
|
||||
return Some(vec![]);
|
||||
}
|
||||
// An end's holes are contours of the same path wound against its outline, so turning the
|
||||
// whole path keeps them holes under the nonzero rule.
|
||||
let mut outline = f.path().to_bezpath();
|
||||
if vectorcraft_geom::kurbo::Shape::area(&outline) < 0.0 {
|
||||
outline = outline.reverse_subpaths();
|
||||
}
|
||||
let clip = Node::path(id, PathData::from_bezpath(&outline), Appearance::default());
|
||||
Some(vec![Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))])
|
||||
}
|
||||
|
||||
/// The areas of map `m`'s symbol placed on `surface` laid out flat, cut into straight pieces.
|
||||
/// Empty for a symbol the document does not have or whose art is past the limits of a
|
||||
/// graphic's art. `None` when the pieces of the object's maps take more than
|
||||
/// [`MAX_ELEMENTS`] points together.
|
||||
fn unrolled(&self, m: &SurfaceMap, surface: &SolidSurface, budget: &mut MapBudget) -> Option<Vec<Unrolled>> {
|
||||
let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) };
|
||||
let Ok(art) = pieces_of(self.doc, symbol) else { return Some(vec![]) };
|
||||
let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) };
|
||||
let place = m.placement(bounds, flat_center(surface), false);
|
||||
let mut pieces = vec![];
|
||||
for piece in art {
|
||||
let placed = place * piece.path.to_bezpath();
|
||||
let mut polygons = straight_pieces(&placed, &mut budget.input)?;
|
||||
polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite()));
|
||||
let boxes: Vec<Rect> = polygons.iter().filter_map(|polygon| box_of(polygon)).collect();
|
||||
let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue };
|
||||
pieces.push(Unrolled {
|
||||
polygons,
|
||||
boxes,
|
||||
bounds,
|
||||
rule: piece.rule,
|
||||
paint: piece.paint,
|
||||
opacity: piece.opacity,
|
||||
blend: piece.blend,
|
||||
place,
|
||||
});
|
||||
}
|
||||
Some(pieces)
|
||||
}
|
||||
}
|
||||
|
||||
/// The center of `surface` laid out flat, which a map's offset is measured from: the middle of a
|
||||
/// wall or a bevel, whose flat coordinates start at its corner, and the origin of Revolve's side,
|
||||
/// whose flat coordinates start at its middle.
|
||||
pub fn flat_center(surface: &SolidSurface) -> Point {
|
||||
match surface.kind {
|
||||
SurfaceKind::Side => Point::ZERO,
|
||||
SurfaceKind::End(_) => surface.center.unwrap_or(Point::ZERO),
|
||||
SurfaceKind::Wall | SurfaceKind::Bevel => Point::new(surface.width / 2.0, surface.height / 2.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn box_of(points: &[Point]) -> Option<Rect> {
|
||||
points.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// A map from a region of a flat surface onto the page.
|
||||
enum Mapper {
|
||||
Affine(Affine),
|
||||
/// The projective map that takes the rectangle with corner `origin` and size `size` onto a
|
||||
/// quadrilateral: `rows` are its coefficients on the unit square.
|
||||
Quad {
|
||||
origin: Point,
|
||||
size: (f64, f64),
|
||||
rows: [f64; 8],
|
||||
},
|
||||
}
|
||||
|
||||
impl Mapper {
|
||||
fn at(&self, p: Point) -> Point {
|
||||
match self {
|
||||
Mapper::Affine(a) => *a * p,
|
||||
Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => {
|
||||
let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1);
|
||||
let w = g * u + h * v + 1.0;
|
||||
Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The point of the flat surface this map takes to `p` on the page. `None` where there is none.
|
||||
fn back(&self, p: Point) -> Option<Point> {
|
||||
let q = match self {
|
||||
Mapper::Affine(a) => a.inverse() * p,
|
||||
Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => {
|
||||
// x (g u + h v + 1) = a u + b v + c, and the same for y, solved for u and v.
|
||||
let (m00, m01, r0) = (a - g * p.x, b - h * p.x, p.x - c);
|
||||
let (m10, m11, r1) = (d - g * p.y, e - h * p.y, p.y - f);
|
||||
let det = m00 * m11 - m01 * m10;
|
||||
let (u, v) = ((r0 * m11 - m01 * r1) / det, (m00 * r1 - r0 * m10) / det);
|
||||
Point::new(origin.x + u * size.0, origin.y + v * size.1)
|
||||
}
|
||||
};
|
||||
q.is_finite().then_some(q)
|
||||
}
|
||||
|
||||
/// The affine map nearest this one around `p`, for gradients and patterns.
|
||||
fn local(&self, p: Point, step: f64) -> Affine {
|
||||
match self {
|
||||
Mapper::Affine(a) => *a,
|
||||
Mapper::Quad { .. } => {
|
||||
let (o, x, y) = (self.at(p), self.at(Point::new(p.x + step, p.y)), self.at(Point::new(p.x, p.y + step)));
|
||||
let (dx, dy) = ((x - o) / step, (y - o) / step);
|
||||
Affine::new([dx.x, dx.y, dy.x, dy.y, o.x - dx.x * p.x - dy.x * p.y, o.y - dx.y * p.x - dy.y * p.y])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The projective map of `cell`, a cell whose flat corners are those of an upright rectangle, in
|
||||
/// order along its edge nearest the origin and back: exact for a flat wall under a perspective. `None`
|
||||
/// for any other cell and for a quadrilateral the map turns inside out.
|
||||
fn quad_mapper(cell: &MapCell) -> Option<(Vec<Point>, Mapper)> {
|
||||
let [mut u0, mut u1, mut u2, mut u3] = <[Point; 4]>::try_from(cell.uv.as_slice()).ok()?;
|
||||
let [mut p0, mut p1, mut p2, mut p3] = <[Point; 4]>::try_from(cell.page.as_slice()).ok()?;
|
||||
// A cell whose first edge runs from right to left is read from its other end.
|
||||
if u1.x < u0.x {
|
||||
(u0, u1, u2, u3) = (u1, u0, u3, u2);
|
||||
(p0, p1, p2, p3) = (p1, p0, p3, p2);
|
||||
}
|
||||
let size = (u1.x - u0.x, u3.y - u0.y);
|
||||
let upright = u1.y == u0.y && u2.x == u1.x && u2.y == u3.y && u3.x == u0.x && size.0 > 1e-9 && size.1 > 1e-9;
|
||||
if !upright {
|
||||
return None;
|
||||
}
|
||||
let (dx1, dx2, sx) = (p1.x - p2.x, p3.x - p2.x, p0.x - p1.x + p2.x - p3.x);
|
||||
let (dy1, dy2, sy) = (p1.y - p2.y, p3.y - p2.y, p0.y - p1.y + p2.y - p3.y);
|
||||
let den = dx1 * dy2 - dx2 * dy1;
|
||||
let scale = dx1.abs() + dx2.abs() + dy1.abs() + dy2.abs();
|
||||
if den.is_nan() || den.abs() <= 1e-12 * scale * scale {
|
||||
return None;
|
||||
}
|
||||
let (g, h) = ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den);
|
||||
let rows = [p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x, p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y, g, h];
|
||||
let inside = g + 1.0 > 1e-6 && h + 1.0 > 1e-6 && g + h + 1.0 > 1e-6;
|
||||
(inside && rows.iter().all(|v| v.is_finite())).then(|| (vec![u0, u1, u2, u3], Mapper::Quad { origin: u0, size, rows }))
|
||||
}
|
||||
|
||||
/// The regions of `cell` on its flat surface, each a convex polygon wound as [`clip_convex`] reads
|
||||
/// it, with its map onto the page: the whole of an upright rectangle ([`quad_mapper`]), else the
|
||||
/// triangles the cell is cut into.
|
||||
fn regions(cell: &MapCell) -> Vec<(Vec<Point>, Mapper)> {
|
||||
if let Some(quad) = quad_mapper(cell) {
|
||||
return vec![quad];
|
||||
}
|
||||
let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
|
||||
triangles
|
||||
.iter()
|
||||
.filter_map(|corners| {
|
||||
let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::<Option<Vec<Point>>>();
|
||||
let (uv, page) = (pick(&cell.uv)?, pick(&cell.page)?);
|
||||
Some((counterclockwise(&uv)?.to_vec(), Mapper::Affine(triangle_map(&uv, &page)?)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for
|
||||
/// each of its edges), wound so that its inside is on the positive side of each edge.
|
||||
fn clip_convex(polygon: &[Point], window: &[Point]) -> Vec<Point> {
|
||||
let mut out = polygon.to_vec();
|
||||
for (k, &a) in window.iter().enumerate() {
|
||||
let Some(&b) = window.get((k + 1) % window.len()) else { continue };
|
||||
let side = |p: Point| (b - a).cross(p - a);
|
||||
let input = std::mem::take(&mut out);
|
||||
for (i, &p) in input.iter().enumerate() {
|
||||
let Some(&q) = input.get((i + 1) % input.len()) else { continue };
|
||||
let (sp, sq) = (side(p), side(q));
|
||||
if sp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (sp >= 0.0) != (sq >= 0.0) {
|
||||
out.push(p.lerp(q, sp / (sp - sq)));
|
||||
}
|
||||
}
|
||||
if out.len() < 3 {
|
||||
return vec![];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How far `p` lies outside the convex `polygon`, wound with its inside on the positive side of each
|
||||
/// edge, across the edges for which `counts` holds: 0 or less when it lies inside them.
|
||||
fn beyond(polygon: &[Point], p: Point, counts: &dyn Fn(Point, Point) -> bool) -> f64 {
|
||||
let mut most = f64::NEG_INFINITY;
|
||||
for (k, &a) in polygon.iter().enumerate() {
|
||||
let Some(&b) = polygon.get((k + 1) % polygon.len()) else { continue };
|
||||
let length = (b - a).hypot();
|
||||
if length > 0.0 && counts(a, b) {
|
||||
most = most.max(-(b - a).cross(p - a) / length);
|
||||
}
|
||||
}
|
||||
most
|
||||
}
|
||||
|
||||
/// `regions` of `cell` ([`regions`]) with the edges they share with the cell's own outline moved out
|
||||
/// on the flat surface, far enough that their maps reach the outline of facet `f` where its curved
|
||||
/// edges bow out of the cell: each outline point is taken back onto the flat surface through the
|
||||
/// region's own map. The edge between two triangles stays, so the regions do not overlap. A region
|
||||
/// moves out at most four times the size of the cell, and one whose projective map would turn
|
||||
/// inside out where it reaches stays as it is. Without a curved outline, or where the outline stays
|
||||
/// inside the cell, the regions are returned unchanged.
|
||||
fn reaching_outline(regions: Vec<(Vec<Point>, Mapper)>, cell: &MapCell, f: &Facet) -> Vec<(Vec<Point>, Mapper)> {
|
||||
let Some(outline) = f.outline.as_ref() else { return regions };
|
||||
let Some(uv) = box_of(&cell.uv) else { return regions };
|
||||
// The cell on the page, wound with its inside on the positive side of each edge.
|
||||
let mut around = cell.page.clone();
|
||||
let turn: f64 = around.iter().zip(around.iter().cycle().skip(1)).map(|(a, b)| a.to_vec2().cross(b.to_vec2())).sum();
|
||||
if turn < 0.0 {
|
||||
around.reverse();
|
||||
}
|
||||
// The points of the outline that lie outside the cell on the page, or near enough that the
|
||||
// curve between them may: the curve strays from its flattened points by up to the tolerance,
|
||||
// so each point counts as the corners of a square of that half width around it.
|
||||
let mut out = vec![];
|
||||
let outline = outline.to_bezpath();
|
||||
let t = SURFACE_TOLERANCE;
|
||||
vectorcraft_geom::kurbo::flatten(outline.elements().iter().copied(), t, |el| {
|
||||
if let vectorcraft_geom::kurbo::PathEl::MoveTo(p) | vectorcraft_geom::kurbo::PathEl::LineTo(p) = el
|
||||
&& beyond(&around, p, &|_, _| true) > -2.0 * t
|
||||
{
|
||||
out.extend([(t, t), (t, -t), (-t, t), (-t, -t)].map(|(x, y)| p + vectorcraft_geom::Vec2::new(x, y)));
|
||||
}
|
||||
});
|
||||
if out.is_empty() {
|
||||
return regions;
|
||||
}
|
||||
let most = 4.0 * uv.width().hypot(uv.height());
|
||||
let on_outline = |a: Point, b: Point| {
|
||||
let at = |q: Point| cell.uv.iter().position(|u| *u == q);
|
||||
let count = cell.uv.len();
|
||||
matches!((at(a), at(b)), (Some(i), Some(j)) if (i + 1) % count == j || (j + 1) % count == i)
|
||||
};
|
||||
regions
|
||||
.into_iter()
|
||||
.map(|(window, mapper)| {
|
||||
let reach = out.iter().filter_map(|p| mapper.back(*p)).map(|q| beyond(&window, q, &on_outline)).fold(0.0f64, f64::max);
|
||||
if reach <= 0.0 {
|
||||
return (window, mapper);
|
||||
}
|
||||
// A little past the farthest point, so the cut to the outline meets it.
|
||||
let reach = (reach * 1.01 + 1e-9).min(most);
|
||||
let grown = grown_window(&window, reach, &on_outline);
|
||||
let holds = match &mapper {
|
||||
Mapper::Affine(_) => true,
|
||||
Mapper::Quad { origin, size, rows } => grown.iter().all(|p| {
|
||||
let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1);
|
||||
rows[6] * u + rows[7] * v + 1.0 > 1e-6
|
||||
}),
|
||||
};
|
||||
(if holds && grown.len() == window.len() { grown } else { window }, mapper)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The convex `window`, wound as [`clip_convex`] reads it, with each edge for which `moves` holds
|
||||
/// moved out by `by`, and its corners where the moved edges meet.
|
||||
fn grown_window(window: &[Point], by: f64, moves: &dyn Fn(Point, Point) -> bool) -> Vec<Point> {
|
||||
let count = window.len();
|
||||
// Each edge as a point on its line and its direction, moved out where it moves.
|
||||
let lines: Vec<(Point, vectorcraft_geom::Vec2)> = (0..count)
|
||||
.filter_map(|k| {
|
||||
let (a, b) = (*window.get(k)?, *window.get((k + 1) % count)?);
|
||||
let d = b - a;
|
||||
let length = d.hypot();
|
||||
let out = if moves(a, b) && length > 0.0 { vectorcraft_geom::Vec2::new(d.y, -d.x) * (by / length) } else { vectorcraft_geom::Vec2::ZERO };
|
||||
Some((a + out, d))
|
||||
})
|
||||
.collect();
|
||||
(0..count)
|
||||
.filter_map(|k| {
|
||||
let ((p1, d1), (p2, d2)) = (*lines.get((k + count - 1) % count)?, *lines.get(k)?);
|
||||
let den = d1.cross(d2);
|
||||
if den.abs() <= 1e-12 * d1.hypot() * d2.hypot() {
|
||||
return Some(p2);
|
||||
}
|
||||
let t = (p2 - p1).cross(d2) / den;
|
||||
let p = p1 + d1 * t;
|
||||
p.is_finite().then_some(p)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The parts of `pieces`, a map's art on its flat surface, that fall on `cell`, the cell of facet
|
||||
/// `f`, drawn on the page. `None` past the limits.
|
||||
fn cell_art(
|
||||
id: NodeId,
|
||||
pieces: &[Unrolled],
|
||||
cell: &MapCell,
|
||||
f: &Facet,
|
||||
recolor: &dyn Fn(Color) -> Color,
|
||||
budget: &mut MapBudget,
|
||||
copies: &mut usize,
|
||||
) -> Option<Vec<Arc<Node>>> {
|
||||
if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) {
|
||||
return Some(vec![]);
|
||||
}
|
||||
let Some(reach) = box_of(&cell.uv) else { return Some(vec![]) };
|
||||
// A facet cut after it was built, or one whose edges follow the profile's curves, draws only the
|
||||
// part of the art inside its own outline, which the regions reach where it bows out of the cell.
|
||||
let whole = f.outline.is_none() && f.contours.first() == Some(&cell.page);
|
||||
let regions = if whole { regions(cell) } else { reaching_outline(regions(cell), cell, f) };
|
||||
let within = regions.iter().filter_map(|(w, _)| box_of(w)).fold(reach, |a, b| a.union(b));
|
||||
let apart = |b: &Rect| b.x1 < within.x0 || b.x0 > within.x1 || b.y1 < within.y0 || b.y0 > within.y1;
|
||||
let mut out = vec![];
|
||||
for piece in pieces.iter().filter(|p| !apart(&p.bounds)) {
|
||||
// Each contour's bounds test counts as one point cut, whether or not the contour reaches
|
||||
// the cell.
|
||||
budget.cuts = budget.cuts.saturating_add(piece.boxes.len());
|
||||
if budget.cuts > MAX_SURFACE_CUTS {
|
||||
return None;
|
||||
}
|
||||
let near: Vec<&Vec<Point>> = piece.polygons.iter().zip(&piece.boxes).filter(|(_, b)| !apart(b)).map(|(p, _)| p).collect();
|
||||
let mut path = BezPath::new();
|
||||
for (window, mapper) in ®ions {
|
||||
for polygon in &near {
|
||||
budget.cuts = budget.cuts.saturating_add(polygon.len());
|
||||
if budget.cuts > MAX_SURFACE_CUTS {
|
||||
return None;
|
||||
}
|
||||
let cut = clip_convex(polygon, window);
|
||||
let Some((first, rest)) = cut.split_first() else { continue };
|
||||
path.move_to(mapper.at(*first));
|
||||
rest.iter().for_each(|q| path.line_to(mapper.at(*q)));
|
||||
path.close_path();
|
||||
budget.points = budget.points.saturating_add(cut.len());
|
||||
}
|
||||
}
|
||||
if budget.points > MAX_SURFACE_POINTS {
|
||||
return None;
|
||||
}
|
||||
if path.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (path, rule) = if whole {
|
||||
(path, piece.rule)
|
||||
} else {
|
||||
let cut = vectorcraft_pathops::boolean(
|
||||
&PathData::from_bezpath(&path),
|
||||
piece.rule,
|
||||
&f.path(),
|
||||
FillRule::NonZero,
|
||||
vectorcraft_pathops::BoolOp::Intersect,
|
||||
);
|
||||
(cut.to_bezpath(), FillRule::NonZero)
|
||||
};
|
||||
if path.elements().is_empty() || !path.elements().iter().all(el_is_finite) {
|
||||
continue;
|
||||
}
|
||||
let seam = takes_seam(piece);
|
||||
if !crate::revolve::paint_copies_add(copies, 1 + usize::from(seam), &piece.paint) {
|
||||
return None;
|
||||
}
|
||||
// Gradients and patterns follow the cell's map as it is at the cell's middle.
|
||||
let middle = reach.center();
|
||||
let local = regions.first().map_or(Affine::IDENTITY, |(_, m)| m.local(middle, (reach.width().max(reach.height()) * 1e-3).max(1e-6)));
|
||||
let node = piece_node(
|
||||
id,
|
||||
piece.paint.clone(),
|
||||
(piece.opacity, piece.blend),
|
||||
(path, rule),
|
||||
local * piece.place,
|
||||
recolor,
|
||||
seam.then_some(SURFACE_SEAM),
|
||||
);
|
||||
out.push(Arc::new(node));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn el_is_finite(el: &vectorcraft_geom::kurbo::PathEl) -> bool {
|
||||
use vectorcraft_geom::kurbo::PathEl;
|
||||
match *el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) => p.is_finite(),
|
||||
PathEl::QuadTo(a, p) => a.is_finite() && p.is_finite(),
|
||||
PathEl::CurveTo(a, b, p) => a.is_finite() && b.is_finite() && p.is_finite(),
|
||||
PathEl::ClosePath => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// One painted area of mapped art on the page: `path` filled under `rule` with `paint`, its
|
||||
/// gradients and pattern tiles placed through `gradient_map`, its colors through `recolor`, and
|
||||
/// with `seam` a stroke of that width in the same paint over the seams between neighboring parts.
|
||||
fn piece_node(
|
||||
id: NodeId,
|
||||
mut paint: Paint,
|
||||
(opacity, blend): (f32, vectorcraft_doc::color::BlendMode),
|
||||
(path, rule): (BezPath, FillRule),
|
||||
gradient_map: Affine,
|
||||
recolor: &dyn Fn(Color) -> Color,
|
||||
seam: Option<f64>,
|
||||
) -> Node {
|
||||
if let Paint::Pattern { xf, .. } = &mut paint {
|
||||
*xf = gradient_map * *xf;
|
||||
}
|
||||
let mut fill = FillLayer::new(paint);
|
||||
fill.opacity = opacity;
|
||||
fill.blend = blend;
|
||||
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
|
||||
appearance.transform_gradients(gradient_map);
|
||||
for item in appearance.items.iter_mut() {
|
||||
if let AppearanceItem::Fill(f) = item {
|
||||
// Pattern tiles keep their colors: the document's pattern draws them.
|
||||
vectorcraft_doc::recolor::map_paint(&mut f.paint, recolor);
|
||||
}
|
||||
}
|
||||
if let (Some(width), Some(AppearanceItem::Fill(f))) = (seam, appearance.items.first()) {
|
||||
let mut stroke = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), width);
|
||||
stroke.join = vectorcraft_doc::LineJoin::Round;
|
||||
appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
}
|
||||
let mut node = Node::path(id, PathData::from_bezpath(&path), appearance);
|
||||
if let NodeKind::Path { rule: r, .. } = &mut node.kind {
|
||||
*r = rule;
|
||||
}
|
||||
node
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests_map_art.rs"]
|
||||
mod tests;
|
||||
@@ -801,6 +801,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
|
||||
surface: None,
|
||||
membrane: None,
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
cell: None,
|
||||
};
|
||||
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
|
||||
// z = x - 8: behind the wall left of x = 8, in front of it right of it.
|
||||
|
||||
@@ -187,6 +187,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() {
|
||||
surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }),
|
||||
membrane: None,
|
||||
plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
cell: None,
|
||||
}
|
||||
};
|
||||
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
|
||||
|
||||
@@ -0,0 +1,710 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Symbol;
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use super::super::super::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, MapSurface, map_surfaces_at, solid_art_in, validate_three_d_at_in, validate_three_d_in};
|
||||
use super::*;
|
||||
use crate::CLASSIC_REVOLVE;
|
||||
|
||||
const RED: Color = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 };
|
||||
const GREEN: Color = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 };
|
||||
const BLUE: Color = Color::Rgb { r: 0.0, g: 0.0, b: 1.0 };
|
||||
|
||||
fn square(id: u64, r: Rect, c: Color) -> Node {
|
||||
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// A document with symbol "Mark", a red 10 × 10 square, and symbol "Corner", 30 × 30: a red square
|
||||
/// at its top left, a blue one to the right of it and a green one below it.
|
||||
fn document() -> Document {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), RED)) });
|
||||
let corner = Node::group(
|
||||
NodeId(0),
|
||||
vec![
|
||||
Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), RED)),
|
||||
Arc::new(square(0, Rect::new(20.0, 0.0, 30.0, 10.0), BLUE)),
|
||||
Arc::new(square(0, Rect::new(0.0, 20.0, 10.0, 30.0), GREEN)),
|
||||
],
|
||||
);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Corner".into(), art: Arc::new(corner) });
|
||||
d
|
||||
}
|
||||
|
||||
/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view
|
||||
/// straight on with No Shading.
|
||||
fn object(id: &str, params: Value) -> Node {
|
||||
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "surface": "none"});
|
||||
if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) {
|
||||
p.extend(extra.clone());
|
||||
}
|
||||
let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.5, 0.5, 0.5));
|
||||
n.appearance.effects.push(crate::new_effect(id, &p).unwrap());
|
||||
n
|
||||
}
|
||||
|
||||
/// The paths of `art` filled with color `c`, in drawing order.
|
||||
fn filled(art: &Node, c: Color) -> Vec<PathData> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
let fill = n.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.color(),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
});
|
||||
if fill.is_some_and(|f| f.to_rgb().iter().zip(c.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4))
|
||||
&& let Some(p) = n.path_data()
|
||||
{
|
||||
out.push(p.clone());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn bounds_of(paths: &[PathData]) -> Rect {
|
||||
paths.iter().filter_map(|p| p.bounds()).reduce(|a, b| a.union(b)).unwrap()
|
||||
}
|
||||
|
||||
fn close(a: Rect, b: Rect) -> bool {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6)
|
||||
}
|
||||
|
||||
fn surfaces(n: &Node) -> Vec<MapSurface> {
|
||||
map_surfaces_at(Some(&document()), n, None, 0).unwrap()
|
||||
}
|
||||
|
||||
/// Which way round the "Corner" symbol reads in `art`: positive when its blue square is to the
|
||||
/// right of its red one and its green one below, as the symbol is drawn, at any turn; negative
|
||||
/// when it is mirrored.
|
||||
fn handedness(art: &Node) -> f64 {
|
||||
let at = |c: Color| bounds_of(&filled(art, c)).center();
|
||||
(at(BLUE) - at(RED)).cross(at(GREEN) - at(RED))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_surfaces_are_the_caps_then_each_wall_then_each_bevel() {
|
||||
let kinds = |n: &Node| surfaces(n).iter().map(|s| s.kind).collect::<Vec<_>>();
|
||||
let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back));
|
||||
let solid = object(CLASSIC_EXTRUDE, json!({}));
|
||||
assert_eq!(kinds(&solid), [vec![front, back], vec![SurfaceKind::Wall; 4]].concat());
|
||||
// Each wall runs from corner to corner of the square and is as deep as the solid.
|
||||
for wall in surfaces(&solid).iter().skip(2) {
|
||||
assert!((wall.width - 100.0).abs() < 1e-6 && (wall.height - 50.0).abs() < 1e-6, "{wall:?}");
|
||||
}
|
||||
assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"cap": false}))), vec![SurfaceKind::Wall; 4]);
|
||||
let beveled = object(CLASSIC_EXTRUDE, json!({"bevel": "classic"}));
|
||||
assert_eq!(kinds(&beveled), [vec![front, back], vec![SurfaceKind::Wall; 4], vec![SurfaceKind::Bevel; 4]].concat());
|
||||
// With no depth the art is a plane, which has its front only.
|
||||
assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"depth": 0}))), vec![front]);
|
||||
// An outline with no corner has one wall.
|
||||
let mut round = Node::path(NodeId(7), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
round.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({})).unwrap());
|
||||
assert_eq!(kinds(&round), vec![front, back, SurfaceKind::Wall]);
|
||||
// Revolve (Classic) has its side, and Rotate (Classic) takes no maps.
|
||||
assert_eq!(kinds(&object(CLASSIC_REVOLVE, json!({}))), vec![SurfaceKind::Side]);
|
||||
assert_eq!(map_surfaces_at(Some(&document()), &object(CLASSIC_ROTATE, json!({})), None, 0), None);
|
||||
// Seen straight on, only the front cap is turned toward the viewer.
|
||||
let seen: Vec<bool> = surfaces(&solid).iter().map(|s| s.visible).collect();
|
||||
assert_eq!(seen, [true, false, false, false, false, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bevel_as_deep_as_the_solid_leaves_no_walls_and_its_bevels_take_their_maps() {
|
||||
let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back));
|
||||
let solid = |maps: Value| object(CLASSIC_EXTRUDE, json!({"depth": 10, "bevel": "classic", "bevelHeight": 10, "mapArt": maps}));
|
||||
let kinds: Vec<SurfaceKind> = surfaces(&solid(json!([]))).iter().map(|s| s.kind).collect();
|
||||
assert_eq!(kinds, [vec![front, back], vec![SurfaceKind::Bevel; 4]].concat());
|
||||
// Seen straight on, the front bevels draw the art mapped onto them.
|
||||
let bevels: Vec<Value> = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect();
|
||||
let art = solid_art_in(Some(&document()), &solid(json!(bevels))).unwrap();
|
||||
assert!(!filled(&art, RED).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_on_the_front_cap_draws_the_symbol_at_its_offset_scales_and_turn() {
|
||||
let d = document();
|
||||
let map = |m: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": [m]}))).unwrap();
|
||||
// Without a map nothing red is drawn.
|
||||
assert!(filled(&solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({}))).unwrap(), RED).is_empty());
|
||||
// The art's center is at the center of the cap, its size the symbol's own.
|
||||
let centered = filled(&map(json!({"surface": 1, "symbol": "Mark"})), RED);
|
||||
assert!(close(bounds_of(¢ered), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds_of(¢ered));
|
||||
// An offset moves it, and each scale sizes one side.
|
||||
let moved = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 10, "y": -5, "scaleX": 200, "scaleY": 300})), RED);
|
||||
assert!(close(bounds_of(&moved), Rect::new(50.0, 30.0, 70.0, 60.0)), "{:?}", bounds_of(&moved));
|
||||
// A quarter turn swaps the sides.
|
||||
let turned = filled(&map(json!({"surface": 1, "symbol": "Mark", "scaleX": 200, "rotation": 90})), RED);
|
||||
assert!(close(bounds_of(&turned), Rect::new(45.0, 40.0, 55.0, 60.0)), "{:?}", bounds_of(&turned));
|
||||
// The art is clipped to the cap.
|
||||
let past = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 50})), RED);
|
||||
assert_eq!(past.len(), 1);
|
||||
let art = map(json!({"surface": 1, "symbol": "Mark", "x": 50}));
|
||||
let mut clipped = false;
|
||||
art.walk(&mut |n| clipped |= matches!(&n.kind, NodeKind::Group { clip: true, .. }));
|
||||
assert!(clipped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_on_a_side_wall_reads_the_right_way_round_from_outside() {
|
||||
let d = document();
|
||||
let all_walls: Vec<Value> = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect();
|
||||
for turn in [-90.0, 90.0] {
|
||||
// Seen from one side, one wall faces the viewer: it alone carries its map.
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"rotationY": turn, "mapArt": all_walls}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
assert_eq!(filled(&art, RED).len(), 1, "one wall is seen at {turn}");
|
||||
// The wall is 100 along the outline and 50 deep: the art keeps its size at its middle.
|
||||
let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat());
|
||||
assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "{whole:?}");
|
||||
assert!((whole.center().x - 50.0).abs() < 1e-6 && (whole.center().y - 50.0).abs() < 1e-6, "{whole:?}");
|
||||
assert!(handedness(&art) > 0.0, "the art is mirrored at {turn}");
|
||||
}
|
||||
// The walls seen from above and below read the right way round too.
|
||||
for turn in [-90.0, 90.0] {
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"rotationX": turn, "mapArt": all_walls}));
|
||||
assert!(handedness(&solid_art_in(Some(&d), &n).unwrap()) > 0.0, "the art is mirrored at {turn}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wall_beside_a_bevel_is_laid_out_at_its_own_length() {
|
||||
let d = document();
|
||||
// A bevel 10 wide added around the square sets each wall 10 out, so each wall is 120 long; a
|
||||
// bevel takes the length of the wall it sits above. Carved in, the walls are the square's own.
|
||||
for (inside, length) in [(false, 120.0), (true, 100.0)] {
|
||||
let solid = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside}));
|
||||
for side in surfaces(&solid).iter().skip(2) {
|
||||
assert!((side.width - length).abs() < 1e-6, "inside {inside}: {side:?}");
|
||||
}
|
||||
// Seen from one side, the art on the wall that faces the viewer keeps its size.
|
||||
let walls: Vec<Value> = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect();
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside, "rotationY": 90, "mapArt": walls}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat());
|
||||
assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "inside {inside}: {whole:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() {
|
||||
let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
// The facet's top edge follows a curve that bows into the quad, down to y = 2.
|
||||
let mut curved = BezPath::new();
|
||||
curved.move_to((0.0, 0.0));
|
||||
curved.curve_to((10.0 / 3.0, 8.0 / 3.0), (20.0 / 3.0, 8.0 / 3.0), (10.0, 0.0));
|
||||
curved.line_to((10.0, 10.0));
|
||||
curved.line_to((0.0, 10.0));
|
||||
curved.close_path();
|
||||
let facet = Facet {
|
||||
contours: vec![quad.clone()],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
rgb_gradient: None,
|
||||
outline: Some(PathData::from_bezpath(&curved)),
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
plane: None,
|
||||
surface: None,
|
||||
membrane: None,
|
||||
cell: None,
|
||||
};
|
||||
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad.clone() };
|
||||
let whole = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
let art = Unrolled {
|
||||
polygons: vec![quad],
|
||||
boxes: vec![whole],
|
||||
bounds: whole,
|
||||
rule: FillRule::NonZero,
|
||||
paint: Paint::solid(RED),
|
||||
opacity: 1.0,
|
||||
blend: Default::default(),
|
||||
place: Affine::IDENTITY,
|
||||
};
|
||||
let (mut budget, mut copies) = (MapBudget::default(), 0);
|
||||
let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap();
|
||||
let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum();
|
||||
let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs();
|
||||
assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() {
|
||||
let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
// The facet's top edge follows a curve that bows out of the quad, up to y = -2.
|
||||
let mut curved = BezPath::new();
|
||||
curved.move_to((0.0, 0.0));
|
||||
curved.curve_to((10.0 / 3.0, -8.0 / 3.0), (20.0 / 3.0, -8.0 / 3.0), (10.0, 0.0));
|
||||
curved.line_to((10.0, 10.0));
|
||||
curved.line_to((0.0, 10.0));
|
||||
curved.close_path();
|
||||
let facet = Facet {
|
||||
contours: vec![quad.clone()],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
rgb_gradient: None,
|
||||
outline: Some(PathData::from_bezpath(&curved)),
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
plane: None,
|
||||
surface: None,
|
||||
membrane: None,
|
||||
cell: None,
|
||||
};
|
||||
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad };
|
||||
// Art that covers the facet and more.
|
||||
let cover = vec![Point::new(-5.0, -5.0), Point::new(15.0, -5.0), Point::new(15.0, 15.0), Point::new(-5.0, 15.0)];
|
||||
let whole = Rect::new(-5.0, -5.0, 15.0, 15.0);
|
||||
let art = Unrolled {
|
||||
polygons: vec![cover],
|
||||
boxes: vec![whole],
|
||||
bounds: whole,
|
||||
rule: FillRule::NonZero,
|
||||
paint: Paint::solid(RED),
|
||||
opacity: 1.0,
|
||||
blend: Default::default(),
|
||||
place: Affine::IDENTITY,
|
||||
};
|
||||
let (mut budget, mut copies) = (MapBudget::default(), 0);
|
||||
let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap();
|
||||
let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum();
|
||||
let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs();
|
||||
assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() {
|
||||
let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
let facet = Facet {
|
||||
contours: vec![quad.clone()],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
rgb_gradient: None,
|
||||
outline: None,
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
plane: None,
|
||||
surface: None,
|
||||
membrane: None,
|
||||
cell: None,
|
||||
};
|
||||
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad };
|
||||
// Small contours on either side of the cell: the piece's bounds reach across it, but no
|
||||
// contour's own bounds do.
|
||||
let polygons: Vec<Vec<Point>> = (0..2000)
|
||||
.map(|k| {
|
||||
let x = if k % 2 == 0 { -1000.0 } else { 1000.0 };
|
||||
vec![Point::new(x, 0.0), Point::new(x + 1.0, 0.0), Point::new(x + 1.0, 1.0)]
|
||||
})
|
||||
.collect();
|
||||
let boxes: Vec<Rect> = polygons.iter().filter_map(|p| box_of(p)).collect();
|
||||
let art = Unrolled {
|
||||
polygons,
|
||||
boxes,
|
||||
bounds: Rect::new(-1000.0, 0.0, 1001.0, 1.0),
|
||||
rule: FillRule::NonZero,
|
||||
paint: Paint::solid(RED),
|
||||
opacity: 1.0,
|
||||
blend: Default::default(),
|
||||
place: Affine::IDENTITY,
|
||||
};
|
||||
let mut budget = MapBudget { cuts: MAX_SURFACE_CUTS - 10, ..MapBudget::default() };
|
||||
assert!(cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_on_the_back_cap_reads_the_right_way_round_from_behind() {
|
||||
let d = document();
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"rotationY": 180, "mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 2, "symbol": "Corner"}]}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
// Only the back cap is seen, and it carries its own map's art.
|
||||
assert_eq!(filled(&art, RED).len(), 1);
|
||||
assert_eq!((filled(&art, BLUE).len(), filled(&art, GREEN).len()), (1, 1));
|
||||
assert!(handedness(&art) > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_past_the_shared_limits_leaves_out_the_mapped_art_of_every_solid() {
|
||||
let mut d = document();
|
||||
// A zigzag of half the straight sides one 3D effect's mapped art may draw.
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 0.0));
|
||||
for i in 1..=MAX_ELEMENTS / 2 {
|
||||
b.line_to((i as f64 * 0.00005, (i % 2) as f64));
|
||||
}
|
||||
b.close_path();
|
||||
let half = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Half".into(), art: Arc::new(half) });
|
||||
let gray = Color::rgb(0.5, 0.5, 0.5);
|
||||
// A group of two squares: the first solid's front is surface 1, the second's surface 7.
|
||||
let art = |maps: Value, invisible: bool| {
|
||||
let members =
|
||||
vec![Arc::new(square(8, Rect::new(0.0, 0.0, 100.0, 100.0), gray)), Arc::new(square(9, Rect::new(200.0, 0.0, 300.0, 100.0), gray))];
|
||||
let mut g = Node::group(NodeId(7), members);
|
||||
let p = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "mapInvisible": invisible, "mapArt": maps});
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &p).unwrap());
|
||||
solid_art_in(Some(&d), &g).unwrap()
|
||||
};
|
||||
// One solid's art fits.
|
||||
assert!(!filled(&art(json!([{"surface": 1, "symbol": "Half"}]), false), RED).is_empty());
|
||||
// Both together are past the limit: no solid draws its art, and with Invisible Geometry every
|
||||
// solid's faces draw.
|
||||
let both = json!([{"surface": 1, "symbol": "Half"}, {"surface": 7, "symbol": "Half"}]);
|
||||
assert!(filled(&art(both.clone(), false), RED).is_empty());
|
||||
let hidden = art(both, true);
|
||||
assert!(filled(&hidden, RED).is_empty());
|
||||
let faces = bounds_of(&filled(&hidden, gray));
|
||||
assert!(faces.x0 < 1.0 && faces.x1 > 299.0, "{faces:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wall_under_a_perspective_maps_its_art_whole() {
|
||||
let d = document();
|
||||
let all_walls: Vec<Value> = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect();
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"rotationY": -60, "perspectiveAngle": 90, "mapArt": all_walls}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
// The wall is one flat face: the square maps onto it as one four-cornered area, not as two
|
||||
// pieces that meet along the face's diagonal.
|
||||
let marks = filled(&art, RED);
|
||||
assert_eq!(marks.len(), 1);
|
||||
let mark = &marks[0];
|
||||
assert_eq!((mark.subpaths.len(), mark.subpaths[0].anchors.len()), (1, 4), "{mark:?}");
|
||||
// Nearer the viewer the square's side is longer.
|
||||
let side = |i: usize| mark.subpaths[0].anchors[i].p.distance(mark.subpaths[0].anchors[(i + 1) % 4].p);
|
||||
let uneven = (side(0) - side(2)).abs().max((side(1) - side(3)).abs());
|
||||
assert!(uneven > 0.05, "{} {} {} {}", side(0), side(1), side(2), side(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shade_artwork_and_invisible_geometry_change_what_is_drawn() {
|
||||
let d = document();
|
||||
let params = |extra: Value| {
|
||||
let mut p = json!({"surface": "diffuse", "rotationY": -60, "lightIntensity": 0, "ambient": 20, "mapArt": [{"surface": 1, "symbol": "Mark"}]});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, p)).unwrap()
|
||||
};
|
||||
// Unshaded, the art keeps its own color on a shaded face.
|
||||
assert_eq!(filled(¶ms(json!({})), RED).len(), 1);
|
||||
// Shaded, it darkens toward black with its face.
|
||||
let shaded = params(json!({"mapShade": true}));
|
||||
assert!(filled(&shaded, RED).is_empty());
|
||||
let mut darkest = 1.0f32;
|
||||
shaded.walk(&mut |n| {
|
||||
for item in &n.appearance.items {
|
||||
if let AppearanceItem::Fill(f) = item
|
||||
&& let Some([r, g, b]) = f.paint.color().map(|c| c.to_rgb())
|
||||
&& g < 1e-4
|
||||
&& b < 1e-4
|
||||
&& r > 0.0
|
||||
{
|
||||
darkest = darkest.min(r);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(darkest < 0.999, "the art is as dark as its face: {darkest}");
|
||||
// With Invisible Geometry only the art is drawn.
|
||||
let count = |art: &Node| {
|
||||
let mut paths = 0;
|
||||
art.walk(&mut |n| paths += usize::from(n.path_data().is_some() && !n.appearance.items.is_empty()));
|
||||
paths
|
||||
};
|
||||
assert!(count(¶ms(json!({}))) > 1);
|
||||
assert_eq!(count(¶ms(json!({"mapInvisible": true}))), 1);
|
||||
// Without a map Invisible Geometry leaves the solid as it is, and Wireframe draws no art.
|
||||
let plain = object(CLASSIC_EXTRUDE, json!({"mapInvisible": true}));
|
||||
assert!(count(&solid_art_in(Some(&d), &plain).unwrap()) > 0);
|
||||
assert!(filled(¶ms(json!({"surface": "wireframe"})), RED).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_past_the_surfaces_draws_nothing_and_a_missing_symbol_is_left_out() {
|
||||
let d = document();
|
||||
let art = |maps: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": maps}))).unwrap();
|
||||
assert!(filled(&art(json!([{"surface": 7, "symbol": "Mark"}])), RED).is_empty());
|
||||
assert!(filled(&art(json!([{"surface": 1, "symbol": "Gone"}])), RED).is_empty());
|
||||
// A hollow solid's first surface is its first wall, so the cap's map draws nothing there.
|
||||
let hollow = object(CLASSIC_EXTRUDE, json!({"cap": false, "mapArt": [{"surface": 1, "symbol": "Mark"}]}));
|
||||
assert!(filled(&solid_art_in(Some(&d), &hollow).unwrap(), RED).is_empty());
|
||||
assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Gone"}]})), Some("Gone".to_string()));
|
||||
assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_points_drawn_on_earlier_surfaces_leave_the_next_symbol_its_own_allowance() {
|
||||
let d = document();
|
||||
let art = MapArt::of(Some(&d), CLASSIC_EXTRUDE, &json!({"mapArt": [{"surface": 3, "symbol": "Mark"}]})).unwrap();
|
||||
let wall = SolidSurface { kind: SurfaceKind::Wall, width: 100.0, height: 50.0, center: None };
|
||||
// Earlier surfaces drew more points on their faces than one symbol may take cut into pieces.
|
||||
let mut budget = MapBudget { points: MAX_ELEMENTS + 1, ..MapBudget::default() };
|
||||
let pieces = art.unrolled(&art.maps[0], &wall, &mut budget).expect("the symbol is cut into pieces");
|
||||
assert_eq!(pieces.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_past_the_paint_copies_allowance_leaves_the_allowance_to_later_art() {
|
||||
let d = document();
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((100.0, 0.0));
|
||||
b.line_to((100.0, 100.0));
|
||||
let path = PathData::from_bezpath(&b);
|
||||
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
|
||||
let n = Node::path(NodeId(7), path.clone(), Appearance::basic(Paint::None, gray.clone(), 1.0));
|
||||
let p = crate::merged_params(
|
||||
CLASSIC_REVOLVE,
|
||||
&json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]}),
|
||||
);
|
||||
let art = MapArt::of(Some(&d), CLASSIC_REVOLVE, &p).unwrap();
|
||||
let bounds = path.bounds().unwrap();
|
||||
let options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(CLASSIC_REVOLVE, &p) };
|
||||
let (width, height) = vectorcraft_three_d::revolve_surface_size(&path, bounds, options).unwrap();
|
||||
let layout = SolidLayout { first: 0, surfaces: vec![SolidSurface { kind: SurfaceKind::Side, width, height, center: None }], ends: None };
|
||||
let facets = vectorcraft_three_d::revolve_facets(&path, bounds, options).unwrap();
|
||||
// The side's art, with the copies of its paint and its points counted from `copies` and
|
||||
// `budget` already used.
|
||||
let draw = |copies: &mut usize, budget: &mut MapBudget| {
|
||||
let mapped = crate::solids::classic::Mapped { art: &art, layout: &layout, budget, copies };
|
||||
let blend = vectorcraft_doc::color::BlendMode::Normal;
|
||||
crate::solids::classic::surface(&n, &facets, &gray, (1.0, blend), &p, Some(mapped), false).0
|
||||
};
|
||||
let (mut copies, mut budget) = (0, MapBudget::default());
|
||||
assert!(!filled(&draw(&mut copies, &mut budget), RED).is_empty());
|
||||
assert!(copies > 0 && budget != MapBudget::default());
|
||||
// With the allowance used up, the art is left out, and so are the copies and the points it
|
||||
// would have taken.
|
||||
let full = crate::revolve::MAX_PAINT_COPIES;
|
||||
let (mut copies, mut budget) = (full, MapBudget::default());
|
||||
assert!(filled(&draw(&mut copies, &mut budget), RED).is_empty());
|
||||
assert_eq!(copies, full);
|
||||
assert_eq!(budget, MapBudget::default());
|
||||
}
|
||||
|
||||
fn missing(d: &Document, p: &Value) -> Option<String> {
|
||||
super::super::missing_symbol(d, p, None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_classic_wraps_its_map_around_the_side() {
|
||||
let d = document();
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((100.0, 0.0));
|
||||
b.line_to((100.0, 100.0));
|
||||
let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0));
|
||||
let view =
|
||||
json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Corner"}]});
|
||||
n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &view).unwrap());
|
||||
let art = crate::revolve_art_in(Some(&d), &n).unwrap();
|
||||
// The art is drawn at the middle of the side that faces the viewer, the right way round.
|
||||
assert!(!filled(&art, RED).is_empty());
|
||||
assert!(handedness(&art) > 0.0);
|
||||
let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat());
|
||||
assert!((whole.center().y - 50.0).abs() < 1.0, "{whole:?}");
|
||||
// A map of another surface draws nothing.
|
||||
n.appearance.effects[0].params["mapArt"] = json!([{"surface": 2, "symbol": "Corner"}]);
|
||||
assert!(filled(&crate::revolve_art_in(Some(&d), &n).unwrap(), RED).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invisible_geometry_leaves_out_every_member_of_a_revolved_group() {
|
||||
let d = document();
|
||||
let gray = Color::rgb(0.5, 0.5, 0.5);
|
||||
let line = |id: u64, x: f64, height: f64| {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((x, 0.0));
|
||||
b.line_to((x, height));
|
||||
Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0)))
|
||||
};
|
||||
// The map goes on the side of the longer member; the shorter one has none.
|
||||
let art = |extra: Value| {
|
||||
let mut p =
|
||||
json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
let mut g = Node::group(NodeId(7), vec![line(8, 100.0, 100.0), line(9, 140.0, 30.0)]);
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &p).unwrap());
|
||||
crate::revolve_art_in(Some(&d), &g).unwrap()
|
||||
};
|
||||
let shown = art(json!({}));
|
||||
assert!(!filled(&shown, RED).is_empty() && !filled(&shown, gray).is_empty());
|
||||
let hidden = art(json!({"mapInvisible": true}));
|
||||
assert!(!filled(&hidden, RED).is_empty());
|
||||
assert!(filled(&hidden, gray).is_empty(), "no member's faces are drawn");
|
||||
// On Wireframe the members are drawn as they are without a map.
|
||||
let wire = art(json!({"mapInvisible": true, "surface": "wireframe"}));
|
||||
let mut strokes = 0;
|
||||
wire.walk(&mut |n| strokes += usize::from(n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_)))));
|
||||
assert!(strokes > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_revolved_group_past_its_shared_limits_lists_no_surface() {
|
||||
let gray = Color::rgb(0.5, 0.5, 0.5);
|
||||
// Profiles of five anchors each; one alone fits Revolve's limits.
|
||||
let profile = |id: u64, x: f64| {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((x, 0.0));
|
||||
for i in 1..5 {
|
||||
b.line_to((x + f64::from(i % 2), f64::from(i) * 10.0));
|
||||
}
|
||||
Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0)))
|
||||
};
|
||||
let group = |count: u64| {
|
||||
let mut g = Node::group(NodeId(7), (0..count).map(|k| profile(k + 8, 100.0 + k as f64 * 0.01)).collect());
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({})).unwrap());
|
||||
g
|
||||
};
|
||||
let d = document();
|
||||
assert_eq!(map_surfaces_at(Some(&d), &group(2), None, 0).map(|s| s.len()), Some(1));
|
||||
// 4,000 of them together are past the anchors the members share.
|
||||
assert!(map_surfaces_at(Some(&d), &group(4000), None, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_extruded_group_past_the_faces_of_one_object_lists_no_surface() {
|
||||
// Polygons of 1,000 corners: each solid alone has about 1,000 faces.
|
||||
let polygon = |id: u64, x: f64| {
|
||||
let mut b = BezPath::new();
|
||||
for i in 0..1000 {
|
||||
let a = f64::from(i) * std::f64::consts::TAU / 1000.0;
|
||||
let p = (x + 40.0 * a.cos(), 40.0 * a.sin());
|
||||
if i == 0 { b.move_to(p) } else { b.line_to(p) }
|
||||
}
|
||||
b.close_path();
|
||||
Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)))
|
||||
};
|
||||
let group = |count: u64| {
|
||||
let mut g = Node::group(NodeId(7), (0..count).map(|k| polygon(k + 8, k as f64 * 100.0)).collect());
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({"drawHiddenFaces": true})).unwrap());
|
||||
g
|
||||
};
|
||||
let d = document();
|
||||
assert!(map_surfaces_at(Some(&d), &group(2), None, 0).is_some());
|
||||
// 200 of them together have more faces than one object draws.
|
||||
assert!(map_surfaces_at(Some(&d), &group(200), None, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_maps_are_refused() {
|
||||
let d = document();
|
||||
let check = |id: &str, p: Value| {
|
||||
let n = object(id, json!({}));
|
||||
validate_three_d_in(Some(&d), &n, id, &crate::merged_params(id, &p))
|
||||
};
|
||||
assert_eq!(check(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 3, "symbol": "Mark", "scaleX": 50}]})), Ok(()));
|
||||
assert_eq!(check(CLASSIC_REVOLVE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}], "mapShade": true})), Ok(()));
|
||||
for (p, error) in [
|
||||
(json!({"mapArt": {}}), "`mapArt` must be an array"),
|
||||
(json!({"mapArt": [7]}), "each of `mapArt` must be an object"),
|
||||
(json!({"mapArt": [{"symbol": "Mark"}]}), "needs `surface`"),
|
||||
(json!({"mapArt": [{"surface": 0, "symbol": "Mark"}]}), "needs `surface`"),
|
||||
(json!({"mapArt": [{"surface": 1.5, "symbol": "Mark"}]}), "needs `surface`"),
|
||||
(json!({"mapArt": [{"surface": 100001, "symbol": "Mark"}]}), "needs `surface`"),
|
||||
(json!({"mapArt": [{"surface": 1}]}), "needs `symbol`"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark", "face": "front"}]}), "not `face`"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark", "scaleX": 0}]}), "scaleX must be a number from 1 to 10000"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark", "rotation": 361}]}), "rotation must be a number from -360 to 360"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark", "x": "left"}]}), "x must be a number"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}]}), "maps surface 1 more than once"),
|
||||
(json!({"mapShade": 1}), "`mapShade` must be true or false"),
|
||||
(json!({"mapInvisible": "yes"}), "`mapInvisible` must be true or false"),
|
||||
] {
|
||||
for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] {
|
||||
let e = check(id, p.clone()).unwrap_err();
|
||||
assert!(e.contains(error), "{id} {p}: {e}");
|
||||
}
|
||||
}
|
||||
let many: Vec<Value> = (1..=65).map(|k| json!({"surface": k, "symbol": "Mark"})).collect();
|
||||
assert!(check(CLASSIC_EXTRUDE, json!({"mapArt": many})).unwrap_err().contains("at most 64 maps"));
|
||||
// Rotate (Classic) has no surface to map onto.
|
||||
let e = check(CLASSIC_ROTATE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})).unwrap_err();
|
||||
assert!(e.contains(MAP_ART_NOT_TAKEN), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mapped_symbol_past_the_limits_of_a_graphics_art_is_refused() {
|
||||
let mut d = document();
|
||||
// A zigzag of more straight sides than one 3D effect's graphics may draw.
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 0.0));
|
||||
for i in 1..=MAX_ELEMENTS {
|
||||
b.line_to((i as f64 * 0.001, (i % 2) as f64));
|
||||
}
|
||||
b.close_path();
|
||||
let dense = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(dense) });
|
||||
for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] {
|
||||
let p = crate::merged_params(id, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]}));
|
||||
let e = validate_three_d_in(Some(&d), &object(id, json!({})), id, &p).unwrap_err();
|
||||
assert!(e.contains("too complex"), "{id}: {e}");
|
||||
}
|
||||
// On a fill, as on the object.
|
||||
let plain = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.5, 0.5, 0.5));
|
||||
let p = crate::merged_params(CLASSIC_REVOLVE, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]}));
|
||||
let e = validate_three_d_at_in(Some(&d), &plain, CLASSIC_REVOLVE, &p, (Some(0), 0)).unwrap_err();
|
||||
assert!(e.contains("too complex"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mapped_symbol_whose_curves_cut_into_too_many_pieces_is_refused() {
|
||||
let mut d = document();
|
||||
// Large circles: a few curves each, but many straight pieces once they are cut.
|
||||
let loops = |name: &str, count: usize| {
|
||||
let mut b = BezPath::new();
|
||||
for k in 0..count {
|
||||
let r = 1e5;
|
||||
let circle = vectorcraft_geom::kurbo::Circle::new((k as f64 * 2.1 * r, 0.0), r);
|
||||
b.extend(vectorcraft_geom::kurbo::Shape::path_elements(&circle, 0.1));
|
||||
}
|
||||
let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }
|
||||
};
|
||||
d.symbols.push(loops("Loop", 1));
|
||||
d.symbols.push(loops("Loops", 400));
|
||||
let check = |id: &str, surface: usize, symbol: &str| {
|
||||
let p = crate::merged_params(id, &json!({"mapArt": [{"surface": surface, "symbol": symbol}]}));
|
||||
validate_three_d_in(Some(&d), &object(id, json!({})), id, &p)
|
||||
};
|
||||
// Extrude & Bevel's surface 3 is a wall, and Revolve's surface 1 its side.
|
||||
for (id, surface) in [(CLASSIC_EXTRUDE, 3), (CLASSIC_REVOLVE, 1)] {
|
||||
assert_eq!(check(id, surface, "Loop"), Ok(()), "{id}");
|
||||
let e = check(id, surface, "Loops").unwrap_err();
|
||||
assert!(e.contains("too complex"), "{id}: {e}");
|
||||
}
|
||||
// A cap draws the curves as they are, without cutting them.
|
||||
assert_eq!(check(CLASSIC_EXTRUDE, 1, "Loops"), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_are_set_cleared_and_renamed_with_their_symbols() {
|
||||
let p = json!({"depth": 20});
|
||||
let map =
|
||||
|surface: usize, symbol: &str| SurfaceMap { surface, symbol: symbol.into(), x: 0.0, y: 0.0, scale_x: 100.0, scale_y: 100.0, rotation: 0.0 };
|
||||
let p = with_surface_map(&p, 4, Some(&map(4, "Mark")));
|
||||
let p = with_surface_map(&p, 2, Some(&map(2, "Corner")));
|
||||
let p = with_surface_map(&p, 4, Some(&map(4, "Corner")));
|
||||
// One map for a surface, in the order of the surfaces; the other parameters stay.
|
||||
assert_eq!(surface_maps(&p), vec![map(2, "Corner"), map(4, "Corner")]);
|
||||
assert_eq!(p["depth"], json!(20));
|
||||
assert_eq!(surface_maps(&with_surface_map(&p, 2, None)), vec![map(4, "Corner")]);
|
||||
// A file's maps: entries that are not valid and a surface's second map are left out.
|
||||
let loaded = json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}, {"surface": 0, "symbol": "Mark"}, 3]});
|
||||
assert_eq!(surface_maps(&loaded), vec![map(1, "Mark")]);
|
||||
// Renaming a symbol renames it in the maps of the effects that take them.
|
||||
let mut n = object(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]}));
|
||||
assert_eq!(super::super::graphic_symbols(&n), vec!["Mark".to_string()]);
|
||||
assert!(super::super::rename_graphic_symbol(&mut n, "Mark", "Logo"));
|
||||
assert_eq!(surface_maps(&n.appearance.effects[0].params)[0].symbol, "Logo");
|
||||
// Scale to Fit fills the surface: each side by its own scale when the art is square to it.
|
||||
assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)), Some((1000.0, 500.0)));
|
||||
let turned = SurfaceMap { rotation: 90.0, ..map(1, "Mark") };
|
||||
assert_eq!(turned.fitting_scales(Rect::new(0.0, 0.0, 10.0, 20.0), (100.0, 50.0)), Some((500.0, 500.0)));
|
||||
let aslant = SurfaceMap { rotation: 45.0, ..map(1, "Mark") };
|
||||
let (sx, sy) = aslant.fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)).unwrap();
|
||||
assert!((sx - sy).abs() < 1e-9 && (sx - 50.0 / (20.0 * 0.5f64.sqrt()) * 100.0).abs() < 1e-6, "{sx} {sy}");
|
||||
assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 0.0, 10.0), (100.0, 50.0)), None);
|
||||
}
|
||||
@@ -41,6 +41,7 @@ vectorcraft-eps = { workspace = true }
|
||||
vectorcraft-metafile = { workspace = true }
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true }
|
||||
vectorcraft-cdr = { workspace = true }
|
||||
vectorcraft-scriptcheck = { workspace = true }
|
||||
vectorcraft-js = { workspace = true }
|
||||
# The commands' parameter schemas (schemas.rs).
|
||||
@@ -95,6 +96,7 @@ craft-jxl = { workspace = true }
|
||||
hayro-ccitt = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true, features = ["synth"] }
|
||||
vectorcraft-cdr = { workspace = true, features = ["synth"] }
|
||||
crc32fast = { workspace = true }
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example appearance_rows_bench` prints the time three Appearance row edits
|
||||
//! take with every path of documents of 2,000, 10,000 and 20,000 squares selected, each square with one fill row and one
|
||||
//! stroke row. For each size it first times the step that keeps the objects whose shown rows the edit wrote, on the same
|
||||
//! ids, two ways: each id looked up in the list of written objects (a list of ids, and a list of ids with the kind of row,
|
||||
//! as the commands held them), and each id looked up in a set built from that list. It checks that both ways keep the
|
||||
//! same ids in the same order. Then it times the whole `appearance.setItem` (`index` 1, `weight` 2),
|
||||
//! `appearance.duplicateItem` (`index` 0) and `stroke.set` (`item` 1, `weight` 2) commands, each on a fresh copy of the
|
||||
//! document made before the clock starts.
|
||||
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere it is wall time, and
|
||||
//! the first line says which. `ITERS` sets the runs per row (default 7); each row is the median in ms. The two lookup
|
||||
//! ways run in alternating order.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
|
||||
fn ms(f: impl FnOnce()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), Instant::now());
|
||||
f();
|
||||
match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f64>) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// `n` closed 10 pt squares, each with a red fill row and a 1 pt black stroke row, and their ids in paint order.
|
||||
fn document(n: usize) -> (Document, Vec<NodeId>) {
|
||||
let mut doc = Document::new(4000.0, 4000.0);
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let mut ids = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
|
||||
let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)];
|
||||
let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true));
|
||||
let id = doc.alloc_id();
|
||||
let looks = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::BLACK), 1.0);
|
||||
doc.insert(layer, usize::MAX, Node::path(id, path, looks)).unwrap();
|
||||
ids.push(id);
|
||||
}
|
||||
(doc, ids)
|
||||
}
|
||||
|
||||
/// The ids among `ids` that `wrote` holds, each looked up in the list: the lookup the row edits made.
|
||||
fn in_list(ids: Vec<NodeId>, wrote: &[NodeId]) -> Vec<NodeId> {
|
||||
ids.into_iter().filter(|id| wrote.contains(id)).collect()
|
||||
}
|
||||
|
||||
/// [`in_list`] with each id looked up in a set built from `wrote`.
|
||||
fn in_set(ids: Vec<NodeId>, wrote: &[NodeId]) -> Vec<NodeId> {
|
||||
let wrote: HashSet<NodeId> = wrote.iter().copied().collect();
|
||||
ids.into_iter().filter(|id| wrote.contains(id)).collect()
|
||||
}
|
||||
|
||||
/// The ids among `ids` that `edited` holds with either kind of row, each looked up in the list, as `appearance.setItem`
|
||||
/// did.
|
||||
fn in_kind_list(ids: Vec<NodeId>, edited: &[(NodeId, bool)]) -> Vec<NodeId> {
|
||||
ids.into_iter().filter(|id| edited.iter().any(|(e, _)| e == id)).collect()
|
||||
}
|
||||
|
||||
/// [`in_kind_list`] with each id looked up in a set built from the ids of `edited`.
|
||||
fn in_kind_set(ids: Vec<NodeId>, edited: &[(NodeId, bool)]) -> Vec<NodeId> {
|
||||
let wrote: HashSet<NodeId> = edited.iter().map(|(id, _)| *id).collect();
|
||||
ids.into_iter().filter(|id| wrote.contains(id)).collect()
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<52} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
/// The medians of `old` and `new` over [`iters`] runs, alternating which goes first; each run filters `ids` `reps` times
|
||||
/// on copies made before the clock starts and gives the time of one.
|
||||
fn time_both<W: ?Sized>(ids: &[NodeId], wrote: &W, old: fn(Vec<NodeId>, &W) -> Vec<NodeId>, new: fn(Vec<NodeId>, &W) -> Vec<NodeId>) -> (f64, f64) {
|
||||
let reps = (200_000 / ids.len()).max(1);
|
||||
let run = |f: fn(Vec<NodeId>, &W) -> Vec<NodeId>| {
|
||||
let mut work: Vec<Vec<NodeId>> = (0..reps).map(|_| ids.to_vec()).collect();
|
||||
ms(|| {
|
||||
for it in &mut work {
|
||||
black_box(f(black_box(std::mem::take(it)), wrote));
|
||||
}
|
||||
}) / reps as f64
|
||||
};
|
||||
let (mut a, mut b) = (vec![], vec![]);
|
||||
for i in 0..iters() {
|
||||
if i % 2 == 0 {
|
||||
a.push(run(old));
|
||||
b.push(run(new));
|
||||
} else {
|
||||
b.push(run(new));
|
||||
a.push(run(old));
|
||||
}
|
||||
}
|
||||
(median(a), median(b))
|
||||
}
|
||||
|
||||
fn bench(n: usize) {
|
||||
println!("{n} squares, all selected");
|
||||
let (doc, ids) = document(n);
|
||||
// Every object's topmost stroke row was written, as when every selected object takes the edit.
|
||||
let edited: Vec<(NodeId, bool)> = ids.iter().map(|id| (*id, false)).collect();
|
||||
// A list missing every other id, so lookups that fail are timed too.
|
||||
let half: Vec<NodeId> = ids.iter().copied().step_by(2).collect();
|
||||
for wrote in [&ids, &half] {
|
||||
assert_eq!(in_list(ids.clone(), wrote), in_set(ids.clone(), wrote), "both ways keep the same ids");
|
||||
}
|
||||
assert_eq!(in_kind_list(ids.clone(), &edited), in_kind_set(ids.clone(), &edited), "both ways keep the same ids");
|
||||
let (old, new) = time_both(&ids, ids.as_slice(), in_list, in_set);
|
||||
row("keep written ids, every id in the list", old);
|
||||
row("keep written ids, every id in a set", new);
|
||||
let (old, new) = time_both(&ids, half.as_slice(), in_list, in_set);
|
||||
row("keep written ids, half the ids in the list", old);
|
||||
row("keep written ids, half the ids in a set", new);
|
||||
let (old, new) = time_both(&ids, edited.as_slice(), in_kind_list, in_kind_set);
|
||||
row("keep written ids, (id, kind) list", old);
|
||||
row("keep written ids, (id, kind) set", new);
|
||||
|
||||
let all: Vec<u64> = ids.iter().map(|id| id.0).collect();
|
||||
let commands: [(&str, Value); 3] = [
|
||||
("appearance.setItem", json!({"ids": all, "index": 1, "weight": 2})),
|
||||
("appearance.duplicateItem", json!({"ids": all, "index": 0})),
|
||||
("stroke.set", json!({"ids": all, "item": 1, "weight": 2})),
|
||||
];
|
||||
for (cmd, p) in &commands {
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut s = Session::new();
|
||||
s.add_document(doc.clone(), None);
|
||||
let t = ms(|| drop(black_box(s.execute(cmd, p).unwrap())));
|
||||
drop(black_box(s));
|
||||
t
|
||||
})
|
||||
.collect();
|
||||
row(&format!("{cmd}, whole command"), median(runs));
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
|
||||
for n in [2_000, 10_000, 20_000] {
|
||||
bench(n);
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ pub mod expand;
|
||||
pub(crate) mod fileinfo;
|
||||
pub mod fileio;
|
||||
pub mod findfiles;
|
||||
pub mod flare;
|
||||
pub mod flatten;
|
||||
pub mod fontfiles;
|
||||
mod fonts;
|
||||
@@ -47,6 +48,7 @@ mod info;
|
||||
pub(crate) mod inline;
|
||||
mod interactivity;
|
||||
mod intertwine;
|
||||
pub mod kinsokusets;
|
||||
pub(crate) mod layer;
|
||||
mod layerpanel;
|
||||
pub mod library;
|
||||
@@ -74,6 +76,7 @@ pub mod perspgrid;
|
||||
pub mod place;
|
||||
pub mod plugin;
|
||||
pub(crate) mod plugin_call;
|
||||
mod preflight;
|
||||
pub mod prefscmds;
|
||||
pub mod print;
|
||||
pub(crate) mod printadvanced;
|
||||
@@ -98,12 +101,13 @@ pub(crate) mod symboledit;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
mod textedit;
|
||||
mod xmlattrs;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
mod retype;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
pub(crate) mod threads;
|
||||
pub mod toast;
|
||||
pub(crate) mod typecmd;
|
||||
mod typemenu;
|
||||
mod variablecmds;
|
||||
@@ -321,6 +325,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(pathops::specs());
|
||||
v.extend(compoundshape::specs());
|
||||
v.extend(typecmd::specs());
|
||||
v.extend(retype::specs());
|
||||
v.extend(retype::fonts::specs());
|
||||
v.extend(menucmds::specs());
|
||||
v.extend(live::specs());
|
||||
v.extend(colorcmds::specs());
|
||||
@@ -331,8 +337,10 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(textstyles::specs());
|
||||
v.extend(fonts::specs());
|
||||
v.extend(compositefonts::specs());
|
||||
v.extend(kinsokusets::specs());
|
||||
v.extend(fontfiles::specs());
|
||||
v.extend(help::specs());
|
||||
v.extend(toast::specs());
|
||||
v.extend(threads::specs());
|
||||
v.extend(textwrap::specs());
|
||||
v.extend(graph::specs());
|
||||
@@ -382,6 +390,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(package::specs());
|
||||
v.extend(slices::specs());
|
||||
v.extend(print::specs());
|
||||
v.extend(preflight::specs());
|
||||
v.extend(recovery::specs());
|
||||
v.extend(fileio::dxfimport::specs());
|
||||
v.extend(webexport::specs());
|
||||
@@ -842,6 +851,7 @@ pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
pub use object::{reflect_axis, scale_factors, shear_tangent};
|
||||
pub(crate) use paint::LIVE_PAINT_BUCKET;
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
@@ -874,10 +884,14 @@ pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs,
|
||||
/// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs).
|
||||
pub use compoundshape::selected_member_modes;
|
||||
|
||||
/// Make Compound Shape's warning when a member is an open path that encloses no area.
|
||||
pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
|
||||
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]).
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps.
|
||||
pub use attributes::RECENT_URLS;
|
||||
pub use overprint::AttributesInfo;
|
||||
|
||||
/// Object → Flatten Transparency settings (`object.flattenTransparency`).
|
||||
@@ -901,6 +915,8 @@ pub(crate) use buildcmds::TracePresetChanges;
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
/// The tile counts Create Object Mosaic would use (the dialog's Use Ratio button sets them).
|
||||
pub use menucmds::mosaic_counts;
|
||||
/// The Shape Mode commands' warning when a selected open path encloses no area.
|
||||
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
|
||||
|
||||
@@ -911,6 +927,10 @@ pub use buildcmds::live_paint_gaps;
|
||||
/// Control bar enable it when it changes one).
|
||||
pub use brushsym::reset_transformation_changes;
|
||||
|
||||
/// Whether an object is a symbol set (the Symbolism Tools Options' Symbol Set Density applies to
|
||||
/// the selected ones).
|
||||
pub use brushsym::is_symbol_set;
|
||||
|
||||
/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every
|
||||
/// frame without running the command).
|
||||
pub use brushsym::current_symbol;
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
|
||||
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
|
||||
//! ([`tangents`]) and Tangent Circle
|
||||
//! ([`tangent_circle`]).
|
||||
//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add
|
||||
//! Bounding Circle ([`bounding`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
mod bounding;
|
||||
mod bridge;
|
||||
mod corners;
|
||||
#[cfg(test)]
|
||||
@@ -188,6 +189,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(bridge::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::specs());
|
||||
v.extend(bounding::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Add Bounding Rectangle and Add Bounding Circle: a live rectangle on the selection's geometric
|
||||
//! bounding box, or the smallest live circle around its outlines. The circle is the geometry crate's
|
||||
//! ([`enclosing_circle`](vectorcraft_geom::shapes::enclosing_circle)).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind, SymbolBoxes};
|
||||
use vectorcraft_geom::kurbo::ParamCurveExtrema;
|
||||
use vectorcraft_geom::{Affine, CubicBez, FillRule, ParamCurve, PathSeg, Point, Rect, shapes};
|
||||
|
||||
use super::super::super::edit::{no_symbol_part, selected_roots_to_transform};
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or};
|
||||
use crate::sanity::rect_in_range;
|
||||
use crate::{Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Add Bounding Rectangle's command.
|
||||
pub(crate) const RECTANGLE: &str = "addon.pathtools.boundingRectangle";
|
||||
/// Add Bounding Circle's command.
|
||||
pub(crate) const CIRCLE: &str = "addon.pathtools.boundingCircle";
|
||||
|
||||
/// How far a curve may stray from the points the circle is fitted to, in points. The circle's
|
||||
/// radius grows by as much, so it holds the curves themselves.
|
||||
const FLATNESS: f64 = 0.01;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.pathtools.boundingRectangle",
|
||||
"Add Bounding Rectangle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{each?: bool (default false: one rectangle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added on every side)} draw a live rectangle on the geometric bounding box of the selected objects (strokes and effects left out; a path of a compound path selected on its own counts as an object), with the current paint, on top of the current layer or of the isolated group, as other new art; the rectangles are selected; one undo step. An object whose box has no width or no height (a straight horizontal or vertical line) gets no rectangle unless `offset` is more than 0, nor does an object with no bounds (an empty group); with `each` the result's `skipped` counts them. It is an error when no rectangle is left (\"the shape would have no size\" when a rectangle with no size was left out, else \"nothing to enclose\") and when an edge of a rectangle would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Rectangle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first rectangle, ids, skipped?}",
|
||||
whole_objects,
|
||||
bounding_rectangle
|
||||
),
|
||||
cmd!(
|
||||
"addon.pathtools.boundingCircle",
|
||||
"Add Bounding Circle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{each?: bool (default false: one circle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added to the radius)} draw the smallest live circle that holds the outlines of the selected objects (paths and compound paths by their curves, clip groups and sublayers that clip their contents by their clipping paths, other sublayers by their shown objects, images by their corners, type and other objects by the corners of their bounding box; strokes and effects left out; a path of a compound path selected on its own counts as an object), with the radius 0.01 pt larger so it holds the curves themselves, with the current paint, on top of the current layer or of the isolated group, as other new art; the circles are selected; one undo step. An object at a single point gets no circle unless `offset` is more than 0, nor does an object with no outline (an empty group); with `each` the result's `skipped` counts them. It is an error when no circle is left (\"the shape would have no size\" when a circle with no size was left out, else \"nothing to enclose\") and when an edge of a circle's bounding box would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Circle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first circle, ids, skipped?}",
|
||||
whole_objects,
|
||||
bounding_circle
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Enabled with a selection that is not an object of a symbol instance's art, which
|
||||
/// [`selected_roots_to_transform`] refuses.
|
||||
fn whole_objects(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
no_symbol_part(s)
|
||||
}
|
||||
|
||||
/// The shape a command draws.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Kind {
|
||||
Rectangle,
|
||||
Circle,
|
||||
}
|
||||
|
||||
fn bounding_rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add(s, p, Kind::Rectangle)
|
||||
}
|
||||
|
||||
fn bounding_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add(s, p, Kind::Circle)
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let (c, label) = match kind {
|
||||
Kind::Rectangle => (RECTANGLE, "Add Bounding Rectangle"),
|
||||
Kind::Circle => (CIRCLE, "Add Bounding Circle"),
|
||||
};
|
||||
let each = switch_or(p, "each", false, c)?;
|
||||
let offset = number_or(p, "offset", 0.0, c)?;
|
||||
if !(offset.is_finite() && offset >= 0.0) {
|
||||
return Err(bad(c, "`offset` must be 0 or more"));
|
||||
}
|
||||
// The objects `object.transform` moves: a path of a compound path selected on its own is one.
|
||||
let roots = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let groups: Vec<Vec<NodeId>> = if each { roots.iter().map(|id| vec![*id]).collect() } else { vec![roots] };
|
||||
let mut made: Vec<LiveShape> = vec![];
|
||||
// Objects that get no shape: no outline, or a shape with no size.
|
||||
let mut skipped = 0;
|
||||
let mut no_size = false;
|
||||
// The shapes share the halvings, so the work stays bounded however many objects are selected.
|
||||
let splits = split_share(groups.len());
|
||||
for ids in &groups {
|
||||
match shape_around(d, &symbols, ids, kind, offset, splits) {
|
||||
Around::Shape(live) => made.push(live),
|
||||
Around::NoOutline => skipped += 1,
|
||||
Around::NoSize => {
|
||||
skipped += 1;
|
||||
no_size = true;
|
||||
}
|
||||
Around::PastCanvas => return Err(bad(c, "the shape would reach past the edge of the canvas")),
|
||||
}
|
||||
}
|
||||
if made.is_empty() {
|
||||
return Err(bad(c, if no_size { "the shape would have no size" } else { "nothing to enclose" }));
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
let mut ids = vec![];
|
||||
for live in made {
|
||||
let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false };
|
||||
let mut n = Node::new(d.alloc_id(), kind);
|
||||
look.apply(d, &mut n);
|
||||
ids.push(n.id);
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
let first = ids.first().map_or(0, |id| id.0);
|
||||
let mut out = json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() });
|
||||
if skipped > 0 {
|
||||
out["skipped"] = json!(skipped);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What [`shape_around`] finds.
|
||||
enum Around {
|
||||
Shape(LiveShape),
|
||||
/// The objects have no bounds or no outline.
|
||||
NoOutline,
|
||||
/// The rectangle would have no width or no height, or the circle no radius.
|
||||
NoSize,
|
||||
/// An edge of the shape would lie more than [`MAX_COORD`](crate::MAX_COORD) from the origin
|
||||
/// along either axis.
|
||||
PastCanvas,
|
||||
}
|
||||
|
||||
/// The live rectangle or circle around `ids`, grown by `offset`. A circle halves its curves as
|
||||
/// `splits` allows.
|
||||
fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, offset: f64, splits: Splits) -> Around {
|
||||
match kind {
|
||||
Kind::Rectangle => {
|
||||
let Some(r) = d.bounds_of_with(ids, false, symbols) else { return Around::NoOutline };
|
||||
let r = r.inflate(offset, offset);
|
||||
if !rect_in_range(r) {
|
||||
return Around::PastCanvas;
|
||||
}
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Around::NoSize;
|
||||
}
|
||||
Around::Shape(LiveShape::Rectangle {
|
||||
w: r.width(),
|
||||
h: r.height(),
|
||||
radii: [0.0; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::translate(r.origin().to_vec2()),
|
||||
})
|
||||
}
|
||||
Kind::Circle => {
|
||||
let mut gathered = Gathered::new();
|
||||
gathered.splits = splits;
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
outline_points(n, symbols, &mut gathered, 0);
|
||||
gathered.compact();
|
||||
}
|
||||
let Some((center, radius)) = shapes::enclosing_circle(&gathered.points) else { return Around::NoOutline };
|
||||
if radius + offset <= 0.0 {
|
||||
return Around::NoSize;
|
||||
}
|
||||
let r = radius + FLATNESS + offset;
|
||||
let b = Rect::new(center.x - r, center.y - r, center.x + r, center.y + r);
|
||||
if !rect_in_range(b) {
|
||||
return Around::PastCanvas;
|
||||
}
|
||||
Around::Shape(LiveShape::Ellipse { w: b.width(), h: b.height(), pie: (0.0, 360.0), xf: Affine::translate(b.origin().to_vec2()) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to `out` points on the outline of `n`, as its geometric bounds measure it: the points of
|
||||
/// its paths ([`curve_points`]); the clipping path of a clip group or of a sublayer that clips its
|
||||
/// contents; the shown contents of a sublayer (a layer that an opened file put inside a group); the
|
||||
/// corners of an image; and the corners of the geometric bounding box of anything else. A group or
|
||||
/// layer `depth` levels below the selected object that is nested deeper than a document holds
|
||||
/// ([`vectorcraft_doc::MAX_DEPTH`]) counts by the corners of its geometric bounding box.
|
||||
fn outline_points(n: &Node, symbols: &SymbolBoxes, out: &mut Gathered, depth: usize) {
|
||||
let nests = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. });
|
||||
if nests && depth >= vectorcraft_doc::MAX_DEPTH {
|
||||
out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten());
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
// The anchors count too, so a path of one anchor, which has no segments, is held.
|
||||
for p in path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)) {
|
||||
out.points.push(p);
|
||||
out.compact();
|
||||
}
|
||||
for seg in path.to_bezpath().segments() {
|
||||
match seg {
|
||||
PathSeg::Line(l) => out.points.extend([l.p0, l.p1]),
|
||||
_ => curve_points(seg.to_cubic(), 0, &mut out.points, &mut out.splits),
|
||||
}
|
||||
out.compact();
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
if let Some(c) = children.first() {
|
||||
outline_points(c, symbols, out, depth + 1);
|
||||
}
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. } => {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
for c in n.editing_children().iter().filter(|c| c.visible || !layer) {
|
||||
outline_points(c, symbols, out, depth + 1);
|
||||
out.compact();
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let r = Rect::new(0.0, 0.0, im.width as f64, im.height as f64);
|
||||
out.points.extend(corners(r).map(|p| im.xf * p));
|
||||
}
|
||||
_ => out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to `out` points whose convex hull, grown by [`FLATNESS`], holds the curve `c`: the ends of
|
||||
/// pieces whose control points lie within [`FLATNESS`] of their chord, and for pieces still curved
|
||||
/// after [`MAX_SPLITS`] halvings, or when `splits` allows no more ([`Splits::take`]), the corners of
|
||||
/// [`held`]. A flat piece that ends where it starts adds its control points too, so a small loop is
|
||||
/// not taken for a single point. A curve with a point that is not finite adds nothing.
|
||||
fn curve_points(c: CubicBez, depth: u32, out: &mut Vec<Point>, splits: &mut Splits) {
|
||||
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let flat = [c.p1, c.p2].iter().all(|p| distance_to_segment(*p, c.p0, c.p3) <= FLATNESS);
|
||||
if flat {
|
||||
out.extend([c.p0, c.p3]);
|
||||
if c.p0 == c.p3 {
|
||||
out.extend([c.p1, c.p2]);
|
||||
}
|
||||
} else if depth >= MAX_SPLITS || !splits.take(depth) {
|
||||
out.extend(held(c));
|
||||
} else {
|
||||
let (a, b) = c.subdivide();
|
||||
curve_points(a, depth + 1, out, splits);
|
||||
curve_points(b, depth + 1, out, splits);
|
||||
}
|
||||
}
|
||||
|
||||
/// The corners of the convex hull of `c`'s control points cut down to `c`'s bounding box. Each of
|
||||
/// the two holds the curve, so the part they share holds it too. When the cut leaves nothing, which
|
||||
/// rounding can cause, it gives the box's corners.
|
||||
fn held(c: CubicBez) -> Vec<Point> {
|
||||
let b = ParamCurveExtrema::bounding_box(&c);
|
||||
let mut poly = shapes::convex_hull(vec![c.p0, c.p1, c.p2, c.p3]);
|
||||
for (x, bound, below) in [(true, b.x0, false), (true, b.x1, true), (false, b.y0, false), (false, b.y1, true)] {
|
||||
poly = clip(&poly, x, bound, below);
|
||||
}
|
||||
if poly.is_empty() { corners(b).to_vec() } else { poly }
|
||||
}
|
||||
|
||||
/// The convex polygon `poly` cut at `bound` on the x axis (`x`) or the y axis: the part at or below
|
||||
/// `bound` when `below`, else at or above it.
|
||||
fn clip(poly: &[Point], x: bool, bound: f64, below: bool) -> Vec<Point> {
|
||||
let v = |p: Point| if x { p.x } else { p.y };
|
||||
let inside = |p: Point| if below { v(p) <= bound } else { v(p) >= bound };
|
||||
let mut out = vec![];
|
||||
for (&a, &b) in poly.iter().zip(poly.iter().cycle().skip(1)) {
|
||||
if inside(a) {
|
||||
out.push(a);
|
||||
}
|
||||
if inside(a) != inside(b) {
|
||||
let mut p = a.lerp(b, (bound - v(a)) / (v(b) - v(a)));
|
||||
if x {
|
||||
p.x = bound;
|
||||
} else {
|
||||
p.y = bound;
|
||||
}
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many halvings [`curve_points`] makes for one command, over every curve it measures, before
|
||||
/// it halves each further curve [`MIN_SPLITS`] times only; with `each`, every shape gets an equal
|
||||
/// share ([`split_share`]).
|
||||
const TOTAL_SPLITS: usize = 1 << 20;
|
||||
|
||||
/// How many more halvings [`curve_points`] makes for one command once [`TOTAL_SPLITS`] is used up,
|
||||
/// each within the first [`MIN_SPLITS`] halvings of a curve; with `each`, shared as
|
||||
/// [`TOTAL_SPLITS`] is. After that, curves count by [`held`] whole.
|
||||
const EARLY_SPLITS: usize = 7 << 20;
|
||||
|
||||
/// How many times [`curve_points`] halves a curve once [`TOTAL_SPLITS`] is used up: 8 pieces, which
|
||||
/// keeps the circle fitted to a circle of four curves less than 0.3% larger than that circle.
|
||||
const MIN_SPLITS: u32 = 3;
|
||||
|
||||
/// The halvings [`curve_points`] may still make.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Splits {
|
||||
/// Halvings at any depth.
|
||||
any: usize,
|
||||
/// Halvings within the first [`MIN_SPLITS`] of a curve, once `any` is used up.
|
||||
early: usize,
|
||||
}
|
||||
|
||||
impl Splits {
|
||||
/// Takes one halving of a piece `depth` halvings into its curve; false when none is left.
|
||||
fn take(&mut self, depth: u32) -> bool {
|
||||
if self.any > 0 {
|
||||
self.any -= 1;
|
||||
} else if depth < MIN_SPLITS && self.early > 0 {
|
||||
self.early -= 1;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The halvings each of `shapes` shapes may make: an equal share of [`TOTAL_SPLITS`] and of
|
||||
/// [`EARLY_SPLITS`].
|
||||
fn split_share(shapes: usize) -> Splits {
|
||||
let n = shapes.max(1);
|
||||
Splits { any: TOTAL_SPLITS / n, early: EARLY_SPLITS / n }
|
||||
}
|
||||
|
||||
/// How many points [`outline_points`] gathers before it keeps only the corners of their convex hull.
|
||||
const COMPACT_AT: usize = 1 << 16;
|
||||
|
||||
/// Points gathered for a circle, kept down to the corners of their convex hull whenever they grow
|
||||
/// past `limit`: only the hull decides the circle. The points held stay within about twice the
|
||||
/// hull's corners, and grow only with the anchors and objects measured and the halvings
|
||||
/// ([`TOTAL_SPLITS`] and [`EARLY_SPLITS`]).
|
||||
struct Gathered {
|
||||
points: Vec<Point>,
|
||||
limit: usize,
|
||||
/// The halvings [`curve_points`] may still make (one shape's whole share at first).
|
||||
splits: Splits,
|
||||
}
|
||||
|
||||
impl Gathered {
|
||||
fn new() -> Self {
|
||||
Self { points: vec![], limit: COMPACT_AT, splits: split_share(1) }
|
||||
}
|
||||
|
||||
/// Keeps only the hull's corners once there are more than `limit` points; the next time waits
|
||||
/// until there are twice as many as the hull has, so each point is sorted a few times at most.
|
||||
fn compact(&mut self) {
|
||||
if self.points.len() > self.limit {
|
||||
self.points = shapes::convex_hull(std::mem::take(&mut self.points));
|
||||
self.limit = (self.points.len() * 2).max(COMPACT_AT);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times [`curve_points`] halves a curve at most: up to 1,024 pieces.
|
||||
const MAX_SPLITS: u32 = 10;
|
||||
|
||||
/// The distance from `p` to the segment from `a` to `b`.
|
||||
fn distance_to_segment(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()
|
||||
}
|
||||
|
||||
fn corners(r: Rect) -> [Point; 4] {
|
||||
[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
//! Add Bounding Rectangle and Add Bounding Circle: the box and the smallest circle, the current
|
||||
//! paint and placement on top of the current layer or the isolated group, `each` and `skipped`,
|
||||
//! shapes of no size, clip groups and clipping sublayers, paths of compound paths, huge curves and
|
||||
//! small loops, and the errors that leave the document as it was.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{CubicBez, Point, Rect, Vec2, shapes};
|
||||
|
||||
use super::{CIRCLE, COMPACT_AT, Gathered, RECTANGLE, Splits};
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
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 undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn object_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether two rectangles agree to within `tol` on every edge.
|
||||
fn rect_near(b: Rect, want: Rect, tol: f64) -> bool {
|
||||
[(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < tol)
|
||||
}
|
||||
|
||||
/// The live shape of `id`.
|
||||
fn live(s: &Session, id: NodeId) -> LiveShape {
|
||||
match &node(s, id).kind {
|
||||
NodeKind::Path { live: Some(live), .. } => live.as_ref().clone(),
|
||||
other => panic!("not a live shape: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometric bounds of `id`.
|
||||
fn bounds(s: &Session, id: NodeId) -> Rect {
|
||||
s.doc().unwrap().doc.bounds_of(&[id], false).unwrap()
|
||||
}
|
||||
|
||||
/// The last child of `parent`, the top of its stacking order.
|
||||
fn top_of(s: &Session, parent: NodeId) -> NodeId {
|
||||
node(s, parent).children().unwrap().last().unwrap().id
|
||||
}
|
||||
|
||||
/// Runs `command` with `p` and checks that it fails and leaves the document as it was.
|
||||
fn refused(s: &mut Session, command: &str, p: Value) -> String {
|
||||
let (undo, objects) = (undo_len(s), object_count(s));
|
||||
let e = s.execute(command, &p).unwrap_err().to_string();
|
||||
assert_eq!((undo_len(s), object_count(s)), (undo, objects), "{p} changed the document");
|
||||
e
|
||||
}
|
||||
|
||||
/// A live rectangle on the selection's geometric bounding box, strokes left out, with the current
|
||||
/// paint, on top of the current layer, selected; one undo removes it.
|
||||
#[test]
|
||||
fn a_bounding_rectangle_is_the_geometric_box_on_top_of_the_layer() {
|
||||
let mut s = session();
|
||||
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let b = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 60, "height": 80})).unwrap());
|
||||
assert_eq!(node(&s, a).appearance.stroke_width(), 10.0, "the strokes reach past the geometric box");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let (before, undo) = (object_count(&s), undo_len(&s));
|
||||
let out = s.execute(RECTANGLE, &json!({})).unwrap();
|
||||
let id = id_of(&out);
|
||||
assert_eq!(ids_of(&out), vec![id]);
|
||||
assert!(out.get("skipped").is_none(), "{out}");
|
||||
assert!(matches!(live(&s, id), LiveShape::Rectangle { .. }));
|
||||
assert!(rect_near(bounds(&s, id), Rect::new(10.0, 20.0, 160.0, 130.0), 1e-9), "{:?}", bounds(&s, id));
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
assert_eq!(top_of(&s, layer), id);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert_eq!(object_count(&s), before + 1);
|
||||
// The current paint, as a shape drawn now gets it.
|
||||
let reference = rect(&mut s, 300.0, 300.0, 5.0, 5.0);
|
||||
let (n, r) = (node(&s, id), node(&s, reference));
|
||||
assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint()));
|
||||
assert_eq!(n.appearance.stroke_width(), r.appearance.stroke_width());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(object_count(&s), before);
|
||||
}
|
||||
|
||||
/// A bounding circle around a right triangle stands on its hypotenuse; around a circle it is that
|
||||
/// circle, grown by at most the flattening allowance; `offset` grows the radius, and a rectangle's
|
||||
/// sides, by that much.
|
||||
#[test]
|
||||
fn a_bounding_circle_is_the_smallest_circle_around_the_outlines() {
|
||||
let mut s = session();
|
||||
let tri =
|
||||
id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}], "closed": true})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [tri.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
match live(&s, c) {
|
||||
LiveShape::Ellipse { w, h, pie, .. } => {
|
||||
assert!((w - 100.02).abs() < 1e-9 && (h - 100.02).abs() < 1e-9 && pie == (0.0, 360.0), "{w} {h}");
|
||||
}
|
||||
other => panic!("not a circle: {other:?}"),
|
||||
}
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(-10.01, -20.01, 90.01, 80.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
// A circle of radius 50 and a dot inside it: the bounding circle is the circle itself.
|
||||
let round = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 100, "height": 100})).unwrap());
|
||||
let dot = rect(&mut s, 240.0, 240.0, 2.0, 2.0);
|
||||
s.execute("select.set", &json!({"ids": [round.0, dot.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({"offset": 5})).unwrap());
|
||||
let got = bounds(&s, c);
|
||||
let want = Rect::new(195.0, 195.0, 305.0, 305.0);
|
||||
assert!(rect_near(got, want, 0.03), "{got:?}");
|
||||
assert!(got.x0 <= want.x0 + 1e-9 && got.x1 >= want.x1 - 1e-9 && got.y0 <= want.y0 + 1e-9 && got.y1 >= want.y1 - 1e-9, "{got:?}");
|
||||
|
||||
s.execute("select.set", &json!({"ids": [tri.0]})).unwrap();
|
||||
let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 4})).unwrap());
|
||||
assert!(rect_near(bounds(&s, r), Rect::new(-4.0, -4.0, 84.0, 64.0), 1e-9));
|
||||
}
|
||||
|
||||
/// A shape with no size is not drawn: a straight horizontal line gets no rectangle and a path of
|
||||
/// one anchor no circle, unless `offset` gives them room; with `each` they are counted in
|
||||
/// `skipped`, and alone they are an error.
|
||||
#[test]
|
||||
fn shapes_of_no_size_are_skipped_unless_offset_gives_them_room() {
|
||||
let mut s = session();
|
||||
let line = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 10, "y": 50}, {"x": 90, "y": 50}]})).unwrap());
|
||||
let lone = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 50, "y": 70}]})).unwrap());
|
||||
let box_ = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
assert!(refused(&mut s, RECTANGLE, json!({})).contains("the shape would have no size"));
|
||||
let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 2})).unwrap());
|
||||
assert!(rect_near(bounds(&s, r), Rect::new(8.0, 48.0, 92.0, 52.0), 1e-9), "{:?}", bounds(&s, r));
|
||||
// The line has length, so its circle has size.
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(9.99, 9.99, 90.01, 90.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
s.execute("select.set", &json!({"ids": [lone.0]})).unwrap();
|
||||
assert!(refused(&mut s, CIRCLE, json!({})).contains("the shape would have no size"));
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3})).unwrap());
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(46.99, 66.99, 53.01, 73.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap();
|
||||
let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(2)), "{out}");
|
||||
assert!(rect_near(bounds(&s, id_of(&out)), Rect::new(200.0, 200.0, 210.0, 210.0), 1e-9));
|
||||
s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (2, Some(1)), "{out}");
|
||||
}
|
||||
|
||||
/// With `each`, every selected object gets a shape of its own, all in one undo step, on top of the
|
||||
/// layer in the selection's stacking order, and the new shapes are selected.
|
||||
#[test]
|
||||
fn each_draws_one_shape_around_each_object() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 30.0);
|
||||
s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap();
|
||||
let ids = ids_of(&out);
|
||||
assert_eq!(ids.len(), 2);
|
||||
assert!(rect_near(bounds(&s, ids[0]), Rect::new(0.0, 0.0, 10.0, 10.0), 1e-9));
|
||||
assert!(rect_near(bounds(&s, ids[1]), Rect::new(100.0, 0.0, 120.0, 30.0), 1e-9));
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
let order: Vec<NodeId> = node(&s, layer).children().unwrap().iter().map(|n| n.id).collect();
|
||||
assert_eq!(order, vec![a, b, ids[0], ids[1]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// An object with no outline (an empty group) gets no shape and the result counts it; with only
|
||||
/// such objects selected the command draws nothing.
|
||||
#[test]
|
||||
fn each_counts_the_objects_without_an_outline() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let empty = s
|
||||
.edit("Group", |d, _| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(d.default_layer(), 0, Node::group(id, vec![]))?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(1)), "{out}");
|
||||
s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({})).unwrap();
|
||||
assert!(out.get("skipped").is_none(), "{out}");
|
||||
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
|
||||
assert!(refused(&mut s, RECTANGLE, json!({"each": true})).contains("nothing to enclose"));
|
||||
}
|
||||
|
||||
/// Curves over a hundred thousand points across are held by their circle: every point along the
|
||||
/// curves is inside the circle, whose radius is the 0.01 pt allowance larger than the circle around
|
||||
/// the flattened points. The farthest point of the lopsided arc lies between two flattened points,
|
||||
/// about 0.001 pt outside the circle around them, so it needs that allowance.
|
||||
#[test]
|
||||
fn the_circle_holds_huge_curves() {
|
||||
let mut s = session();
|
||||
let d = "M 0 0 C 0 -90000 120000 -90000 120000 0 C 60000 40000 30000 70000 0 0 Z";
|
||||
let blob = id_of(&s.execute("path.create", &json!({"d": d})).unwrap());
|
||||
let arc = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 20 400 380 500 400 0"})).unwrap());
|
||||
for big in [blob, arc] {
|
||||
s.execute("select.set", &json!({"ids": [big.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") };
|
||||
let (center, r) = (xf * Point::new(w / 2.0, w / 2.0), w / 2.0);
|
||||
let path = node(&s, big).path_data().unwrap().to_bezpath();
|
||||
let mut farthest: f64 = 0.0;
|
||||
for seg in path.segments() {
|
||||
for i in 0..=4000 {
|
||||
let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0);
|
||||
farthest = farthest.max(p.distance(center));
|
||||
}
|
||||
}
|
||||
assert!(farthest <= r + 1e-6, "a point {farthest} from the center is outside the circle of radius {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Clip groups count by their clipping paths; for art inside one, the shape goes on top of the
|
||||
/// current layer, never into the clip group.
|
||||
#[test]
|
||||
fn clip_groups_count_by_their_clipping_paths() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let clip = id_of(&s.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [art.0, clip.0]})).unwrap();
|
||||
let group = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let b = bounds(&s, id);
|
||||
assert!((b.width() / 2.0 - 25.01).abs() < 0.03 && b.center().distance(Point::new(35.0, 35.0)) < 0.03, "{b:?}");
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer));
|
||||
s.execute("select.set", &json!({"ids": [clip.0]})).unwrap();
|
||||
let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer));
|
||||
assert!(rect_near(bounds(&s, id), Rect::new(10.0, 10.0, 60.0, 60.0), 1e-6));
|
||||
}
|
||||
|
||||
/// A sublayer that clips its contents counts by its clipping path, and the hidden objects of a
|
||||
/// sublayer are left out; a sublayer inside a selected group (as an opened file can put one there)
|
||||
/// counts the same way.
|
||||
#[test]
|
||||
fn sublayers_count_by_their_clipping_path_and_shown_art() {
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap());
|
||||
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let hidden = rect(&mut s, 300.0, 300.0, 10.0, 10.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(sub), "the art is in the sublayer");
|
||||
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (sub_node, symbols) = (d.node(sub).unwrap().clone(), d.symbol_boxes());
|
||||
let mut g = Gathered::new();
|
||||
super::outline_points(&sub_node, &symbols, &mut g, 0);
|
||||
let (center, r) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(Point::new(50.0, 50.0)) < 1e-9 && (r - 50.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}");
|
||||
|
||||
// The top object of the sublayer becomes its clipping path.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let clip = rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(clip), Some(sub));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let sub_node = d.node(sub).unwrap().clone();
|
||||
let mut g = Gathered::new();
|
||||
super::outline_points(&sub_node, &d.symbol_boxes(), &mut g, 0);
|
||||
let (center, r) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(Point::new(25.0, 25.0)) < 1e-9 && (r - 5.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}");
|
||||
|
||||
let group = s
|
||||
.edit("Group", |d, _| {
|
||||
let layer = d.remove(sub)?;
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(top), usize::MAX, Node::group(id, vec![layer]))?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let b = bounds(&s, c);
|
||||
assert!(b.center().distance(Point::new(25.0, 25.0)) < 1e-9 && (b.width() / 2.0 - (5.0 * 2f64.sqrt() + 0.01)).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
/// A path of a compound path selected on its own is an object, as `object.transform` moves it:
|
||||
/// the shape goes around that path only, and with `each` each selected path gets a shape. The
|
||||
/// compound path selected whole is one object.
|
||||
#[test]
|
||||
fn a_path_of_a_compound_path_selected_on_its_own_is_an_object() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 120.0, 100.0, 10.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
let members: Vec<NodeId> = node(&s, compound).children().unwrap().iter().map(|n| n.id).collect();
|
||||
assert_eq!(members.len(), 2);
|
||||
for kind in [RECTANGLE, CIRCLE] {
|
||||
s.execute("select.set", &json!({"ids": [members[0].0]})).unwrap();
|
||||
let id = id_of(&s.execute(kind, &json!({})).unwrap());
|
||||
let (got, want) = (bounds(&s, id), bounds(&s, members[0]));
|
||||
if kind == RECTANGLE {
|
||||
assert!(rect_near(got, want, 1e-9), "{got:?} on {want:?}");
|
||||
} else {
|
||||
let d = want.width().hypot(want.height()) + 0.02;
|
||||
assert!(got.center().distance(want.center()) < 1e-9 && (got.width() - d).abs() < 1e-9, "{got:?} around {want:?}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [members[0].0, members[1].0]})).unwrap();
|
||||
assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 2, "{kind}");
|
||||
s.execute("select.set", &json!({"ids": [compound.0]})).unwrap();
|
||||
assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 1, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A small closed curve whose handles lie within the 0.01 pt allowance of its one anchor is not a
|
||||
/// single point: it gets a circle.
|
||||
#[test]
|
||||
fn a_small_loop_gets_a_circle() {
|
||||
let mut s = session();
|
||||
let lp = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 0.005 0 0 0.005 0 0"})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [lp.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let LiveShape::Ellipse { w, .. } = live(&s, c) else { panic!("not a circle") };
|
||||
assert!(w > 0.02, "{w}");
|
||||
}
|
||||
|
||||
/// Once the command has used up both kinds of halvings, a curve counts by its control points' hull
|
||||
/// cut down to its bounding box: the points stay inside both and reach no farther than the curve
|
||||
/// along either axis, while its handles may.
|
||||
#[test]
|
||||
fn a_curve_past_the_halvings_counts_by_its_hull_inside_its_bounding_box() {
|
||||
// With nothing left, `curve_points` takes no halving, so `none` stays as it is.
|
||||
let mut none = Splits { any: 0, early: 0 };
|
||||
let c = CubicBez::new((0.0, 0.0), (20.0, 400.0), (380.0, 500.0), (400.0, 0.0));
|
||||
let b = vectorcraft_geom::kurbo::ParamCurveExtrema::bounding_box(&c);
|
||||
let mut out = vec![];
|
||||
super::curve_points(c, 0, &mut out, &mut none);
|
||||
assert!(out.len() >= 4 && out.iter().all(|p| b.inflate(1e-9, 1e-9).contains(*p)), "{out:?} in {b:?}");
|
||||
assert!(out.iter().any(|p| (p.y - b.y1).abs() < 1e-9), "the curve's lowest point is reached: {out:?}");
|
||||
let (center, r) = shapes::enclosing_circle(&out).unwrap();
|
||||
for i in 0..=1000 {
|
||||
let p = vectorcraft_geom::ParamCurve::eval(&c, f64::from(i) / 1000.0);
|
||||
assert!(p.distance(center) <= r + 1e-9, "{p:?} outside");
|
||||
}
|
||||
// The handle at x = 4,000,000 stays out: the curve reaches x = 16,000,000 / 9.
|
||||
let reach = CubicBez::new((0.0, 0.0), (4.0e6, 0.0), (0.0, 0.0), (0.0, 0.0));
|
||||
out.clear();
|
||||
super::curve_points(reach, 0, &mut out, &mut none);
|
||||
let far = out.iter().map(|p| p.x).fold(0.0, f64::max);
|
||||
assert!((far - 16.0e6 / 9.0).abs() < 1e-6, "{far}");
|
||||
out.clear();
|
||||
let mut splits = Splits { any: 3, early: 0 };
|
||||
super::curve_points(c, 0, &mut out, &mut splits);
|
||||
assert_eq!(splits, Splits { any: 0, early: 0 });
|
||||
assert!(out.len() > 4, "{out:?}");
|
||||
}
|
||||
|
||||
/// The circle fitted to a circle of four curves: less than 0.3% larger with only the early halvings
|
||||
/// left, and up to about 14% larger by the curves' hulls once those are used up too.
|
||||
#[test]
|
||||
fn a_circle_measured_past_the_halvings_stays_close() {
|
||||
let fitted = |mut splits: Splits| {
|
||||
let circle = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).to_bezpath();
|
||||
let mut out = vec![];
|
||||
for seg in circle.segments() {
|
||||
super::curve_points(seg.to_cubic(), 0, &mut out, &mut splits);
|
||||
}
|
||||
shapes::enclosing_circle(&out).unwrap()
|
||||
};
|
||||
let (center, r) = fitted(Splits { any: 0, early: 1000 });
|
||||
assert!(center.to_vec2().hypot() < 0.1 && (100.0..100.3).contains(&r), "{center:?} {r}");
|
||||
let (_, r) = fitted(Splits { any: 0, early: 0 });
|
||||
assert!((110.0..115.0).contains(&r), "{r}");
|
||||
}
|
||||
|
||||
/// Past the halvings at any depth, only the first [`super::MIN_SPLITS`] halvings of a curve take
|
||||
/// from the early ones; with `each`, every shape gets an equal share of both.
|
||||
#[test]
|
||||
fn early_halvings_are_taken_near_the_start_of_a_curve_and_shared() {
|
||||
let mut s = Splits { any: 1, early: 1 };
|
||||
assert!(s.take(super::MIN_SPLITS + 1));
|
||||
assert!(!s.take(super::MIN_SPLITS));
|
||||
assert!(s.take(0));
|
||||
assert!(!s.take(0));
|
||||
let whole = Splits { any: super::TOTAL_SPLITS, early: super::EARLY_SPLITS };
|
||||
assert_eq!(super::split_share(0), whole);
|
||||
assert_eq!(super::split_share(1), whole);
|
||||
assert_eq!(super::split_share(4), Splits { any: super::TOTAL_SPLITS / 4, early: super::EARLY_SPLITS / 4 });
|
||||
}
|
||||
|
||||
/// In an isolated group the shape goes on top of the group's art; in an isolated compound path it
|
||||
/// goes beside the compound path, never into it.
|
||||
#[test]
|
||||
fn shapes_go_into_an_isolated_group_but_not_an_isolated_compound_path() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": group.0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group));
|
||||
assert_eq!(top_of(&s, group), id);
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
|
||||
let c = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let e = rect(&mut s, 120.0, 100.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap();
|
||||
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": compound.0})).unwrap();
|
||||
let members: Vec<u64> = node(&s, compound).children().unwrap().iter().map(|n| n.id.0).collect();
|
||||
s.execute("select.set", &json!({"ids": members})).unwrap();
|
||||
let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.parent_of(id), Some(compound), "the circle does not join the compound path");
|
||||
assert_eq!(d.parent_of(id), d.parent_of(compound));
|
||||
assert_eq!(node(&s, compound).children().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
/// An offset or each that is not one the commands take is an error, and nothing is drawn; with
|
||||
/// nothing selected the commands are not available.
|
||||
#[test]
|
||||
fn bad_params_and_an_empty_selection_draw_nothing() {
|
||||
let mut s = session();
|
||||
assert!(s.execute(RECTANGLE, &json!({})).is_err(), "nothing selected");
|
||||
assert!(s.execute(CIRCLE, &json!({})).is_err(), "nothing selected");
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
for p in [json!({"offset": -1}), json!({"offset": "5"}), json!({"each": "yes"})] {
|
||||
refused(&mut s, command, p);
|
||||
}
|
||||
assert!(refused(&mut s, command, json!({"offset": -1})).contains("`offset` must be 0 or more"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An offset that would put an edge of the shape more than 4,000,000 pt from the origin along
|
||||
/// either axis is an error that names the canvas edge, and nothing is drawn; the largest offsets
|
||||
/// that stay inside are drawn, for the rectangle and for the circle.
|
||||
#[test]
|
||||
fn an_offset_past_the_canvas_edge_draws_nothing() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
for offset in [1e308, 4.0e6] {
|
||||
let e = refused(&mut s, command, json!({ "offset": offset }));
|
||||
assert!(e.contains("the shape would reach past the edge of the canvas"), "{command} {offset}: {e}");
|
||||
}
|
||||
}
|
||||
let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 3.99e6})).unwrap());
|
||||
assert!(rect_near(bounds(&s, r), Rect::new(-3.99e6, -3.99e6, 3.99e6 + 10.0, 3.99e6 + 10.0), 1e-3));
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3.99e6})).unwrap());
|
||||
// The circle around the square from (0, 0) to (10, 10), 0.01 pt larger, then the offset.
|
||||
let radius = 50.0f64.sqrt() + 0.01 + 3.99e6;
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(5.0 - radius, 5.0 - radius, 5.0 + radius, 5.0 + radius), 1e-3));
|
||||
}
|
||||
|
||||
/// The limit holds along each axis on its own: a shape whose right edge would pass 4,000,000 pt is
|
||||
/// refused although its other edges, and its distance along the other axis, are small.
|
||||
#[test]
|
||||
fn one_edge_past_the_canvas_edge_is_enough_to_refuse() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 3_999_980.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
let e = refused(&mut s, command, json!({"offset": 20}));
|
||||
assert!(e.contains("the shape would reach past the edge of the canvas"), "{command}: {e}");
|
||||
}
|
||||
assert!(s.execute(RECTANGLE, &json!({"offset": 5})).is_ok(), "the right edge at 3,999,995 pt is inside");
|
||||
}
|
||||
|
||||
/// A large circle close to the canvas edge, whose arcs stay curved after the most halvings, gets a
|
||||
/// circle within 0.05 pt of the farthest point of its curves, which stays inside the edge.
|
||||
#[test]
|
||||
fn a_large_circle_near_the_canvas_edge_gets_a_close_circle() {
|
||||
let mut s = session();
|
||||
let e = id_of(&s.execute("shape.ellipse", &json!({"x": 3_799_950.0, "y": 0.0, "width": 200_000.0, "height": 200_000.0})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [e.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") };
|
||||
let center = xf * Point::new(w / 2.0, w / 2.0);
|
||||
let mut farthest: f64 = 0.0;
|
||||
for seg in node(&s, e).path_data().unwrap().to_bezpath().segments() {
|
||||
for i in 0..=4000 {
|
||||
farthest = farthest.max(vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0).distance(center));
|
||||
}
|
||||
}
|
||||
assert!(w / 2.0 >= farthest && w / 2.0 < farthest + 0.05, "radius {} for curves reaching {farthest}", w / 2.0);
|
||||
}
|
||||
|
||||
/// The commands are dimmed while an object of a symbol instance's art is selected, which they
|
||||
/// refuse, and available again once it is not.
|
||||
#[test]
|
||||
fn a_selected_symbol_part_dims_the_commands() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let enabled = |s: &Session, id: &str| (crate::find_command(id).unwrap().enabled)(s);
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
assert!(enabled(&s, command).is_ok(), "{command}");
|
||||
}
|
||||
s.doc_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: a, path: vec![0] });
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
assert!(enabled(&s, command).is_err(), "{command} with a symbol part selected");
|
||||
}
|
||||
s.doc_mut().unwrap().selection.symbol_part = None;
|
||||
assert!(enabled(&s, RECTANGLE).is_ok());
|
||||
}
|
||||
|
||||
/// Many points keep only their hull's corners, and the circle around them is the one around all
|
||||
/// of the points.
|
||||
#[test]
|
||||
fn gathered_points_keep_their_hull_and_circle() {
|
||||
let mut g = Gathered::new();
|
||||
let c = Point::new(500.0, 300.0);
|
||||
for i in 0..200_000 {
|
||||
let angle = f64::from(i) * 0.618;
|
||||
let r = if i % 1000 == 0 { 250.0 } else { f64::from(i % 200) };
|
||||
g.points.push(c + Vec2::from_angle(angle) * r);
|
||||
g.compact();
|
||||
}
|
||||
assert!(g.points.len() <= COMPACT_AT + 1, "{} points kept", g.points.len());
|
||||
let (center, radius) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(c) < 1e-6 && (radius - 250.0).abs() < 1e-6, "{center:?} {radius}");
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
|
||||
//! circles, replacing the circles or added above them.
|
||||
//! circles, or three or more each joined the same way to the others within reach and united where
|
||||
//! the bridges connect, replacing the circles or added above them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
@@ -20,6 +21,12 @@ const LABEL: &str = "Smooth Bridge";
|
||||
/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range.
|
||||
const RADIUS: f64 = 100.0;
|
||||
const RADII: (f64, f64) = (1.0, 1000.0);
|
||||
/// The gap (pt) added to the smaller circle's radius to give the arcs' radius: the range.
|
||||
const GAPS: (f64, f64) = (0.0, 1000.0);
|
||||
/// How far apart (pt) the outlines of two of three or more circles may be for a bridge between
|
||||
/// them: by default, and the range.
|
||||
const REACH: f64 = 10.0;
|
||||
const REACHES: (f64, f64) = (0.0, 10000.0);
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -27,16 +34,33 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Smooth Bridge",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}",
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
|
||||
let percent = given(p, "radius", Some(RADII), C)?;
|
||||
let gap = given(p, "gap", Some(GAPS), C)?;
|
||||
let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH);
|
||||
if percent.is_some() && gap.is_some() {
|
||||
// As the parameter check words it (`EXCLUSIVE_KEYS`), for a caller that skips that check.
|
||||
let (key, other) = ("radius", "gap");
|
||||
return Err(bad(C, format!("give `{key}` or `{other}`, not both")));
|
||||
}
|
||||
let arc = match gap {
|
||||
Some(gap) => pt::ArcRadius::Gap(gap),
|
||||
None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0),
|
||||
};
|
||||
let keep = switch_or(p, "keepOriginals", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
// An id given twice is one circle.
|
||||
roots.sort_unstable();
|
||||
roots.dedup();
|
||||
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
|
||||
return Err(bad(C, "select at most 2000 circles to bridge"));
|
||||
}
|
||||
let circles: Vec<(NodeId, pt::Circle)> = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
@@ -48,48 +72,93 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else {
|
||||
return Err(bad(C, "select two circles to bridge"));
|
||||
};
|
||||
let (below, above) = (*below, *above);
|
||||
let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0);
|
||||
let outline = match at(percent) {
|
||||
Ok(sp) => PathData::single(sp),
|
||||
Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")),
|
||||
// A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed.
|
||||
Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => {
|
||||
return Err(bad(C, "the circles are too far apart for this radius: raise the radius"));
|
||||
if circles.len() != roots.len() || circles.len() < 2 {
|
||||
return Err(bad(C, "select two or more circles to bridge"));
|
||||
}
|
||||
let only: Vec<pt::Circle> = circles.iter().map(|(_, c)| *c).collect();
|
||||
// Each shape: the circles it joins, in paint order, and its outline.
|
||||
let (shapes, alone): (Vec<(Vec<NodeId>, PathData)>, Vec<NodeId>) = match only.as_slice() {
|
||||
[a, b] => match pt::smooth_bridge(*a, *b, arc.between(*a, *b)) {
|
||||
Ok(sp) => (vec![(roots_of(&circles, &[0, 1]), PathData::single(sp))], vec![]),
|
||||
Err(e) => return Err(refusal(e, arc, |largest| pt::smooth_bridge(*a, *b, largest.between(*a, *b)).is_ok())),
|
||||
},
|
||||
_ => {
|
||||
let made = pt::bridge_many(&only, arc, reach).map_err(|e| match e {
|
||||
pt::ManyError::TooManyCircles => bad(C, "select at most 2000 circles to bridge"),
|
||||
pt::ManyError::TooManyBridges => bad(C, "that makes too many bridges (at most 8000): lower the reach"),
|
||||
pt::ManyError::NoneInReach => bad(C, "no two circles are within reach: raise the reach"),
|
||||
pt::ManyError::TooComplex => bad(C, "the bridged circles are too complex to unite"),
|
||||
// Under the many-circle rules: a pair the largest radius or gap bridges on its own
|
||||
// can still have a neck too thin to unite among the others.
|
||||
pt::ManyError::Pair(_, _, e) => refusal(e, arc, |largest| pt::bridges_any(&only, largest, reach)),
|
||||
pt::ManyError::Bad => bad(C, "select two or more circles to bridge"),
|
||||
})?;
|
||||
let shapes = made.joined.into_iter().map(|j| (roots_of(&circles, &j.members), j.outline)).collect();
|
||||
(shapes, roots_of(&circles, &made.alone))
|
||||
}
|
||||
Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")),
|
||||
Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")),
|
||||
};
|
||||
let id = s.edit(LABEL, |d, sel| {
|
||||
let id = if keep {
|
||||
// A copy of the upper circle (its appearance) with the outline as its path, right above
|
||||
// it; the circles stay as they are, live shapes included.
|
||||
// Fresh ids throughout, its opacity mask's art included.
|
||||
let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?;
|
||||
let mut n = d.reid(&upper);
|
||||
if let NodeKind::Path { path, live, .. } = &mut n.kind {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
let made = s.edit(LABEL, |d, sel| {
|
||||
let mut made = Vec::with_capacity(shapes.len());
|
||||
if keep {
|
||||
// A copy of each shape's topmost circle (its appearance) with the outline as its path,
|
||||
// right above it; the circles stay as they are, live shapes included. Fresh ids
|
||||
// throughout, an opacity mask's art included.
|
||||
let tops: Vec<NodeId> = shapes.iter().filter_map(|(members, _)| members.last().copied()).collect();
|
||||
let mut beside = Beside::above(d, &tops);
|
||||
for ((_, outline), top) in shapes.into_iter().zip(tops) {
|
||||
let upper = d.node(top).cloned().ok_or(EngineError::NoNode(top))?;
|
||||
let mut n = d.reid(&upper);
|
||||
if let NodeKind::Path { path, live, .. } = &mut n.kind {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
made.push(n.id);
|
||||
beside.put(d, top, vec![n])?;
|
||||
}
|
||||
let id = n.id;
|
||||
let mut beside = Beside::above(d, &[above]);
|
||||
beside.put(d, above, vec![n])?;
|
||||
beside.finish(d)?;
|
||||
id
|
||||
} else {
|
||||
// The upper circle becomes the outline (a plain path now) and the lower one goes.
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
// Each shape's topmost circle becomes its outline (a plain path now) and the others go.
|
||||
let mut gone = vec![];
|
||||
for (members, outline) in shapes {
|
||||
let Some((&top, rest)) = members.split_last() else { continue };
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(top).map(|n| &mut n.kind) {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
made.push(top);
|
||||
gone.extend_from_slice(rest);
|
||||
}
|
||||
remove_each(d, &[below])?;
|
||||
above
|
||||
};
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
remove_each(d, &gone)?;
|
||||
}
|
||||
sel.set(made.iter().chain(&alone).copied());
|
||||
Ok(made)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
let mut out = json!({ "ids": made.iter().map(|id| id.0).collect::<Vec<_>>(), "alone": alone.iter().map(|id| id.0).collect::<Vec<_>>() });
|
||||
if let ([id], 2) = (made.as_slice(), only.len()) {
|
||||
out["id"] = json!(id.0);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
|
||||
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
|
||||
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
|
||||
}
|
||||
|
||||
/// The error for circles that arcs of `arc` can't bridge. A larger radius or gap bridges circles a
|
||||
/// smaller one cannot, so it suggests one only when `bridges` says the largest allowed would.
|
||||
fn refusal(e: pt::BridgeError, arc: pt::ArcRadius, bridges: impl FnOnce(pt::ArcRadius) -> bool) -> EngineError {
|
||||
let largest = match arc {
|
||||
pt::ArcRadius::Share(_) => pt::ArcRadius::Share(RADII.1 / 100.0),
|
||||
pt::ArcRadius::Gap(_) => pt::ArcRadius::Gap(GAPS.1),
|
||||
};
|
||||
let would = e == pt::BridgeError::TooFar && bridges(largest);
|
||||
match (e, arc, would) {
|
||||
(pt::BridgeError::Inside, ..) => bad(C, "one circle is inside the other"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), true) => bad(C, "the circles are too far apart for this radius: raise the radius"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), false) => bad(C, "the circles are too far apart for this radius"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), true) => bad(C, "the circles are too far apart for this gap: raise the gap"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), false) => bad(C, "the circles are too far apart for this gap"),
|
||||
(pt::BridgeError::Bad, ..) => bad(C, "select two or more circles to bridge"),
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
|
||||
//! and what it refuses.
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius or
|
||||
//! gap, many circles joined to their neighbors within reach, and what it refuses.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
@@ -46,6 +46,8 @@ fn two_circles_become_one_outline_in_the_upper_ones_place() {
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute(BRIDGE, &json!({})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0));
|
||||
assert_eq!(r["ids"], json!([b.0]), "the same result fields as for more circles");
|
||||
assert_eq!(r["alone"], json!([]));
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") };
|
||||
@@ -158,9 +160,11 @@ fn far_apart_nested_and_other_objects_are_refused() {
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other"));
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}");
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, square.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two or more circles to bridge"), "{ids}");
|
||||
}
|
||||
// Three circles: each two within reach are bridged, and one inside another is refused there too.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0, inner.0]})).contains("one circle is inside the other"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number"));
|
||||
@@ -169,6 +173,174 @@ fn far_apart_nested_and_other_objects_are_refused() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100).
|
||||
fn grid(s: &mut Session) -> Vec<NodeId> {
|
||||
(0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect()
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_of_circles_joins_each_to_its_neighbors_in_one_shape() {
|
||||
let mut s = session();
|
||||
let g = grid(&mut s);
|
||||
select(&mut s, &g);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// Reach 5: the side neighbors (4 apart) are bridged, the diagonal ones (about 13.9 apart) not.
|
||||
let r = s.execute(BRIDGE, &json!({"gap": 4, "reach": 5})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [g[8]], "one shape, in the topmost circle's place");
|
||||
assert_eq!(ids(&r["alone"]), []);
|
||||
assert_eq!(top_level(&s), [g[8]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g[8]]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
// Its outline and a hole in each square of four circles, which no diagonal bridge fills.
|
||||
let outline = path(&s, g[8]);
|
||||
assert_eq!(outline.subpaths.len(), 5, "{}", outline.subpaths.len());
|
||||
let inside = |p: &vectorcraft_geom::PathData, x: f64, y: f64| p.to_bezpath().winding(vectorcraft_geom::kurbo::Point::new(x, y)) != 0;
|
||||
assert!(inside(&outline, 112.0, 100.0) && inside(&outline, 100.0, 112.0) && !inside(&outline, 112.0, 112.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(top_level(&s), g);
|
||||
// Reach 15 takes in the diagonal neighbors, whose bridges fill the middle of each square.
|
||||
select(&mut s, &g);
|
||||
s.execute(BRIDGE, &json!({"gap": 4, "reach": 15})).unwrap();
|
||||
let outline = path(&s, g[8]);
|
||||
assert_eq!(outline.subpaths.len(), 1);
|
||||
assert!(inside(&outline, 112.0, 112.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_with_no_neighbor_in_reach_stays_as_it_is() {
|
||||
let mut s = session();
|
||||
let g = grid(&mut s);
|
||||
let far = circle(&mut s, 300.0, 250.0, 10.0);
|
||||
let pair = [circle(&mut s, 300.0, 40.0, 8.0), circle(&mut s, 320.0, 40.0, 8.0)];
|
||||
let mut all = g.clone();
|
||||
all.extend([far, pair[0], pair[1]]);
|
||||
let r = s.execute(BRIDGE, &json!({"ids": all.iter().map(|i| i.0).collect::<Vec<_>>(), "reach": 5})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [g[8], pair[1]]);
|
||||
assert_eq!(ids(&r["alone"]), [far]);
|
||||
assert_eq!(top_level(&s), [g[8], far, pair[1]]);
|
||||
assert!(matches!(&s.doc().unwrap().doc.node(far).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "untouched");
|
||||
let mut selected = s.doc().unwrap().selection.objects.to_vec();
|
||||
selected.sort();
|
||||
let mut want = vec![g[8], pair[1], far];
|
||||
want.sort();
|
||||
assert_eq!(selected, want, "the shapes and the circle left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_originals_adds_each_shape_above_its_topmost_circle() {
|
||||
let mut s = session();
|
||||
let row: Vec<NodeId> = (0..3).map(|i| circle(&mut s, 100.0 + 25.0 * i as f64, 100.0, 10.0)).collect();
|
||||
let other = [circle(&mut s, 100.0, 200.0, 10.0), circle(&mut s, 122.0, 200.0, 10.0)];
|
||||
s.execute("paint.setFill", &json!({"ids": [row[2].0], "color": "#00ff00"})).unwrap();
|
||||
let all: Vec<u64> = row.iter().chain(&other).map(|i| i.0).collect();
|
||||
let r = s.execute(BRIDGE, &json!({"ids": all, "keepOriginals": true})).unwrap();
|
||||
let made = ids(&r["ids"]);
|
||||
assert_eq!(made.len(), 2);
|
||||
assert_eq!(top_level(&s), [row[0], row[1], row[2], made[0], other[0], other[1], made[1]]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(made[0]).unwrap().appearance, d.node(row[2]).unwrap().appearance, "painted as the topmost circle");
|
||||
let b = d.node(made[0]).unwrap().path_data().unwrap().bounds().unwrap();
|
||||
assert!((b.x0 - 90.0).abs() < 1e-2 && (b.x1 - 160.0).abs() < 1e-2, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gap_form_gives_arcs_the_smaller_radius_plus_the_gap() {
|
||||
let area_with = |p: Value| {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 124.0, 100.0, 10.0);
|
||||
let mut p = p;
|
||||
p["ids"] = json!([a.0, b.0]);
|
||||
let id = NodeId(s.execute(BRIDGE, &p).unwrap()["id"].as_u64().unwrap());
|
||||
area(&s, id)
|
||||
};
|
||||
// Radius 10 plus a gap of 4 is 140% of 10.
|
||||
let (gap, percent) = (area_with(json!({"gap": 4})), area_with(json!({"radius": 140})));
|
||||
assert!((gap - percent).abs() < 1e-9, "{gap} {percent}");
|
||||
assert!(area_with(json!({"gap": 0})) < gap && gap < area_with(json!({"gap": 20})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_circle_and_gap_refusals() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 50.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 250.0, 100.0, 10.0);
|
||||
let c = circle(&mut s, 330.0, 100.0, 10.0);
|
||||
let far = circle(&mut s, 380.0, 100.0, 10.0);
|
||||
let before = top_level(&s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "radius": 100, "gap": 4})).contains("give `radius` or `gap`, not both"));
|
||||
// Centers 200 apart: a gap of 0 does not bridge them, the largest (1000 pt) does. With centers
|
||||
// 330 apart even that one closes the neck: it stays open only below 2 × √(10² + 2 × 10 × 1010)
|
||||
// ≈ 285.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 0})).ends_with("too far apart for this gap: raise the gap"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "gap": 0})).ends_with("the circles are too far apart for this gap"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 5})).contains("no two circles are within reach: raise the reach"));
|
||||
// b and c are 60 apart: within a reach of 100, but too far for the default radius.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 100})).ends_with("too far apart for this radius: raise the radius"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": -1})).contains("`reach` must be from 0 to 10000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 1001})).contains("`gap` must be from 0 to 1000"));
|
||||
assert_eq!(top_level(&s), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_larger_radius_is_suggested_only_when_it_bridges_among_the_other_circles() {
|
||||
let mut s = session();
|
||||
// Centers 91.65 apart: the largest radius (1000%, 100 pt) bridges these two on their own, but
|
||||
// with a neck about 0.0007 pt wide, too thin to unite among three or more circles.
|
||||
let a = circle(&mut s, 20.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 111.65, 100.0, 10.0);
|
||||
let far = circle(&mut s, 380.0, 100.0, 10.0);
|
||||
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": 1000})).is_ok());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).ends_with("too far apart for this radius: raise the radius"));
|
||||
for radius in [100, 1000] {
|
||||
let e = err(&mut s, json!({"ids": [a.0, b.0, far.0], "radius": radius, "reach": 100}));
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_circles_or_bridges_are_refused() {
|
||||
let mut s = session();
|
||||
// 130 overlapping circles in a row: 8,385 pairs within reach.
|
||||
let row: Vec<u64> = (0..130).map(|i| circle(&mut s, 20.0 + i as f64 * 0.2, 100.0, 10.0).0).collect();
|
||||
assert!(err(&mut s, json!({ "ids": row })).contains("that makes too many bridges (at most 8000): lower the reach"));
|
||||
let many: Vec<u64> = (0..2001).map(|i| circle(&mut s, 20.0 + (i % 50) as f64 * 7.0, 150.0 + (i / 50) as f64 * 3.0, 1.0).0).collect();
|
||||
assert!(err(&mut s, json!({ "ids": many })).contains("select at most 2000 circles to bridge"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_given_twice_is_one_circle() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
let r = s.execute(BRIDGE, &json!({"ids": [a.0, a.0, b.0]})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0), "two circles, bridged");
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() {
|
||||
let mut s = session();
|
||||
// Radius 3: arcs of 3 pt (100%) join a and b (2 apart) but close before reaching c (6 from b,
|
||||
// within the default reach of 10).
|
||||
let (a, b, c) = (circle(&mut s, 100.0, 100.0, 3.0), circle(&mut s, 108.0, 100.0, 3.0), circle(&mut s, 120.0, 100.0, 3.0));
|
||||
let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [b]);
|
||||
assert_eq!(ids(&r["alone"]), [c]);
|
||||
assert_eq!(top_level(&s), [b, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let mut s = session();
|
||||
@@ -176,9 +348,9 @@ fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
|
||||
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
|
||||
//! crossing into either, added as separate open paths, with the line joining their centers if
|
||||
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it
|
||||
//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Common Tangents",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
has_selection,
|
||||
common_tangents
|
||||
)]
|
||||
}
|
||||
|
||||
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
|
||||
/// else the path's one closed convex subpath.
|
||||
/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact
|
||||
/// ellipse for a whole live ellipse, else the path's one closed convex subpath.
|
||||
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
|
||||
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
if sp.anchors.len() == 1
|
||||
&& let Some(only) = sp.anchors.first()
|
||||
{
|
||||
return pt::Outline::point(only.p).map_err(refusal);
|
||||
}
|
||||
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
if span < 1e-9 || 360.0 - span < 1e-9 {
|
||||
@@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ordered = d.paint_order(roots.iter().copied());
|
||||
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
|
||||
if a.is_point() && b.is_point() {
|
||||
return Err(bad(C, "select two closed paths"));
|
||||
}
|
||||
// A point goes first, so that each line runs from it to where it touches the path.
|
||||
let point = a.is_point() || b.is_point();
|
||||
let (a, b) = if b.is_point() { (b, a) } else { (a, b) };
|
||||
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
|
||||
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
|
||||
let keep = |t: &&pt::Tangent| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
// A point's external and internal tangents are the same lines: every kind keeps them.
|
||||
let keep = |t: &&pt::Tangent| {
|
||||
point
|
||||
|| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
|
||||
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
|
||||
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
|
||||
let (external_kept, internal_kept) = match (point, kinds) {
|
||||
(true, "internal") => (0, kept.len()),
|
||||
(true, _) => (kept.len(), 0),
|
||||
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
|
||||
};
|
||||
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
|
||||
if lines.is_empty() && point {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds it.
|
||||
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
|
||||
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
|
||||
}
|
||||
if lines.is_empty() {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
|
||||
// external tangent means one path lies inside the other and touches it there; paths that
|
||||
|
||||
@@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() {
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
}
|
||||
|
||||
fn point(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() {
|
||||
let mut s = session();
|
||||
// The point is drawn after the oval, so it is the upper object; the lines still start at it.
|
||||
let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap());
|
||||
let dot = point(&mut s, 100.0, 200.0);
|
||||
select(&mut s, &[oval, dot]);
|
||||
let before = steps(&s);
|
||||
let r = s.execute(C, &json!({"centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 3, "two tangents and the centerline");
|
||||
let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
|
||||
// From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points
|
||||
// are x = -a²/200 = -8, y = ±b √(1 - x²/a²).
|
||||
let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt();
|
||||
for sy in [1.0, -1.0] {
|
||||
let touch = c + Vec2::new(-8.0, sy * y);
|
||||
assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}");
|
||||
}
|
||||
assert_eq!(r["centerline"], r["ids"][2]);
|
||||
assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]);
|
||||
// Every `tangents` value gives the same two lines.
|
||||
for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] {
|
||||
let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}");
|
||||
assert_eq!(lines(&s, &r).len(), 2, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_below_the_path_still_starts_the_lines() {
|
||||
let mut s = session();
|
||||
// The point is drawn first, so it is the lower object and needs no swap.
|
||||
let dot = point(&mut s, 100.0, 200.0);
|
||||
let round = circle(&mut s, 300.0, 200.0, 50.0);
|
||||
let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 3, "two tangents and the centerline");
|
||||
let p = Point::new(100.0, 200.0);
|
||||
assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}");
|
||||
// From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long.
|
||||
let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt();
|
||||
assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}");
|
||||
assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_on_or_inside_a_path_and_two_points() {
|
||||
let mut s = session();
|
||||
let round = circle(&mut s, 200.0, 200.0, 50.0);
|
||||
// On the circle: one line, centered on the point and as long as the circle is wide.
|
||||
let on = point(&mut s, 250.0, 200.0);
|
||||
let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap();
|
||||
assert_eq!(r["external"].as_u64(), Some(1), "{r}");
|
||||
let (p, q) = lines(&s, &r)[0];
|
||||
assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}");
|
||||
// Inside: nothing changes, and the warning says why.
|
||||
let inside = point(&mut s, 210.0, 190.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
// Two points, or a point and an open path, are refused.
|
||||
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths"));
|
||||
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
|
||||
assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open"));
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_selections_and_params_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveCorners, LiveShape, NodeId};
|
||||
use vectorcraft_geom::shapes::CornerKind;
|
||||
use vectorcraft_geom::{AnchorKind, PathData, Point, SubPath};
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
use vectorcraft_tools::{Action, Overlay, PointerEvent, PointerKind};
|
||||
|
||||
use crate::{Session, ViewInfo};
|
||||
|
||||
@@ -1055,6 +1055,37 @@ fn the_slide_tool_previews_and_commits_one_step() {
|
||||
assert_eq!(at(&s), Point::new(200.0, 100.0));
|
||||
}
|
||||
|
||||
/// The Tangent Circle tool's release draws the circle and then tells the tool, which forgets the
|
||||
/// first segment. When the command fails the session does not tell the tool, so the first segment
|
||||
/// stays picked: the circle shows again over the second segment. The second click draws it in one
|
||||
/// undo step.
|
||||
#[test]
|
||||
fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() {
|
||||
let mut s = session();
|
||||
line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
|
||||
line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("tangentCircle", view).unwrap();
|
||||
let at = |s: &mut Session, kind, x, y| s.pointer(&PointerEvent::new(kind, x, y), view);
|
||||
let shown = |s: &mut Session| {
|
||||
at(s, PointerKind::Move, 200.0, 139.0).unwrap();
|
||||
s.overlays(view).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00")))
|
||||
};
|
||||
at(&mut s, PointerKind::Down, 150.0, 101.0).unwrap();
|
||||
at(&mut s, PointerKind::Up, 150.0, 101.0).unwrap();
|
||||
assert!(shown(&mut s), "the first segment is picked");
|
||||
// The tool's release with a command that fails: three points on one line.
|
||||
let n = steps(&s);
|
||||
let failing = Action::Exec("shape.circleThroughPoints".into(), json!({"points": [[0, 0], [10, 0], [20, 0]]}));
|
||||
assert!(s.apply_actions(vec![failing, Action::Notify("tangentCircle.drawn".into())]).is_err());
|
||||
assert_eq!(steps(&s), n, "nothing drawn");
|
||||
assert!(shown(&mut s), "the first segment is still picked");
|
||||
at(&mut s, PointerKind::Down, 200.0, 139.0).unwrap();
|
||||
at(&mut s, PointerKind::Up, 200.0, 139.0).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn");
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
@@ -22,8 +22,8 @@ const SELECTION_SIZE: &str = "addon.units.selectionSize";
|
||||
const SHOWN_CHARS: usize = 64;
|
||||
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
|
||||
const MAX_TEXT_LEN: usize = 1024;
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
|
||||
/// level of recursion per sign.
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`, a multiplication sign
|
||||
/// counted as a `*`: [`Unit::parse`] takes one level of recursion per sign.
|
||||
const MAX_OPERATORS: usize = 128;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
@@ -88,9 +88,9 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
|
||||
/// signs?
|
||||
/// signs, a multiplication sign typed as `x`, `X` or `×` counted as a `*` ([`arithmetic_signs`])?
|
||||
fn readable(s: &str) -> bool {
|
||||
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
|
||||
s.len() <= MAX_TEXT_LEN && arithmetic_signs(s) <= MAX_OPERATORS
|
||||
}
|
||||
|
||||
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
|
||||
|
||||
@@ -76,6 +76,12 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
// x, X and × multiply as * does, and each counts toward the 128 signs.
|
||||
assert!(near(pt(&mut s, json!({"value": "2x3 mm"})), 6.0 * 72.0 / 25.4));
|
||||
assert!(near(pt(&mut s, json!({"value": "10X2"})), 20.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "0,5×4 in"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "x1".repeat(128))})), 1.0));
|
||||
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -278,6 +278,28 @@ impl ItemTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
|
||||
/// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
|
||||
/// ([`super::paint::live_paint_parts_skipped`]).
|
||||
pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result<Vec<NodeId>> {
|
||||
Ok(self.targets_and_skipped(s, p, fill)?.0)
|
||||
}
|
||||
|
||||
/// [`ItemTarget::targets_for`], and whether it left out any object inside a Live Paint group: a
|
||||
/// group with no part of the edited kind was still given or selected, so the edit does not go
|
||||
/// to new art.
|
||||
pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec<NodeId>, bool)> {
|
||||
let mut ids = self.targets(s, p)?;
|
||||
let mut skipped_any = false;
|
||||
if self == ItemTarget::Top {
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
|
||||
let before = ids.len();
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
skipped_any = ids.len() != before;
|
||||
}
|
||||
Ok((ids, skipped_any))
|
||||
}
|
||||
|
||||
/// The target of a fill (`fill`) or stroke edit: the panel's active item stands only for edits
|
||||
/// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted
|
||||
/// leaves (as without an active item) and vice versa. Explicit items are kept (and checked).
|
||||
@@ -772,7 +794,7 @@ fn edit_items_writing_then(
|
||||
// The objects whose rows `f` edited: on type, no row means its characters.
|
||||
let mut rows = Vec::new();
|
||||
// The objects where `f` wrote the topmost visible row of its kind.
|
||||
let mut wrote = Vec::new();
|
||||
let mut wrote = HashSet::new();
|
||||
// The row of each object `f` wrote: its index, else the topmost row of the kind.
|
||||
let mut written = Vec::new();
|
||||
for (id, item) in ids.iter().zip(&per) {
|
||||
@@ -785,7 +807,7 @@ fn edit_items_writing_then(
|
||||
rows.push(*id);
|
||||
}
|
||||
if index.is_none_or(|i| is_top_shown(n, i)) {
|
||||
wrote.push(*id);
|
||||
wrote.insert(*id);
|
||||
}
|
||||
written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at)));
|
||||
}
|
||||
@@ -1341,7 +1363,8 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, written));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id));
|
||||
let wrote: HashSet<NodeId> = edited.iter().map(|(id, _)| *id).collect();
|
||||
let reached = shown_rows_edited(&before, d, reached, |id| wrote.contains(&id));
|
||||
let labels = capture_row_edits(&before, d, &reached);
|
||||
// A graph line keeps what was written to its topmost visible row, also when it already showed it.
|
||||
let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect();
|
||||
@@ -1503,7 +1526,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
let top_copies: Vec<NodeId> = added.iter().map(|(id, _)| *id).collect();
|
||||
let top_copies: HashSet<NodeId> = added.iter().map(|(id, _)| *id).collect();
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id)));
|
||||
|
||||
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export 3D Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side (in a group, the side of the member with the longest profile) are a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles; its end caps and cut sides stay plain. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
has_doc,
|
||||
export_3d
|
||||
),
|
||||
|
||||
@@ -12,8 +12,9 @@ use super::overprint::{AttributesInfo, apply_overprint, edit_counted, overprint_
|
||||
use super::path::paths_in;
|
||||
use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, str_param, targets};
|
||||
|
||||
/// How many URLs the Attributes panel's recent list keeps.
|
||||
const RECENT_URLS: usize = 10;
|
||||
/// How many URLs the Attributes panel's recent list keeps: the most its Panel Options lets the
|
||||
/// URL menu list.
|
||||
pub const RECENT_URLS: usize = 30;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -22,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
|
||||
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info, newest first, at most 30) → {changed: objects}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
|
||||
@@ -12,10 +12,11 @@ use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{
|
||||
self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation,
|
||||
self as brush, ArtBrush, ArtScale, 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_doc::{Appearance, AppearanceItem, Document, FillLayer, ImageBlob, ImageObject, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::brushsym::{apply_brush, brush_targets, roots, stroke_paint};
|
||||
@@ -172,13 +173,17 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
|
||||
BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash },
|
||||
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
|
||||
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
|
||||
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: "stipple", name: "Stipple", make: stipple },
|
||||
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 },
|
||||
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
|
||||
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
|
||||
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -232,6 +237,54 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length).
|
||||
fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush {
|
||||
Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Art(ArtBrush {
|
||||
art,
|
||||
scale: ArtScale::BetweenGuides { start, end },
|
||||
colorization: Colorization::Tints,
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Arrows: original art brushes whose stems stretch while their heads keep their proportions.
|
||||
fn arrows() -> BrushLibrary {
|
||||
let shaft = || black(shapes::rectangle(Rect::new(0.0, -1.0, 82.0, 1.0)));
|
||||
let head = || black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (82.0, 0.0)]));
|
||||
let solid = group(vec![shaft(), head()]);
|
||||
let outline = group(vec![shaft(), black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (78.0, 4.0), (91.0, 0.0), (78.0, -4.0)]))]);
|
||||
let double = group(vec![
|
||||
black(shapes::rectangle(Rect::new(18.0, -1.0, 82.0, 1.0))),
|
||||
head(),
|
||||
black(polygon(&[(24.0, -7.0), (0.0, 0.0), (24.0, 7.0), (18.0, 0.0)])),
|
||||
]);
|
||||
let chevrons = group(vec![shaft(), head(), black(polygon(&[(53.0, -5.0), (66.0, 0.0), (53.0, 5.0), (56.0, 0.0)]))]);
|
||||
let dashed = group(
|
||||
(0..5)
|
||||
.map(|i| {
|
||||
let x = f64::from(i) * 16.0;
|
||||
black(shapes::rectangle(Rect::new(x, -1.0, x + 10.0, 1.0)))
|
||||
})
|
||||
.chain(std::iter::once(head()))
|
||||
.collect(),
|
||||
);
|
||||
built(
|
||||
"Arrows",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
arrow_art("Solid Arrow", solid, 0.0, 0.76),
|
||||
arrow_art("Open Arrow", outline, 0.0, 0.76),
|
||||
arrow_art("Double Arrow", double, 0.24, 0.76),
|
||||
// The second chevron starts at 53 pt, so only the shaft before it stretches.
|
||||
arrow_art("Chevron Arrow", chevrons, 0.0, 0.53),
|
||||
arrow_art("Dashed Arrow", dashed, 0.0, 0.76),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's
|
||||
/// own pattern, Pinstripes.
|
||||
fn art_ribbons() -> BrushLibrary {
|
||||
@@ -374,6 +427,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o
|
||||
Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) }
|
||||
}
|
||||
|
||||
/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen
|
||||
/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering.
|
||||
fn pressure_sensitive() -> BrushLibrary {
|
||||
let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin()));
|
||||
let pulse = group(vec![
|
||||
black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
|
||||
black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))),
|
||||
]);
|
||||
let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Art(ArtBrush {
|
||||
art,
|
||||
width: light,
|
||||
width_mode: Some(Variation::Pressure),
|
||||
width_max: Some(heavy),
|
||||
colorization: Colorization::Tints,
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Calligraphic(Calligraphic {
|
||||
angle,
|
||||
roundness,
|
||||
size,
|
||||
variation: [0.0, 0.0, variation],
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
|
||||
}),
|
||||
};
|
||||
built(
|
||||
"Pressure Sensitive",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
art_pressure("Flex Ribbon", flex, 35.0, 250.0),
|
||||
art_pressure("Pulse Stroke", pulse, 45.0, 280.0),
|
||||
nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0),
|
||||
nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for
|
||||
/// blending and texture.
|
||||
fn bristle_brushes() -> BrushLibrary {
|
||||
@@ -479,6 +573,80 @@ fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
|
||||
}
|
||||
|
||||
/// Four original raster stamps. Scatter brushes preserve their image art while placing a copy
|
||||
/// along the path; art brushes bend their art and cannot bend an image. Each 24 px stamp is placed
|
||||
/// 6 pt wide, the size of the Scatter Shapes art, so a 1 pt stroke on a 10 pt line shows a stamp.
|
||||
fn image_brush() -> BrushLibrary {
|
||||
const SIDE: u32 = 24;
|
||||
const PT_PER_PX: f64 = 0.25;
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut brushes = Vec::new();
|
||||
for (index, name) in ["Soft Bloom", "Halftone Field", "Solar Grain", "Color Flecks"].into_iter().enumerate() {
|
||||
let mut pixels = Vec::with_capacity((SIDE * SIDE * 4) as usize);
|
||||
for y in 0..SIDE {
|
||||
for x in 0..SIDE {
|
||||
let (dx, dy) = (x as f64 - 11.5, y as f64 - 11.5);
|
||||
let r = dx.hypot(dy);
|
||||
let angle = dy.atan2(dx);
|
||||
let rgba = match index {
|
||||
0 => {
|
||||
let edge = 7.0 + 3.0 * (5.0 * angle).cos();
|
||||
[199, 69, 139, (220.0 * ((edge - r) / 2.5).clamp(0.0, 1.0)) as u8]
|
||||
}
|
||||
1 => {
|
||||
let (gx, gy) = ((x % 6) as f64 - 2.5, (y % 6) as f64 - 2.5);
|
||||
[39, 139, 175, if r < 11.0 && gx.hypot(gy) < 1.9 { 225 } else { 0 }]
|
||||
}
|
||||
2 => {
|
||||
let ray = (9.0 * angle).cos().abs();
|
||||
[234, 144, 40, if r < 3.5 || (r < 10.5 && ray > 0.72) { 235 } else { 0 }]
|
||||
}
|
||||
_ => {
|
||||
let seed = (x * 37 + y * 71 + x * y * 13) % 19;
|
||||
[if seed % 2 == 0 { 67 } else { 114 }, 79, 167, if r < 11.0 && seed < 5 { 210 } else { 0 }]
|
||||
}
|
||||
};
|
||||
pixels.extend_from_slice(&rgba);
|
||||
}
|
||||
}
|
||||
let Ok(image) =
|
||||
craft_image_codecs::Image::from_raw(SIDE, SIDE, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(png) = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else {
|
||||
continue;
|
||||
};
|
||||
let key = format!("image-brush-{index}");
|
||||
doc.images.insert(key.clone(), ImageBlob::png(png));
|
||||
let art = Node::new(
|
||||
NodeId(0),
|
||||
NodeKind::Image(Box::new(ImageObject {
|
||||
key,
|
||||
width: SIDE,
|
||||
height: SIDE,
|
||||
xf: Affine::scale(PT_PER_PX) * Affine::translate((-12.0, -12.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
})),
|
||||
);
|
||||
brushes.push(scatter(
|
||||
name,
|
||||
art,
|
||||
Scatter {
|
||||
size: (90.0, 110.0),
|
||||
spacing: (125.0, 155.0),
|
||||
scatter: (-20.0, 20.0),
|
||||
rotation: (-15.0, 15.0),
|
||||
colorization: Colorization::None,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
}
|
||||
built("Image Brush", doc, brushes)
|
||||
}
|
||||
|
||||
/// Scatter Shapes: scatter brushes of shapes drawn here; Sparkles scatters the library's own
|
||||
/// symbol, Sparkle.
|
||||
fn scatter_shapes() -> BrushLibrary {
|
||||
@@ -535,6 +703,44 @@ fn scatter_shapes() -> BrushLibrary {
|
||||
built("Scatter Shapes", doc, brushes)
|
||||
}
|
||||
|
||||
/// Stipple: original dot-based scatter brushes for fine and broad shading along a path.
|
||||
fn stipple() -> BrushLibrary {
|
||||
let dot = |x: f64, y: f64, r: f64, opacity: f32| {
|
||||
Node::path(
|
||||
NodeId(0),
|
||||
shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)),
|
||||
Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer { opacity, ..FillLayer::new(Paint::solid(Color::BLACK)) })],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
};
|
||||
let base = Scatter { colorization: Colorization::Tints, ..Default::default() };
|
||||
let brushes = vec![
|
||||
scatter(
|
||||
"Fine Stipple",
|
||||
dot(0.0, 0.0, 0.8, 1.0),
|
||||
Scatter { size: (70.0, 110.0), spacing: (80.0, 130.0), scatter: (-100.0, 100.0), ..base.clone() },
|
||||
),
|
||||
scatter(
|
||||
"Dense Stipple",
|
||||
group(vec![dot(-1.7, -1.4, 1.0, 1.0), dot(1.5, 0.5, 0.8, 1.0), dot(-0.5, 1.8, 0.65, 1.0)]),
|
||||
Scatter { size: (80.0, 120.0), spacing: (55.0, 90.0), scatter: (-70.0, 70.0), ..base.clone() },
|
||||
),
|
||||
scatter(
|
||||
"Soft Stipple",
|
||||
group(vec![dot(-1.2, -0.8, 1.0, 0.45), dot(1.2, 1.1, 0.7, 0.35)]),
|
||||
Scatter { size: (55.0, 135.0), spacing: (80.0, 140.0), scatter: (-140.0, 140.0), ..base.clone() },
|
||||
),
|
||||
scatter(
|
||||
"Bold Stipple",
|
||||
group(vec![dot(-1.5, -1.0, 1.8, 1.0), dot(1.6, 1.3, 1.4, 1.0)]),
|
||||
Scatter { size: (80.0, 125.0), spacing: (75.0, 115.0), scatter: (-95.0, 95.0), ..base },
|
||||
),
|
||||
];
|
||||
built("Stipple", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// Game Trails: art brushes for motion lines and impact streaks (original game HUD / VFX art).
|
||||
fn game_trails() -> BrushLibrary {
|
||||
let speed = {
|
||||
|
||||
Loaded 100 of 674 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user