mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 01:10:54 +01:00
Merge remote-tracking branch 'origin/main' into fix/outline-stroke-context-menu
# Conflicts: # docs/gaps.md # docs/target-app-parity.md # docs/ui-parity.md
This commit is contained in:
commit
042c4db8e8
664 files changed
+70719
-4728
No files matched your search
Generated
+16
-13
@@ -217,7 +217,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -986,12 +986,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1060,7 +1060,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1081,7 +1081,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1108,7 +1108,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1620,7 +1620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3869,7 +3869,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4391,7 +4391,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4769,7 +4769,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4828,7 +4828,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5687,7 +5687,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6326,6 +6326,7 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"futures-lite",
|
||||
"image",
|
||||
"log",
|
||||
"muda",
|
||||
@@ -6475,6 +6476,7 @@ dependencies = [
|
||||
"vectorcraft-plugins",
|
||||
"vectorcraft-text",
|
||||
"vectorcraft-three-d",
|
||||
"vectorcraft-trace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6853,6 +6855,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"toml",
|
||||
"vectorcraft-apischema",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-cad",
|
||||
"vectorcraft-color",
|
||||
@@ -7516,7 +7519,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+3
-3
@@ -14,18 +14,18 @@ repository = "https://github.com/storytold/vectorcraft"
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
|
||||
@@ -238,14 +238,17 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
prefs_dir::attach_profile_store(&mut h.session);
|
||||
prefs_dir::attach_color_settings(&mut h.session);
|
||||
prefs_dir::attach_plugin_store(&mut h.session);
|
||||
prefs_dir::attach_pdf_preset_store(&mut h.session);
|
||||
prefs_dir::attach_custom_dictionary(&mut h.session);
|
||||
prefs_dir::attach_arrowheads(&mut h.session);
|
||||
h
|
||||
}
|
||||
|
||||
|
||||
@@ -107,6 +107,9 @@ wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
|
||||
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
|
||||
# through winit and rfd.
|
||||
wayland-backend = { version = "0.3", features = ["client_system"] }
|
||||
# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same
|
||||
# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus.
|
||||
futures-lite = "2"
|
||||
|
||||
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
|
||||
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::portal_save;
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::tablet;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::{linux_screen_color, tablet};
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::{mac_save_format, mac_screen_color, mac_tablet};
|
||||
|
||||
@@ -354,8 +354,10 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
@@ -408,6 +410,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Linux: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the XDG desktop
|
||||
//! portal's color sampler ([`portal`]). A thread of its own asks the portal and waits for the
|
||||
//! person, so the UI keeps drawing; it sends the color to the UI and wakes the window. The dialog's
|
||||
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
|
||||
|
||||
mod portal;
|
||||
mod request;
|
||||
|
||||
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
|
||||
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let (ui, window) = (ui.clone(), parent.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
// The thread names the window and holds it until the export that names it is dropped.
|
||||
let (handle, export) = match window.as_deref() {
|
||||
Some(window) => {
|
||||
let (handle, export) = super::portal_save::exported_parent(window);
|
||||
(handle, Some(export))
|
||||
}
|
||||
None => (String::new(), None),
|
||||
};
|
||||
let picked = portal::connect(zbus::blocking::connection::Builder::session()).and_then(|conn| portal::pick(&conn, &handle));
|
||||
drop(export);
|
||||
drop(window);
|
||||
let answer = picked.map_err(|failure| {
|
||||
log::warn!("the portal's screen color sampler gave no color: {}", failure.detail());
|
||||
failure.message().to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
"the screen color sampler failed".to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
//! The XDG desktop portal's `Screenshot.PickColor`
|
||||
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html>):
|
||||
//! the call returns a request path at once, and the request's `Response` signal later carries the
|
||||
//! color the person picked, as sRGB components from 0 to 1, or a code for a cancel or another end.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use zbus::blocking::{Connection, Proxy};
|
||||
use zbus::zvariant::{OwnedValue, Value};
|
||||
|
||||
/// How long the portal has to return a request path for `PickColor`. VectorCraft's own limit,
|
||||
/// 25 seconds as libdbus's default for a method call. The portal returns the path before it shows
|
||||
/// the sampler, so the person's time with the sampler does not count.
|
||||
const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
|
||||
|
||||
/// Why no color came back, as the status bar shows it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Failure {
|
||||
/// No session bus, no portal, or a portal without the Screenshot interface's `PickColor`.
|
||||
Unavailable(String),
|
||||
/// The portal did not return a request path in time, or it left the bus before it answered.
|
||||
NoAnswer(String),
|
||||
/// The portal ended the request without a color, or its answer can't be read.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
/// The status bar's message (English; the status bar translates it).
|
||||
pub(super) fn message(&self) -> &'static str {
|
||||
match self {
|
||||
Failure::Unavailable(_) => "this system has no screen color sampler",
|
||||
Failure::NoAnswer(_) => "the screen color sampler did not answer",
|
||||
Failure::Failed(_) => "the screen color sampler failed",
|
||||
}
|
||||
}
|
||||
|
||||
/// What went wrong, for the log.
|
||||
pub(super) fn detail(&self) -> &str {
|
||||
match self {
|
||||
Failure::Unavailable(d) | Failure::NoAnswer(d) | Failure::Failed(d) => d,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// D-Bus errors that mean the session has no portal, or none that answers `PickColor`.
|
||||
const UNAVAILABLE: &[&str] = &[
|
||||
"org.freedesktop.DBus.Error.ServiceUnknown",
|
||||
"org.freedesktop.DBus.Error.NameHasNoOwner",
|
||||
"org.freedesktop.DBus.Error.UnknownMethod",
|
||||
"org.freedesktop.DBus.Error.UnknownInterface",
|
||||
"org.freedesktop.DBus.Error.UnknownObject",
|
||||
];
|
||||
|
||||
/// The connection `builder` makes, with [`CALL_TIMEOUT`] for its method calls.
|
||||
pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<'_>>) -> Result<Connection, Failure> {
|
||||
builder.and_then(|b| b.method_timeout(CALL_TIMEOUT).build()).map_err(|e| Failure::Unavailable(e.to_string()))
|
||||
}
|
||||
|
||||
/// Shows the portal's color sampler over the window `parent` names and waits for the color, `None`
|
||||
/// when the person canceled it. `conn`'s method timeout bounds the call; the wait for the person
|
||||
/// after it has no bound, and ends when the portal answers or leaves the bus.
|
||||
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
let token = super::request::token("vectorcraft_color").map_err(Failure::Failed)?;
|
||||
// Made before the call: a portal can send its answer before the call returns.
|
||||
let replies = super::request::Responses::new(conn).map_err(Failure::Failed)?;
|
||||
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
|
||||
.map_err(|e| Failure::Failed(e.to_string()))?;
|
||||
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
|
||||
let call = proxy.call_method("PickColor", &(parent, options)).map_err(|e| call_failure(&e))?;
|
||||
let reply = replies.wait(&call).map_err(Failure::NoAnswer)?;
|
||||
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| Failure::Failed(e.to_string()))?;
|
||||
answer(code, &results)
|
||||
}
|
||||
|
||||
/// The [`Failure`] for an error the `PickColor` call returned. zbus reports a call that outlives
|
||||
/// the connection's method timeout as an `InputOutput` error of kind `TimedOut`.
|
||||
fn call_failure(e: &zbus::Error) -> Failure {
|
||||
match e {
|
||||
zbus::Error::MethodError(name, ..) if UNAVAILABLE.contains(&name.as_str()) => Failure::Unavailable(e.to_string()),
|
||||
zbus::Error::InputOutput(io) if io.kind() == std::io::ErrorKind::TimedOut => Failure::NoAnswer(e.to_string()),
|
||||
_ => Failure::Failed(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color in a `Response` with `code` and `results`: response 0 carries it, 1 is a cancel, and
|
||||
/// any other code ends the request without one. The components are passed on as given;
|
||||
/// `screen_color::sampled` clamps them to 0 to 1, as for the other systems' samplers.
|
||||
fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f32; 3]>, Failure> {
|
||||
match code {
|
||||
0 => {}
|
||||
1 => return Ok(None),
|
||||
_ => return Err(Failure::Failed(format!("the portal ended the request (response {code})"))),
|
||||
}
|
||||
let color = results.get("color").ok_or_else(|| Failure::Failed("no color in the portal's answer".into()))?;
|
||||
// Matched field by field: zvariant's tuple conversion panics on a structure with fewer fields.
|
||||
match &**color {
|
||||
Value::Structure(s) => match s.fields() {
|
||||
[Value::F64(r), Value::F64(g), Value::F64(b)] => Ok(Some([*r, *g, *b].map(|v| v as f32))),
|
||||
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
|
||||
},
|
||||
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
|
||||
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
|
||||
}
|
||||
|
||||
fn failed<T: std::fmt::Debug>(r: Result<T, Failure>) -> bool {
|
||||
matches!(r, Err(Failure::Failed(_)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picked_color_keeps_its_srgb_values() {
|
||||
assert_eq!(answer(0, &color((0.25, 0.5, 0.75))), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert_eq!(answer(0, &color((0.0, 1.0, 0.0))), Ok(Some([0.0, 1.0, 0.0])));
|
||||
// Outside 0 to 1: passed on for `screen_color::sampled` to clamp.
|
||||
assert_eq!(answer(0, &color((-0.5, 1.5, 1.0))), Ok(Some([-0.5, 1.5, 1.0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_needs_no_color() {
|
||||
assert_eq!(answer(1, &HashMap::new()), Ok(None));
|
||||
assert_eq!(answer(1, &color((0.25, 0.5, 0.75))), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_response_codes_are_failures() {
|
||||
for code in [2, 3, u32::MAX] {
|
||||
assert!(failed(answer(code, &color((0.25, 0.5, 0.75)))), "{code}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_success_without_a_valid_color_is_a_failure() {
|
||||
assert!(failed(answer(0, &HashMap::new())));
|
||||
let wrong = HashMap::from([("color".into(), OwnedValue::from(1_u32))]);
|
||||
assert!(failed(answer(0, &wrong)));
|
||||
// Fewer fields, more fields, and fields of another type: an error, not a panic.
|
||||
for wrong in [Value::from((0.5, 0.5)), Value::from((0.5, 0.5, 0.5, 0.5)), Value::from((1_u32, 0.5, 0.5)), Value::from(vec![0.5, 0.5, 0.5])] {
|
||||
let wrong = HashMap::from([("color".into(), OwnedValue::try_from(wrong).unwrap())]);
|
||||
assert!(failed(answer(0, &wrong)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_errors_say_whether_the_system_has_a_sampler() {
|
||||
let reply = |name: &str| {
|
||||
let call = zbus::Message::method_call("/org/freedesktop/portal/desktop", "PickColor").unwrap().build(&()).unwrap();
|
||||
let error = zbus::Message::error(&call.header(), name).unwrap().build(&("detail",)).unwrap();
|
||||
zbus::Error::from(error)
|
||||
};
|
||||
for name in UNAVAILABLE {
|
||||
assert!(matches!(call_failure(&reply(name)), Failure::Unavailable(_)), "{name}");
|
||||
}
|
||||
assert!(matches!(call_failure(&reply("org.freedesktop.portal.Error.NotAllowed")), Failure::Failed(_)));
|
||||
let timed_out = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::TimedOut.into()));
|
||||
assert!(matches!(call_failure(&timed_out), Failure::NoAnswer(_)));
|
||||
let broken = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::BrokenPipe.into()));
|
||||
assert!(matches!(call_failure(&broken), Failure::Failed(_)));
|
||||
let messages = [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())].map(|f| f.message());
|
||||
assert_eq!(
|
||||
messages,
|
||||
["this system has no screen color sampler", "the screen color sampler did not answer", "the screen color sampler failed"]
|
||||
);
|
||||
assert_eq!(call_failure(&broken).detail(), broken.to_string());
|
||||
}
|
||||
|
||||
/// Every language that translates the sampler's other messages translates these too. The
|
||||
/// i18n tests of `vectorcraft-ui-egui` do not read this crate's messages.
|
||||
#[test]
|
||||
fn the_messages_are_translated_where_the_sampler_is() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
const OPEN: &str = "the screen color sampler is already open";
|
||||
let langs: Vec<Lang> = Lang::all().filter(|&lang| message(lang, OPEN) != OPEN).collect();
|
||||
assert!(!langs.is_empty(), "no language translates {OPEN:?}");
|
||||
for lang in langs {
|
||||
for failure in [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())] {
|
||||
assert_ne!(message(lang, failure.message()), failure.message(), "{}", lang.code());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
|
||||
fn private_bus() -> Option<(Daemon, String)> {
|
||||
use std::io::BufRead as _;
|
||||
let spawning = crate::spawning();
|
||||
let daemon = std::process::Command::new("dbus-daemon")
|
||||
.args(["--session", "--nofork", "--print-address=1"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
drop(spawning);
|
||||
let Ok(daemon) = daemon else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return None;
|
||||
};
|
||||
let mut daemon = Daemon(daemon);
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
|
||||
Some((daemon, address.trim().to_string()))
|
||||
}
|
||||
|
||||
/// Stops the private bus when the test ends, unwinding included.
|
||||
struct Daemon(std::process::Child);
|
||||
|
||||
impl Drop for Daemon {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
|
||||
fn client(address: &str) -> Connection {
|
||||
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
|
||||
}
|
||||
|
||||
/// The portal's name, owned on the private bus at `address` before any call, so the bus never
|
||||
/// starts an installed portal in its place.
|
||||
fn portal(address: &str) -> Connection {
|
||||
zbus::blocking::connection::Builder::address(address).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap()
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: an answer that comes before the call returns is kept; answers on
|
||||
/// other request paths or from other connections are ignored; a cancel gives no color; and a
|
||||
/// portal that leaves the bus while the person picks ends the wait.
|
||||
#[test]
|
||||
fn the_answer_is_the_portals_response_on_the_returned_path() {
|
||||
use zbus::blocking::MessageIterator;
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
|
||||
let Some((_daemon, address)) = private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let server = portal(address);
|
||||
let impostor = zbus::blocking::connection::Builder::address(address).unwrap().build().unwrap();
|
||||
let incoming = MessageIterator::from(&server);
|
||||
let worker = std::thread::spawn(move || {
|
||||
let mut calls = Vec::new();
|
||||
for msg in incoming {
|
||||
let msg = msg.unwrap();
|
||||
let header = msg.header();
|
||||
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("PickColor") {
|
||||
continue;
|
||||
}
|
||||
let (parent, options): (String, HashMap<String, OwnedValue>) = msg.body().deserialize().unwrap();
|
||||
let token = String::try_from(options.get("handle_token").unwrap().try_clone().unwrap()).unwrap();
|
||||
assert!(token.starts_with("vectorcraft_color_"));
|
||||
assert!(token.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_'));
|
||||
assert!(!calls.iter().any(|(_, old)| old == &token));
|
||||
calls.push((parent, token));
|
||||
// A portal older than version 0.9 answers on a path of its own, not the token's.
|
||||
let path = format!("/org/freedesktop/portal/desktop/request/independent/pick_{}", calls.len());
|
||||
let handle = OwnedObjectPath::try_from(path.as_str()).unwrap();
|
||||
if calls.len() == 4 {
|
||||
server.reply(&header, &handle).unwrap();
|
||||
assert!(server.release_name("org.freedesktop.portal.Desktop").unwrap());
|
||||
break;
|
||||
}
|
||||
let to = header.sender().cloned().map(zbus::names::BusName::from);
|
||||
// Another connection can't end the wait by claiming the portal left.
|
||||
impostor
|
||||
.emit_signal(
|
||||
to.clone(),
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"NameOwnerChanged",
|
||||
&("org.freedesktop.portal.Desktop", server.unique_name().unwrap().as_str(), ""),
|
||||
)
|
||||
.unwrap();
|
||||
let wrong = color((1.0, 0.0, 0.0));
|
||||
impostor.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
|
||||
let unrelated = "/org/freedesktop/portal/desktop/request/unrelated";
|
||||
server.emit_signal(to.clone(), unrelated, "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
|
||||
let code = if calls.len() == 2 { 1_u32 } else { 0_u32 };
|
||||
server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &color((0.25, 0.5, 0.75)))).unwrap();
|
||||
// The reply that names the path goes last: every answer above came before it.
|
||||
server.reply(&header, &handle).unwrap();
|
||||
}
|
||||
calls
|
||||
});
|
||||
let client = client(address);
|
||||
assert_eq!(pick(&client, "x11:12"), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert_eq!(pick(&client, "wayland:example"), Ok(None));
|
||||
assert_eq!(pick(&client, ""), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert!(matches!(pick(&client, ""), Err(Failure::NoAnswer(_))));
|
||||
let calls = worker.join().unwrap();
|
||||
assert_eq!(calls.iter().map(|(parent, _)| parent.as_str()).collect::<Vec<_>>(), ["x11:12", "wayland:example", "", ""]);
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: a portal without `PickColor` ends the request as a system without a
|
||||
/// sampler, and the sampler's connection gives the call [`CALL_TIMEOUT`].
|
||||
#[test]
|
||||
fn a_portal_without_pick_color_ends_the_request() {
|
||||
let Some((_daemon, address)) = private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let server = portal(address);
|
||||
let incoming = zbus::blocking::MessageIterator::from(&server);
|
||||
let worker = std::thread::spawn(move || {
|
||||
for msg in incoming {
|
||||
let msg = msg.unwrap();
|
||||
let header = msg.header();
|
||||
if header.member().map(|m| m.as_str()) == Some("PickColor") {
|
||||
server.reply_error(&header, "org.freedesktop.DBus.Error.UnknownMethod", &("no PickColor",)).unwrap();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let client = client(address);
|
||||
assert_eq!(client.method_timeout(), Some(CALL_TIMEOUT));
|
||||
let failure = pick(&client, "");
|
||||
assert!(matches!(failure, Err(Failure::Unavailable(_))), "{failure:?}");
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! The answer to the color sampler's XDG desktop portal request
|
||||
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>).
|
||||
//! The wait ends with the request's `Response`, or with an error when the portal leaves the bus
|
||||
//! first.
|
||||
|
||||
use std::io::Read as _;
|
||||
|
||||
use futures_lite::{StreamExt as _, future};
|
||||
use zbus::blocking::{Connection, MessageIterator};
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
|
||||
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
|
||||
/// token is unique and can't be guessed, as the Request documentation asks.
|
||||
pub(super) fn token(prefix: &str) -> Result<String, String> {
|
||||
let mut bytes = [0; 16];
|
||||
std::fs::File::open("/dev/urandom")
|
||||
.and_then(|mut file| file.read_exact(&mut bytes))
|
||||
.map_err(|e| format!("could not create a portal request token: {e}"))?;
|
||||
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
|
||||
Ok(format!("{prefix}_{random}"))
|
||||
}
|
||||
|
||||
/// Subscriptions made before a portal method call, on every request path: a portal older than
|
||||
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
|
||||
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
|
||||
pub(super) struct Responses {
|
||||
replies: MessageIterator,
|
||||
owners: MessageIterator,
|
||||
}
|
||||
|
||||
impl Responses {
|
||||
pub(super) fn new(conn: &Connection) -> Result<Self, String> {
|
||||
let reply_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender(DESKTOP)
|
||||
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
|
||||
.and_then(|b| b.member("Response"))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
let owner_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender("org.freedesktop.DBus")
|
||||
.and_then(|b| b.path("/org/freedesktop/DBus"))
|
||||
.and_then(|b| b.interface("org.freedesktop.DBus"))
|
||||
.and_then(|b| b.member("NameOwnerChanged"))
|
||||
.and_then(|b| b.arg(0, DESKTOP))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
Ok(Self {
|
||||
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
|
||||
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `Response` on the request path `call` returned, from the connection that returned it.
|
||||
/// An error when that connection leaves the bus first, or the bus connection closes.
|
||||
pub(super) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
|
||||
enum Event {
|
||||
Reply(Option<zbus::Result<zbus::Message>>),
|
||||
Owner(Option<zbus::Result<zbus::Message>>),
|
||||
}
|
||||
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
|
||||
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
|
||||
let mut replies = self.replies.into_inner();
|
||||
let mut owners = self.owners.into_inner();
|
||||
future::block_on(async {
|
||||
loop {
|
||||
let event = future::or(async { Event::Reply(replies.next().await) }, async { Event::Owner(owners.next().await) }).await;
|
||||
match event {
|
||||
Event::Reply(reply) => {
|
||||
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
|
||||
let header = reply.header();
|
||||
if header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
|
||||
{
|
||||
return Ok(reply);
|
||||
}
|
||||
}
|
||||
Event::Owner(message) => {
|
||||
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
|
||||
if owner_disappeared(&message, &portal)? {
|
||||
return Err("the desktop portal disappeared while waiting for its answer".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
|
||||
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
|
||||
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
|
||||
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
|
||||
return Ok(false);
|
||||
}
|
||||
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
|
||||
Ok(name == DESKTOP && old == portal && new != portal)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_bus_can_report_portal_owner_loss() {
|
||||
let changed = |sender, name, old, new| {
|
||||
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
|
||||
.unwrap()
|
||||
.sender(sender)
|
||||
.unwrap()
|
||||
.build(&(name, old, new))
|
||||
.unwrap()
|
||||
};
|
||||
let forged = changed(":1.42", DESKTOP, ":1.7", "");
|
||||
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
|
||||
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
|
||||
assert!(owner_disappeared(&real, ":1.7").unwrap());
|
||||
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
|
||||
assert!(!owner_disappeared(&other, ":1.7").unwrap());
|
||||
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
|
||||
assert!(!owner_disappeared(&old, ":1.7").unwrap());
|
||||
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
|
||||
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,6 @@ trait Backend {
|
||||
fn suspend(&mut self, window: &Self::Window);
|
||||
fn restore(&mut self, window: &Self::Window);
|
||||
fn build(&mut self, request: &Request) -> Option<Self::Cursor>;
|
||||
fn current(&self) -> Option<Self::Cursor>;
|
||||
fn set(&mut self, cursor: &Self::Cursor);
|
||||
}
|
||||
|
||||
@@ -73,9 +72,10 @@ impl<B: Backend> State<B> {
|
||||
&& *key == request.key
|
||||
&& *owned == window
|
||||
{
|
||||
if self.backend.current().as_ref() != Some(cursor) {
|
||||
self.backend.set(cursor);
|
||||
}
|
||||
// AppKit can show the system arrow when the pointer moves while
|
||||
// `NSCursor.currentCursor` (the app's last set cursor) still reads as ours, so a
|
||||
// comparison would keep the arrow. Setting the cursor again costs nothing.
|
||||
self.backend.set(cursor);
|
||||
return;
|
||||
}
|
||||
self.release();
|
||||
@@ -135,9 +135,6 @@ impl Backend for AppKit {
|
||||
fn build(&mut self, request: &Request) -> Option<Self::Cursor> {
|
||||
build(&request.bitmap)
|
||||
}
|
||||
fn current(&self) -> Option<Self::Cursor> {
|
||||
Some(NSCursor::currentCursor())
|
||||
}
|
||||
fn set(&mut self, cursor: &Self::Cursor) {
|
||||
cursor.set();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ use std::cell::Cell;
|
||||
struct Fake {
|
||||
window: Option<u8>,
|
||||
suspended: Vec<u8>,
|
||||
current: Option<Key>,
|
||||
sets: usize,
|
||||
builds: usize,
|
||||
restores: Vec<u8>,
|
||||
@@ -27,17 +26,12 @@ impl Backend for Fake {
|
||||
fn restore(&mut self, w: &u8) {
|
||||
self.suspended.retain(|v| v != w);
|
||||
self.restores.push(*w);
|
||||
self.current = None;
|
||||
}
|
||||
fn build(&mut self, r: &Request) -> Option<Key> {
|
||||
self.builds += 1;
|
||||
(!self.fail).then_some(r.key)
|
||||
}
|
||||
fn current(&self) -> Option<Key> {
|
||||
self.current
|
||||
}
|
||||
fn set(&mut self, cursor: &Key) {
|
||||
self.current = Some(*cursor);
|
||||
fn set(&mut self, _: &Key) {
|
||||
self.sets += 1;
|
||||
}
|
||||
}
|
||||
@@ -66,19 +60,16 @@ fn deliver(state: &mut State<Fake>, request: Option<Request>) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_cursor_ownership_deduplicates_reasserts_and_restores() {
|
||||
fn mac_cursor_ownership_reasserts_every_pass_and_restores() {
|
||||
let req = request(1.0);
|
||||
let mut state = fake_state();
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.suspended, [1]);
|
||||
assert_eq!((state.backend.builds, state.backend.sets), (1, 1));
|
||||
// The pointer moves and AppKit shows the system arrow, but the app's current cursor
|
||||
// still reads as ours. The next pass sets it again without rebuilding or re-suspending.
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.sets, 1);
|
||||
// Simulate a platform fallback replacing the cursor after finalization. The next pass
|
||||
// reasserts; this proves the protocol, not AppKit timing or absence of transient flicker.
|
||||
state.backend.current = None;
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.sets, 2);
|
||||
assert_eq!((state.backend.builds, state.backend.sets, state.backend.suspended.len()), (1, 2, 1));
|
||||
deliver(&mut state, None);
|
||||
assert_eq!(state.backend.restores, [1]);
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
|
||||
@@ -32,6 +32,8 @@ mod cursor_theme;
|
||||
mod gpu;
|
||||
mod hang_watch;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_screen_color;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_stylus;
|
||||
mod logging;
|
||||
#[cfg(all(target_os = "macos", feature = "wgpu"))]
|
||||
@@ -476,6 +478,7 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
|
||||
prefs_dir::attach_scripts_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
@@ -485,6 +488,8 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_pdf_preset_store(&mut app.session);
|
||||
// The custom dictionary's words, kept in their own file next to the preferences.
|
||||
prefs_dir::attach_custom_dictionary(&mut app.session);
|
||||
// The custom arrowheads, kept in their own file next to the preferences.
|
||||
prefs_dir::attach_arrowheads(&mut app.session);
|
||||
// Fit the window to its monitor, or put it back where it was (still hidden).
|
||||
let winit_window = cc.winit_window().cloned();
|
||||
if let Some(w) = &winit_window {
|
||||
|
||||
@@ -242,6 +242,13 @@ fn parent(window: &winit::window::Window) -> (String, Option<wayland::Export>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`parent`] for another dialog of the portal (the screen color sampler, `linux_screen_color`):
|
||||
/// the identifier stays valid until the second value is dropped.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn exported_parent(window: &winit::window::Window) -> (String, impl Send + 'static) {
|
||||
parent(window)
|
||||
}
|
||||
|
||||
/// The portal's identifier of `window`: its X11 id, else empty (no Wayland export is made off
|
||||
/// Linux).
|
||||
#[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
|
||||
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Have File › New start each category's documents from its profile in the `New Document
|
||||
/// Profiles` folder, which `file.newProfiles.edit` makes.
|
||||
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("New Document Profiles") {
|
||||
session.attach_new_doc_profiles(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
|
||||
/// now on there. After the preferences were restored: the folder is the one place the presets live.
|
||||
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
|
||||
@@ -81,6 +89,14 @@ pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the custom arrowheads (Stroke panel menu › Edit Arrowheads…) in the `Arrowheads.vectorcraft`
|
||||
/// file next to the settings, and list the heads it holds.
|
||||
pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(path) = store_dir(vectorcraft_engine::cmd::arrowheads::FILE_NAME) {
|
||||
session.attach_arrowheads_file(path.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -250,7 +250,8 @@ impl ParamSchema {
|
||||
/// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated
|
||||
/// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or
|
||||
/// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with
|
||||
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`].
|
||||
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`], or a
|
||||
/// [`Type::Ids`] or [`Type::Point`], whose values are all lists, at the nesting limit.
|
||||
pub fn definition_problem(&self) -> Option<String> {
|
||||
object_problem("", self.params, 0)
|
||||
}
|
||||
@@ -319,7 +320,9 @@ pub enum Problem {
|
||||
Missing,
|
||||
/// The value is not of the parameter's type: `expected` says what it must be.
|
||||
WrongType { expected: String, got: String },
|
||||
/// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]).
|
||||
/// The value nests deeper than [`MAX_DEPTH`] here: a list given for a [`Type::Color`] at the
|
||||
/// nesting limit, or any value under a schema that nests too deeply itself
|
||||
/// ([`ParamSchema::definition_problem`]).
|
||||
TooDeep,
|
||||
}
|
||||
|
||||
@@ -779,6 +782,8 @@ fn type_problem(at: &str, ty: &Type, depth: usize) -> Option<String> {
|
||||
Type::Object(params) => object_problem(at, params, depth + 1),
|
||||
Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
|
||||
Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1),
|
||||
// Every value of these is a list, and a list at the nesting limit is refused.
|
||||
Type::Ids | Type::Point if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +156,36 @@ fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() {
|
||||
assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok());
|
||||
}
|
||||
|
||||
/// `ty` inside `levels` lists.
|
||||
fn in_lists(levels: usize, ty: Type) -> Type {
|
||||
(0..levels).fold(ty, |inner, _| Type::Array(Box::leak(Box::new(inner))))
|
||||
}
|
||||
|
||||
/// `v` inside `levels` lists.
|
||||
fn wrapped(levels: usize, v: Value) -> Value {
|
||||
(0..levels).fold(v, |inner, _| Value::Array(vec![inner]))
|
||||
}
|
||||
|
||||
/// The schema check and the value check agree on the fixed-shape lists at the nesting limit: an id
|
||||
/// list or a point there could take no value, so the schema is wrong in itself, and a color there
|
||||
/// takes a string, while a color list is refused as nested too deeply, at its path.
|
||||
#[test]
|
||||
fn fixed_shape_lists_at_the_nesting_limit_follow_the_schema_check() {
|
||||
for ty in [Type::Ids, Type::Point, Type::Color] {
|
||||
assert_eq!(one(in_lists(MAX_DEPTH - 1, ty)).definition_problem(), None, "{ty:?}");
|
||||
}
|
||||
for ty in [Type::Ids, Type::Point] {
|
||||
let problem = one(in_lists(MAX_DEPTH, ty)).definition_problem();
|
||||
assert!(problem.as_deref().is_some_and(|p| p.contains("nests deeper")), "{ty:?}: {problem:?}");
|
||||
}
|
||||
let color = one(in_lists(MAX_DEPTH, Type::Color));
|
||||
assert_eq!(color.definition_problem(), None);
|
||||
assert_eq!(color.validate(&json!({"x": wrapped(MAX_DEPTH, json!("#ff0000"))})).unwrap(), None);
|
||||
let e = color.validate(&json!({"x": wrapped(MAX_DEPTH, json!([1, 0, 0]))})).unwrap_err();
|
||||
assert_eq!(e.problem, Problem::TooDeep);
|
||||
assert_eq!(e.path, format!("x{}", "[0]".repeat(MAX_DEPTH)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_retired_key_past_the_nesting_limit_is_refused() {
|
||||
let params = holding("older", nested_lists(500_000));
|
||||
|
||||
+12
-9
@@ -370,11 +370,14 @@ pub struct ArtBrush {
|
||||
pub scale: ArtScale,
|
||||
/// Width in percent.
|
||||
pub width: f64,
|
||||
/// How the width varies along a stroke: `None` (Fixed) always `width`; Pressure goes from
|
||||
/// `width` at the lightest pen pressure to [`Self::width_max`] at the heaviest.
|
||||
/// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the
|
||||
/// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure
|
||||
/// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing
|
||||
/// and Rotation from −180° to 180° (half way at 0°).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_mode: Option<Variation>,
|
||||
/// The width at the heaviest pen pressure (%), for Pressure (`width` without one).
|
||||
/// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or
|
||||
/// at 180° (`width` without one).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_max: Option<f64>,
|
||||
pub flip_along: bool,
|
||||
@@ -388,11 +391,11 @@ impl ArtBrush {
|
||||
/// The range of the width (%).
|
||||
pub const WIDTH_RANGE: (f64, f64) = (1.0, 1000.0);
|
||||
|
||||
/// The widths (%) at the lightest and the heaviest pen pressure: `width` for both unless the
|
||||
/// width follows the pressure.
|
||||
/// The widths (%) where the pen reads 0 and 1 for the width's mode (the lightest and the
|
||||
/// heaviest pressure, for Pressure): `width` for both unless the width follows the pen.
|
||||
pub fn width_range(&self) -> (f64, f64) {
|
||||
match self.width_mode {
|
||||
Some(Variation::Pressure) => (self.width, self.width_max.unwrap_or(self.width)),
|
||||
Some(m) if m.follows_pen() => (self.width, self.width_max.unwrap_or(self.width)),
|
||||
_ => (self.width, self.width),
|
||||
}
|
||||
}
|
||||
@@ -713,8 +716,8 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0);
|
||||
// The width follows the pen's pressure or stays fixed.
|
||||
if a.width_mode != Some(Variation::Pressure) {
|
||||
// The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed.
|
||||
if !a.width_mode.is_some_and(Variation::follows_pen) {
|
||||
a.width_mode = None;
|
||||
}
|
||||
a.width_max = a.width_max.map(|w| within(w, ArtBrush::WIDTH_RANGE, a.width));
|
||||
@@ -806,7 +809,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
let mut out = match &brush.kind {
|
||||
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
};
|
||||
|
||||
@@ -1371,6 +1371,62 @@ fn art_brush_width_follows_the_pressure() {
|
||||
assert!(plain.get("width_mode").is_none() && plain.get("width_max").is_none(), "{plain}");
|
||||
}
|
||||
|
||||
/// Art Brush Options: Width on Tilt goes from Width with the pen lying flat to the second width
|
||||
/// upright, and on Bearing or Rotation from Width at −180° to the second width at 180°, along the
|
||||
/// stroke as the pen recorded it; each mode reads only its own input.
|
||||
#[test]
|
||||
fn art_brush_width_follows_tilt_bearing_and_rotation() {
|
||||
let brush = |mode: Variation| {
|
||||
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut b.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(mode), Some(300.0));
|
||||
}
|
||||
b
|
||||
};
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
|
||||
// Tilt, upright at the start (300 %: 6 pt either side of 4 pt art) to flat at the end (50 %: 1 pt).
|
||||
let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
|
||||
let out = draw(&brush(Variation::Tilt), &upright_to_flat);
|
||||
assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
|
||||
assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0));
|
||||
assert!(near(half_width(&out, 49.0, 51.0), 3.5, 0.15), "{}", half_width(&out, 49.0, 51.0));
|
||||
// Bearing and Rotation: half way at 0°, a quarter of the way at −90°, three quarters at 90°.
|
||||
for (mode, angle, half) in [
|
||||
(Variation::Bearing, 0.0, 3.5),
|
||||
(Variation::Bearing, -90.0, 2.25),
|
||||
(Variation::Bearing, 90.0, 4.75),
|
||||
(Variation::Rotation, -90.0, 2.25),
|
||||
(Variation::Rotation, 90.0, 4.75),
|
||||
] {
|
||||
let st = if mode == Variation::Bearing { posed(Some(0.5), Some(angle), None) } else { posed(None, None, Some(angle)) };
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, 2.0 * half, 1e-6), "{mode:?} {angle}: {h}");
|
||||
}
|
||||
// Each mode reads its own input: without it (the pressure, or another of the pen's values
|
||||
// recorded instead), the art is half way between the two widths.
|
||||
let others = [
|
||||
(Variation::Tilt, posed(None, Some(90.0), Some(90.0))),
|
||||
(Variation::Tilt, pressed(vec![(0.0, 0.0), (1.0, 1.0)])),
|
||||
(Variation::Bearing, posed(Some(0.0), None, Some(90.0))),
|
||||
(Variation::Rotation, posed(Some(0.0), Some(90.0), None)),
|
||||
(Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0))),
|
||||
];
|
||||
for (mode, st) in others {
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, 7.0, 1e-6), "{mode:?}: {h}");
|
||||
}
|
||||
// The pen's modes are kept when a definition is read, and Random is read as Fixed.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "t", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "tilt", "width_max": 300.0},
|
||||
{"name": "b", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "bearing", "width_max": 300.0},
|
||||
{"name": "r", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "rotation", "width_max": 300.0},
|
||||
{"name": "x", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "random", "width_max": 300.0},
|
||||
]));
|
||||
let modes: Vec<_> = lib.iter().map(|b| if let BrushKind::Art(a) = &b.kind { a.width_mode } else { None }).collect();
|
||||
assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]);
|
||||
}
|
||||
|
||||
/// Definitions from files and commands are kept within their ranges.
|
||||
#[test]
|
||||
fn sanitize_keeps_values_within_their_ranges() {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurveNearest;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::track::{Rng, Track, normal, seed_of, tracks};
|
||||
@@ -503,9 +503,10 @@ fn art_on_run(
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
}
|
||||
|
||||
/// An art brush's art along `bp`. With a width that follows the pen's pressure, the art is as
|
||||
/// wide as the pressure recorded at each point of the stroke gives (half way without a recording).
|
||||
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&PressureProfile>) -> Vec<Node> {
|
||||
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
|
||||
/// or rotation), the art is as wide as what `stroke` recorded at each point gives (half way
|
||||
/// without a recording).
|
||||
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec<Node> {
|
||||
let Some((art, b)) = oriented(&a.art, a.direction, a.flip_along, a.flip_across) else { return vec![] };
|
||||
let (light, heavy) = a.width_range();
|
||||
let width = light.max(heavy);
|
||||
@@ -522,7 +523,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre
|
||||
}
|
||||
// A run past the start of a closed track wraps round to it.
|
||||
let at = if s > l { s - l } else { s };
|
||||
let p = pressure.map_or(PressureProfile::MID, |p| p.at(at / l)).clamp(0.0, 1.0);
|
||||
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
|
||||
|
||||
@@ -187,6 +187,9 @@ pub struct HpglOutput {
|
||||
pub pens: Vec<[u8; 3]>,
|
||||
/// What was approximated or left out.
|
||||
pub warnings: Vec<String>,
|
||||
/// Notes on the options: sorting the paths or drawing the inner paths first was applied only
|
||||
/// in part.
|
||||
pub setting_notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Write the visible art of `doc` over `opts.region` as an HP-GL plot. Live geometry effects are
|
||||
@@ -280,10 +283,11 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
|
||||
if !by_pen.iter().all(Vec::is_empty) {
|
||||
pen_warnings.iter().for_each(|w| warn(&mut warnings, w));
|
||||
}
|
||||
let mut setting_notes = vec![];
|
||||
if opts.sort || opts.inside_first {
|
||||
let (mut at, mut work) = ((0, 0), MAX_SORT_WORK);
|
||||
for paths in &mut by_pen {
|
||||
at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut warnings);
|
||||
at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut setting_notes);
|
||||
}
|
||||
}
|
||||
if opts.version == Version::Hpgl && by_pen.iter().flatten().flatten().any(|(x, y)| !CLASSIC_RANGE.contains(x) || !CLASSIC_RANGE.contains(y)) {
|
||||
@@ -293,7 +297,7 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
|
||||
Version::Hpgl => plain(&by_pen),
|
||||
Version::Hpgl2 => encoded(&by_pen, &pens),
|
||||
};
|
||||
out.push(HpglOutput { bytes, pens: pens.clone(), warnings });
|
||||
out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -366,20 +370,20 @@ fn box_dist2(p: (i64, i64), b: [i64; 4]) -> i128 {
|
||||
/// for a closed path any of its points (where it then starts); without, the first in paint order.
|
||||
/// With `inside_first`, a path is drawn only once every path lying inside it ([`nest::outer`]) is.
|
||||
/// Once `work` is spent, the paths left keep paint order, each after the paths inside it with
|
||||
/// `inside_first`, with a warning. Returns where the pen stops.
|
||||
/// `inside_first`, with a note in `notes`. Returns where the pen stops.
|
||||
fn reorder(
|
||||
paths: &mut Vec<Vec<(i64, i64)>>,
|
||||
mut at: (i64, i64),
|
||||
work: &mut u64,
|
||||
nearest: bool,
|
||||
inside_first: bool,
|
||||
warnings: &mut Vec<String>,
|
||||
notes: &mut Vec<String>,
|
||||
) -> (i64, i64) {
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| nest::bounds(p)).collect();
|
||||
// The paths each path lies inside, and how many paths inside each are still to draw.
|
||||
let outer = inside_first.then(|| nest::outer(paths, &boxes, work)).flatten();
|
||||
if inside_first && outer.is_none() {
|
||||
warn(warnings, UNNESTED);
|
||||
warn(notes, UNNESTED);
|
||||
}
|
||||
let mut waiting = vec![0usize; paths.len()];
|
||||
for o in outer.iter().flatten().flatten() {
|
||||
@@ -430,11 +434,11 @@ fn reorder(
|
||||
if *work == 0 || best.0 >= left.len() {
|
||||
match &outer {
|
||||
Some(outer) => {
|
||||
warn(warnings, UNSORTED_INSIDE);
|
||||
warn(notes, UNSORTED_INSIDE);
|
||||
inner_first(left.into_iter().map(|(j, p, _)| (j, p)).collect(), outer, &mut waiting, paths);
|
||||
}
|
||||
None => {
|
||||
warn(warnings, UNSORTED);
|
||||
warn(notes, UNSORTED);
|
||||
paths.extend(left.into_iter().map(|(_, p, _)| p));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,7 +852,8 @@ fn sorting_measures_a_closed_path_by_its_nearest_point() {
|
||||
fn sorting_stops_at_its_budget_and_keeps_every_path() {
|
||||
let d = doc_with(|d| (0..600).map(|i| stroked(d, line((1.0 + (i % 100) as f64, 10.0), (1.0 + (i % 100) as f64, 20.0)), Color::BLACK)).collect());
|
||||
let out = plot(&d, &HpglOptions { sort: true, ..opts(&d) });
|
||||
assert!(out.warnings.iter().any(|w| w == UNSORTED), "{:?}", out.warnings);
|
||||
assert_eq!(out.setting_notes, [UNSORTED]);
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
assert_eq!(text(&out).matches("PD").count(), 600);
|
||||
}
|
||||
|
||||
@@ -944,18 +945,18 @@ fn inside_first_orders_each_pens_paths() {
|
||||
}
|
||||
|
||||
/// Finding which of 100 nested rings lie inside which is past the budget: they are drawn in
|
||||
/// paint order, with a warning.
|
||||
/// paint order, with a note on the option.
|
||||
#[test]
|
||||
fn inside_first_past_its_budget_draws_in_paint_order() {
|
||||
let d = doc_with(|d| (0..100).map(|i| stroked(d, rect(1.0 + 0.4 * f64::from(i), 10.0, 199.0, 90.0), Color::BLACK)).collect());
|
||||
let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) });
|
||||
assert_eq!(out.warnings, [UNNESTED]);
|
||||
assert_eq!(out.setting_notes, [UNNESTED]);
|
||||
let l = lefts(&out);
|
||||
assert_eq!(l.len(), 100);
|
||||
assert!(l.windows(2).all(|w| w[0] <= w[1]), "{l:?}");
|
||||
// With `sort` too, the budget is spent before sorting starts: paint order, with both warnings.
|
||||
// With `sort` too, the budget is spent before sorting starts: paint order, with both notes.
|
||||
let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) });
|
||||
assert_eq!(out.warnings, [UNNESTED, UNSORTED]);
|
||||
assert_eq!(out.setting_notes, [UNNESTED, UNSORTED]);
|
||||
assert_eq!(lefts(&out), l);
|
||||
}
|
||||
|
||||
@@ -969,7 +970,7 @@ fn inside_first_past_its_sorting_budget_keeps_the_rings_last() {
|
||||
v
|
||||
});
|
||||
let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) });
|
||||
assert_eq!(out.warnings, [UNSORTED_INSIDE]);
|
||||
assert_eq!(out.setting_notes, [UNSORTED_INSIDE]);
|
||||
let l = lefts(&out);
|
||||
assert_eq!(l.len(), 602);
|
||||
assert_eq!(l.get(600..), Some(&[plu(0.7), plu(0.5)][..]));
|
||||
|
||||
@@ -410,6 +410,9 @@ pub struct DxfOutput {
|
||||
pub images: Vec<DxfImage>,
|
||||
/// What was approximated or left out.
|
||||
pub warnings: Vec<String>,
|
||||
/// What was left out because an option turns it off (Include Placed Images or Include Fill
|
||||
/// Hatches off).
|
||||
pub setting_notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// The smallest and largest `scale` (drawing units per unit).
|
||||
|
||||
+16
-4
@@ -520,6 +520,8 @@ pub(crate) struct Scene<'a> {
|
||||
/// Image keys → index into `images` (`None`: left out).
|
||||
by_key: HashMap<String, Option<usize>>,
|
||||
warnings: Vec<String>,
|
||||
/// What was left out because an option asked for it ([`DxfOutput::setting_notes`]).
|
||||
setting_notes: Vec<String>,
|
||||
brushes: Option<Vec<vectorcraft_brush::Brush>>,
|
||||
extents: Option<[f64; 4]>,
|
||||
/// The opacity of the containers around the current object.
|
||||
@@ -554,6 +556,7 @@ impl<'a> Scene<'a> {
|
||||
files: vec![],
|
||||
by_key: HashMap::new(),
|
||||
warnings: vec![],
|
||||
setting_notes: vec![],
|
||||
brushes: None,
|
||||
extents: None,
|
||||
opacity: 1.0,
|
||||
@@ -588,15 +591,24 @@ impl<'a> Scene<'a> {
|
||||
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
|
||||
next: self.next,
|
||||
};
|
||||
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings }
|
||||
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes }
|
||||
}
|
||||
|
||||
/// Note `w`, once, about something of the document that the drawing leaves out or that reaches
|
||||
/// it changed. A note about an option goes to [`Self::note_setting`].
|
||||
fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) {
|
||||
self.warnings.push(w.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Note `w`, once, about something left out because an option turns it off.
|
||||
fn note_setting(&mut self, w: &str) {
|
||||
if !self.setting_notes.iter().any(|x| x == w) {
|
||||
self.setting_notes.push(w.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(&mut self) -> Handle {
|
||||
let h = Handle(self.next);
|
||||
self.next = self.next.saturating_add(1);
|
||||
@@ -660,7 +672,7 @@ impl<'a> Scene<'a> {
|
||||
self.shape(n, &bp, *rule);
|
||||
}
|
||||
NodeKind::Text(t) => self.text(n, t),
|
||||
NodeKind::Image(im) => self.image(im),
|
||||
NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)),
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let doc = self.doc;
|
||||
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
|
||||
@@ -930,7 +942,7 @@ impl<'a> Scene<'a> {
|
||||
// The outlines close as the fill does, so an open path's fill keeps its closing edge.
|
||||
self.lines(&closed_fill(outline), style, 0.0);
|
||||
if !self.o.include_hatches {
|
||||
self.warn(HATCHES_OFF);
|
||||
self.note_setting(HATCHES_OFF);
|
||||
return;
|
||||
}
|
||||
let h = self.handle();
|
||||
@@ -1321,7 +1333,7 @@ impl<'a> Scene<'a> {
|
||||
return;
|
||||
}
|
||||
if !self.o.include_images {
|
||||
self.warn(IMAGES_OFF);
|
||||
self.note_setting(IMAGES_OFF);
|
||||
return;
|
||||
}
|
||||
let Some(i) = self.image_def(im) else { return };
|
||||
|
||||
+13
-8
@@ -881,12 +881,13 @@ fn fills_without_hatches_keep_their_outlines() {
|
||||
let d = shapes_doc();
|
||||
let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap();
|
||||
assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle");
|
||||
assert_eq!(out.warnings, [HATCHES_OFF]);
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
assert_eq!(out.setting_notes, [HATCHES_OFF]);
|
||||
let e = entities(&out);
|
||||
assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight");
|
||||
// Hatches stay by default, with no note.
|
||||
let on = export(&d, &opts(&d)).unwrap();
|
||||
assert!(kinds(&on).iter().any(|k| k == "HATCH") && !on.warnings.iter().any(|w| w == HATCHES_OFF));
|
||||
assert!(kinds(&on).iter().any(|k| k == "HATCH") && on.setting_notes.is_empty());
|
||||
// The outlines are the ones written beside hatches, also for overlapping subpaths, which are
|
||||
// merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way.
|
||||
let compound = doc_with(|d| {
|
||||
@@ -916,13 +917,14 @@ fn fills_without_hatches_keep_their_outlines() {
|
||||
assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered));
|
||||
// Nothing filled: no note.
|
||||
let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
assert!(export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap().warnings.is_empty());
|
||||
let none = export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap();
|
||||
assert!(none.warnings.is_empty() && none.setting_notes.is_empty());
|
||||
// R12 has no hatches anyway: the same outlines, and its own note alone.
|
||||
let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap();
|
||||
let (off, on) = (r12(false), r12(true));
|
||||
assert_eq!(off.bytes, on.bytes);
|
||||
assert_eq!(off.warnings, on.warnings);
|
||||
assert!(!off.warnings.iter().any(|w| w == HATCHES_OFF));
|
||||
assert!(off.setting_notes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -957,15 +959,18 @@ fn images_can_be_left_out_with_their_files() {
|
||||
let p = pairs(&out.bytes);
|
||||
assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES")));
|
||||
assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE")));
|
||||
assert_eq!(out.warnings, [IMAGES_OFF]);
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
assert_eq!(out.setting_notes, [IMAGES_OFF]);
|
||||
// An image that can't be decoded is not read when images are left out.
|
||||
let mut broken = d.clone();
|
||||
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
|
||||
assert_eq!(export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap().warnings, [IMAGES_OFF]);
|
||||
let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap();
|
||||
assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings);
|
||||
assert_eq!(left_out.setting_notes, [IMAGES_OFF]);
|
||||
assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded")));
|
||||
// R12 has no images anyway: its own note alone.
|
||||
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap();
|
||||
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && !r12.warnings.iter().any(|w| w == IMAGES_OFF));
|
||||
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -983,7 +988,7 @@ fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_b
|
||||
let cnc = run(DxfPreset::Cnc.options());
|
||||
assert_eq!(kinds(&cnc), ["LWPOLYLINE"]);
|
||||
assert!(cnc.images.is_empty());
|
||||
assert!(cnc.warnings.iter().any(|w| w == IMAGES_OFF) && cnc.warnings.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.warnings);
|
||||
assert!(cnc.setting_notes.iter().any(|w| w == IMAGES_OFF) && cnc.setting_notes.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.setting_notes);
|
||||
let custom = DxfPreset::Custom.options();
|
||||
assert!(custom.include_images && custom.include_hatches, "Custom keeps both");
|
||||
}
|
||||
|
||||
+78
-13
@@ -6,8 +6,9 @@
|
||||
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
|
||||
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
|
||||
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
|
||||
//! * The **active settings** (Edit → Color Settings) are process-wide; [`crate::Color::to_rgb`]
|
||||
//! uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
|
||||
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
|
||||
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
|
||||
//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
|
||||
|
||||
pub mod generic;
|
||||
pub mod icc;
|
||||
@@ -320,6 +321,9 @@ pub struct Cms {
|
||||
settings: ColorSettings,
|
||||
rgb: RgbSpace,
|
||||
cmyk: CmykSpace,
|
||||
/// The working settings, when a document's assigned profiles take the place of their spaces
|
||||
/// ([`use_document_profiles`]): a [`ProofTarget::WorkingCmyk`] proof simulates their CMYK space.
|
||||
working: Option<Arc<Cms>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Cms {
|
||||
@@ -330,7 +334,7 @@ impl std::fmt::Debug for Cms {
|
||||
|
||||
impl Default for Cms {
|
||||
fn default() -> Self {
|
||||
Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()) }
|
||||
Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()), working: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,7 +342,7 @@ impl Cms {
|
||||
/// Profiles named by a legacy name are stored under their current name.
|
||||
pub fn new(settings: &ColorSettings) -> Result<Self, CmsError> {
|
||||
let settings = ColorSettings { rgb: canonical_name(&settings.rgb).into(), cmyk: canonical_name(&settings.cmyk).into(), ..settings.clone() };
|
||||
Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings })
|
||||
Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings, working: None })
|
||||
}
|
||||
pub fn settings(&self) -> &ColorSettings {
|
||||
&self.settings
|
||||
@@ -542,8 +546,9 @@ impl Cms {
|
||||
ProofTarget::Deuteranopia => simulate_cvd(srgb, &DEUTERANOPIA),
|
||||
ProofTarget::Tritanopia => TRITANOPIA.simulate(srgb),
|
||||
ProofTarget::WorkingCmyk => {
|
||||
let cmyk = self.srgb_to_cmyk(srgb, proof.intent);
|
||||
self.cmyk_to_srgb(cmyk, proof.simulate_paper)
|
||||
let working = self.working_cms();
|
||||
let cmyk = working.srgb_to_cmyk(srgb, proof.intent);
|
||||
working.cmyk_to_srgb(cmyk, proof.simulate_paper)
|
||||
}
|
||||
ProofTarget::Cmyk(name) => match cmyk_space(name) {
|
||||
Ok(sp) => {
|
||||
@@ -555,20 +560,29 @@ impl Cms {
|
||||
}
|
||||
}
|
||||
|
||||
/// Display sRGB of CMYK inks in the proof's CMYK space (the working space for RGB targets).
|
||||
/// Display sRGB of CMYK inks in the proof's CMYK space (this context's CMYK space for RGB
|
||||
/// targets).
|
||||
pub fn proof_cmyk_to_srgb(&self, cmyk: [f32; 4], proof: &ProofSetup) -> [f32; 3] {
|
||||
match &proof.target {
|
||||
ProofTarget::Cmyk(name) => match cmyk_space(name) {
|
||||
Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc),
|
||||
Err(_) => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
|
||||
},
|
||||
ProofTarget::WorkingCmyk => self.working_cms().cmyk_to_srgb(cmyk, proof.simulate_paper),
|
||||
_ => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
|
||||
}
|
||||
}
|
||||
|
||||
/// The context of the working settings: the one [`use_document_profiles`] put a document's
|
||||
/// profiles in place of, else this one.
|
||||
fn working_cms(&self) -> &Cms {
|
||||
self.working.as_deref().unwrap_or(self)
|
||||
}
|
||||
|
||||
/// A cached 3-D lookup table implementing [`Cms::proof_srgb`] for 8-bit pixels.
|
||||
pub fn proof_lut(&self, proof: &ProofSetup) -> Arc<ProofLut> {
|
||||
let key = format!("{:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper);
|
||||
let working = self.working.as_ref().map(|w| &w.settings);
|
||||
let key = format!("{:?}|{working:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper);
|
||||
let mut cache = PROOF_CACHE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((_, l)) = cache.iter().find(|(k, _)| *k == key) {
|
||||
return l.clone();
|
||||
@@ -890,10 +904,12 @@ impl CmykLut {
|
||||
// ---------- the active (process-wide) settings ----------
|
||||
|
||||
static ACTIVE: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
|
||||
static WORKING: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
|
||||
static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true);
|
||||
static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// The active colour-management context (Edit → Color Settings).
|
||||
/// The active color-management context: the working settings, with the profiles
|
||||
/// [`use_document_profiles`] last put in place of the working spaces.
|
||||
pub fn active() -> Arc<Cms> {
|
||||
if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||
return c.clone();
|
||||
@@ -906,13 +922,62 @@ pub fn active_settings() -> ColorSettings {
|
||||
active().settings.clone()
|
||||
}
|
||||
|
||||
/// Replace the active settings (fails, leaving them unchanged, if a profile is unknown).
|
||||
/// The color-management context of Edit → Color Settings (the working spaces, intent and black
|
||||
/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned.
|
||||
pub fn working() -> Arc<Cms> {
|
||||
if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||
return c.clone();
|
||||
}
|
||||
let mut w = WORKING.write().unwrap_or_else(|e| e.into_inner());
|
||||
w.get_or_insert_with(|| Arc::new(Cms::default())).clone()
|
||||
}
|
||||
|
||||
/// The settings of [`working`].
|
||||
pub fn working_settings() -> ColorSettings {
|
||||
working().settings.clone()
|
||||
}
|
||||
|
||||
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
|
||||
/// leaving both unchanged, if a profile is unknown).
|
||||
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
let cms = Cms::new(settings)?;
|
||||
let cms = Arc::new(Cms::new(settings)?);
|
||||
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
|
||||
install(cms);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make the working settings the active settings, with the profiles a document is assigned
|
||||
/// (`None`: none) in place of the working spaces. An assigned profile that is not available, or
|
||||
/// is not of its model, leaves the working space. The working settings stay as they are. True when
|
||||
/// the active settings changed.
|
||||
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
|
||||
let working = working();
|
||||
let mut st = working.settings.clone();
|
||||
if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) {
|
||||
st.rgb = p.name;
|
||||
}
|
||||
if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) {
|
||||
st.cmyk = p.name;
|
||||
}
|
||||
if st == active().settings {
|
||||
return false;
|
||||
}
|
||||
if st == working.settings {
|
||||
install(working);
|
||||
return true;
|
||||
}
|
||||
// The working settings were checked when they were set; a working profile removed since then
|
||||
// leaves the active settings as they are.
|
||||
let Ok(mut cms) = Cms::new(&st) else { return false };
|
||||
cms.working = Some(working);
|
||||
install(Arc::new(cms));
|
||||
true
|
||||
}
|
||||
|
||||
fn install(cms: Arc<Cms>) {
|
||||
RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed);
|
||||
CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed);
|
||||
*ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(cms));
|
||||
Ok(())
|
||||
*ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(cms);
|
||||
}
|
||||
|
||||
/// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB.
|
||||
|
||||
@@ -8,6 +8,9 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::Color;
|
||||
use crate::freeform::Freeform;
|
||||
|
||||
mod spread;
|
||||
pub use spread::{MAX_SPREAD_LEVEL, MAX_SPREAD_RUNS, MAX_SPREAD_STOPS, Padded};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum GradientKind {
|
||||
#[default]
|
||||
@@ -94,6 +97,82 @@ impl GradientMethod {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the
|
||||
/// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times
|
||||
/// along the vector (around the circle, for a conic), and keep going past both of its ends.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
|
||||
pub enum GradientSpread {
|
||||
/// The first and last stops' colors carry on past the ends, as gradients always did.
|
||||
#[default]
|
||||
Pad,
|
||||
/// The stops start again at each end.
|
||||
Repeat,
|
||||
/// The stops run back the other way at each end, so every other run is mirrored.
|
||||
Reflect,
|
||||
}
|
||||
|
||||
impl GradientSpread {
|
||||
/// Every spread, in the order the Gradient panel lists them.
|
||||
pub const ALL: [GradientSpread; 3] = [GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect];
|
||||
/// Parse a spread name (`pad`, `repeat`, `reflect`; any case).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Pad => "Pad",
|
||||
Self::Repeat => "Repeat",
|
||||
Self::Reflect => "Reflect",
|
||||
}
|
||||
}
|
||||
pub fn is_pad(&self) -> bool {
|
||||
*self == Self::Pad
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for GradientSpread {
|
||||
/// A spread name; a file's unknown name or other value reads as Pad.
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Name(String),
|
||||
Other(serde::de::IgnoredAny),
|
||||
}
|
||||
Ok(match Raw::deserialize(d)? {
|
||||
Raw::Name(s) => Self::parse(&s).unwrap_or_default(),
|
||||
Raw::Other(_) => Self::Pad,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Most times a gradient's stops run along its vector ([`Gradient::repeats`]): VectorCraft's own
|
||||
/// limit.
|
||||
pub const MAX_REPEATS: u32 = 100;
|
||||
|
||||
fn one_repeat() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_one_repeat(n: &u32) -> bool {
|
||||
*n == 1
|
||||
}
|
||||
|
||||
/// A file's repeat count: a number, rounded and kept within 1 to [`MAX_REPEATS`]; anything else
|
||||
/// reads as 1.
|
||||
fn lenient_repeats<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Number(f64),
|
||||
Other(serde::de::IgnoredAny),
|
||||
}
|
||||
Ok(match Raw::deserialize(d)? {
|
||||
Raw::Number(n) if n.is_finite() => n.round().clamp(1.0, f64::from(MAX_REPEATS)) as u32,
|
||||
_ => 1,
|
||||
})
|
||||
}
|
||||
|
||||
/// How far (display RGB, 0..1) the straight line between a Perceptual gradient's neighbouring
|
||||
/// expanded stops may stray from the perceptual mix: under half a colour level.
|
||||
const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
|
||||
@@ -259,6 +338,15 @@ pub struct Gradient {
|
||||
/// How the colours between the stops are mixed (Classic unless set; written only when not).
|
||||
#[serde(default, skip_serializing_if = "GradientMethod::is_classic")]
|
||||
pub method: GradientMethod,
|
||||
/// What it paints past the ends of its stops (Pad unless set; written only when not). A
|
||||
/// freeform gradient has no ends and ignores it.
|
||||
#[serde(default, skip_serializing_if = "GradientSpread::is_pad")]
|
||||
pub spread: GradientSpread,
|
||||
/// How many times the stops run along the vector with Repeat and Reflect, 1 to
|
||||
/// [`MAX_REPEATS`] (use [`Self::repeat_count`]: a value set in code may be out of range); Pad
|
||||
/// ignores it. Written only when it is not 1.
|
||||
#[serde(default = "one_repeat", skip_serializing_if = "is_one_repeat", deserialize_with = "lenient_repeats")]
|
||||
pub repeats: u32,
|
||||
}
|
||||
|
||||
impl Default for Gradient {
|
||||
@@ -271,7 +359,55 @@ impl Default for Gradient {
|
||||
impl Gradient {
|
||||
/// A gradient of `kind` through `stops`, with the default options.
|
||||
pub fn new(kind: GradientKind, stops: Vec<GradientStop>) -> Self {
|
||||
Self { kind, stops, dither: false, method: GradientMethod::Classic }
|
||||
Self { kind, stops, dither: false, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1 }
|
||||
}
|
||||
/// [`Self::repeats`] kept within 1 to [`MAX_REPEATS`].
|
||||
pub fn repeat_count(&self) -> u32 {
|
||||
self.repeats.clamp(1, MAX_REPEATS)
|
||||
}
|
||||
/// Does it paint something other than its end colors past the ends of its stops, or run its
|
||||
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
|
||||
pub fn is_spread(&self) -> bool {
|
||||
!self.spread.is_pad() && self.kind != GradientKind::Freeform
|
||||
}
|
||||
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
|
||||
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
|
||||
/// for two gradients whose spreads paint alike.
|
||||
pub fn painted_spread(&self) -> (GradientSpread, u32) {
|
||||
if self.is_spread() { (self.spread, self.repeat_count()) } else { (GradientSpread::Pad, 1) }
|
||||
}
|
||||
/// The position (0..1) along the stops that gradient parameter `t` (0 at the start of the
|
||||
/// vector, 1 at its end; [`GradientGeom::param_at`]) samples: `t` itself with Pad (the stops
|
||||
/// clamp it), else `t` × [`Self::repeat_count`] wrapped back into 0..1, every other run
|
||||
/// mirrored with Reflect. A `t` that is not finite is returned as it is.
|
||||
pub fn spread_param(&self, t: f64) -> f64 {
|
||||
self.spreader()(t)
|
||||
}
|
||||
/// How many wedges a conic gradient is written as ([`GradientGeom::conic_wedges`]) where
|
||||
/// `per_turn` would do for stops that run once around: that many for each time the stops run
|
||||
/// around, at most [`MAX_CONIC_WEDGES`]. Sample each wedge at [`Self::spread_param`] of its
|
||||
/// turn.
|
||||
pub fn conic_wedge_count(&self, per_turn: usize) -> usize {
|
||||
let runs = if self.is_spread() { self.repeat_count() as usize } else { 1 };
|
||||
per_turn.saturating_mul(runs).clamp(1, MAX_CONIC_WEDGES)
|
||||
}
|
||||
/// [`Self::spread_param`] as a function that holds no borrow of the gradient.
|
||||
pub fn spreader(&self) -> impl Fn(f64) -> f64 + Copy + use<> {
|
||||
let spread = if self.is_spread() { self.spread } else { GradientSpread::Pad };
|
||||
let n = f64::from(self.repeat_count());
|
||||
move |t: f64| {
|
||||
if !t.is_finite() {
|
||||
return t;
|
||||
}
|
||||
match spread {
|
||||
GradientSpread::Pad => t,
|
||||
GradientSpread::Repeat => (t * n).rem_euclid(1.0),
|
||||
GradientSpread::Reflect => {
|
||||
let w = (t * n).rem_euclid(2.0);
|
||||
if w > 1.0 { 2.0 - w } else { w }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Colour and opacity at `t` (honours midpoints and the method).
|
||||
pub fn sample(&self, t: f32) -> (Color, f32) {
|
||||
@@ -544,10 +680,18 @@ impl Gradient {
|
||||
GradientStop { opacity, ..GradientStop::new(offset, color) }
|
||||
};
|
||||
let d = to - from;
|
||||
let mut stops = vec![stop(0.0, from)];
|
||||
let expanded = self.expanded_stops();
|
||||
// Where stops share the offset `from` (a sharp step, as where the runs of a repeating
|
||||
// gradient meet), the piece starts with the color after the step; sampling gives the one
|
||||
// before it.
|
||||
let first = match expanded.iter().rev().find(|(t, ..)| *t == from) {
|
||||
Some(&(_, color, opacity)) if d > 1e-6 => GradientStop { opacity, ..GradientStop::new(0.0, color) },
|
||||
_ => stop(0.0, from),
|
||||
};
|
||||
let mut stops = vec![first];
|
||||
if d > 1e-6 {
|
||||
stops.extend(
|
||||
self.expanded_stops()
|
||||
expanded
|
||||
.into_iter()
|
||||
.filter(|(t, ..)| *t > from && *t < to)
|
||||
.map(|(t, color, opacity)| GradientStop { opacity, ..GradientStop::new((t - from) / d, color) }),
|
||||
@@ -954,6 +1098,35 @@ impl GradientGeom {
|
||||
self.set_focal(Some(m * q));
|
||||
}
|
||||
}
|
||||
/// The placement whose level `t` is this one's level `k`·`t` (`k` > 0), for a linear, radial or
|
||||
/// diamond gradient: the vector `k` times as long from the same start, and for an off-center
|
||||
/// radial the extent ellipse scaled `k` times about the focal point, which stays. A conic keeps
|
||||
/// its placement (its level is a turn).
|
||||
pub fn levels_scaled(&self, kind: GradientKind, k: f64) -> GradientGeom {
|
||||
if kind == GradientKind::Conic || !(k.is_finite() && k > 0.0) {
|
||||
return *self;
|
||||
}
|
||||
let u = self.end - self.start;
|
||||
let mut out = *self;
|
||||
if kind == GradientKind::Radial
|
||||
&& let (Some(f), Some(frame)) = (self.focal, self.unit_frame())
|
||||
{
|
||||
// Level t of an off-center radial is the extent ellipse scaled by t about the line
|
||||
// from the focal point to the center: the new center sits on that line, `k` times as
|
||||
// far from the focal point.
|
||||
let f = (frame.inverse() * f).to_vec2();
|
||||
out.start = frame * (f * (1.0 - k)).to_point();
|
||||
}
|
||||
out.end = out.start + u * k;
|
||||
out
|
||||
}
|
||||
|
||||
/// The placement over which one run of the stops of a gradient that repeats `n` times along
|
||||
/// its vector lies ([`Self::levels_scaled`] by 1/`n`).
|
||||
pub fn period(&self, kind: GradientKind, n: u32) -> GradientGeom {
|
||||
self.levels_scaled(kind, 1.0 / f64::from(n.max(1)))
|
||||
}
|
||||
|
||||
pub fn angle_deg(&self) -> f64 {
|
||||
let v = self.end - self.start;
|
||||
(-v.y).atan2(v.x).to_degrees()
|
||||
@@ -1148,12 +1321,13 @@ impl GradientPaint {
|
||||
inks: bool,
|
||||
) -> impl Iterator<Item = [u8; N]> + use<N> {
|
||||
let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither);
|
||||
let spread = self.gradient.spreader();
|
||||
let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1)));
|
||||
let (x0, y0) = (area.x0, area.y0);
|
||||
let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end));
|
||||
down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| {
|
||||
let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch);
|
||||
let c = ramp.at(geom.param_at(kind, p) as f32);
|
||||
let c = ramp.at(spread(geom.param_at(kind, p)) as f32);
|
||||
std::array::from_fn(|k| {
|
||||
if k + 1 == N {
|
||||
return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
//! A repeating or reflecting gradient as one that pads, for formats whose gradients only pad
|
||||
//! past their ends: the stops repeated (every other run mirrored, for Reflect) as many times as
|
||||
//! the painted area needs, and the vector stretched over those runs.
|
||||
|
||||
use kurbo::{Point, Rect, Vec2};
|
||||
|
||||
use super::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientSpread, GradientStop};
|
||||
use crate::Color;
|
||||
|
||||
/// Most runs of the stops [`Gradient::padded_over`] writes.
|
||||
pub const MAX_SPREAD_RUNS: usize = 256;
|
||||
|
||||
/// Most stops [`Gradient::padded_over`] writes, all runs together.
|
||||
pub const MAX_SPREAD_STOPS: usize = 16384;
|
||||
|
||||
/// The farthest level from its center a radial or diamond gradient's runs are written out to by
|
||||
/// [`Gradient::padded_over`] (its stops' offsets, single-precision fractions of it, stay apart),
|
||||
/// nearer for stops closer together than a run ([`MIN_OFFSET_GAP`]).
|
||||
pub const MAX_SPREAD_LEVEL: f64 = 65536.0;
|
||||
|
||||
/// The least difference between two stops' offsets [`Gradient::padded_over`] writes as
|
||||
/// different: sixteen times single precision's step just below 1.
|
||||
const MIN_OFFSET_GAP: f64 = 1e-6;
|
||||
|
||||
/// A repeating or reflecting gradient written as one that pads ([`Gradient::padded_over`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Padded {
|
||||
/// The gradient with its stops repeated, padding past its ends.
|
||||
pub gradient: Gradient,
|
||||
/// Where those runs lie.
|
||||
pub geom: GradientGeom,
|
||||
/// Where along `geom` (0 to 1) the first run written starts: 0 for a linear gradient, the
|
||||
/// first run's level over the last one's outer level for a radial or diamond one.
|
||||
pub first: f64,
|
||||
/// How many runs are written, evenly spaced from [`Self::first`] to 1.
|
||||
pub runs: usize,
|
||||
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or more than half the stops allowed,
|
||||
/// two to a run), or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
|
||||
pub capped: bool,
|
||||
}
|
||||
|
||||
impl Gradient {
|
||||
/// A linear, radial or diamond gradient that repeats or reflects, placed at `geom`, as a
|
||||
/// gradient that pads and paints `area` the same way: its stops repeated, each run's
|
||||
/// placement [`GradientGeom::period`] of `geom`, as many runs as the area reaches (a radial or
|
||||
/// diamond from its first level, 0, the first stop's color inside the area's innermost run).
|
||||
/// `None` for a gradient that pads, a conic or
|
||||
/// freeform one, one without stops, and a placement whose levels at the corners are not
|
||||
/// finite.
|
||||
pub fn padded_over(&self, geom: &GradientGeom, area: Rect) -> Option<Padded> {
|
||||
self.padded_within(geom, area, MAX_SPREAD_STOPS)
|
||||
}
|
||||
|
||||
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run). When the runs
|
||||
/// written need more stops than that, each run leaves out the stops that change its colors
|
||||
/// least ([`fit_run`]), so every run is still written.
|
||||
pub fn padded_within(&self, geom: &GradientGeom, area: Rect, max_stops: usize) -> Option<Padded> {
|
||||
let kind = self.kind;
|
||||
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let period = geom.period(kind, self.repeat_count());
|
||||
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)];
|
||||
let ts = corners.map(|p| period.param_at(kind, p));
|
||||
if ts.iter().any(|t| !t.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let centered = kind.is_centered();
|
||||
// The level's range over the area. A linear gradient's extremes lie at corners. Radial and
|
||||
// diamond levels are nested convex rings from level 0: the largest at a corner, the
|
||||
// smallest 0 when the area holds the rings' center, else on its edge.
|
||||
let lo = if centered { inner_level(&period, kind, area).floor() } else { ts.iter().copied().fold(f64::INFINITY, f64::min).floor() };
|
||||
let hi = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil().max(lo + 1.0);
|
||||
let budget = max_stops.min(MAX_SPREAD_STOPS);
|
||||
let most = MAX_SPREAD_RUNS.min(budget / 2).max(1);
|
||||
let capped = hi - lo > most as f64;
|
||||
// Capped, the runs kept are the area's innermost ones (radial and diamond), or (linear)
|
||||
// those around the vector's start where the area reaches it, else the area's runs nearest
|
||||
// to it.
|
||||
let lo = match capped {
|
||||
true if !centered => (-((most / 2) as f64)).clamp(lo, hi - most as f64),
|
||||
_ => lo,
|
||||
};
|
||||
let n = (hi - lo).min(most as f64).max(1.0);
|
||||
let one = fit_run(whole_run(&self.stops), budget / n as usize, self.method);
|
||||
// A radial or diamond writes its runs among the levels from 0, which its stops' offsets
|
||||
// (single-precision fractions of the outermost level) tell apart only so far out, the
|
||||
// nearer the closer its stops lie: past that, the runs end there and the gradient pads.
|
||||
let gap = one.windows(2).map(|w| f64::from(w[1].offset - w[0].offset)).filter(|d| *d > 0.0).fold(1.0, f64::min);
|
||||
// A whole level, so the runs keep their places (and Reflect its mirrored ones).
|
||||
let farthest = MAX_SPREAD_LEVEL.min(gap / MIN_OFFSET_GAP).floor().max(n);
|
||||
let far = centered && lo + n > farthest;
|
||||
let (lo, capped) = if far { ((farthest - n).max(0.0), true) } else { (lo, capped) };
|
||||
// `lo` is a whole number, possibly past what an integer holds: its parity in floating point.
|
||||
let first_odd = lo.rem_euclid(2.0) >= 1.0;
|
||||
let (stops, geom) = if centered {
|
||||
// The levels from 0, the runs from level `lo` (the first stop's color inside it).
|
||||
(self.runs(&one, first_odd, lo, n as usize, lo + n), period.levels_scaled(kind, lo + n))
|
||||
} else {
|
||||
let u = period.end - period.start;
|
||||
(
|
||||
self.runs(&one, first_odd, 0.0, n as usize, n),
|
||||
GradientGeom { start: period.start + u * lo, end: period.start + u * (lo + n), ..period },
|
||||
)
|
||||
};
|
||||
let gradient = Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() };
|
||||
let first = if centered { lo / (lo + n) } else { 0.0 };
|
||||
Some(Padded { gradient, geom, first, runs: n as usize, capped })
|
||||
}
|
||||
|
||||
/// The gradient as it runs from the start of its vector (0) to its end (1), as one that
|
||||
/// pads: a gradient that repeats or reflects with its stops repeated [`Self::repeat_count`]
|
||||
/// times between 0 and 1 (every other run mirrored, for Reflect), for what only shows that
|
||||
/// stretch (a gradient along or across a stroke, a swatch's preview). Others as they are.
|
||||
pub fn unrolled(&self) -> std::borrow::Cow<'_, Gradient> {
|
||||
self.unrolled_within(MAX_SPREAD_STOPS)
|
||||
}
|
||||
|
||||
/// [`Self::unrolled`] with at most `max_stops` stops: every run, each run without the stops
|
||||
/// that change its colors least ([`fit_run`]) when the runs need more stops than that. Only with
|
||||
/// fewer than two stops for each run do the runs past those that fit pad with the last one.
|
||||
pub fn unrolled_within(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
|
||||
use std::borrow::Cow;
|
||||
if !self.is_spread() {
|
||||
return Cow::Borrowed(self);
|
||||
}
|
||||
// Without stops there is nothing to repeat: it pads all the same.
|
||||
if self.stops.is_empty() {
|
||||
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
|
||||
}
|
||||
let n = self.repeat_count() as usize;
|
||||
let budget = max_stops.min(MAX_SPREAD_STOPS);
|
||||
let kept = n.min(budget / 2).max(1);
|
||||
let one = fit_run(whole_run(&self.stops), budget / kept, self.method);
|
||||
let stops = self.runs(&one, false, 0.0, kept, n as f64);
|
||||
Cow::Owned(Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() })
|
||||
}
|
||||
|
||||
/// The gradient as [`Self::unrolled`] gives it with at most `max_stops` stops (at least two):
|
||||
/// a gradient that repeats or reflects as [`Self::unrolled_within`] gives it, and one that
|
||||
/// pads with more stops than that without the stops that change its colors least
|
||||
/// ([`fit_run`]). Others as they are.
|
||||
pub fn fitted(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
|
||||
use std::borrow::Cow;
|
||||
if self.is_spread() {
|
||||
return self.unrolled_within(max_stops);
|
||||
}
|
||||
if self.stops.len() <= max_stops.max(2) {
|
||||
return Cow::Borrowed(self);
|
||||
}
|
||||
Cow::Owned(Gradient { stops: fit_run(whole_run(&self.stops), max_stops, self.method), ..self.clone() })
|
||||
}
|
||||
|
||||
/// One cycle of a gradient that repeats or reflects, which repeated end to end paints it, as
|
||||
/// a gradient that pads: one run of the stops (Repeat), or a run and its mirror (Reflect),
|
||||
/// between 0 and 1, and how many runs that is (1 or 2). `None` for a gradient that pads and
|
||||
/// one without stops.
|
||||
pub fn cycle(&self) -> Option<(Gradient, u32)> {
|
||||
if !self.is_spread() || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let one = whole_run(&self.stops);
|
||||
let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 };
|
||||
let stops = self.runs(&one, false, 0.0, runs, runs as f64);
|
||||
Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32))
|
||||
}
|
||||
|
||||
/// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1,
|
||||
/// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with
|
||||
/// Reflect, the odd-numbered runs are mirrored).
|
||||
fn runs(&self, one: &[GradientStop], first_odd: bool, start: f64, n: usize, of: f64) -> Vec<GradientStop> {
|
||||
let mirrored_run = (self.spread == GradientSpread::Reflect).then(|| mirror(one));
|
||||
let mut stops = Vec::with_capacity(one.len() * n);
|
||||
for j in 0..n {
|
||||
let run = match &mirrored_run {
|
||||
Some(m) if (j % 2 == 1) != first_odd => m.as_slice(),
|
||||
_ => one,
|
||||
};
|
||||
stops.extend(run.iter().map(|s| GradientStop { offset: ((start + j as f64 + f64::from(s.offset)) / of) as f32, ..s.clone() }));
|
||||
}
|
||||
stops
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest level of radial or diamond gradient `geom` over `area`, less a run (for rounding):
|
||||
/// 0 when the area holds the rings' center (a radial's focal point, a diamond's center), else the
|
||||
/// smallest along its sides, worked out in the gradient's unit frame from the sides' ends rather
|
||||
/// than from samples along them, so a long side does not hide a run near it. 0 for a placement
|
||||
/// without a frame.
|
||||
fn inner_level(geom: &GradientGeom, kind: GradientKind, area: Rect) -> f64 {
|
||||
let center = if kind == GradientKind::Radial { geom.focal_point() } else { geom.start };
|
||||
if area.contains(center) {
|
||||
return 0.0;
|
||||
}
|
||||
let frame = if kind == GradientKind::Diamond { geom.diamond_frame() } else { geom.unit_frame() };
|
||||
let Some(to_unit) = frame.map(|m| m.inverse()) else { return 0.0 };
|
||||
let focal = geom.focal.filter(|_| kind == GradientKind::Radial).map(|f| (to_unit * f).to_vec2());
|
||||
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)]
|
||||
.map(|p| (to_unit * p).to_vec2());
|
||||
let mut least = f64::INFINITY;
|
||||
for (&a, &b) in corners.iter().zip(corners.iter().cycle().skip(1)) {
|
||||
let side = if kind == GradientKind::Diamond { diamond_least(a, b) } else { radial_least(a, b, focal) };
|
||||
least = least.min(side);
|
||||
}
|
||||
if least.is_finite() { (least - 1.0).max(0.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The smallest diamond level, |x| + |y| in its unit frame, on the segment from `a` to `b`: the
|
||||
/// level is linear between the points where the segment crosses an axis, so the smallest is at
|
||||
/// an end or at one of those crossings.
|
||||
fn diamond_least(a: Vec2, b: Vec2) -> f64 {
|
||||
let d = b - a;
|
||||
let crossings = [(d.x != 0.0).then(|| -a.x / d.x), (d.y != 0.0).then(|| -a.y / d.y)];
|
||||
[Some(0.0), Some(1.0), crossings[0], crossings[1]]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|u| (0.0..=1.0).contains(u))
|
||||
.map(|u| {
|
||||
let p = a + d * u;
|
||||
p.x.abs() + p.y.abs()
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Halvings at most in [`radial_least`]: enough to bring any finite span below a quarter level.
|
||||
const RADIAL_HALVINGS: usize = 1100;
|
||||
|
||||
/// The smallest radial level on the segment from `a` to `b` in the unit frame, at most a quarter
|
||||
/// level under it: the distance to the center for a centered radial. An off-center radial's level
|
||||
/// `t` is the circle of radius `t` about `f`(1 − `t`), `f` its focal point; the segment's distance
|
||||
/// from that center less `t` falls as `t` grows (the center moves |`f`| < 1 per level), and the
|
||||
/// smallest level is where it reaches 0, found by halving. 0 for a focal point not inside the
|
||||
/// extent ellipse.
|
||||
fn radial_least(a: Vec2, b: Vec2, focal: Option<Vec2>) -> f64 {
|
||||
let Some(f) = focal else { return distance_to_segment(a, b, Vec2::ZERO) };
|
||||
let reach = f.hypot();
|
||||
if reach.is_nan() || reach >= 1.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let past = |t: f64| distance_to_segment(a, b, f * (1.0 - t)) <= t;
|
||||
// At this level the circle reaches the segment's nearest point to the ellipse's center.
|
||||
let mut hi = (distance_to_segment(a, b, Vec2::ZERO) / (1.0 - reach)).max(1.0);
|
||||
let mut lo = 0.0;
|
||||
if !hi.is_finite() || past(lo) {
|
||||
return 0.0;
|
||||
}
|
||||
for _ in 0..RADIAL_HALVINGS {
|
||||
let mid = lo + (hi - lo) / 2.0;
|
||||
if hi - lo <= 0.25 || mid <= lo || mid >= hi {
|
||||
break;
|
||||
}
|
||||
if past(mid) { hi = mid } else { lo = mid }
|
||||
}
|
||||
lo
|
||||
}
|
||||
|
||||
/// How far `c` is from the segment from `a` to `b`.
|
||||
fn distance_to_segment(a: Vec2, b: Vec2, c: Vec2) -> f64 {
|
||||
let d = b - a;
|
||||
let along = (c - a).dot(d) / d.hypot2();
|
||||
let u = if along.is_finite() { along.clamp(0.0, 1.0) } else { 0.0 };
|
||||
(a + d * u - c).hypot()
|
||||
}
|
||||
|
||||
/// The stops of one run, from offset 0 to 1: the end colors held out to the ends.
|
||||
fn whole_run(stops: &[GradientStop]) -> Vec<GradientStop> {
|
||||
let mut out = stops.to_vec();
|
||||
if let Some(first) = out.first().filter(|s| s.offset > 0.0).cloned() {
|
||||
out.insert(0, GradientStop { offset: 0.0, ..first });
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
// The last stop's midpoint leads nowhere; the copy at 1 takes over.
|
||||
if last.offset < 1.0 {
|
||||
let end = GradientStop { offset: 1.0, ..last.clone() };
|
||||
out.push(end);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `one` (a run of a gradient's stops, [`whole_run`]) with at most `budget` stops (at least two):
|
||||
/// as it is when it fits, else without the stops that change its colors least, left out one at a
|
||||
/// time. Leaving out a stop costs how far its color lies from the one that mixing the stops still
|
||||
/// on either side of it by `method` gives there, and how far its CMYK inks, opacity, tint or
|
||||
/// process plates lie from the line between theirs (a whole unit when its swatch link or color
|
||||
/// model differs from either of theirs, and a whole unit more when its midpoint or the one before
|
||||
/// it is off center), so the ends, sharp steps, ink changes and shaped spans stay. A stop whose
|
||||
/// next stop was left out gets its midpoint centered. The work is the stops times their logarithm.
|
||||
fn fit_run(one: Vec<GradientStop>, budget: usize, method: GradientMethod) -> Vec<GradientStop> {
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BinaryHeap;
|
||||
let budget = budget.max(2);
|
||||
let n = one.len();
|
||||
if n <= budget {
|
||||
return one;
|
||||
}
|
||||
let mix = |x: &Color, y: &Color, v: f32| match method {
|
||||
GradientMethod::Classic => x.lerp_keep_model(y, v),
|
||||
m => m.mix(x, y, v),
|
||||
};
|
||||
let cost = |a: &GradientStop, s: &GradientStop, b: &GradientStop| -> u32 {
|
||||
let span = b.offset - a.offset;
|
||||
let u = if span > 0.0 { ((s.offset - a.offset) / span).clamp(0.0, 1.0) } else { 0.0 };
|
||||
// Left out, the span from `a` to `b` has a centered midpoint, so it mixes them by `u`.
|
||||
let (want, cs) = (mix(&a.color, &b.color, u).to_rgb(), s.color.to_rgb());
|
||||
let color = (0..3).map(|k| (want[k] - cs[k]).abs()).fold(0.0, f32::max);
|
||||
let opacity = (a.opacity + (b.opacity - a.opacity) * u - s.opacity).abs();
|
||||
// Process inks, which colors that look alike can print differently: off their line, or a
|
||||
// change of color model.
|
||||
let process = match (&a.color, &s.color, &b.color) {
|
||||
(Color::Cmyk { c: c0, m: m0, y: y0, k: k0 }, Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c1, m: m1, y: y1, k: k1 }) => {
|
||||
[(c0, c, c1), (m0, m, m1), (y0, y, y1), (k0, k, k1)].iter().map(|(p, q, r)| (*p + (*r - *p) * u - *q).abs()).fold(0.0, f32::max)
|
||||
}
|
||||
_ if a.color.model() == s.color.model() && s.color.model() == b.color.model() => 0.0,
|
||||
_ => 1.0,
|
||||
};
|
||||
let color = color.max(process);
|
||||
// Separations: a change of swatch link, or of tint or process plates off their line.
|
||||
let ink = if s.swatch != a.swatch || s.swatch != b.swatch {
|
||||
1.0
|
||||
} else {
|
||||
let tint = (a.tint + (b.tint - a.tint) * u - s.tint).abs();
|
||||
let plates = match (a.plates, s.plates, b.plates) {
|
||||
(None, None, None) => 0.0,
|
||||
(Some(pa), Some(ps), Some(pb)) => (0..4).map(|k| (pa[k] + (pb[k] - pa[k]) * u - ps[k]).abs()).fold(0.0, f32::max),
|
||||
_ => 1.0,
|
||||
};
|
||||
tint.max(plates)
|
||||
};
|
||||
// Leaving it out merges two spans, and an off-center midpoint shapes one of them.
|
||||
let shaped = if [a.midpoint, s.midpoint].iter().any(|m| (m - 0.5).abs() > 1e-3) { 1.0 } else { 0.0 };
|
||||
// Non-negative, so the bits order as the numbers do (NaN counts as 0).
|
||||
(color.max(opacity).max(ink) + shaped).max(0.0).to_bits()
|
||||
};
|
||||
// The stops still kept on either side of each stop, and each stop's latest cost entry.
|
||||
let mut prev: Vec<usize> = (0..n).map(|i| i.saturating_sub(1)).collect();
|
||||
let mut next: Vec<usize> = (1..=n).collect();
|
||||
let mut gone = vec![false; n];
|
||||
let mut version = vec![0u32; n];
|
||||
let mut heap: BinaryHeap<Reverse<(u32, usize, u32)>> = (1..n - 1).map(|i| Reverse((cost(&one[i - 1], &one[i], &one[i + 1]), i, 0))).collect();
|
||||
let mut left = n;
|
||||
while left > budget {
|
||||
let Some(Reverse((_, i, v))) = heap.pop() else { break };
|
||||
if gone[i] || v != version[i] {
|
||||
continue;
|
||||
}
|
||||
gone[i] = true;
|
||||
left -= 1;
|
||||
let (a, b) = (prev[i], next[i]);
|
||||
next[a] = b;
|
||||
prev[b] = a;
|
||||
for j in [a, b] {
|
||||
if j != 0 && j != n - 1 {
|
||||
version[j] += 1;
|
||||
heap.push(Reverse((cost(&one[prev[j]], &one[j], &one[next[j]]), j, version[j])));
|
||||
}
|
||||
}
|
||||
}
|
||||
one.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| !gone[*i])
|
||||
.map(|(i, s)| if next[i] == i + 1 { s } else { GradientStop { midpoint: 0.5, ..s } })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A run mirrored: the stops in reverse, each midpoint measured from the other side.
|
||||
fn mirror(run: &[GradientStop]) -> Vec<GradientStop> {
|
||||
let mut g = Gradient::new(GradientKind::Linear, run.to_vec());
|
||||
g.reverse();
|
||||
g.stops
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,480 @@
|
||||
use kurbo::Vec2;
|
||||
|
||||
use super::*;
|
||||
use crate::gradient::{GradientPaint, MAX_REPEATS};
|
||||
use crate::{Color, GradientMethod};
|
||||
|
||||
fn spread(kind: GradientKind, spread: GradientSpread, repeats: u32) -> Gradient {
|
||||
Gradient { spread, repeats, ..Gradient::new(kind, Gradient::default().stops) }
|
||||
}
|
||||
|
||||
fn black_white() -> Vec<GradientStop> {
|
||||
let mut a = GradientStop::new(0.0, Color::BLACK);
|
||||
a.midpoint = 0.3;
|
||||
vec![a, GradientStop::new(1.0, Color::WHITE)]
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
/// Repeat wraps the parameter, `repeats` times along the vector and on past both ends; Reflect
|
||||
/// runs every other run backwards; Pad leaves it to the stops to clamp; a freeform gradient has
|
||||
/// no ends to spread past.
|
||||
#[test]
|
||||
fn spread_maps_the_parameter_to_a_place_along_the_stops() {
|
||||
let repeat = spread(GradientKind::Linear, GradientSpread::Repeat, 3);
|
||||
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (0.5, 0.5), (1.0 / 3.0 + 0.1, 0.3), (1.1, 0.3), (-0.1, 0.7)] {
|
||||
assert!(close(repeat.spread_param(t), want), "repeat {t}: {}", repeat.spread_param(t));
|
||||
}
|
||||
let reflect = spread(GradientKind::Radial, GradientSpread::Reflect, 3);
|
||||
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (1.0 / 3.0 + 0.1, 0.7), (2.0 / 3.0 + 0.1, 0.3), (1.0, 1.0), (-0.1, 0.3)] {
|
||||
assert!(close(reflect.spread_param(t), want), "reflect {t}: {}", reflect.spread_param(t));
|
||||
}
|
||||
let pad = spread(GradientKind::Linear, GradientSpread::Pad, 3);
|
||||
assert_eq!((pad.spread_param(1.7), pad.spread_param(-0.2)), (1.7, -0.2));
|
||||
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
|
||||
assert_eq!(free.spread_param(0.7), 0.7);
|
||||
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
|
||||
assert!(repeat.spread_param(f64::NAN).is_nan());
|
||||
// A count out of range (set in code) counts as the nearest one in range.
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 5000).repeat_count(), MAX_REPEATS);
|
||||
}
|
||||
|
||||
/// The native format writes the spread and count only when they are not Pad and 1, reads a file
|
||||
/// without them as Pad and 1, and reads an unknown spread or a count out of range as the nearest
|
||||
/// one it can hold.
|
||||
#[test]
|
||||
fn the_file_keeps_the_spread_and_reads_bad_values_leniently() {
|
||||
let plain = serde_json::to_value(Gradient::default()).unwrap();
|
||||
assert!(plain.get("spread").is_none() && plain.get("repeats").is_none(), "{plain}");
|
||||
let g = spread(GradientKind::Conic, GradientSpread::Reflect, 4);
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
assert_eq!((v["spread"].as_str(), v["repeats"].as_u64()), (Some("Reflect"), Some(4)));
|
||||
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
|
||||
let read = |spread: serde_json::Value, repeats: serde_json::Value| {
|
||||
let mut v = serde_json::to_value(Gradient::default()).unwrap();
|
||||
v["spread"] = spread;
|
||||
v["repeats"] = repeats;
|
||||
let g: Gradient = serde_json::from_value(v).unwrap();
|
||||
(g.spread, g.repeats)
|
||||
};
|
||||
assert_eq!(read("Repeat".into(), 3.4.into()), (GradientSpread::Repeat, 3));
|
||||
assert_eq!(read("Spiral".into(), (-5).into()), (GradientSpread::Pad, 1));
|
||||
assert_eq!(read(7.into(), 1e12.into()), (GradientSpread::Pad, MAX_REPEATS));
|
||||
assert_eq!(read(serde_json::Value::Null, "many".into()), (GradientSpread::Pad, 1));
|
||||
let missing: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap();
|
||||
assert_eq!((missing.spread, missing.repeats), (GradientSpread::Pad, 1));
|
||||
}
|
||||
|
||||
/// One run's placement: a level of the period is the gradient's level times the count, for
|
||||
/// linear, diamond and off-center radial gradients; a conic keeps its placement.
|
||||
#[test]
|
||||
fn a_period_holds_one_run_of_the_stops() {
|
||||
let p = Point::new(72.0, 61.0);
|
||||
let linear = GradientGeom { start: Point::new(10.0, 20.0), end: Point::new(60.0, 40.0), aspect: 1.0, focal: None };
|
||||
let radial = GradientGeom { start: Point::new(50.0, 50.0), end: Point::new(60.0, 50.0), aspect: 0.6, focal: Some(Point::new(55.0, 52.0)) };
|
||||
let diamond = GradientGeom { end: Point::new(58.0, 56.0), focal: None, ..radial };
|
||||
for (kind, geom) in [(GradientKind::Linear, linear), (GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
|
||||
let period = geom.period(kind, 4);
|
||||
assert!(close(period.param_at(kind, p), 4.0 * geom.param_at(kind, p)), "{kind:?}");
|
||||
assert_eq!(period.focal, geom.focal, "{kind:?}");
|
||||
}
|
||||
assert_eq!(radial.period(GradientKind::Conic, 4), radial);
|
||||
assert_eq!(linear.period(GradientKind::Linear, 0), linear, "a count of 0 counts as 1");
|
||||
}
|
||||
|
||||
/// The stops repeated over the area: as many runs as its corners reach, each in place.
|
||||
#[test]
|
||||
fn a_linear_gradient_pads_with_its_stops_repeated_over_the_area() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(-5.0, 0.0, 25.0, 10.0)).unwrap();
|
||||
assert!(!p.capped);
|
||||
// Runs of 10 from -10 to 30: four of them.
|
||||
assert_eq!((p.geom.start, p.geom.end), (Point::new(-10.0, 0.0), Point::new(30.0, 0.0)));
|
||||
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0]);
|
||||
assert!(p.gradient.stops.iter().step_by(2).all(|s| s.color == Color::BLACK && (s.midpoint - 0.3).abs() < 1e-6));
|
||||
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
|
||||
// Every point gets the color the gradient gives it.
|
||||
for x in [-4.0, 1.0, 7.5, 13.0, 24.0] {
|
||||
let q = Point::new(x, 5.0);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0;
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0;
|
||||
assert!(want.to_rgb().iter().zip(got.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_mirrors_every_other_run_and_its_midpoints() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
let colors: Vec<Color> = p.gradient.stops.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK]);
|
||||
// Black → white with the midpoint at 0.3 mirrors to white → black with it at 0.7.
|
||||
assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_inside_a_run_hold_their_colors_to_its_ends() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let stops = vec![GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.75, Color::WHITE)];
|
||||
let g = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.125, 0.375, 0.5, 0.5, 0.625, 0.875, 1.0]);
|
||||
}
|
||||
|
||||
/// An off-center radial grows about its focal point, a diamond about its center; every point
|
||||
/// keeps its color.
|
||||
#[test]
|
||||
fn radial_and_diamond_gradients_pad_in_rings_from_their_first_level() {
|
||||
let c = Point::new(50.0, 50.0);
|
||||
let radial = GradientGeom { start: c, end: Point::new(60.0, 50.0), aspect: 1.0, focal: Some(Point::new(55.0, 50.0)) };
|
||||
let diamond = GradientGeom { focal: None, ..radial };
|
||||
for (kind, geom) in [(GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 100.0)).unwrap();
|
||||
assert!(p.gradient.stops.len() / 2 >= 10, "{kind:?}: {}", p.gradient.stops.len());
|
||||
assert_eq!(p.geom.focal, geom.focal);
|
||||
for q in [Point::new(72.0, 61.0), Point::new(10.0, 95.0), Point::new(52.0, 49.0)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-4), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of the stops far too short for the area is written with at most so many runs, and pads
|
||||
/// past them; a gradient of many stops is written with every run the area needs, each run
|
||||
/// without the stops that change its colors least, within so many stops; a conic, a padding
|
||||
/// gradient and one without stops have nothing to pad.
|
||||
#[test]
|
||||
fn far_repeats_are_capped_and_many_stops_are_sampled() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.01, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
|
||||
assert!(p.capped);
|
||||
assert_eq!(p.gradient.stops.len(), 2 * MAX_SPREAD_RUNS);
|
||||
let many: Vec<GradientStop> = (0..=4000).map(|i| GradientStop::new(i as f32 / 4000.0, Color::gray(i as f32 / 4000.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 50, ..Gradient::new(GradientKind::Linear, many) };
|
||||
let wide = GradientGeom { end: Point::new(100.0, 0.0), ..geom };
|
||||
let p = g.padded_over(&wide, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
|
||||
assert!(!p.capped && p.runs == 50 && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {}", p.runs, p.gradient.stops.len());
|
||||
for x in [0.7, 33.3, 66.1, 99.5] {
|
||||
let q = Point::new(x, 0.5);
|
||||
let want = g.sample(g.spread_param(wide.param_at(GradientKind::Linear, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
assert!(g.unrolled().stops.len() <= MAX_SPREAD_STOPS);
|
||||
assert!(p.gradient.padded_over(&p.geom, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none(), "it pads");
|
||||
assert!(spread(GradientKind::Conic, GradientSpread::Repeat, 3).padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
|
||||
let empty = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, vec![]) };
|
||||
assert!(empty.padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
|
||||
}
|
||||
|
||||
/// The runs written are the ones the area shows: a radial or diamond centered a thousand runs
|
||||
/// from the area writes the hundred it crosses, not the first 256 from the center; a linear
|
||||
/// gradient over an area of 1,100 runs far before its start, capped, keeps the runs nearest it.
|
||||
/// Every point checked gets the color the gradient gives it.
|
||||
#[test]
|
||||
fn the_runs_written_cover_a_distant_area() {
|
||||
let centered = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(1.0, 50.0), aspect: 1.0, focal: None };
|
||||
let before = GradientGeom { start: Point::new(5000.0, 0.0), end: Point::new(5001.0, 0.0), aspect: 1.0, focal: None };
|
||||
for (kind, geom, area) in [
|
||||
(GradientKind::Radial, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
|
||||
(GradientKind::Diamond, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
|
||||
(GradientKind::Linear, before, Rect::new(0.0, 0.0, 1100.0, 100.0)),
|
||||
] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, area).unwrap();
|
||||
assert_eq!(p.capped, kind == GradientKind::Linear, "{kind:?}");
|
||||
assert!(p.gradient.stops.len() <= MAX_SPREAD_STOPS);
|
||||
for q in [Point::new(1000.5, 0.5), Point::new(1050.25, 50.0), Point::new(1099.5, 99.5), Point::new(1010.75, 90.0)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tiny radial centered just outside the area, beside a side between any evenly spaced
|
||||
/// samples of it: the runs written start from the area's true innermost level.
|
||||
#[test]
|
||||
fn the_innermost_level_is_found_between_samples() {
|
||||
let c = Point::new(-0.0005, 7.8125);
|
||||
let geom = GradientGeom { start: c, end: c + Vec2::new(0.001, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 1000.0, 1000.0)).unwrap();
|
||||
for q in [Point::new(0.05, 7.8125), Point::new(0.1, 7.9)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Radial, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Radial, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An area four billion units wide whose long side passes 50 runs from a tiny radial or diamond's
|
||||
/// center: the runs written start from that side's true innermost level, so the runs beside it
|
||||
/// keep their colors.
|
||||
#[test]
|
||||
fn the_innermost_level_is_found_along_a_very_long_side() {
|
||||
let area = Rect::new(-1.3e9, 0.0, 2.9e9, 1.0);
|
||||
for x in [0.3, 12345.678, -7777.25, 98765.4321] {
|
||||
let c = Point::new(x, -0.00005);
|
||||
let run = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
|
||||
let off_center = GradientGeom { focal: Some(c + Vec2::new(0.5e-6, 0.0)), ..run };
|
||||
for (kind, geom) in [(GradientKind::Diamond, run), (GradientKind::Radial, run), (GradientKind::Radial, off_center)] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, area).unwrap();
|
||||
assert!(p.capped, "{kind:?}");
|
||||
for q in [Point::new(x, 1e-5), Point::new(x + 2e-5, 2e-5), Point::new(x - 1e-5, 0.0001)] {
|
||||
let level = geom.param_at(kind, q);
|
||||
assert!((40.0..200.0).contains(&level), "{kind:?} {q:?}: level {level}");
|
||||
let want = g.sample(g.spread_param(level) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a billion levels from a radial's center are past what the stops' offsets can tell apart:
|
||||
/// the gradient is written capped, its stops still apart and in order.
|
||||
#[test]
|
||||
fn runs_too_far_from_the_center_are_capped() {
|
||||
let c = Point::new(0.0, 0.0);
|
||||
let geom = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(1000.0, 0.0, 1000.0001, 0.0001)).unwrap();
|
||||
assert!(p.capped);
|
||||
assert!(p.gradient.stops.windows(2).all(|w| w[0].offset <= w[1].offset), "in order");
|
||||
let distinct = p.gradient.stops.windows(2).filter(|w| w[1].offset > w[0].offset).count();
|
||||
assert!(distinct * 2 + 2 >= p.gradient.stops.len(), "the runs stay apart: {distinct} of {}", p.gradient.stops.len());
|
||||
}
|
||||
|
||||
/// A run of 1,000 close stops is written only as far out as their offsets stay apart: around
|
||||
/// level 50,000 it is capped, every stop written apart from the next.
|
||||
#[test]
|
||||
fn close_stops_are_written_only_where_they_stay_apart() {
|
||||
let many: Vec<GradientStop> = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray(i as f32 / 1000.0))).collect();
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.001, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 1, ..Gradient::new(GradientKind::Diamond, many) };
|
||||
let p = g.padded_over(&geom, Rect::new(50.0, 0.0, 50.002, 0.002)).unwrap();
|
||||
assert!(p.capped);
|
||||
// Only where one run meets the next do two stops share an offset.
|
||||
let runs = p.gradient.stops.len() / 1001;
|
||||
let shared = p.gradient.stops.windows(2).filter(|w| w[1].offset <= w[0].offset).count();
|
||||
assert!(shared < runs, "{shared} stops share an offset in {runs} runs");
|
||||
// Stops 0.0001234 of a run apart are written out to level 123, on whole runs: an area within
|
||||
// it gets the gradient's colors, Reflect's mirrored runs included.
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.0001234, Color::gray(0.5)), GradientStop::new(1.0, Color::WHITE)];
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Diamond, stops) };
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0), aspect: 1.0, focal: None };
|
||||
let p = g.padded_over(&geom, Rect::new(121.0, 0.0, 123.9, 0.2)).unwrap();
|
||||
assert!(p.capped, "past level 123 it pads");
|
||||
for x in [121.3, 121.9, 122.5] {
|
||||
let q = Point::new(x, 0.1);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Diamond, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Diamond, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece of a gradient that starts where two runs meet (a gradient along a stroke, sliced at a
|
||||
/// corner there) starts with the new run's first color, not the old run's last.
|
||||
#[test]
|
||||
fn a_piece_starting_at_a_sharp_step_takes_the_color_after_it() {
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, Gradient::default().stops) };
|
||||
let piece = g.unrolled().span(0.5, 1.0);
|
||||
assert_eq!(piece.stops.first().map(|s| s.color), Some(Color::WHITE), "{:?}", piece.stops);
|
||||
assert_eq!(piece.stops.last().map(|s| s.color), Some(Color::BLACK));
|
||||
let before = g.unrolled().span(0.0, 0.5);
|
||||
assert_eq!((before.stops[0].color, before.stops.last().unwrap().color), (Color::WHITE, Color::BLACK));
|
||||
}
|
||||
|
||||
/// An area very far past a very short reflecting vector (a file's numbers) is padded without the
|
||||
/// run count overflowing.
|
||||
#[test]
|
||||
fn a_far_area_pads_without_overflowing() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1e-300, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(1e3, 0.0, 2e3, 1.0));
|
||||
assert!(p.is_none_or(|p| p.gradient.stops.len() <= MAX_SPREAD_STOPS));
|
||||
// Runs of 1e-8: the area's levels lie past 1e19, more than an integer holds.
|
||||
let geom = GradientGeom { end: Point::new(1e-6, 0.0), ..geom };
|
||||
let p = g.padded_over(&geom, Rect::new(1e11, 0.0, 1e11 + 1.0, 1.0)).unwrap();
|
||||
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {} {:?}", p.capped, p.gradient.stops.len(), p.geom);
|
||||
}
|
||||
|
||||
/// Unrolled, the stops run `repeats` times between 0 and 1 (every other run mirrored with
|
||||
/// Reflect); one cycle is a run, or a run and its mirror.
|
||||
#[test]
|
||||
fn unrolled_and_cycle_stops() {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let u = g.unrolled();
|
||||
let offsets: Vec<f32> = u.stops.iter().map(|s| (s.offset * 3.0).round()).collect();
|
||||
assert_eq!(offsets, [0.0, 1.0, 1.0, 2.0, 2.0, 3.0]);
|
||||
let colors: Vec<Color> = u.stops.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK, Color::BLACK, Color::WHITE]);
|
||||
for t in [0.05, 0.4, 0.71, 0.99] {
|
||||
let (a, b) = (g.sample(g.spread_param(t) as f32).0.to_rgb(), u.sample(t as f32).0.to_rgb());
|
||||
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), "{t}");
|
||||
}
|
||||
let (cycle, runs) = g.cycle().unwrap();
|
||||
assert_eq!((runs, cycle.stops.len()), (2, 4));
|
||||
let repeat = Gradient { spread: GradientSpread::Repeat, ..g.clone() };
|
||||
assert_eq!(repeat.cycle().unwrap().1, 1);
|
||||
assert!(Gradient::default().cycle().is_none());
|
||||
assert!(matches!(Gradient::default().unrolled(), std::borrow::Cow::Borrowed(_)));
|
||||
}
|
||||
|
||||
/// A gradient of more stops than [`MAX_SPREAD_STOPS`] allows for all its runs keeps every run
|
||||
/// when unrolled, each run without the stops that change its colors least: its last run ends on
|
||||
/// its last color instead of the rest padding with it.
|
||||
#[test]
|
||||
fn unrolled_many_stops_keep_every_run() {
|
||||
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(i as f32 / 199.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let u = g.unrolled();
|
||||
assert!(u.stops.len() <= MAX_SPREAD_STOPS, "{}", u.stops.len());
|
||||
for t in [0.005, 0.5051, 0.9149, 0.9951] {
|
||||
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
|
||||
let got = u.sample(t as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{t}: {want:?} vs {got:?}");
|
||||
}
|
||||
// A padding gradient fitted to fewer stops keeps its ends.
|
||||
let pad = Gradient::new(GradientKind::Linear, g.stops.clone());
|
||||
let fitted = pad.fitted(16);
|
||||
assert_eq!(fitted.stops.len(), 16);
|
||||
for (stop, want) in [(&fitted.stops[0], Color::gray(0.0)), (&fitted.stops[15], Color::gray(1.0))] {
|
||||
assert!(stop.color.to_rgb().iter().zip(want.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-5), "{:?}", stop.color);
|
||||
}
|
||||
assert!(matches!(pad.fitted(500), std::borrow::Cow::Borrowed(_)));
|
||||
}
|
||||
|
||||
/// One run of more stops than the limit (255 inside it, and a copy of each end color at 0 and 1)
|
||||
/// is written within the limit, every run the area needs included.
|
||||
#[test]
|
||||
fn a_run_over_the_stop_limit_is_written_within_it() {
|
||||
let stops: Vec<GradientStop> = (1..=255).map(|i| GradientStop::new(i as f32 / 256.0, Color::gray(i as f32 / 256.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
|
||||
let p = g.padded_within(&geom, Rect::new(0.0, 0.0, 20.0, 1.0), 256).unwrap();
|
||||
assert!(!p.capped && p.runs == 2 && p.gradient.stops.len() <= 256, "{} {} {}", p.capped, p.runs, p.gradient.stops.len());
|
||||
assert!(g.unrolled_within(256).stops.len() <= 256);
|
||||
}
|
||||
|
||||
/// Fitting a run to fewer stops keeps a narrow band between two sharp steps, a stop linked to a
|
||||
/// swatch, and each kept stop's link and tint, where sampling at evenly spaced places would lose
|
||||
/// them.
|
||||
#[test]
|
||||
fn fitting_keeps_sharp_steps_and_swatch_links() {
|
||||
let mut stops: Vec<GradientStop> = (0..300).map(|i| GradientStop::new(i as f32 / 299.0, Color::gray(i as f32 / 299.0))).collect();
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
// A band of red from 0.5003 to 0.5013, with a sharp step at each side.
|
||||
for (offset, color) in [(0.5003, None), (0.5003, Some(red)), (0.5013, Some(red)), (0.5013, None)] {
|
||||
let gray = Color::gray(offset);
|
||||
stops.push(GradientStop::new(offset, color.unwrap_or(gray)));
|
||||
}
|
||||
let spot = GradientStop { swatch: Some("Ink".into()), tint: 0.4, ..GradientStop::new(0.25, Color::gray(0.25)) };
|
||||
stops.push(spot.clone());
|
||||
// Three stops of one ink that look alike but print at different tints.
|
||||
for (offset, tint) in [(0.8, 0.2), (0.81, 0.9), (0.82, 0.2)] {
|
||||
stops.push(GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(offset)) });
|
||||
}
|
||||
// A span shaped by an off-center midpoint.
|
||||
if let Some(s) = stops.iter_mut().find(|s| (s.offset - 0.6).abs() < 2e-3) {
|
||||
s.midpoint = 0.13;
|
||||
}
|
||||
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
let g = Gradient::new(GradientKind::Linear, stops);
|
||||
let fitted = g.fitted(32);
|
||||
assert!(fitted.stops.len() <= 32, "{}", fitted.stops.len());
|
||||
let red_at = |t: f32| fitted.sample(t).0.to_rgb();
|
||||
assert_eq!(red_at(0.5008), [1.0, 0.0, 0.0], "the band stays");
|
||||
assert!(red_at(0.499)[1] > 0.4 && red_at(0.503)[1] > 0.4, "the band stays narrow");
|
||||
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.4 && s.offset == 0.25), "{:?}", fitted.stops);
|
||||
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink2") && s.tint == 0.9), "the tint change stays");
|
||||
assert!(fitted.stops.iter().any(|s| s.midpoint == 0.13), "the shaped span stays");
|
||||
// Of a stop that changes only its ink's tint and one that the colors' line nearly gives, the
|
||||
// first stays. (The stop before an ink starts stays as well: leaving it out would blend the
|
||||
// ink in sooner.)
|
||||
let ink = |offset: f32, tint: f32| GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(0.5)) };
|
||||
let few = vec![
|
||||
GradientStop::new(0.0, Color::gray(0.0)),
|
||||
GradientStop::new(0.2, Color::gray(0.17)),
|
||||
GradientStop::new(0.3, Color::gray(0.3)),
|
||||
ink(0.4, 0.2),
|
||||
ink(0.5, 0.9),
|
||||
ink(0.6, 0.2),
|
||||
GradientStop::new(1.0, Color::gray(1.0)),
|
||||
];
|
||||
let fitted = Gradient::new(GradientKind::Linear, few).fitted(6).into_owned();
|
||||
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.3, 0.4, 0.5, 0.6, 1.0]);
|
||||
// A Perceptual gradient leaves out the stop its own mixing gives, not the one the RGB line
|
||||
// gives.
|
||||
let (blue, yellow, gray) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0), Color::rgb(0.5, 0.5, 0.5));
|
||||
let on_curve = GradientMethod::Perceptual.mix(&gray, &yellow, 0.5);
|
||||
let stops = vec![GradientStop::new(0.0, blue), GradientStop::new(0.5, gray), GradientStop::new(0.75, on_curve), GradientStop::new(1.0, yellow)];
|
||||
let perceptual = Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let fitted = perceptual.fitted(3).into_owned();
|
||||
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.5, 1.0]);
|
||||
// A black of other inks between blacks that look the same prints differently: it stays.
|
||||
let k = |offset: f32| GradientStop::new(offset, Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0 });
|
||||
let rich = GradientStop::new(0.5, Color::Cmyk { c: 0.6, m: 0.4, y: 0.4, k: 1.0 });
|
||||
let blacks = vec![k(0.0), k(0.4), rich, k(0.6), k(1.0)];
|
||||
let fitted = Gradient::new(GradientKind::Linear, blacks).fitted(3).into_owned();
|
||||
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.5, 1.0]);
|
||||
let spread = Gradient { spread: GradientSpread::Repeat, repeats: 4, ..g.clone() };
|
||||
let u = spread.unrolled_within(128);
|
||||
assert_eq!(u.stops.iter().filter(|s| s.swatch.as_deref() == Some("Ink")).count(), 4, "one linked stop a run");
|
||||
}
|
||||
|
||||
/// Pixels (what the canvas draws a diamond, dithered or Perceptual gradient as, and what SVG and
|
||||
/// PDF write as images) repeat with the stops, for each kind.
|
||||
#[test]
|
||||
fn pixels_repeat_and_reflect_for_every_kind() {
|
||||
let b = Rect::new(0.0, 0.0, 40.0, 40.0);
|
||||
let c = Point::new(20.0, 20.0);
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
|
||||
for sp in [GradientSpread::Repeat, GradientSpread::Reflect] {
|
||||
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
|
||||
let mut g = GradientPaint::new(Gradient { spread: sp, repeats: 3, method, ..Gradient::new(kind, Gradient::default().stops) });
|
||||
let geom = if kind == GradientKind::Linear {
|
||||
GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(40.0, 10.0), aspect: 1.0, focal: None }
|
||||
} else {
|
||||
GradientGeom { start: c, end: c + Vec2::new(18.0, 4.0), aspect: 0.8, focal: None }
|
||||
};
|
||||
g.geom = Some(geom);
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 40, 40, false, &Color::to_rgb).collect();
|
||||
for (i, got) in px.iter().enumerate().step_by(37) {
|
||||
let p = Point::new((i % 40) as f64 + 0.5, (i / 40) as f64 + 0.5);
|
||||
let t = g.gradient.spread_param(geom.param_at(kind, p));
|
||||
// Not where Repeat jumps from the last stop back to the first.
|
||||
if sp == GradientSpread::Repeat && !(0.03..0.97).contains(&t) {
|
||||
continue;
|
||||
}
|
||||
let want = g.gradient.sample(t as f32).0.to_rgba8(1.0);
|
||||
assert!(got[0].abs_diff(want[0]) <= 2, "{kind:?} {sp:?} {method:?} {p:?}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A conic gradient's wedges: as many for each time the stops run around as for one turn, at most
|
||||
/// so many.
|
||||
#[test]
|
||||
fn conic_wedges_count_each_run() {
|
||||
let g = spread(GradientKind::Conic, GradientSpread::Repeat, 4);
|
||||
assert_eq!(g.conic_wedge_count(360), 1440);
|
||||
assert_eq!(spread(GradientKind::Conic, GradientSpread::Pad, 4).conic_wedge_count(360), 360);
|
||||
assert_eq!(spread(GradientKind::Conic, GradientSpread::Reflect, MAX_REPEATS).conic_wedge_count(360), crate::gradient::MAX_CONIC_WEDGES);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ pub mod swatch;
|
||||
|
||||
pub use blend::BlendMode;
|
||||
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
|
||||
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop};
|
||||
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop};
|
||||
pub use libraries::SwatchLibrary;
|
||||
pub use swatch::{Swatch, SwatchGroup, default_swatches};
|
||||
|
||||
|
||||
@@ -196,8 +196,10 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
};
|
||||
// Stops that repeat or reflect run that many times across the box.
|
||||
let unrolled = g.gradient.unrolled();
|
||||
let stops: Vec<String> =
|
||||
if mirrored { g.gradient.stops.iter().rev().map(stop).collect() } else { g.gradient.stops.iter().map(stop).collect() };
|
||||
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
|
||||
@@ -261,6 +261,29 @@ fn css_preserves_fractional_gradient_stop_positions() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient swatch that repeats or reflects has its stops written that many times across the
|
||||
/// box, every other run backwards for Reflect.
|
||||
#[test]
|
||||
fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
|
||||
for (spread, want) in [
|
||||
(crate::GradientSpread::Repeat, "#ffffff 0%, #000000 50%, #ffffff 50%, #000000 100%"),
|
||||
(crate::GradientSpread::Reflect, "#ffffff 0%, #000000 50%, #000000 50%, #ffffff 100%"),
|
||||
] {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch {
|
||||
name: "Bands".into(),
|
||||
paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::default() }))),
|
||||
global: false,
|
||||
spot: false,
|
||||
}],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert!(text.contains(&format!("--bands: linear-gradient(90deg, {want});")), "{spread:?}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
|
||||
@@ -485,6 +485,88 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
|
||||
rows
|
||||
}
|
||||
|
||||
/// The distinct colors [`theme_palette`] clusters, at most.
|
||||
const THEME_CANDIDATES: usize = 4096;
|
||||
|
||||
/// The color palette of the weighted colors `samples` (color, weight), for Recolor Artwork's Color
|
||||
/// Theme Picker: at most `n` colors. The same color given twice counts once with both weights,
|
||||
/// and past [`THEME_CANDIDATES`] distinct colors, colors close in Lab merge into the heaviest of
|
||||
/// them first.
|
||||
/// The colors are grouped as [`cluster`] groups them, each group shows its heaviest color (a color
|
||||
/// of `samples`, in its own model; on a tie the one given first), and the heaviest group comes
|
||||
/// first (on a tie the group whose first color was given first). Samples without a positive,
|
||||
/// finite weight are left out, so no samples give no colors.
|
||||
pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
|
||||
let mut index: std::collections::HashMap<ColorKey, usize> = std::collections::HashMap::new();
|
||||
let mut colors: Vec<Color> = vec![];
|
||||
let mut weights: Vec<f32> = vec![];
|
||||
for (c, w) in samples {
|
||||
if !(w.is_finite() && *w > 0.0) {
|
||||
continue;
|
||||
}
|
||||
let i = *index.entry(ColorKey::of(c)).or_insert_with(|| {
|
||||
colors.push(*c);
|
||||
weights.push(0.0);
|
||||
colors.len() - 1
|
||||
});
|
||||
weights[i] += w;
|
||||
}
|
||||
if colors.is_empty() || n == 0 {
|
||||
return vec![];
|
||||
}
|
||||
// At most THEME_CANDIDATES colors are clustered: past that, colors in the same cube of Lab
|
||||
// space merge into the heaviest of them, the cubes doubling in size until few enough remain.
|
||||
if colors.len() > THEME_CANDIDATES {
|
||||
let labs: Vec<[f32; 3]> = colors
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let l = c.to_lab();
|
||||
[l.l, l.a, l.b]
|
||||
})
|
||||
.collect();
|
||||
let mut side = 2.0f32;
|
||||
loop {
|
||||
let mut cube: std::collections::HashMap<[i32; 3], usize> = std::collections::HashMap::new();
|
||||
let (mut top, mut sum): (Vec<usize>, Vec<f32>) = (vec![], vec![]);
|
||||
for (i, lab) in labs.iter().enumerate() {
|
||||
let k = lab.map(|v| (v / side).floor() as i32);
|
||||
match cube.get(&k) {
|
||||
Some(&j) => {
|
||||
sum[j] += weights[i];
|
||||
if weights[i] > weights[top[j]] {
|
||||
top[j] = i;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
cube.insert(k, top.len());
|
||||
top.push(i);
|
||||
sum.push(weights[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if top.len() <= THEME_CANDIDATES {
|
||||
colors = top.iter().map(|&i| colors[i]).collect();
|
||||
weights = sum;
|
||||
break;
|
||||
}
|
||||
side *= 2.0;
|
||||
}
|
||||
}
|
||||
let mut groups: Vec<(f32, usize, Color)> = cluster(&colors, &weights, n)
|
||||
.into_iter()
|
||||
.filter_map(|g| {
|
||||
let total: f32 = g.iter().map(|&i| weights[i]).sum();
|
||||
let top = g.iter().copied().fold(None::<usize>, |best, i| match best {
|
||||
Some(b) if weights[b] >= weights[i] => Some(b),
|
||||
_ => Some(i),
|
||||
})?;
|
||||
Some((total, *g.first()?, colors[top]))
|
||||
})
|
||||
.collect();
|
||||
groups.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
|
||||
groups.into_iter().map(|g| g.2).collect()
|
||||
}
|
||||
|
||||
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Palette(Vec<(Color, Lab)>);
|
||||
@@ -691,6 +773,39 @@ mod tests {
|
||||
assert!(cluster(&[], &[], 3).is_empty());
|
||||
}
|
||||
|
||||
/// The Color Theme Picker's palette: similar colors merge, each group shows its heaviest
|
||||
/// color in its own model, and the heaviest group comes first.
|
||||
#[test]
|
||||
fn theme_palette_takes_the_heaviest_color_of_each_group_heaviest_first() {
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let pink = Color::rgb(1.0, 0.2, 0.2);
|
||||
let blue = Color::cmyk(1.0, 0.8, 0.0, 0.0);
|
||||
let navy = Color::cmyk(1.0, 0.9, 0.0, 0.3);
|
||||
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 2.5), (red, 0.5)];
|
||||
// Blue and navy weigh 4.5, and so do red (3 + 0.5, its two samples add up) and pink.
|
||||
assert_eq!(theme_palette(&samples, 2), vec![red, navy], "a tie: the group given first");
|
||||
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 1.0)];
|
||||
assert_eq!(theme_palette(&samples, 2), vec![red, blue], "heaviest group first, its heaviest color");
|
||||
assert_eq!(theme_palette(&samples, 9).len(), 4, "never more colors than given");
|
||||
assert_eq!(theme_palette(&samples, 1), vec![red]);
|
||||
assert!(theme_palette(&samples, 0).is_empty());
|
||||
assert!(theme_palette(&[(red, 0.0), (blue, f32::NAN), (pink, -1.0)], 3).is_empty(), "no weight, no colors");
|
||||
assert!(theme_palette(&[], 3).is_empty());
|
||||
}
|
||||
|
||||
/// Past 4,096 distinct colors, close colors merge before clustering: the palette still keeps
|
||||
/// a heavy color apart from thousands of light ones.
|
||||
#[test]
|
||||
fn theme_palette_merges_close_colors_past_its_candidate_limit() {
|
||||
let mut samples: Vec<(Color, f32)> = (0..20_000).map(|i| (Color::rgb(0.0, 0.0, 0.3 + 0.7 * i as f32 / 20_000.0), 0.001)).collect();
|
||||
samples.extend((0..20_000).map(|i| (Color::rgb(1.0, 0.8 * i as f32 / 20_000.0, 0.0), 0.0001)));
|
||||
samples.push((Color::rgb(0.0, 1.0, 0.0), 50.0));
|
||||
let p = theme_palette(&samples, 3);
|
||||
assert_eq!(p.len(), 3);
|
||||
assert_eq!(p[0], Color::rgb(0.0, 1.0, 0.0), "the heavy green first, exactly as given");
|
||||
assert!(p[1].to_hsb()[0] > 180.0 && p[2].to_hsb()[0] < 90.0, "then the blues, then the reds and oranges: {p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_shift_with_own_model_puts_every_colour_of_the_row_in_the_new_model() {
|
||||
let to = Color::cmyk(0.0, 1.0, 1.0, 0.0);
|
||||
|
||||
@@ -10,7 +10,7 @@ mod stroke_style;
|
||||
|
||||
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
|
||||
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
|
||||
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
pub use stroke_style::{ArrowAlign, Arrowhead, CustomArrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
|
||||
/// One entry of the appearance stack.
|
||||
// A stroke takes 328 bytes and a fill 104; an appearance holds a few of each.
|
||||
|
||||
@@ -193,8 +193,10 @@ impl StrokeLayer {
|
||||
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
|
||||
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
|
||||
pub fn head_reach(&self, end: bool) -> f64 {
|
||||
let head = if end { self.end_arrow } else { self.start_arrow };
|
||||
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
|
||||
let head = if end { &self.end_arrow } else { &self.start_arrow };
|
||||
// A custom head can paint in front of its tip, which Extend puts past the end point.
|
||||
let reach = |k: &Arrowhead| if self.arrow_align == ArrowAlign::Extend { k.reach().max(k.length()) } else { k.reach() };
|
||||
head.as_ref().map_or(0.0, |k| reach(k) * self.arrow_weight(end) + self.width / 2.0)
|
||||
}
|
||||
/// How far the arrowheads can reach from the path's end points (0 without heads).
|
||||
pub fn arrow_reach(&self) -> f64 {
|
||||
|
||||
@@ -202,6 +202,13 @@ impl AngleProfile {
|
||||
if v.is_finite() { vectorcraft_geom::normalize_deg(v) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The angle at `t` (0..1) as [`Self::at`] reads it, but in the samples' own running degrees,
|
||||
/// so the whole turns the curve makes along the stroke are kept; 0 without any samples.
|
||||
pub fn unwrapped_at(&self, t: f64) -> f64 {
|
||||
let v = interpolated(&self.points, t).unwrap_or(0.0);
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A profile from (position, degrees) samples in order along the stroke: non-finite ones are
|
||||
/// dropped, each sample is joined to the one before it the shorter way round, and the curve is
|
||||
/// simplified to within 1° and kept to [`PressureProfile::MAX_POINTS`]. `None` without a sample.
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{PathData, Rect};
|
||||
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -53,8 +57,74 @@ impl Dash {
|
||||
/// (the open arrow's arms are cut square a little behind the box).
|
||||
const HEAD_REACH: f64 = 4.6;
|
||||
|
||||
/// An arrowhead the user drew (Stroke panel menu › Edit Arrowheads…), carried with its art so a
|
||||
/// document that uses it draws it wherever it opens.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(from = "CustomArrowheadData")]
|
||||
pub struct CustomArrowhead {
|
||||
/// The name the arrowhead menus show (the symbol's name in the arrowheads file).
|
||||
pub name: String,
|
||||
/// The filled outline (non-zero rule) in head units: x from the tip (0) back along the line, y
|
||||
/// across it, positive to the right of the direction the head points. A head is 4 units wide,
|
||||
/// as the built-in heads are, and a unit is the head's weight.
|
||||
pub path: PathData,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CustomArrowheadData {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
path: PathData,
|
||||
}
|
||||
|
||||
impl From<CustomArrowheadData> for CustomArrowhead {
|
||||
fn from(d: CustomArrowheadData) -> Self {
|
||||
CustomArrowhead::new(d.name, d.path)
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomArrowhead {
|
||||
/// The most anchors a custom head's outline may have, and the most subpaths.
|
||||
pub const MAX_ANCHORS: usize = 4096;
|
||||
/// How far from the tip a custom head's outline may reach, in head units.
|
||||
pub const MAX_UNITS: f64 = 64.0;
|
||||
|
||||
/// Head `name` with outline `path` (in head units). An outline with more than
|
||||
/// [`Self::MAX_ANCHORS`] anchors or subpaths, a point that is not finite, or a point farther
|
||||
/// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing.
|
||||
pub fn new(name: String, path: PathData) -> Self {
|
||||
let path = if Self::fits(&path) { path } else { PathData::default() };
|
||||
CustomArrowhead { name, path }
|
||||
}
|
||||
/// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with
|
||||
/// finite points within [`Self::MAX_UNITS`] only.
|
||||
pub fn fits(path: &PathData) -> bool {
|
||||
let anchors = path.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>();
|
||||
let near = |p: vectorcraft_geom::Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= Self::MAX_UNITS && p.y.abs() <= Self::MAX_UNITS;
|
||||
anchors <= Self::MAX_ANCHORS
|
||||
&& path.subpaths.len() <= Self::MAX_ANCHORS
|
||||
&& path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| near(a.p) && near(a.h_in) && near(a.h_out))
|
||||
}
|
||||
fn bounds(&self) -> Option<Rect> {
|
||||
self.path.control_bounds()
|
||||
}
|
||||
/// How far any part of the head can be from its tip, in head units.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.bounds().map_or(0.0, |b| b.x0.hypot(b.y0).max(b.x1.hypot(b.y0)).max(b.x0.hypot(b.y1)).max(b.x1.hypot(b.y1)))
|
||||
}
|
||||
/// How far the head spreads either side of its line, in head units.
|
||||
pub fn half_width(&self) -> f64 {
|
||||
self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs()))
|
||||
}
|
||||
/// Where the stroke ends under the head, in head units back from the tip: halfway along the
|
||||
/// head's length.
|
||||
pub fn stop(&self) -> f64 {
|
||||
self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Arrowhead {
|
||||
Triangle,
|
||||
TriangleOpen,
|
||||
@@ -102,6 +172,8 @@ pub enum Arrowhead {
|
||||
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
|
||||
/// the other heads.
|
||||
LineArrow,
|
||||
/// A head the user drew, with its art.
|
||||
Custom(Arc<CustomArrowhead>),
|
||||
}
|
||||
|
||||
impl Arrowhead {
|
||||
@@ -151,23 +223,43 @@ impl Arrowhead {
|
||||
];
|
||||
|
||||
/// How far any part of the head can be from its tip, in units of its weight.
|
||||
pub fn reach(self) -> f64 {
|
||||
pub fn reach(&self) -> f64 {
|
||||
match self {
|
||||
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
|
||||
Arrowhead::LineArrow => 5.75,
|
||||
Arrowhead::Custom(c) => c.reach(),
|
||||
_ => HEAD_REACH,
|
||||
}
|
||||
}
|
||||
/// How far the head spreads either side of its line, in units of its weight.
|
||||
pub fn half_width(self) -> f64 {
|
||||
pub fn half_width(&self) -> f64 {
|
||||
match self {
|
||||
Arrowhead::LineArrow => 4.0,
|
||||
Arrowhead::Custom(c) => c.half_width(),
|
||||
_ => 2.0,
|
||||
}
|
||||
}
|
||||
/// How far past its end point a head placed with [`ArrowAlign::Extend`] can paint, in units of
|
||||
/// its weight: the built-in heads' length, or a custom head's reach past its tip, which sits
|
||||
/// [`CustomArrowhead::stop`] past the end point.
|
||||
pub fn length(&self) -> f64 {
|
||||
match self {
|
||||
Arrowhead::Custom(c) => c.stop() + c.reach(),
|
||||
_ => 4.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The name the arrowhead menus show.
|
||||
pub fn label(self) -> &'static str {
|
||||
/// The name the arrowhead menus show: [`Self::label`], or a custom head's own name.
|
||||
pub fn name(&self) -> &str {
|
||||
match self {
|
||||
Arrowhead::Custom(c) => &c.name,
|
||||
_ => self.label(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name the arrowhead menus show for a built-in head ("Custom" for a custom one, whose
|
||||
/// own name is [`Self::name`]).
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Arrowhead::Triangle => "Triangle",
|
||||
Arrowhead::TriangleOpen => "Triangle (open)",
|
||||
@@ -210,6 +302,7 @@ impl Arrowhead {
|
||||
Arrowhead::TriangleBar => "Triangle to Bar",
|
||||
Arrowhead::Oval => "Oval",
|
||||
Arrowhead::LineArrow => "Line Arrow",
|
||||
Arrowhead::Custom(_) => "Custom",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,13 +337,65 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
|
||||
];
|
||||
for name in SAVED {
|
||||
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
|
||||
assert_eq!(serde_json::to_value(a).unwrap(), name);
|
||||
assert_eq!(serde_json::to_value(&a).unwrap(), name);
|
||||
assert_eq!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once");
|
||||
}
|
||||
let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect();
|
||||
assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct");
|
||||
}
|
||||
|
||||
/// A custom head: a triangle from its tip back 3 units, 2 units right and 1 left of its line.
|
||||
fn custom_head() -> Arrowhead {
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
let path = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
|
||||
Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), path)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_arrowheads_carry_their_art_and_measure_it() {
|
||||
let head = custom_head();
|
||||
assert_eq!((head.name(), head.label()), ("Wedge", "Custom"));
|
||||
assert_eq!(head.reach(), 3.0f64.hypot(2.0));
|
||||
assert_eq!(head.half_width(), 2.0);
|
||||
let Arrowhead::Custom(c) = &head else { panic!("custom") };
|
||||
assert_eq!(c.stop(), 1.5, "the line stops halfway along the head");
|
||||
// Saved with the stroke, art and all, beside the built-in heads' names.
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
(st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone()));
|
||||
let json = serde_json::to_value(&st).unwrap();
|
||||
assert_eq!(json["start_arrow"], "Triangle");
|
||||
assert_eq!(json["end_arrow"]["Custom"]["name"], "Wedge");
|
||||
let back: StrokeLayer = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(back, st);
|
||||
// Extended, the tip sits the stop past the end point; on it, only the reach counts.
|
||||
assert_eq!(head.length(), 1.5 + head.reach());
|
||||
assert_eq!(st.head_reach(true), head.length() * 2.0 + 1.0);
|
||||
st.arrow_align = ArrowAlign::Tip;
|
||||
assert_eq!(st.head_reach(true), head.reach() * 2.0 + 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_arrowheads_out_of_bounds_draw_nothing() {
|
||||
let Arrowhead::Custom(c) = custom_head() else { panic!("custom") };
|
||||
let mut path = c.path.clone();
|
||||
path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0));
|
||||
// A file can hold what `new` drops: reading it drops it too.
|
||||
let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap();
|
||||
let far: CustomArrowhead = serde_json::from_value(json).unwrap();
|
||||
assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0));
|
||||
assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0));
|
||||
let anchors = vec![vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1.0, 0.0)); CustomArrowhead::MAX_ANCHORS + 1];
|
||||
let many = CustomArrowhead::new("Many".into(), vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::new(anchors, true)));
|
||||
assert!(many.path.subpaths.is_empty(), "too many anchors");
|
||||
// Empty subpaths add no anchors, and still count.
|
||||
let mut hollow = c.path.clone();
|
||||
hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS));
|
||||
assert!(!CustomArrowhead::fits(&hollow), "too many subpaths");
|
||||
let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap();
|
||||
let hollow: CustomArrowhead = serde_json::from_value(json).unwrap();
|
||||
assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_align_defaults_to_extend_and_round_trips() {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
|
||||
+484
-17
@@ -5,7 +5,8 @@
|
||||
//! winding and to the start points that keep them from twisting, or to the anchors the Blend
|
||||
//! tool clicked.
|
||||
//! - **Paint**: colours, gradients (stops resampled to a common set when their counts differ),
|
||||
//! opacity, stroke weight, dashes, miter limit and width profiles interpolate; what can't
|
||||
//! opacity, stroke weight, dashes, miter limit, width profiles and the pen pressure, tilt,
|
||||
//! bearing and rotation 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.
|
||||
@@ -22,7 +23,7 @@ use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
|
||||
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile};
|
||||
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile};
|
||||
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use crate::node::{Node, NodeId, NodeKind};
|
||||
use crate::text::TextObject;
|
||||
@@ -152,6 +153,11 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<Gradien
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// Two gradients that repeat (or reflect) step their count from one to the other; a spread
|
||||
// that differs switches halfway, as the method does.
|
||||
if a.gradient.is_spread() && a.gradient.spread == b.gradient.spread {
|
||||
out.gradient.repeats = lerp_f32(a.gradient.repeat_count() as f32, b.gradient.repeat_count() as f32, t).round() as u32;
|
||||
}
|
||||
out.angle = a.angle + (b.angle - a.angle) * t as f64;
|
||||
out.swatch = None;
|
||||
if let (Some(ga), Some(gb)) = (a.geom, b.geom) {
|
||||
@@ -230,7 +236,8 @@ fn lcm(a: usize, b: usize) -> usize {
|
||||
a.checked_div(x).map_or(0, |q| q * b)
|
||||
}
|
||||
|
||||
/// Interpolate width profiles (none is uniform) at every position either has a width point.
|
||||
/// Interpolate width profiles (none is uniform) at every position either has a width point,
|
||||
/// keeping their discontinuous points (a position where either steps gives two points).
|
||||
fn lerp_profile(x: Option<&WidthProfile>, y: Option<&WidthProfile>, t: f64) -> Option<WidthProfile> {
|
||||
if x.is_none() && y.is_none() {
|
||||
return None;
|
||||
@@ -239,20 +246,135 @@ fn lerp_profile(x: Option<&WidthProfile>, y: Option<&WidthProfile>, t: f64) -> O
|
||||
let (x, y) = (x.unwrap_or(&uniform), y.unwrap_or(&uniform));
|
||||
let mut at: Vec<f64> = x.points.iter().chain(&y.points).map(|p| p.0).filter(|p| p.is_finite()).collect();
|
||||
at.sort_by(f64::total_cmp);
|
||||
at.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
|
||||
let points = at
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
let ((l1, r1), (l2, r2)) = (x.at(p), y.at(p));
|
||||
(p, lerp_f64(l1, l2, t), lerp_f64(r1, r2, t))
|
||||
})
|
||||
.collect();
|
||||
// Within the distance `around` reads a discontinuous point at, so a point near one keeps it.
|
||||
at.dedup_by(|a, b| (*a - *b).abs() <= 1e-7);
|
||||
// Each profile is a smooth curve through its own points: samples between the positions keep
|
||||
// both curves' shapes where the other profile's points and steps change the tangents. Two
|
||||
// profiles with points at the same positions need none (so a preset on both keys stays it).
|
||||
let same_positions = x.points.len() == y.points.len() && x.points.iter().zip(&y.points).all(|(p, q)| (p.0 - q.0).abs() <= 1e-7);
|
||||
let per_span = if same_positions { 1 } else { (4096 / at.len().max(1)).clamp(1, 8) };
|
||||
let mut points = Vec::with_capacity(at.len() * per_span + 2);
|
||||
let mix = |p: f64, (l1, r1): (f64, f64), (l2, r2): (f64, f64)| (p, lerp_f64(l1, l2, t), lerp_f64(r1, r2, t));
|
||||
for (k, &p) in at.iter().enumerate() {
|
||||
let ((xb, xa), (yb, ya)) = (x.around(p), y.around(p));
|
||||
points.push(mix(p, xb, yb));
|
||||
// A discontinuous point ends the curve on each side even where both widths match.
|
||||
if steps_at(x, p) || steps_at(y, p) {
|
||||
points.push(mix(p, xa, ya));
|
||||
}
|
||||
if let Some(&q) = at.get(k + 1) {
|
||||
for j in 1..per_span {
|
||||
let f = p + (q - p) * j as f64 / per_span as f64;
|
||||
points.push(mix(f, x.at(f), y.at(f)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(WidthProfile { points })
|
||||
}
|
||||
|
||||
/// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale and width
|
||||
/// profile into `o` (a copy of the nearer stroke, so caps, joins, alignment, arrowheads and
|
||||
/// brushes switch halfway).
|
||||
/// Whether width profile `w` has a discontinuous point at `p` (two points there, within `1e-7`,
|
||||
/// as [`WidthProfile::around`] reads them).
|
||||
fn steps_at(w: &WidthProfile, p: f64) -> bool {
|
||||
let i = w.points.partition_point(|q| q.0 < p - 1e-7);
|
||||
w.points.get(i..).unwrap_or_default().iter().take_while(|q| q.0 <= p + 1e-7).count() > 1
|
||||
}
|
||||
|
||||
/// The positions along the stroke where either of two pen recordings has a sample, in order.
|
||||
fn sample_positions(x: Option<&[(f64, f64)]>, y: Option<&[(f64, f64)]>) -> Vec<f64> {
|
||||
let mut at: Vec<f64> = x.unwrap_or_default().iter().chain(y.unwrap_or_default()).map(|p| p.0).filter(|p| p.is_finite()).collect();
|
||||
at.sort_by(f64::total_cmp);
|
||||
// Within the distance `step_after` reads a step at, so a sample near a step keeps the step.
|
||||
at.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
|
||||
if at.is_empty() {
|
||||
at = vec![0.0, 1.0];
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The value pen recording `p` steps to at position `f`, where two or more of its samples share
|
||||
/// that position (reading at `f` gives the first of them); None where it doesn't step.
|
||||
fn step_after(p: Option<&[(f64, f64)]>, f: f64) -> Option<f64> {
|
||||
let p = p?;
|
||||
let i = p.partition_point(|q| q.0 < f - 1e-9);
|
||||
let j = p.partition_point(|q| q.0 <= f + 1e-9).checked_sub(1)?;
|
||||
(j > i && (p.get(i)?.0 - f).abs() <= 1e-9).then(|| p.get(j).map(|q| q.1)).flatten()
|
||||
}
|
||||
|
||||
/// Two pen recordings read at every position either has a sample, as (position, x's value, y's
|
||||
/// value): `read_x` and `read_y` read them, and `clean` makes a stepped sample's value one they
|
||||
/// would read. A position where either steps gives two, before and after the step.
|
||||
fn paired_samples(
|
||||
x: Option<&[(f64, f64)]>,
|
||||
y: Option<&[(f64, f64)]>,
|
||||
read_x: impl Fn(f64) -> f64,
|
||||
read_y: impl Fn(f64) -> f64,
|
||||
clean: impl Fn(f64) -> f64,
|
||||
) -> Vec<(f64, f64, f64)> {
|
||||
let mut out = Vec::new();
|
||||
for f in sample_positions(x, y) {
|
||||
let (a, b) = (read_x(f), read_y(f));
|
||||
out.push((f, a, b));
|
||||
let (sa, sb) = (step_after(x, f), step_after(y, f));
|
||||
if sa.is_some() || sb.is_some() {
|
||||
out.push((f, sa.map_or(a, &clean), sb.map_or(b, &clean)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Interpolate pen pressure or tilt recordings at every position either has a sample, keeping
|
||||
/// their steps. A stroke without one reads as [`PressureProfile::MID`], as brushes read it; None
|
||||
/// when neither has one.
|
||||
fn lerp_pressure(x: Option<&PressureProfile>, y: Option<&PressureProfile>, t: f64) -> Option<PressureProfile> {
|
||||
if x.is_none() && y.is_none() {
|
||||
return None;
|
||||
}
|
||||
let read = |p: Option<&PressureProfile>, f: f64| p.map_or(PressureProfile::MID, |p| p.at(f));
|
||||
let clean = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { PressureProfile::MID };
|
||||
let samples = paired_samples(x.map(|p| p.points.as_slice()), y.map(|p| p.points.as_slice()), |f| read(x, f), |f| read(y, f), clean);
|
||||
PressureProfile::from_samples(samples.into_iter().map(|(f, a, b)| (f, lerp_f64(a, b, t))))
|
||||
}
|
||||
|
||||
/// Interpolate pen angle recordings (bearing or barrel rotation) at every position either has a
|
||||
/// sample: the steps turn from one key's angle to the other's the shorter way round at the
|
||||
/// stroke's start, and keep the whole turns each recording makes along the stroke. A stroke
|
||||
/// without one reads as 0°, as brushes read it; None when neither has one.
|
||||
fn lerp_angle(x: Option<&AngleProfile>, y: Option<&AngleProfile>, t: f64) -> Option<AngleProfile> {
|
||||
if x.is_none() && y.is_none() {
|
||||
return None;
|
||||
}
|
||||
let read = |p: Option<&AngleProfile>, f: f64| p.map_or(0.0, |p| p.unwrapped_at(f));
|
||||
let clean = |v: f64| if v.is_finite() { v } else { 0.0 };
|
||||
let pairs = paired_samples(x.map(|p| p.points.as_slice()), y.map(|p| p.points.as_slice()), |f| read(x, f), |f| read(y, f), clean);
|
||||
// Whole turns that bring the two angles within half a turn of each other at the first position.
|
||||
let d0 = pairs.first().map_or(0.0, |&(_, a, b)| b - a);
|
||||
let turns = vectorcraft_geom::normalize_deg(d0) - d0;
|
||||
let value = |a: f64, b: f64| a + (b - a + turns) * t;
|
||||
// Both curves are straight between two positions; samples are added where the steps turn
|
||||
// through 90° or more between them, since `AngleProfile::from_samples` joins neighbours the
|
||||
// shorter way round. A document's recordings can be long, so the added samples are limited.
|
||||
let mut budget = 4 * PressureProfile::MAX_POINTS;
|
||||
let mut samples = Vec::with_capacity(pairs.len());
|
||||
let mut prev: Option<(f64, f64)> = None;
|
||||
for (f, a, b) in pairs {
|
||||
let v = value(a, b);
|
||||
if let Some((pf, pv)) = prev.filter(|p| f - p.0 > 1e-9) {
|
||||
let parts = ((v - pv).abs() / 90.0).ceil().min((budget + 1) as f64) as usize;
|
||||
for k in 1..parts {
|
||||
let g = pf + (f - pf) * k as f64 / parts as f64;
|
||||
samples.push((g, value(read(x, g), read(y, g))));
|
||||
}
|
||||
budget -= parts.saturating_sub(1).min(budget);
|
||||
}
|
||||
samples.push((f, v));
|
||||
prev = Some((f, v));
|
||||
}
|
||||
AngleProfile::from_samples(samples)
|
||||
}
|
||||
|
||||
/// 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).
|
||||
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);
|
||||
@@ -262,6 +384,10 @@ fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) {
|
||||
o.dash = lerp_dash(x.dash.as_ref(), y.dash.as_ref(), t);
|
||||
o.arrow_scale = (lerp_f64(x.arrow_scale.0, y.arrow_scale.0, t), lerp_f64(x.arrow_scale.1, y.arrow_scale.1, t));
|
||||
o.profile = lerp_profile(x.profile.as_ref(), y.profile.as_ref(), t);
|
||||
o.pressure = lerp_pressure(x.pressure.as_ref(), y.pressure.as_ref(), t);
|
||||
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);
|
||||
}
|
||||
|
||||
/// Interpolate appearance stacks: item by item when their structure matches, else the top fill
|
||||
@@ -385,6 +511,161 @@ fn reverse_closed(sp: &mut SubPath) {
|
||||
sp.anchors.rotate_right(1);
|
||||
}
|
||||
|
||||
/// How a key's subpaths were turned for its blend, so that its stroke's profiles, pen
|
||||
/// recordings and arrowheads turn with it: position `u` along the turned subpath is position
|
||||
/// `start + u` (`start - u` when `reversed`) along the key's own, wrapping round a closed one.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Orient {
|
||||
start: f64,
|
||||
reversed: bool,
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
impl Orient {
|
||||
fn of(sp: &SubPath) -> Self {
|
||||
Self { closed: sp.closed, ..Self::default() }
|
||||
}
|
||||
|
||||
/// The subpath now starts at the fraction `f` of its length.
|
||||
fn rotate(&mut self, f: f64) {
|
||||
self.start += if self.reversed { -f } else { f };
|
||||
}
|
||||
|
||||
/// The subpath now runs the other way.
|
||||
fn reverse(&mut self) {
|
||||
self.start += if self.reversed { -1.0 } else { 1.0 };
|
||||
self.reversed = !self.reversed;
|
||||
}
|
||||
|
||||
/// As [`start_at`] turns `sp` (call it before).
|
||||
fn start_at(&mut self, sp: &SubPath, i: usize) {
|
||||
let n = sp.anchors.len();
|
||||
if i >= n {
|
||||
return;
|
||||
}
|
||||
if sp.closed {
|
||||
self.rotate(arc_fraction(sp, i));
|
||||
} else if i + 1 == n && n > 1 {
|
||||
self.reverse();
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a closed subpath now starts, as a fraction of its length; 0 for an open one.
|
||||
fn seam(&self) -> f64 {
|
||||
let s = if self.closed { self.start.rem_euclid(1.0) } else { 0.0 };
|
||||
if s > 1e-9 && s < 1.0 - 1e-9 { s } else { 0.0 }
|
||||
}
|
||||
|
||||
fn is_identity(&self) -> bool {
|
||||
!self.reversed && self.seam() == 0.0
|
||||
}
|
||||
|
||||
/// Whether two subpaths were turned alike, so one stroke along both turns the same way.
|
||||
fn same_turn(&self, o: &Self) -> bool {
|
||||
self.reversed == o.reversed && (self.seam() - o.seam()).abs() < 1e-9
|
||||
}
|
||||
}
|
||||
|
||||
/// How far along `sp` its anchor `i` sits, as a fraction of its length.
|
||||
fn arc_fraction(sp: &SubPath, i: usize) -> f64 {
|
||||
let pos = sp.anchor_arc_positions();
|
||||
match (pos.get(i), pos.last()) {
|
||||
(Some(&at), Some(&total)) if total.is_finite() && total > 1e-12 => (at / total).clamp(0.0, 1.0),
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (position, value) along a key's subpath, read along the subpath turned as `o` says.
|
||||
/// A closed subpath starting elsewhere starts the samples there too: the ones before it move
|
||||
/// past the seam (`wrap` applied), which keeps any step the seam makes, and a value between
|
||||
/// samples is read with `at`. A reversed subpath then reads them backwards (`flip` applied).
|
||||
fn reoriented<V: Copy>(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wrap: impl Fn(V) -> V, flip: impl Fn(V) -> V) -> Vec<(f64, V)> {
|
||||
let s = o.seam();
|
||||
let mut out = points.to_vec();
|
||||
if s > 0.0
|
||||
&& let (Some(&(_, first)), Some(&(_, last))) = (points.first(), points.last())
|
||||
{
|
||||
let i = points.partition_point(|q| q.0 < s - 1e-9);
|
||||
let j = points.partition_point(|q| q.0 <= s + 1e-9).max(i);
|
||||
let (before, after) = match points.get(i..j) {
|
||||
Some([p, .., q]) => (p.1, q.1),
|
||||
Some([p]) => (p.1, p.1),
|
||||
_ => (at(s), at(s)),
|
||||
};
|
||||
out = Vec::with_capacity(points.len() + 4);
|
||||
out.push((0.0, after));
|
||||
out.extend(points.get(j..).unwrap_or_default().iter().map(|&(t, v)| (t - s, v)));
|
||||
out.push((1.0 - s, last));
|
||||
out.push((1.0 - s, wrap(first)));
|
||||
out.extend(points.get(..i).unwrap_or_default().iter().map(|&(t, v)| (t + 1.0 - s, wrap(v))));
|
||||
out.push((1.0, wrap(before)));
|
||||
}
|
||||
if o.reversed {
|
||||
out = out.into_iter().rev().map(|(t, v)| (1.0 - t, flip(v))).collect();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A key's stroke read along its subpath turned as `o` says: its width profile (whose sides swap
|
||||
/// when reversed), pen pressure, tilt, bearing and rotation, and on a reversed open path its
|
||||
/// arrowheads.
|
||||
fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
|
||||
if o.is_identity() {
|
||||
return;
|
||||
}
|
||||
let same = |v: f64| v;
|
||||
if let Some(p) = &mut s.profile {
|
||||
let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect();
|
||||
// A width profile is a smooth curve through its points: where the new start splits a span,
|
||||
// samples of that span keep its curve once its ends become ends of the profile.
|
||||
let seam = o.seam();
|
||||
let i = p.points.partition_point(|q| q.0 < seam);
|
||||
if seam > 0.0
|
||||
&& let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| p.points.get(j)), p.points.get(i))
|
||||
&& seam - a.0 > 1e-9
|
||||
&& b.0 - seam > 1e-9
|
||||
{
|
||||
const SAMPLES: usize = 32;
|
||||
let (a, b) = (a.0, b.0);
|
||||
let extra: Vec<(f64, (f64, f64))> =
|
||||
(1..SAMPLES).map(|k| a + (b - a) * k as f64 / SAMPLES as f64).filter(|f| (f - seam).abs() > 1e-9).map(|f| (f, p.at(f))).collect();
|
||||
pts.splice(i..i, extra);
|
||||
}
|
||||
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() {
|
||||
let out = reoriented(&p.points, o, |f| p.at(f), same, same);
|
||||
p.points = out;
|
||||
}
|
||||
for p in [&mut s.bearing, &mut s.rotation].into_iter().flatten() {
|
||||
// The samples moved past the seam carry the whole turns the recording makes along the
|
||||
// stroke, so the angle does not jump by them there.
|
||||
let turns = match (p.points.first(), p.points.last()) {
|
||||
(Some(a), Some(b)) if (b.1 - a.1).is_finite() => ((b.1 - a.1) / 360.0).round() * 360.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
let out = reoriented(&p.points, o, |f| p.unwrapped_at(f), |v| v + turns, same);
|
||||
p.points = out;
|
||||
}
|
||||
if o.reversed && !o.closed {
|
||||
std::mem::swap(&mut s.start_arrow, &mut s.end_arrow);
|
||||
s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` with every stroke read along its subpaths turned as `o` says.
|
||||
fn reorient_strokes(n: &mut Node, o: Orient) {
|
||||
if o.is_identity() {
|
||||
return;
|
||||
}
|
||||
for it in n.appearance.items.iter_mut() {
|
||||
if let AppearanceItem::Stroke(s) = it {
|
||||
reorient_stroke(s, o);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchor positions of a subpath relative to its box, scaled to unit size.
|
||||
fn normalised(sp: &SubPath) -> Vec<Vec2> {
|
||||
let pts = sp.anchors.iter().map(|a| a.p);
|
||||
@@ -422,6 +703,8 @@ fn best_rotation(a: &SubPath, b: &SubPath) -> usize {
|
||||
pub struct PathPair {
|
||||
a: Vec<SubPath>,
|
||||
b: Vec<SubPath>,
|
||||
/// How each path's subpaths were turned, where all of them turned alike (else unturned).
|
||||
orient: (Orient, Orient),
|
||||
}
|
||||
|
||||
impl PathPair {
|
||||
@@ -433,6 +716,7 @@ impl PathPair {
|
||||
let cb = b.bounds().map(|r| r.center()).unwrap_or_default();
|
||||
let degenerate = |like: &SubPath, c: Point| SubPath::new(vec![Anchor::corner(c); like.anchors.len().max(1)], like.closed);
|
||||
let (mut va, mut vb) = (Vec::with_capacity(n), Vec::with_capacity(n));
|
||||
let mut orient = (Orient::default(), Orient::default());
|
||||
for i in 0..n {
|
||||
let (mut sa, mut sb) = match (a.subpaths.get(i), b.subpaths.get(i)) {
|
||||
(Some(x), Some(y)) => (x.clone(), y.clone()),
|
||||
@@ -440,17 +724,21 @@ impl PathPair {
|
||||
(None, Some(y)) => (degenerate(y, ca), y.clone()),
|
||||
(None, None) => continue,
|
||||
};
|
||||
let (mut oa, mut ob) = (Orient::of(&sa), Orient::of(&sb));
|
||||
let explicit = i == 0 && (starts.0.is_some() || starts.1.is_some());
|
||||
if explicit {
|
||||
if let Some(s) = starts.0 {
|
||||
oa.start_at(&sa, s);
|
||||
start_at(&mut sa, s);
|
||||
}
|
||||
if let Some(s) = starts.1 {
|
||||
ob.start_at(&sb, s);
|
||||
start_at(&mut sb, s);
|
||||
}
|
||||
}
|
||||
let closed = sa.closed && sb.closed && sa.anchors.len() > 2 && sb.anchors.len() > 2;
|
||||
if closed && (sa.area() * sb.area()) < 0.0 {
|
||||
ob.reverse();
|
||||
reverse_closed(&mut sb);
|
||||
}
|
||||
let m = sa.anchors.len().max(sb.anchors.len());
|
||||
@@ -458,12 +746,26 @@ impl PathPair {
|
||||
grow(&mut sb, m);
|
||||
if closed && !explicit {
|
||||
let r = best_rotation(&sa, &sb);
|
||||
if r != 0 {
|
||||
ob.rotate(arc_fraction(&sb, r));
|
||||
}
|
||||
sb.anchors.rotate_left(r);
|
||||
}
|
||||
// One stroke runs along every subpath of a key, each reading it by its own length, so
|
||||
// it turns only when all of the key's subpaths turned alike.
|
||||
if i == 0 {
|
||||
orient = (oa, ob);
|
||||
}
|
||||
if i < a.subpaths.len() && !orient.0.same_turn(&oa) {
|
||||
orient.0 = Orient::default();
|
||||
}
|
||||
if i < b.subpaths.len() && !orient.1.same_turn(&ob) {
|
||||
orient.1 = Orient::default();
|
||||
}
|
||||
va.push(sa);
|
||||
vb.push(sb);
|
||||
}
|
||||
Self { a: va, b: vb }
|
||||
Self { a: va, b: vb, orient }
|
||||
}
|
||||
|
||||
/// The path at `t` (0 = `a`, 1 = `b`).
|
||||
@@ -578,7 +880,12 @@ impl Lerp {
|
||||
_ => Shape::Other,
|
||||
},
|
||||
};
|
||||
Self { a: a.clone(), b: b.clone(), shape }
|
||||
let (mut a, mut b) = (a.clone(), b.clone());
|
||||
if let Shape::Path { pair, .. } = &shape {
|
||||
reorient_strokes(&mut a, pair.orient.0);
|
||||
reorient_strokes(&mut b, pair.orient.1);
|
||||
}
|
||||
Self { a, b, shape }
|
||||
}
|
||||
|
||||
/// The object at `t` (0 = `a`, 1 = `b`), with id 0.
|
||||
@@ -1480,7 +1787,7 @@ pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
|
||||
// Even position of the step, then where the easing puts its shape and its colours.
|
||||
let u = j as f64 / (n + 1) as f64;
|
||||
// Easing needs a spine: a blend made without one keeps its steps evenly spaced.
|
||||
let eased = rail.is_some() && !spec.no_spine;
|
||||
let eased = rail.is_some() && spec.eases_along_spine();
|
||||
let (t, tc) = (if eased { spec.ease.apply(u) } else { u }, spec.color_position(u));
|
||||
let mut s = lerp.at_eased(t, tc);
|
||||
if let Some(r) = &rail {
|
||||
@@ -1495,6 +1802,7 @@ pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::appearance::Arrowhead;
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
#[test]
|
||||
@@ -1656,6 +1964,25 @@ mod tests {
|
||||
assert!(pair.at(0.5).bounds().unwrap().height() < 1e-6, "the clicked anchors pair up");
|
||||
}
|
||||
|
||||
/// A blend between two gradients that repeat steps the count; one between a gradient that
|
||||
/// pads and one that repeats switches halfway, as the method does.
|
||||
#[test]
|
||||
fn blend_between_repeating_gradients_steps_the_count() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let spread = |spread, repeats| Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats, ..Gradient::default() })));
|
||||
let at = |a: &Paint, b: &Paint, t: f32| match lerp_paint(a, b, t) {
|
||||
Paint::Gradient(g) => (g.gradient.spread, g.gradient.repeat_count()),
|
||||
p => panic!("a gradient, not {p:?}"),
|
||||
};
|
||||
let (two, twenty) = (spread(GradientSpread::Repeat, 2), spread(GradientSpread::Repeat, 20));
|
||||
assert_eq!(at(&two, &twenty, 0.25), (GradientSpread::Repeat, 7));
|
||||
assert_eq!(at(&two, &twenty, 0.5), (GradientSpread::Repeat, 11));
|
||||
assert_eq!(at(&two, &twenty, 1.0), (GradientSpread::Repeat, 20));
|
||||
let pad = spread(GradientSpread::Pad, 1);
|
||||
assert_eq!(at(&pad, &twenty, 0.25), (GradientSpread::Pad, 1));
|
||||
assert_eq!(at(&pad, &twenty, 0.75), (GradientSpread::Repeat, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_between_tints_of_one_swatch_keeps_the_link() {
|
||||
let tinted = |tint: f32| Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint), swatch: Some("Spot".into()), tint };
|
||||
@@ -1731,6 +2058,146 @@ mod tests {
|
||||
assert_eq!(p.at(0.5), (1.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pen_pressure_tilt_and_angles_interpolate_for_brushes() {
|
||||
let stroked = |pressure: Option<f64>, tilt: Option<f64>, bearing: Option<f64>| {
|
||||
let mut ap = Appearance::default();
|
||||
ap.set_stroke(Paint::solid(Color::BLACK));
|
||||
if let Some(s) = ap.stroke_mut() {
|
||||
s.brush = Some("Pressure Round".into());
|
||||
s.pressure = pressure.map(|p| PressureProfile { points: vec![(0.0, p), (1.0, p)] });
|
||||
s.tilt = tilt.map(|p| PressureProfile { points: vec![(0.0, p), (1.0, p)] });
|
||||
s.bearing = bearing.map(|a| AngleProfile { points: vec![(0.0, a), (1.0, a)] });
|
||||
}
|
||||
ap
|
||||
};
|
||||
let at = |ap: &Appearance, f: f64| {
|
||||
let s = ap.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
|
||||
let read = |p: Option<&PressureProfile>| p.map_or(PressureProfile::MID, |p| p.at(f));
|
||||
(read(s.pressure.as_ref()), read(s.tilt.as_ref()), s.bearing.as_ref().map_or(0.0, |p| p.at(f)))
|
||||
};
|
||||
let (light, heavy) = (stroked(Some(0.0), Some(0.2), Some(170.0)), stroked(Some(1.0), Some(0.6), Some(-170.0)));
|
||||
let (p, tilt, bearing) = at(&lerp_appearance(&light, &heavy, 0.25), 0.5);
|
||||
assert!((p - 0.25).abs() < 1e-9 && (tilt - 0.3).abs() < 1e-9, "a quarter of the way: {p} {tilt}");
|
||||
assert!((bearing - 175.0).abs() < 1e-9, "the angle turns the shorter way round, through 180°: {bearing}");
|
||||
assert!((at(&lerp_appearance(&light, &heavy, 0.5), 0.5).2.abs() - 180.0).abs() < 1e-9);
|
||||
// A stroke drawn without a recording reads as half pressure, half tilt and 0°.
|
||||
let plain = stroked(None, None, None);
|
||||
let (p, tilt, bearing) = at(&lerp_appearance(&heavy, &plain, 0.5), 0.0);
|
||||
assert!((p - 0.75).abs() < 1e-9 && (tilt - 0.55).abs() < 1e-9 && (bearing + 85.0).abs() < 1e-9, "{p} {tilt} {bearing}");
|
||||
// Profiles that vary along the stroke interpolate at each position.
|
||||
let mut ramp = stroked(None, None, None);
|
||||
if let Some(s) = ramp.stroke_mut() {
|
||||
s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] });
|
||||
}
|
||||
let mid = lerp_appearance(&ramp, &heavy, 0.5);
|
||||
assert!((at(&mid, 0.0).0 - 0.5).abs() < 1e-9 && (at(&mid, 0.5).0 - 0.75).abs() < 1e-9, "{:?}", mid.stroke().map(|s| &s.pressure));
|
||||
// A step in a recording (two samples at one position) stays a step.
|
||||
let mut stepped = stroked(None, None, None);
|
||||
if let Some(s) = stepped.stroke_mut() {
|
||||
s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)] });
|
||||
}
|
||||
let mid = lerp_appearance(&stepped, &stepped, 0.5);
|
||||
assert!(at(&mid, 0.25).0.abs() < 1e-9 && (at(&mid, 0.75).0 - 1.0).abs() < 1e-9, "{:?}", mid.stroke().map(|s| &s.pressure));
|
||||
// A whole turn recorded along a stroke stays a whole turn in the steps.
|
||||
let mut turning = stroked(None, None, None);
|
||||
if let Some(s) = turning.stroke_mut() {
|
||||
s.rotation = Some(AngleProfile { points: vec![(0.0, 0.0), (1.0, 360.0)] });
|
||||
}
|
||||
let rot = |ap: &Appearance, f: f64| ap.stroke().and_then(|s| s.rotation.as_ref()).map_or(0.0, |p| p.at(f));
|
||||
let same = lerp_appearance(&turning, &turning, 0.5);
|
||||
assert!((rot(&same, 0.25) - 90.0).abs() < 1e-9 && (rot(&same, 0.5).abs() - 180.0).abs() < 1e-9, "{:?}", same.stroke().map(|s| &s.rotation));
|
||||
let half = lerp_appearance(&turning, &plain, 0.5);
|
||||
assert!((rot(&half, 0.5) - 90.0).abs() < 1e-9 && (rot(&half, 1.0).abs() - 180.0).abs() < 1e-9, "{:?}", half.stroke().map(|s| &s.rotation));
|
||||
// Neither key has a recording: the steps have none either.
|
||||
let none = lerp_appearance(&plain, &plain, 0.5);
|
||||
let s = none.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
|
||||
assert!(s.pressure.is_none() && s.tilt.is_none() && s.bearing.is_none() && s.rotation.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_near_the_other_keys_step_keeps_the_step() {
|
||||
let flat = PressureProfile { points: vec![(0.0, 0.0), (0.4999995, 0.0), (1.0, 0.0)] };
|
||||
let stepped = PressureProfile { points: vec![(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)] };
|
||||
let p = lerp_pressure(Some(&flat), Some(&stepped), 1.0).unwrap_or_default();
|
||||
assert!((p.at(0.75) - 1.0).abs() < 1e-9, "{p:?}");
|
||||
let narrow = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.4999995, 1.0, 1.0), (1.0, 1.0, 1.0)] };
|
||||
let stepped = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)] };
|
||||
let w = lerp_profile(Some(&narrow), Some(&stepped), 1.0).unwrap_or_default();
|
||||
assert!(w.at(0.75).0.abs() < 1e-9, "{w:?}");
|
||||
// The other key's step doesn't reshape a smooth profile's curve.
|
||||
let early = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.25, 0.5, 0.5), (1.0, 0.5, 0.5)] };
|
||||
let w = lerp_profile(Some(&WidthProfile::lens()), Some(&early), 0.0).unwrap_or_default();
|
||||
for u in [0.1, 0.125, 0.2, 0.3, 0.4] {
|
||||
let (got, want) = (w.at(u).0, WidthProfile::lens().at(u).0);
|
||||
assert!((got - want).abs() < 5e-3, "at {u}: {got} for {want}: {w:?}");
|
||||
}
|
||||
let lens = WidthProfile::lens();
|
||||
assert_eq!(lerp_profile(Some(&lens), Some(&lens), 0.5).and_then(|p| p.preset_id()), Some("lens"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_profiles_turn_with_a_key_path_started_elsewhere() {
|
||||
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 pressure = |s: &StrokeLayer, f: f64| s.pressure.as_ref().map_or(PressureProfile::MID, |p| p.at(f));
|
||||
// An open key clicked at its last anchor runs the other way, and so do its pressure, its
|
||||
// width profile (whose sides swap) and its arrowheads.
|
||||
let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0)], false));
|
||||
let light = keyed(line(0.0), &|s| s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 0.0)] }));
|
||||
let ramp = keyed(line(100.0), &|s| {
|
||||
s.pressure = Some(PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] });
|
||||
s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 0.0, 0.0)] });
|
||||
s.start_arrow = Some(Arrowhead::Triangle);
|
||||
s.arrow_scale = (200.0, 100.0);
|
||||
});
|
||||
let blend = Lerp::new(&light, &ramp, (None, Some(1)));
|
||||
let s = stroke(&blend.at(0.25));
|
||||
assert!(pressure(&s, 0.0).abs() < 1e-9 && (pressure(&s, 1.0) - 0.25).abs() < 1e-9, "{:?}", s.pressure);
|
||||
let s = stroke(&blend.at(1.0));
|
||||
assert_eq!(s.profile.as_ref().map(|p| p.at(1.0)), Some((0.0, 1.0)), "{:?}", s.profile);
|
||||
assert_eq!((s.start_arrow, s.end_arrow, s.arrow_scale), (None, Some(Arrowhead::Triangle), (100.0, 200.0)));
|
||||
// A key whose other subpaths keep their direction keeps its one stroke as it is.
|
||||
let two = |x: f64| {
|
||||
let sub = |y: f64| SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y)], false);
|
||||
PathData::new(vec![sub(0.0), sub(20.0)])
|
||||
};
|
||||
let ramps = keyed(two(100.0), &|s| s.pressure = Some(PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] }));
|
||||
let s = stroke(&Lerp::new(&keyed(two(0.0), &|_| {}), &ramps, (None, Some(1))).at(1.0));
|
||||
assert!((pressure(&s, 0.0) - 1.0).abs() < 1e-9, "{:?}", s.pressure);
|
||||
// A closed key started half way round starts its recordings there too, keeping the step
|
||||
// where its own start was and the whole turn its rotation makes.
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
let plain = keyed(square(0.0), &|_| {});
|
||||
let turning = keyed(square(100.0), &|s| {
|
||||
s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] });
|
||||
s.rotation = Some(AngleProfile { points: vec![(0.0, 0.0), (1.0, 360.0)] });
|
||||
s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)] });
|
||||
});
|
||||
let blend = Lerp::new(&plain, &turning, (Some(0), Some(2)));
|
||||
let s = stroke(&blend.at(1.0));
|
||||
assert!((pressure(&s, 0.25) - 0.75).abs() < 1e-9 && (pressure(&s, 0.75) - 0.25).abs() < 1e-9, "{:?}", s.pressure);
|
||||
let width = s.profile.as_ref().map_or((1.0, 1.0), |p| p.at(0.75));
|
||||
assert!((width.0 - 0.75).abs() < 1e-6 && (width.1 - 0.75).abs() < 1e-6, "the width steps where the key started: {:?}", s.profile);
|
||||
// A width curve split by the new start keeps its shape.
|
||||
let lensed = keyed(square(100.0), &|s| s.profile = Some(WidthProfile::lens()));
|
||||
let s = stroke(&Lerp::new(&plain, &lensed, (Some(0), Some(1))).at(1.0));
|
||||
for u in [0.05, 0.125, 0.2, 0.6, 0.7, 0.74, 0.76, 0.8, 0.875, 0.95] {
|
||||
let (got, want) = (s.profile.as_ref().map_or(1.0, |p| p.at(u).0), WidthProfile::lens().at((u + 0.25) % 1.0).0);
|
||||
assert!((got - want).abs() < 2e-3, "at {u}: {got} for {want}: {:?}", s.profile);
|
||||
}
|
||||
let rot = |t: f64, f: f64| stroke(&blend.at(t)).rotation.as_ref().map_or(0.0, |p| p.unwrapped_at(f));
|
||||
assert!((vectorcraft_geom::normalize_deg(rot(1.0, 0.25)) + 90.0).abs() < 1e-6, "{:?}", s.rotation);
|
||||
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 odd_dash_blends_to_solid_with_closed_gaps() {
|
||||
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
|
||||
|
||||
@@ -150,7 +150,7 @@ fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to
|
||||
/// that many samples, which includes images whose planes together need more than the decoder's
|
||||
/// limit (256 MB of samples).
|
||||
fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
|
||||
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
|
||||
let mut buf = tiff::decoder::DecodingResult::U8(Vec::new());
|
||||
let layout = d.read_image_to_buffer(&mut buf).ok()?;
|
||||
let data = match buf {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Image Tools › Color Mask: colors of an image object that are hidden while its pixels stay as
|
||||
//! they are.
|
||||
//!
|
||||
//! A masked image is an ordinary image ([`NodeKind::Image`]) with a [`ColorMask`] in its extras
|
||||
//! ([`crate::node::NodeExtras::color_mask`]). The record holds the mask's settings and the key of
|
||||
//! the image's pixels with the hidden colors made clear ([`ColorMask::key`]), made by the engine
|
||||
//! from the pixels named by [`ColorMask::from`]. The image's own key keeps naming its own pixels,
|
||||
//! so removing the mask gives them back. While the image's key is [`ColorMask::from`], it is drawn
|
||||
//! and output with the masked pixels ([`Document::shown_image`]); when another key replaced it
|
||||
//! (a link updated, the image cropped), it shows its own pixels until the engine makes the masked
|
||||
//! pixels again.
|
||||
//!
|
||||
//! The concept is that of PDF's color key masking (ISO 32000-1, 8.9.6.4): samples in the chosen
|
||||
//! colors are not painted and what is behind the image shows through. Which colors match, and how
|
||||
//! near ones fade out, are VectorCraft's own rules.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Document, ImageObject, Node, NodeKind};
|
||||
|
||||
/// Where a color mask's colors come from.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MaskBackground {
|
||||
/// The most common color along the image's edges.
|
||||
#[default]
|
||||
Edges,
|
||||
/// The average of the image's corner pixels that are not clear.
|
||||
Corners,
|
||||
/// The colors in [`ColorMask::colors`].
|
||||
Colors,
|
||||
}
|
||||
|
||||
/// How near a color must be to a masked one.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MaskMatch {
|
||||
/// The RGB distance, as a percentage of the largest one.
|
||||
#[default]
|
||||
Distance,
|
||||
/// The largest difference on one of red, green and blue, as a percentage of a channel's range.
|
||||
Channels,
|
||||
}
|
||||
|
||||
/// The colors an image object hides (see the module docs).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ColorMask {
|
||||
/// Key into [`Document::images`]: the pixels of [`Self::from`] with the hidden colors made
|
||||
/// clear. Named `key` in the file, so the file keeps those pixels with the document.
|
||||
pub key: String,
|
||||
/// The image's own key when the masked pixels were made.
|
||||
pub from: String,
|
||||
#[serde(default)]
|
||||
pub background: MaskBackground,
|
||||
/// The hidden colors (8-bit RGB) with [`MaskBackground::Colors`].
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub colors: Vec<[u8; 3]>,
|
||||
/// Only the matching pixels that reach in from an edge are hidden. A record without it reads
|
||||
/// as `true`, the command's default.
|
||||
#[serde(default = "default_contiguous")]
|
||||
pub contiguous: bool,
|
||||
#[serde(default, rename = "match")]
|
||||
pub measure: MaskMatch,
|
||||
/// How near a color must be to be hidden, 0 to 100 (see [`MaskMatch`]). A record without it
|
||||
/// reads as 10, the command's default.
|
||||
#[serde(default = "default_percent")]
|
||||
pub tolerance: f64,
|
||||
/// The band past the tolerance over which pixels fade from hidden to shown, 0 to 100. A record
|
||||
/// without it reads as 10, the command's default.
|
||||
#[serde(default = "default_percent")]
|
||||
pub softness: f64,
|
||||
}
|
||||
|
||||
fn default_contiguous() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_percent() -> f64 {
|
||||
10.0
|
||||
}
|
||||
|
||||
impl ColorMask {
|
||||
/// Whether the masked pixels were made from the pixels of `im`.
|
||||
pub fn made_for(&self, im: &ImageObject) -> bool {
|
||||
im.pixels.is_none() && self.from == im.key
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Image `im` of node `n` as it is drawn and output. With a color mask whose masked pixels were
|
||||
/// made from the image's own pixels and are in this document ([`ColorMask::made_for`]): a copy
|
||||
/// that shows those pixels and links to no file, so an output that refers to a linked file
|
||||
/// writes the masked pixels instead. Otherwise, and for a mask that hides nothing (its masked
|
||||
/// pixels are the image's own), `im` itself.
|
||||
pub fn shown_image<'a>(&self, n: &Node, im: &'a ImageObject) -> Cow<'a, ImageObject> {
|
||||
match n.extras().color_mask.as_deref() {
|
||||
Some(m) if m.key != im.key && m.made_for(im) && self.images.contains_key(&m.key) => {
|
||||
Cow::Owned(ImageObject { key: m.key.clone(), link: None, ..im.clone() })
|
||||
}
|
||||
_ => Cow::Borrowed(im),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color mask of image node `n`, if it has one.
|
||||
pub fn color_mask_of(n: &Node) -> Option<&ColorMask> {
|
||||
matches!(n.kind, NodeKind::Image(_)).then(|| n.extras().color_mask.as_deref()).flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::*;
|
||||
use crate::{ImageBlob, NodeId};
|
||||
|
||||
fn image(key: &str) -> ImageObject {
|
||||
ImageObject { key: key.into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }
|
||||
}
|
||||
|
||||
fn mask(key: &str, from: &str) -> ColorMask {
|
||||
ColorMask {
|
||||
key: key.into(),
|
||||
from: from.into(),
|
||||
background: MaskBackground::Colors,
|
||||
colors: vec![[255, 255, 255]],
|
||||
contiguous: false,
|
||||
measure: MaskMatch::Distance,
|
||||
tolerance: 10.0,
|
||||
softness: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_masked_image_shows_its_masked_pixels_while_they_were_made_from_its_own() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.images.insert("own".into(), ImageBlob::png(vec![1]));
|
||||
d.images.insert("masked".into(), ImageBlob::png(vec![2]));
|
||||
let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own"))));
|
||||
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
|
||||
assert_eq!(d.shown_image(&n, im).key, "own", "no mask: its own pixels");
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
|
||||
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
|
||||
assert_eq!(d.shown_image(&n, im).key, "masked");
|
||||
// Linked: the shown copy links to nothing, so outputs write the masked pixels.
|
||||
let mut linked = (**im).clone();
|
||||
linked.link = Some(crate::LinkInfo::new("/a.png"));
|
||||
assert_eq!(d.shown_image(&n, &linked).link, None);
|
||||
// Made from other pixels: its own until they are made again.
|
||||
assert_eq!(d.shown_image(&n, &image("other")).key, "other");
|
||||
// Masked pixels the document doesn't have: its own.
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("gone", "own")));
|
||||
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
|
||||
assert_eq!(d.shown_image(&n, im).key, "own");
|
||||
// Pixels an image holds itself are drawn as they are.
|
||||
let own = ImageObject { pixels: Some(Arc::new(ImageBlob::png(vec![3]))), ..image("own") };
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
|
||||
assert_eq!(d.shown_image(&n, &own).key, "own");
|
||||
// A mask that hides nothing (its masked pixels are the image's own): the image itself, so
|
||||
// a linked image stays linked in outputs.
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("own", "own")));
|
||||
assert_eq!(d.shown_image(&n, &linked).link, linked.link);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_saves_and_reads_back_with_its_node() {
|
||||
let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own"))));
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
|
||||
let json = serde_json::to_value(&n).unwrap();
|
||||
assert_eq!(json["color_mask"]["key"], "masked", "the masked pixels' key is a `key` member: {json}");
|
||||
assert_eq!(json["color_mask"]["match"], "distance");
|
||||
let back: Node = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(back, n);
|
||||
// A node without one writes none.
|
||||
let plain = Node::new(NodeId(6), NodeKind::Image(Box::new(image("own"))));
|
||||
assert!(serde_json::to_value(&plain).unwrap().get("color_mask").is_none());
|
||||
}
|
||||
|
||||
/// A record that leaves out settings reads them as the command's defaults: edge color,
|
||||
/// contiguous, distance, tolerance and softness 10.
|
||||
#[test]
|
||||
fn a_record_without_settings_reads_the_defaults() {
|
||||
let m: ColorMask = serde_json::from_value(serde_json::json!({"key": "masked", "from": "own"})).unwrap();
|
||||
assert_eq!(
|
||||
(m.background, m.colors.len(), m.contiguous, m.measure, m.tolerance, m.softness),
|
||||
(MaskBackground::Edges, 0, true, MaskMatch::Distance, 10.0, 10.0)
|
||||
);
|
||||
}
|
||||
|
||||
fn unreachable_kind() -> ! {
|
||||
panic!("an image node")
|
||||
}
|
||||
}
|
||||
@@ -569,7 +569,7 @@ fn clip_contains(clip: &Node, p: Point) -> bool {
|
||||
|
||||
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
|
||||
/// [`clip_contains`].
|
||||
fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
|
||||
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
|
||||
let frame = |n: &Node| {
|
||||
let b = n.geometric_bounds()?;
|
||||
Some(Node::path(n.id, vectorcraft_geom::shapes::rectangle(b), Default::default()))
|
||||
@@ -640,7 +640,7 @@ fn source_of(n: &Node, scope: Option<NodeId>) -> bool {
|
||||
/// Do clicks and marquees skip the child `i` of `parent` with `scope` isolated? For a Shaper
|
||||
/// Group that is its original shapes (its first child), or, in Construction mode, when they are
|
||||
/// isolated, the art the group shows.
|
||||
fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
|
||||
pub fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
|
||||
parent.extras().shaper.is_some() && (i == 0) != source_of(parent, scope)
|
||||
}
|
||||
|
||||
@@ -1356,7 +1356,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
|
||||
/// when the marquee misses it); otherwise it is all of `r`.
|
||||
fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
|
||||
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
|
||||
match parent.children().and_then(|c| c.first()) {
|
||||
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
|
||||
_ => Some(r),
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod blend;
|
||||
pub mod cancel;
|
||||
pub mod clipnest;
|
||||
pub mod cmyk;
|
||||
pub mod color_mask;
|
||||
pub mod compound_shape;
|
||||
pub mod corners;
|
||||
pub mod depth;
|
||||
@@ -51,7 +52,7 @@ pub mod overprint;
|
||||
pub mod pattern;
|
||||
pub mod perspective;
|
||||
mod pixels;
|
||||
pub use pixels::{GraySource, MAX_RASTER_ALLOC};
|
||||
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
|
||||
pub mod placed_document;
|
||||
pub mod plugin_data;
|
||||
pub mod profiles;
|
||||
@@ -61,6 +62,7 @@ pub mod rastersettings;
|
||||
mod reach;
|
||||
pub mod recolor;
|
||||
pub mod selection;
|
||||
pub mod separated;
|
||||
pub mod setup;
|
||||
pub mod shaper;
|
||||
pub mod slices;
|
||||
@@ -82,8 +84,8 @@ pub(crate) mod skip;
|
||||
|
||||
pub use appearance::StrokeGradientMode;
|
||||
pub use appearance::{
|
||||
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile, ProfilePreset,
|
||||
SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
|
||||
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, CustomArrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile,
|
||||
ProfilePreset, SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
|
||||
};
|
||||
pub use assets::ExportAsset;
|
||||
pub use compound_shape::ShapeMode;
|
||||
@@ -263,8 +265,8 @@ pub struct Document {
|
||||
/// File → Document Setup (bleed, transparency grid, paper, type options).
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub setup: DocSetup,
|
||||
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers (by name)
|
||||
/// they were copied from instead of the current layer.
|
||||
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers and
|
||||
/// sublayers they were copied from instead of the current layer.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub paste_remembers_layers: bool,
|
||||
/// File → File Info (its title is [`Document::info_title`]).
|
||||
|
||||
@@ -1025,6 +1025,37 @@ mod tests {
|
||||
assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0)));
|
||||
}
|
||||
|
||||
/// A point on a mesh's outline locates on the edge it lies on, on all four sides alike, with no
|
||||
/// tolerance; a point just outside does not, and a tolerance reaches only as far as it says.
|
||||
/// A point that isn't finite locates nowhere.
|
||||
#[test]
|
||||
fn mesh_locate_takes_a_point_on_any_side_of_the_outline() {
|
||||
for (rows, cols) in [(1, 1), (2, 3)] {
|
||||
let m =
|
||||
GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0)
|
||||
.unwrap();
|
||||
let sides = [
|
||||
("top", Point::new(30.0, 0.0), Vec2::new(0.0, -0.01)),
|
||||
("bottom", Point::new(30.0, 100.0), Vec2::new(0.0, 0.01)),
|
||||
("left", Point::new(0.0, 70.0), Vec2::new(-0.01, 0.0)),
|
||||
("right", Point::new(100.0, 70.0), Vec2::new(0.01, 0.0)),
|
||||
];
|
||||
for (side, p, out) in sides {
|
||||
let (r, c, u, v) = m.locate(p).unwrap_or_else(|| panic!("{rows}×{cols} {side}: {p:?} is not located"));
|
||||
assert!(r < m.rows as usize && c < m.cols as usize && (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v), "{side}");
|
||||
assert!(m.eval(r, c, u, v).distance(p) < 1e-3, "{rows}×{cols} {side}: {:?}", m.eval(r, c, u, v));
|
||||
let mut e = m.clone();
|
||||
assert!(e.add_lines_at(p, 0.0).is_some(), "{rows}×{cols} {side}: no line at {p:?}");
|
||||
assert_eq!(m.locate(p + out), None, "{rows}×{cols} {side}: just outside");
|
||||
assert_eq!(m.locate_within(p + out * 100.0, 0.5), None, "{rows}×{cols} {side}: past the tolerance");
|
||||
assert!(m.locate_within(p + out * 100.0, 1.5).is_some(), "{rows}×{cols} {side}: within the tolerance");
|
||||
}
|
||||
for p in [Point::new(f64::NAN, 0.0), Point::new(30.0, f64::INFINITY)] {
|
||||
assert_eq!(m.locate_within(p, f64::INFINITY), None, "{p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB.
|
||||
#[test]
|
||||
fn a_cmyk_mesh_mixes_its_inks() {
|
||||
|
||||
@@ -119,6 +119,12 @@ impl BlendSpec {
|
||||
pub fn start(&self, i: usize) -> Option<usize> {
|
||||
self.starts.get(i).copied().flatten().map(|a| a as usize)
|
||||
}
|
||||
|
||||
/// Whether [`Self::ease`] moves the steps: the blend has a spine ([`Self::no_spine`] is off)
|
||||
/// and a replaced spine or Align to Path, the cases where the steps are placed along it.
|
||||
pub fn eases_along_spine(&self) -> bool {
|
||||
!self.no_spine && (self.spine.is_some() || self.orientation == BlendOrientation::AlignToPath)
|
||||
}
|
||||
}
|
||||
|
||||
/// The Blend panel's Create Spine setting: whether a new blend gets a spine.
|
||||
|
||||
@@ -119,7 +119,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
|
||||
{
|
||||
out.appearance.warp_linear_gradients(b, &|p| affine_near(w.f, p, w.eps));
|
||||
}
|
||||
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
// A linked opacity mask bends with the object it masks; an unlinked one stays where it is.
|
||||
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) {
|
||||
m.art = Arc::new(map_node(&m.art, w));
|
||||
}
|
||||
match &mut out.kind {
|
||||
@@ -205,12 +206,14 @@ pub fn mesh_warp_cost(cells: usize) -> usize {
|
||||
/// that takes the triangle where `f` takes its corners (with `masked`, the image masked by the
|
||||
/// triangle instead; with `pixelated`, drawn without smoothing). Each piece reaches a little past
|
||||
/// its edges (at most half a point) so neighbors overlap and no seams show. Each piece keeps the
|
||||
/// color `n` colorizes a grayscale image with. The result is a group with `n`'s id, name,
|
||||
/// color `n` colorizes a grayscale image with, and `n`'s color mask. The result is a group with `n`'s id, name,
|
||||
/// transparency, opacity mask and appearance.
|
||||
pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node {
|
||||
let k = cells.max(1);
|
||||
// A grayscale image's fill color colorizes each piece; the group of pieces takes none.
|
||||
let colorize = n.extras().colorize.clone();
|
||||
// Each piece shows what the image shows: its color mask's masked pixels.
|
||||
let color_mask = n.extras().color_mask.clone();
|
||||
let (pw, ph) = (im.width as f64, im.height as f64);
|
||||
let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64);
|
||||
let mut pieces = Vec::with_capacity(2 * k * k);
|
||||
@@ -235,6 +238,7 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
|
||||
let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
|
||||
image.extras_mut().pixelated = pixelated;
|
||||
image.extras_mut().colorize = colorize.clone();
|
||||
image.extras_mut().color_mask = color_mask.clone();
|
||||
if masked {
|
||||
// Preserve Shape Using Transparency: the triangle is the piece's alpha (a
|
||||
// white opacity mask) instead of its clipping path.
|
||||
|
||||
@@ -530,6 +530,10 @@ pub(super) const MAX_BORDER_LINES: usize = 256;
|
||||
/// The most rounds of new lines a mesh made from a path takes to keep its border on the outline.
|
||||
const MAX_BORDER_ROUNDS: usize = 64;
|
||||
|
||||
/// A point this close (in points) to a mesh's outline is on it, for [`GradientMesh::locate_within`]
|
||||
/// with any tolerance.
|
||||
const ON_OUTLINE: f64 = 1e-6;
|
||||
|
||||
/// An anchor whose directions in and out differ by more than this (radians) is a corner: a border
|
||||
/// edge that can't follow the outline takes a mesh line through its sharpest corner first.
|
||||
const SHARP_TURN: f64 = 0.01;
|
||||
@@ -1436,17 +1440,23 @@ impl GradientMesh {
|
||||
}
|
||||
|
||||
/// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the
|
||||
/// patch and local (u, v) of the nearest point of the mesh's edge.
|
||||
/// patch and local (u, v) of the nearest point of the mesh's edge. A point on the outline
|
||||
/// (within [`ON_OUTLINE`]) locates on its edge on every side, with any `tol`.
|
||||
pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> {
|
||||
if !self.is_valid() {
|
||||
if !self.is_valid() || !p.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let bp = self.outline().to_bezpath();
|
||||
if bp.winding(p) == 0 {
|
||||
// A point on the outline takes the nearest point of the edge on every side: the nonzero
|
||||
// winding number counts a point on some edges as outside (a rectangle's bottom and right
|
||||
// edges) and on the others as inside.
|
||||
if let Some((_, r, c, u, v)) = self.nearest_edge(p, ON_OUTLINE).filter(|e| e.0 <= ON_OUTLINE * ON_OUTLINE) {
|
||||
return Some((r, c, u, v));
|
||||
}
|
||||
if self.outline().to_bezpath().winding(p) == 0 {
|
||||
if tol.is_nan() || tol <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v));
|
||||
return self.nearest_edge(p, tol).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v));
|
||||
}
|
||||
const N: usize = 16;
|
||||
let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0);
|
||||
@@ -1484,12 +1494,20 @@ impl GradientMesh {
|
||||
}
|
||||
|
||||
/// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its
|
||||
/// boundary patch and local (u, v).
|
||||
fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> {
|
||||
/// boundary patch and local (u, v). Edges whose control points all lie farther than `within`
|
||||
/// from `p` are skipped, so `None` means no edge is within `within`.
|
||||
fn nearest_edge(&self, p: Point, within: f64) -> Option<(f64, usize, usize, f64, f64)> {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
let (rows, cols) = (self.rows as usize, self.cols as usize);
|
||||
let mut best: Option<(f64, usize, usize, f64, f64)> = None;
|
||||
let mut take = |e: CubicBez, at: (usize, usize, Option<f64>, Option<f64>)| {
|
||||
// The edge lies inside its control points' box, so a box farther than `within` holds
|
||||
// no point of the edge within it.
|
||||
let b = Rect::from_points(e.p0, e.p1).union_pt(e.p2).union_pt(e.p3);
|
||||
let (dx, dy) = ((b.x0 - p.x).max(p.x - b.x1).max(0.0), (b.y0 - p.y).max(p.y - b.y1).max(0.0));
|
||||
if dx * dx + dy * dy > within * within {
|
||||
return;
|
||||
}
|
||||
let n = e.nearest(p, 1e-9);
|
||||
if best.is_none_or(|b| n.distance_sq < b.0) {
|
||||
let (r, c, u, v) = at;
|
||||
|
||||
@@ -261,6 +261,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
b += ALLOC + size_of::<NodeExtras>();
|
||||
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
|
||||
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
|
||||
b += e
|
||||
.color_mask
|
||||
.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.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
|
||||
if e.intertwine_tiers.capacity() > 0 {
|
||||
|
||||
@@ -72,6 +72,9 @@ pub struct NodeExtras {
|
||||
/// Transform panel › Align to Pixel Grid: the path's or compound path's horizontal and vertical
|
||||
/// segments stay on the pixel grid when it is transformed.
|
||||
pub pixel_aligned: bool,
|
||||
/// Image Tools › Color Mask: the colors an image hides while its pixels stay as they are
|
||||
/// ([`crate::color_mask`]).
|
||||
pub color_mask: Option<Box<crate::color_mask::ColorMask>>,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -99,6 +102,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
symbol_overrides: Vec::new(),
|
||||
envelope_edit_margin: None,
|
||||
pixel_aligned: false,
|
||||
color_mask: None,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
+24
-13
@@ -819,7 +819,8 @@ impl Node {
|
||||
impl Node {
|
||||
/// Whether this object shows any transparency, itself or anything inside it: object, fill or
|
||||
/// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient
|
||||
/// stops or a colorized image. Hidden objects show none.
|
||||
/// stops (characters' fills and strokes included) or a colorized image. Hidden objects show
|
||||
/// none.
|
||||
pub fn shows_transparency(&self) -> bool {
|
||||
self.shows_transparency_with(&|_| true)
|
||||
}
|
||||
@@ -827,21 +828,31 @@ impl Node {
|
||||
/// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize`
|
||||
/// accepts it, for files that write some colorized images in their colorize paint (EPS).
|
||||
pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool {
|
||||
self.visible && (self.own_transparency(colorize) || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize))))
|
||||
}
|
||||
|
||||
/// [`Self::shows_transparency`] of the object alone, what it holds left out.
|
||||
pub fn shows_own_transparency(&self) -> bool {
|
||||
self.visible && self.own_transparency(&|_| true)
|
||||
}
|
||||
|
||||
/// The object's own transparency, as [`Self::shows_transparency_with`] counts it.
|
||||
fn own_transparency(&self, colorize: &dyn Fn(&Node) -> bool) -> bool {
|
||||
use vectorcraft_color::Paint;
|
||||
let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0));
|
||||
let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible);
|
||||
self.visible
|
||||
&& (self.opacity < 1.0
|
||||
|| self.blend != BlendMode::Normal
|
||||
|| self.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|
||||
|| (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self))
|
||||
|| effects(&self.appearance.effects)
|
||||
|| self
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
|
||||
|| self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize))))
|
||||
self.opacity < 1.0
|
||||
|| self.blend != BlendMode::Normal
|
||||
|| self.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|
||||
|| (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self))
|
||||
|| effects(&self.appearance.effects)
|
||||
|| self
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
|
||||
// Characters' own fills and strokes, which draw with the object.
|
||||
|| matches!(&self.kind, NodeKind::Text(t) if t.runs.iter().any(|r| see_through(&r.style.fill) || (r.style.stroke_width > 0.0 && see_through(&r.style.stroke))))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ impl Serialize for Node {
|
||||
e.symbol_overrides.is_empty(),
|
||||
e.envelope_edit_margin.is_none(),
|
||||
is_default(&e.pixel_aligned),
|
||||
e.color_mask.is_none(),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
@@ -98,6 +99,7 @@ impl Serialize for Node {
|
||||
field!("symbol_overrides", &e.symbol_overrides);
|
||||
field!("envelope_edit_margin", &e.envelope_edit_margin);
|
||||
field!("pixel_aligned", &e.pixel_aligned);
|
||||
field!("color_mask", &e.color_mask);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -241,6 +243,8 @@ pub(super) struct NodeWire {
|
||||
envelope_edit_margin: Option<[f32; 4]>,
|
||||
#[serde(default)]
|
||||
pixel_aligned: bool,
|
||||
#[serde(default)]
|
||||
color_mask: Option<Box<crate::color_mask::ColorMask>>,
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
@@ -269,6 +273,7 @@ impl From<NodeWire> for Node {
|
||||
symbol_overrides: w.symbol_overrides,
|
||||
envelope_edit_margin: w.envelope_edit_margin,
|
||||
pixel_aligned: w.pixel_aligned,
|
||||
color_mask: w.color_mask,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
@@ -11,6 +11,10 @@ use crate::ImageBlob;
|
||||
/// address and aborts when an allocation fails, so it keeps the decoder's own 512 MB.
|
||||
pub const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
|
||||
|
||||
/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), the
|
||||
/// pixels to sample from it at most, and the pixel centres to take ([`ImageBlob::sample_pixels`]).
|
||||
pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool);
|
||||
|
||||
/// The pixels of encoded image `bytes` as RGBA; `None` when they can't be decoded, would take
|
||||
/// more than `max` bytes as RGBA, or need more than `max` bytes to decode. The size is read from
|
||||
/// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter
|
||||
@@ -61,6 +65,49 @@ impl ImageBlob {
|
||||
Some(Self::png(png))
|
||||
}
|
||||
|
||||
/// For each of `picks`, at most its budget of the image's pixels (at least one), spread evenly
|
||||
/// in rows and columns over the pick's box (`[u0, v0, u1, v1]`, where 0 to 1 spans the
|
||||
/// image's width and height from the top left; clipped to the image; `None`: the whole image),
|
||||
/// as straight RGBA. Only pixels whose centres the pick's function takes (in the same 0 to 1
|
||||
/// units) are given, and the function is called once for each pixel sampled. The image is
|
||||
/// decoded once for all the picks. `None` when it can't be decoded within [`MAX_RASTER_ALLOC`].
|
||||
pub fn sample_pixels(&self, picks: &[PixelPick<'_>]) -> Option<Vec<Vec<[u8; 4]>>> {
|
||||
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
|
||||
let (w, h) = img.dimensions();
|
||||
let (fw, fh) = (f64::from(w), f64::from(h));
|
||||
let span = |a: f64, b: f64, n: f64| {
|
||||
let (a, b) = (a.min(b), a.max(b));
|
||||
((a * n).floor().clamp(0.0, n) as u32, (b * n).ceil().clamp(0.0, n) as u32)
|
||||
};
|
||||
let sample = |area: Option<[f64; 4]>, budget: usize, keep: &dyn Fn(f64, f64) -> bool| {
|
||||
let [u0, v0, u1, v1] = area.unwrap_or([0.0, 0.0, 1.0, 1.0]);
|
||||
let (x0, x1) = span(u0, u1, fw);
|
||||
let (y0, y1) = span(v0, v1, fh);
|
||||
if x0 >= x1 || y0 >= y1 {
|
||||
return vec![];
|
||||
}
|
||||
// Rows and columns in proportion to the box, at most `budget` cells in all.
|
||||
let (bw, bh, budget) = (f64::from(x1 - x0), f64::from(y1 - y0), budget.max(1) as f64);
|
||||
let (sx, sy) = if bw * bh <= budget {
|
||||
(1, 1)
|
||||
} else {
|
||||
let rows = (budget * bh / bw).sqrt().floor().clamp(1.0, bh.min(budget));
|
||||
let cols = (budget / rows).floor().clamp(1.0, bw);
|
||||
((bw / cols).ceil() as usize, (bh / rows).ceil() as usize)
|
||||
};
|
||||
let mut out = vec![];
|
||||
for y in (y0..y1).step_by(sy) {
|
||||
for x in (x0..x1).step_by(sx) {
|
||||
if keep((f64::from(x) + 0.5) / fw, (f64::from(y) + 0.5) / fh) {
|
||||
out.push(img.get_pixel(x, y).0);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
Some(picks.iter().map(|(area, budget, keep)| sample(*area, *budget, *keep)).collect())
|
||||
}
|
||||
|
||||
/// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and
|
||||
/// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct
|
||||
/// color. `None` when the image can't be decoded, or when its file stores grayscale already
|
||||
@@ -276,6 +323,33 @@ mod tests {
|
||||
image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
|
||||
}
|
||||
|
||||
/// Sampling reads the pixels of a box of the image, spread to about the budget, and only those
|
||||
/// whose centres `keep` takes.
|
||||
#[test]
|
||||
fn sampled_pixels_stay_in_their_box_and_budget() {
|
||||
// 4 × 2: a red left half and a blue right half.
|
||||
let (r, b) = ([255, 0, 0, 255], [0, 0, 255, 255]);
|
||||
let img = blob(&[r, r, b, b, r, r, b, b], 4, 2);
|
||||
let any = |_: f64, _: f64| true;
|
||||
let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, budget, &any)]).unwrap().remove(0);
|
||||
assert_eq!(one(&img, None, 100).len(), 8, "the budget covers every pixel");
|
||||
assert_eq!(one(&img, Some([0.5, 0.0, 1.0, 1.0]), 100), vec![b; 4], "the right half");
|
||||
assert_eq!(one(&img, Some([1.0, 1.0, 0.5, 0.0]), 100), vec![b; 4], "a box given backwards");
|
||||
assert!(one(&img, Some([2.0, 0.0, 3.0, 1.0]), 100).is_empty(), "outside the image");
|
||||
assert_eq!(one(&img, None, 2).len(), 2, "every second pixel of every second row");
|
||||
assert_eq!(one(&img, None, 0), vec![r], "a budget of 0 counts as 1");
|
||||
let left = |u: f64, _: f64| u < 0.5;
|
||||
let both = img.sample_pixels(&[(None, 100, &left), (Some([0.5, 0.0, 1.0, 1.0]), 100, &any)]).unwrap();
|
||||
assert_eq!(both, vec![vec![r; 4], vec![b; 4]], "several picks, each with the centres its function takes");
|
||||
let sizes: Vec<usize> = img.sample_pixels(&[(None, 2, &any), (None, 100, &any)]).unwrap().iter().map(Vec::len).collect();
|
||||
assert_eq!(sizes, [2, 8], "each pick keeps to its own budget");
|
||||
// A narrow image keeps to the budget too.
|
||||
let tall = blob(&vec![r; 5000], 1, 5000);
|
||||
let n = one(&tall, None, 100).len();
|
||||
assert!((50..=100).contains(&n), "{n} pixels");
|
||||
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, 100, &any)]).is_none());
|
||||
}
|
||||
|
||||
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
|
||||
/// other pixels, and the decoder makes them transparent.
|
||||
fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> {
|
||||
|
||||
@@ -517,7 +517,12 @@ fn rename(n: &mut Node, prefix: &str) {
|
||||
paint(&mut r.style.stroke);
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => im.key = format!("{prefix}{}", im.key),
|
||||
NodeKind::Image(im) => {
|
||||
im.key = format!("{prefix}{}", im.key);
|
||||
if let Some(m) = n.extras.0.as_deref_mut().and_then(|e| e.color_mask.as_deref_mut()) {
|
||||
(m.key, m.from) = (format!("{prefix}{}", m.key), format!("{prefix}{}", m.from));
|
||||
}
|
||||
}
|
||||
NodeKind::PlacedDocument(p) => p.key = format!("{prefix}{}", p.key),
|
||||
NodeKind::SymbolInstance { symbol, .. } => *symbol = format!("{prefix}{symbol}"),
|
||||
_ => {}
|
||||
@@ -681,6 +686,30 @@ mod tests {
|
||||
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
|
||||
}
|
||||
|
||||
/// A color-masked image in a placed document's art keeps its masked pixels under the prefixed
|
||||
/// names its resources get.
|
||||
#[test]
|
||||
fn a_color_mask_takes_the_prefixed_image_names() {
|
||||
let im =
|
||||
ImageObject { key: "own".into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
|
||||
let mut n = Node::new(NodeId(7), NodeKind::Image(Box::new(im)));
|
||||
n.extras_mut().color_mask = Some(Box::new(crate::color_mask::ColorMask {
|
||||
key: "masked".into(),
|
||||
from: "own".into(),
|
||||
background: Default::default(),
|
||||
colors: vec![],
|
||||
contiguous: true,
|
||||
measure: Default::default(),
|
||||
tolerance: 10.0,
|
||||
softness: 10.0,
|
||||
}));
|
||||
rename(&mut n, "p:");
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
|
||||
let m = Document::color_mask_of(&n).unwrap();
|
||||
assert_eq!((im.key.as_str(), m.key.as_str(), m.from.as_str()), ("p:own", "p:masked", "p:own"));
|
||||
assert!(m.made_for(im));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_json() {
|
||||
let n = Node::new(NodeId(3), NodeKind::PlacedDocument(Box::new(placed("doc1-1"))));
|
||||
|
||||
+237
-69
@@ -1,6 +1,7 @@
|
||||
//! Where a path's strokes paint, from the path's geometry without building their outlines: the
|
||||
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
|
||||
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points.
|
||||
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points,
|
||||
//! and a bevel ends at the corners of the two segments it joins.
|
||||
|
||||
use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit};
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
@@ -39,10 +40,20 @@ fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator<Item = (Point, Vec2,
|
||||
/// path: its tip and the corner's outer offset points, or `None` when the path doesn't turn there
|
||||
/// or the miter limit bevels it.
|
||||
fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[Point; 3]> {
|
||||
let cos = t_in.dot(t_out);
|
||||
// cos(half the turn) is sin(half the angle between the segments): the miter is side / it.
|
||||
let half = ((1.0 + cos) / 2.0).max(0.0).sqrt();
|
||||
if cos >= CORNER_COS || half * limit < 1.0 {
|
||||
let half = ((1.0 + t_in.dot(t_out)) / 2.0).max(0.0).sqrt();
|
||||
if half * limit < 1.0 {
|
||||
return None;
|
||||
}
|
||||
let ([a, b], out) = bevel(at, t_in, t_out, side)?;
|
||||
Some([a, at + out * (side / half), b])
|
||||
}
|
||||
|
||||
/// The bevel at a corner with tangents `t_in`, `t_out` of a stroke reaching `side` from its path:
|
||||
/// the outer corners of the two segments' strokes and the unit direction out of the turn, or
|
||||
/// `None` when the path doesn't turn there.
|
||||
fn bevel(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option<([Point; 2], Vec2)> {
|
||||
if t_in.dot(t_out) >= CORNER_COS {
|
||||
return None;
|
||||
}
|
||||
let out = unit(t_in - t_out);
|
||||
@@ -51,7 +62,7 @@ fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[P
|
||||
let n = Vec2::new(-t.y, t.x);
|
||||
if n.dot(out) >= 0.0 { n } else { -n }
|
||||
};
|
||||
Some([at + outer(t_in) * side, at + out * (side / half), at + outer(t_out) * side])
|
||||
Some(([at + outer(t_in) * side, at + outer(t_out) * side], out))
|
||||
}
|
||||
|
||||
/// The heads' ends of `bp`: the start of its first subpath and the end of its last, when open (as
|
||||
@@ -187,26 +198,44 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
|
||||
}
|
||||
|
||||
impl StrokeLayer {
|
||||
/// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads,
|
||||
/// an alignment that depends on whether the path is closed, or butt caps, which stop at the
|
||||
/// ends of an open path? Else it reaches evenly round it.
|
||||
/// Does bounding this stroke need its path's shape: miter spikes, bevels, projecting caps,
|
||||
/// arrowheads, an alignment that depends on whether the path is closed, or butt caps, which
|
||||
/// stop at the ends of an open path? Else it reaches evenly round it.
|
||||
fn needs_shape(&self) -> bool {
|
||||
self.join == LineJoin::Miter
|
||||
self.join != LineJoin::Round
|
||||
|| self.cap != LineCap::Round
|
||||
|| self.start_arrow.is_some()
|
||||
|| self.end_arrow.is_some()
|
||||
|| self.align != StrokeAlign::Center
|
||||
}
|
||||
|
||||
/// The box this stroke paints along `segs`, the segments with length of an open subpath, when
|
||||
/// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each
|
||||
/// joint between segments paints ([`round_join_box`]), a shallow one included.
|
||||
/// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips
|
||||
/// are measured apart. A segment in the middle is measured only when its own box grown by
|
||||
/// `side`, which holds everything it paints, is not inside the box so far.
|
||||
fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option<Rect> {
|
||||
/// Does this stroke stop at the corners of its segments along a subpath that is `closed` or
|
||||
/// open, where its caps are butt caps on an open subpath or its joins are bevels or miters?
|
||||
/// Dashes with round or projecting caps can end at a corner, so with them only butt caps stop.
|
||||
fn stops_at_corners(&self, closed: bool) -> bool {
|
||||
let capped_dashes = self.cap != LineCap::Butt && self.dash.as_ref().is_some_and(Dash::is_dashed);
|
||||
(self.cap == LineCap::Butt && !closed) || (self.join != LineJoin::Round && !capped_dashes)
|
||||
}
|
||||
|
||||
/// Does this stroke reach past a subpath that is `closed` or open by a margin that follows the
|
||||
/// direction of its segments at their corners: where it stops at them
|
||||
/// ([`Self::stops_at_corners`]) or paints miter spikes, which dashes with round or projecting
|
||||
/// caps also paint?
|
||||
fn reaches_by_corners(&self, closed: bool) -> bool {
|
||||
self.stops_at_corners(closed) || self.join == LineJoin::Miter
|
||||
}
|
||||
|
||||
/// The box this stroke's body paints along `segs`, the segments with length of a subpath, short
|
||||
/// of its caps, joined with `within`: each segment's [`swept_box`] and, with round joins on an
|
||||
/// open subpath, the arc each joint between segments paints ([`round_join_box`]), a shallow one
|
||||
/// included. A bevel stays inside the boxes of the segments it joins. `None` when `segs` is
|
||||
/// empty. Butt dashes stop inside the same box. The caps other than butt ones, the heads and
|
||||
/// miter tips are measured apart. A segment in the middle is measured only when its own box
|
||||
/// grown by `side`, which holds everything it paints, is not inside the box so far, which
|
||||
/// starts as `within` and the first and last segments' boxes.
|
||||
fn body_along(&self, segs: &[PathSeg], side: f64, within: Rect) -> Option<Rect> {
|
||||
let (first, last) = (segs.first()?, segs.last()?);
|
||||
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3));
|
||||
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3)).union(within);
|
||||
let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| {
|
||||
if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) }
|
||||
});
|
||||
@@ -217,24 +246,28 @@ impl StrokeLayer {
|
||||
}
|
||||
|
||||
/// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt
|
||||
/// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its
|
||||
/// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of
|
||||
/// projecting caps and the reach of the arrowheads round their end points.
|
||||
/// caps, and every subpath when the joins are bevels or miters, by [`Self::body_along`] with its
|
||||
/// caps, every other subpath by the box of its segments grown by its reach, with `tips` and,
|
||||
/// when `measure_tips`, the miter spikes the limit keeps, the corners of projecting caps and the
|
||||
/// reach of the arrowheads round their end points.
|
||||
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
|
||||
let els = bp.elements();
|
||||
let subs = subpaths(bp);
|
||||
let mut out = tips.map_or(bounds, |t| bounds.union(t));
|
||||
let mut side_max: f64 = 0.0;
|
||||
// Every subpath reaches evenly unless one is open and butt-capped; only then is each
|
||||
// subpath's own box needed.
|
||||
let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1);
|
||||
let mut even = even_only.then_some(bounds);
|
||||
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
|
||||
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
|
||||
// A butt cap stops at an open subpath's end, and a bevel, or a miter the limit bevels, at
|
||||
// the two segments' corners, so such a subpath is measured along its segments. Every
|
||||
// subpath reaches evenly unless one is measured that way; only then is each subpath's own
|
||||
// box needed.
|
||||
let even_only = !subs.iter().any(|s| self.stops_at_corners(s.1));
|
||||
let mut even = even_only.then_some(bounds);
|
||||
for (r, closed) in subs {
|
||||
let side = self.side_reach(closed);
|
||||
let butt = self.cap == LineCap::Butt && !closed;
|
||||
if !butt {
|
||||
let along = self.stops_at_corners(closed);
|
||||
if !along {
|
||||
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
|
||||
}
|
||||
if side <= 0.0 {
|
||||
@@ -242,10 +275,10 @@ impl StrokeLayer {
|
||||
}
|
||||
let square = self.cap == LineCap::Square && !closed;
|
||||
let miters = measure_tips && self.join == LineJoin::Miter;
|
||||
if !(butt || square || miters || !even_only) {
|
||||
if !(along || square || miters || !even_only) {
|
||||
continue;
|
||||
}
|
||||
let segs = drawn(&els[r]);
|
||||
let segs = drawn(&els[r.clone()]);
|
||||
if miters {
|
||||
for (at, t_in, t_out) in joints(&segs, closed) {
|
||||
if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) {
|
||||
@@ -253,13 +286,24 @@ impl StrokeLayer {
|
||||
}
|
||||
}
|
||||
}
|
||||
if butt {
|
||||
if let Some(body) = self.butt_body(&segs, side) {
|
||||
out = out.union(body);
|
||||
if along {
|
||||
// The path's bounds are in the box already, so only the segments that can reach
|
||||
// past them are measured.
|
||||
match self.body_along(&segs, side, out) {
|
||||
Some(body) => out = out.union(body),
|
||||
// A subpath with no length paints at most its caps' dot.
|
||||
None if !butt => {
|
||||
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
|
||||
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !even_only {
|
||||
if self.cap == LineCap::Round && !closed {
|
||||
for (at, _) in ends(&segs).into_iter().flatten() {
|
||||
out = out.union(Rect::from_center_size(at, (2.0 * side, 2.0 * side)));
|
||||
}
|
||||
}
|
||||
} else if !even_only {
|
||||
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
|
||||
}
|
||||
if square {
|
||||
@@ -279,7 +323,8 @@ impl StrokeLayer {
|
||||
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
|
||||
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
|
||||
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
|
||||
/// with butt caps does not reach past its ends ([`Self::butt_body`]).
|
||||
/// with butt caps does not reach past its ends, and a bevel does not reach round its corner
|
||||
/// ([`Self::body_along`]).
|
||||
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
|
||||
self.reach_along(bp, bounds, None, true)
|
||||
}
|
||||
@@ -329,6 +374,9 @@ impl StrokeLayer {
|
||||
let segs = drawn(&els[r]);
|
||||
let (half, region) = self.body(closed);
|
||||
let full = half * self.profile_max() * dash_caps.unwrap_or(1.0);
|
||||
// Past a butt cap or a bevel the stroke stops at the segments' corners. A width profile
|
||||
// keeps the round reach at the ends.
|
||||
let squared = self.profile.is_none() && self.stops_at_corners(closed);
|
||||
// Every segment near enough to reach `p`: with a width profile the wider side of a
|
||||
// farther segment can paint past the nearest one, so the nearest alone is not enough.
|
||||
let near = segs.iter().enumerate().filter_map(|(i, s)| {
|
||||
@@ -365,7 +413,8 @@ impl StrokeLayer {
|
||||
}
|
||||
})
|
||||
};
|
||||
if d <= half * factor.max(0.0) + tol && on_side(region, d) {
|
||||
if d <= half * factor.max(0.0) + tol && on_side(region, d) && (!squared || self.paints_at_end(&segs, closed, (i, nr.t), p, half, tol))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -393,6 +442,35 @@ impl StrokeLayer {
|
||||
false
|
||||
}
|
||||
|
||||
/// Does this stroke, where it stops at the corners of its segments ([`Self::stops_at_corners`]),
|
||||
/// paint `p`, which is within `side` (and `tol`) of segment `i` of the subpath `segs`
|
||||
/// (`closed`: a closed one) and nearest to it at `t`? It does when `p` is not past the end of
|
||||
/// the segment that `t` is at, by more than `tol`, and past it when a round cap or a round join
|
||||
/// paints there, when the path does not turn at that end, or when `p` is within `tol` of the
|
||||
/// bevel's triangle. Projecting caps and
|
||||
/// miter spikes are checked apart. A curve that bends more tightly than `side` ([`gentle`])
|
||||
/// counts as painting round its ends.
|
||||
fn paints_at_end(&self, segs: &[PathSeg], closed: bool, (i, t): (usize, f64), p: Point, side: f64, tol: f64) -> bool {
|
||||
let (n, at_start) = (segs.len(), t <= 1e-9);
|
||||
let Some(seg) = segs.get(i) else { return true };
|
||||
if (!at_start && t < 1.0 - 1e-9) || !(matches!(seg, PathSeg::Line(_)) || gentle(seg, side)) {
|
||||
return true;
|
||||
}
|
||||
let (at, out) = if at_start { (seg.start(), -tangent(seg, 0.0)) } else { (seg.end(), tangent(seg, 1.0)) };
|
||||
if (p - at).dot(out) <= tol {
|
||||
return true;
|
||||
}
|
||||
// The segment on the other side of this end, `None` at the end of an open subpath.
|
||||
let other = if at_start { (i > 0 || closed).then(|| (i + n - 1) % n) } else { (i + 1 < n || closed).then(|| (i + 1) % n) };
|
||||
let Some(other) = other.and_then(|o| segs.get(o)) else { return self.cap == LineCap::Round };
|
||||
if self.join == LineJoin::Round {
|
||||
return true;
|
||||
}
|
||||
let (t_in, t_out) = if at_start { (tangent(other, 1.0), tangent(seg, 0.0)) } else { (tangent(seg, 1.0), tangent(other, 0.0)) };
|
||||
// A joint where the path does not turn has no bevel: the stroke runs on through it.
|
||||
bevel(at, t_in, t_out, side).is_none_or(|([a, b], _)| in_convex(&[at, a, b], p, tol))
|
||||
}
|
||||
|
||||
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
|
||||
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
|
||||
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
|
||||
@@ -400,13 +478,15 @@ impl StrokeLayer {
|
||||
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
|
||||
/// chord the path bends through under it, so anywhere within its length of the end.
|
||||
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
|
||||
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
|
||||
let Some(kind) = (if end { &self.end_arrow } else { &self.start_arrow }) else { return false };
|
||||
let (hw, v) = (self.arrow_weight(end), p - at);
|
||||
match self.arrow_align {
|
||||
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
|
||||
ArrowAlign::Extend => {
|
||||
let along = v.dot(out);
|
||||
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
|
||||
v.cross(out).abs() <= kind.half_width() * hw + tol
|
||||
&& along <= kind.length() * hw + self.width / 2.0 + tol
|
||||
&& along >= -kind.reach() * hw - tol
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -426,7 +506,7 @@ impl Appearance {
|
||||
}
|
||||
|
||||
/// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape
|
||||
/// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
|
||||
/// (miter spikes, bevels, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
|
||||
pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect {
|
||||
self.painted_strokes().fold(bounds, |acc, s| {
|
||||
if !s.needs_shape() {
|
||||
@@ -437,17 +517,21 @@ impl Appearance {
|
||||
})
|
||||
}
|
||||
|
||||
/// Does this appearance have a visible butt-capped stroke?
|
||||
pub fn has_butt_stroke(&self) -> bool {
|
||||
self.painted_strokes().any(|s| s.cap == LineCap::Butt)
|
||||
/// Does this appearance have a visible stroke that stops at the corners of its segments on an
|
||||
/// open subpath or a closed one, or paints miter spikes: butt caps, or bevel and miter joins
|
||||
/// ([`StrokeLayer::reaches_by_corners`])?
|
||||
pub fn has_cornered_stroke(&self) -> bool {
|
||||
self.painted_strokes().any(|s| s.reaches_by_corners(false))
|
||||
}
|
||||
|
||||
/// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with
|
||||
/// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
|
||||
/// visual box's margin at the stroke's corners there depends on their direction, which a scale
|
||||
/// out of proportion changes.
|
||||
pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
|
||||
if !self.has_butt_stroke() {
|
||||
/// Does a visible stroke of this appearance that stops at the corners of its segments (butt
|
||||
/// caps on an open subpath, bevel and miter joins) or paints miter spikes, dashed ones with
|
||||
/// round or projecting caps included, run along a subpath of `bp` where it does so, with a
|
||||
/// segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
|
||||
/// visual box's margin at those corners, and at miter tips, depends on their direction, which a
|
||||
/// scale out of proportion changes.
|
||||
pub fn has_slanted_stroke_corners(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
|
||||
if !self.has_cornered_stroke() {
|
||||
return false;
|
||||
}
|
||||
let slanted = |v: Vec2| {
|
||||
@@ -455,9 +539,10 @@ impl Appearance {
|
||||
(d.x * d.y).abs() > 1e-9
|
||||
};
|
||||
let els = bp.elements();
|
||||
subpaths(bp)
|
||||
.into_iter()
|
||||
.filter(|(_, closed)| !closed)
|
||||
let subs = subpaths(bp);
|
||||
let cornered = |closed: bool| self.painted_strokes().any(|s| s.reaches_by_corners(closed));
|
||||
subs.into_iter()
|
||||
.filter(|(_, closed)| cornered(*closed))
|
||||
.any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0))))
|
||||
}
|
||||
|
||||
@@ -468,28 +553,28 @@ impl Appearance {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object
|
||||
/// How many symbol instances [`crate::Node::has_slanted_stroke_corners`] looks into for one object
|
||||
/// before it answers yes without looking further.
|
||||
pub const SLANT_INSTANCES: usize = 4096;
|
||||
|
||||
impl crate::Node {
|
||||
/// Does a visible butt-capped stroke of this object, of an object in it or of an object in a
|
||||
/// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment
|
||||
/// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it
|
||||
/// answers yes.
|
||||
pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
|
||||
self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
|
||||
/// Does a visible stroke of this object, of an object in it or of an object in a symbol
|
||||
/// instance's art from `symbols`, placed by `a`, stop at the corners of a segment at a slant
|
||||
/// ([`Appearance::has_slanted_stroke_corners`])? Past [`SLANT_INSTANCES`] instances it answers
|
||||
/// yes.
|
||||
pub fn has_slanted_stroke_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
|
||||
self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
|
||||
}
|
||||
|
||||
/// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into.
|
||||
fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
|
||||
/// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into.
|
||||
fn slanted_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
|
||||
if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind {
|
||||
let Some(l) = left.get().checked_sub(1) else { return true };
|
||||
left.set(l);
|
||||
return symbols.measure_art(symbol, |art| art.slanted_butt(symbols, a * *xf, left)).unwrap_or(false);
|
||||
return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left)).unwrap_or(false);
|
||||
}
|
||||
(self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a)))
|
||||
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left)))
|
||||
(self.appearance.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_stroke_corners(&bp, a)))
|
||||
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,6 +651,79 @@ mod tests {
|
||||
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bevel_stops_at_the_corners_of_the_segments_it_joins() {
|
||||
// A 40 × 100 pt triangle stroked 20 pt: a miter limit of 2 or a bevel join bevels its
|
||||
// 22.6° tip at (20, 0), so the stroke reaches 10 · 20 / √10400 pt above it, not 10 pt.
|
||||
let mut tri = BezPath::new();
|
||||
tri.move_to((0.0, 100.0));
|
||||
tri.line_to((20.0, 0.0));
|
||||
tri.line_to((40.0, 100.0));
|
||||
tri.close_path();
|
||||
let tb = tri.bounding_box();
|
||||
let (top, side) = (-200.0 / 10400.0_f64.sqrt(), 1000.0 / 10400.0_f64.sqrt());
|
||||
let limited = stroke(20.0, |s| s.miter_limit = 2.0);
|
||||
let bevel = stroke(20.0, |s| {
|
||||
s.join = LineJoin::Bevel;
|
||||
s.cap = LineCap::Round;
|
||||
});
|
||||
let b = limited.bounds_on(&tri, tb);
|
||||
assert!((b.y0 - top).abs() < 1e-9, "{b:?}");
|
||||
// The limit keeps the base corners' miters, whose tips reach about 12.2 pt left and right.
|
||||
assert!(b.x0 < -12.0 && b.x1 > 52.0, "{b:?}");
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 20.0);
|
||||
*ap.stroke_mut().unwrap() = bevel.clone();
|
||||
let b = ap.stroked_bounds(tb, || tri.clone());
|
||||
for (got, want) in [(b.x0, -side), (b.y0, top), (b.x1, 40.0 + side), (b.y1, 110.0)] {
|
||||
assert!((got - want).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
// Open, the same corner is beveled and the round caps reach the half weight round the ends.
|
||||
let chevron = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
|
||||
let b = bevel.bounds_on(&chevron, chevron.bounding_box());
|
||||
for (got, want) in [(b.x0, -10.0), (b.y0, top), (b.x1, 50.0), (b.y1, 110.0)] {
|
||||
assert!((got - want).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
// A round join, and the round caps of dashes, which can end at the tip, reach round it.
|
||||
let round = stroke(20.0, |s| s.join = LineJoin::Round);
|
||||
assert!((round.bounds_on(&tri, tb).y0 + 10.0).abs() < 1e-9);
|
||||
let mut dashed = bevel.clone();
|
||||
dashed.dash = Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false });
|
||||
assert!((dashed.bounds_on(&chevron, chevron.bounding_box()).y0 + 10.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_past_a_bevel_or_a_butt_end_misses() {
|
||||
// 5 pt above the triangle's tip is within the half weight of it, but past the bevel, which
|
||||
// reaches about 1.96 pt above it. A round join paints there.
|
||||
let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
|
||||
tri.close_path();
|
||||
let (above, on) = (Point::new(20.0, -5.0), Point::new(20.0, -1.5));
|
||||
for join in [LineJoin::Bevel, LineJoin::Miter] {
|
||||
let st = stroke(20.0, |s| (s.join, s.miter_limit) = (join, 2.0));
|
||||
assert!(!st.hits(&tri, FillRule::NonZero, above, 0.5), "{join:?}");
|
||||
assert!(st.hits(&tri, FillRule::NonZero, on, 0.0), "{join:?}");
|
||||
}
|
||||
assert!(stroke(20.0, |s| s.join = LineJoin::Round).hits(&tri, FillRule::NonZero, above, 0.5));
|
||||
// 1.5 pt past a butt end of a 4 pt line misses, and a quarter point within it hits; a round
|
||||
// cap paints past it.
|
||||
let line = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
|
||||
let butt = stroke(4.0, |s| s.cap = LineCap::Butt);
|
||||
assert!(!butt.hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25));
|
||||
assert!(butt.hits(&line, FillRule::NonZero, Point::new(1.0, -0.2), 0.25));
|
||||
assert!(stroke(4.0, |s| s.cap = LineCap::Round).hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_joint_too_shallow_to_bevel_paints_past_both_segments_ends() {
|
||||
// The path turns by about 0.57° at (100, -0.5), too little to bevel, so the stroke runs on
|
||||
// through the joint: 3.5 pt above it is past the end of both segments and still painted.
|
||||
let kink = polyline(&[(0.0, 0.0), (100.0, -0.5), (200.0, 0.0)]);
|
||||
let above = Point::new(100.0, -4.0);
|
||||
for join in [LineJoin::Bevel, LineJoin::Miter, LineJoin::Round] {
|
||||
assert!(stroke(10.0, |s| s.join = join).hits(&kink, FillRule::NonZero, above, 0.0), "{join:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An open path through `points`.
|
||||
fn polyline(points: &[(f64, f64)]) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
@@ -691,15 +849,25 @@ mod tests {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
|
||||
ap.stroke_mut().unwrap().cap = LineCap::Butt;
|
||||
let id = vectorcraft_geom::Affine::IDENTITY;
|
||||
assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
|
||||
assert!(!ap.has_slanted_stroke_corners(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
|
||||
// Square ends, slanted segments in the middle.
|
||||
let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]);
|
||||
assert!(ap.has_slanted_butt_stroke(&apex, id));
|
||||
// A rotation slants a vertical line; a round cap is never slanted.
|
||||
assert!(ap.has_slanted_stroke_corners(&apex, id));
|
||||
// A rotation slants a vertical line.
|
||||
let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
|
||||
assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3)));
|
||||
assert!(ap.has_slanted_stroke_corners(&v, vectorcraft_geom::Affine::rotate(0.3)));
|
||||
// With round caps, the miter join still stops at the corners of the slanted segments, on a
|
||||
// closed path too; round caps and round joins never do.
|
||||
ap.stroke_mut().unwrap().cap = LineCap::Round;
|
||||
assert!(!ap.has_slanted_butt_stroke(&apex, id));
|
||||
assert!(ap.has_slanted_stroke_corners(&apex, id));
|
||||
let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
|
||||
tri.close_path();
|
||||
ap.stroke_mut().unwrap().join = LineJoin::Bevel;
|
||||
assert!(ap.has_slanted_stroke_corners(&tri, id));
|
||||
assert!(!ap.has_slanted_stroke_corners(&square(), id));
|
||||
ap.stroke_mut().unwrap().join = LineJoin::Round;
|
||||
assert!(!ap.has_slanted_stroke_corners(&apex, id));
|
||||
assert!(!ap.has_slanted_stroke_corners(&tri, id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -723,11 +891,11 @@ mod tests {
|
||||
}
|
||||
let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let symbols = d.symbol_boxes();
|
||||
assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY));
|
||||
assert!(top.has_slanted_stroke_corners(&symbols, vectorcraft_geom::Affine::IDENTITY));
|
||||
assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured());
|
||||
// One instance of S1 holds three instances, all looked into.
|
||||
let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
|
||||
assert!(!one.has_slanted_stroke_corners(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,533 @@
|
||||
//! Separated images: an image whose inks come as one plate each (a DCS file placed linked), kept
|
||||
//! as a TIFF of several images. The first is the composite, the plates mixed into CMYK
|
||||
//! ([`Separated::composite`]), which every reader of a CMYK TIFF sees. Each later image is one
|
||||
//! plate's ink amounts in grayscale (0 is no ink), with its ink's name and CMYK equivalent in its
|
||||
//! ImageDescription. Print separations take each plate from these ([`Separated::coverage`]).
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::cms::PROCESS_PLATES;
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
use crate::ImageBlob;
|
||||
use crate::cmyk::{Inks, MAX_CMYK_PIXELS};
|
||||
|
||||
/// Most plates a separated image holds.
|
||||
pub const MAX_PLATES: usize = 64;
|
||||
/// Most directories a separated image's TIFF holds: its composite and its plates.
|
||||
const MAX_DIRECTORIES: usize = MAX_PLATES + 1;
|
||||
/// Longest ink name kept (bytes).
|
||||
pub const MAX_NAME: usize = 255;
|
||||
/// Most ink amounts the plates of one image hold together (512 MB).
|
||||
pub const MAX_SAMPLES: u64 = 1 << 29;
|
||||
/// How a plate's ImageDescription starts.
|
||||
const MARK: &str = "VectorCraft plate ";
|
||||
|
||||
/// How the composite's ImageDescription starts when plates were read from files of their own.
|
||||
const FILES_MARK: &str = "VectorCraft plate files";
|
||||
|
||||
/// A plate file of its own that a separated image was read from, as it was then: a change to it
|
||||
/// changes the image as a change to the DCS file does.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PlateFile {
|
||||
/// Its file name, in the DCS file's folder.
|
||||
pub name: String,
|
||||
/// Its size (bytes).
|
||||
pub size: u64,
|
||||
/// Its modification time (ms since the Unix epoch; 0 when the file system keeps none).
|
||||
pub modified: u64,
|
||||
}
|
||||
|
||||
/// `text` in hexadecimal (TIFF text is ASCII).
|
||||
fn hex(text: &str) -> String {
|
||||
text.bytes().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// The text [`hex`] wrote, of at most `max` bytes.
|
||||
fn unhex(hex: &str, max: usize) -> Option<String> {
|
||||
if !hex.len().is_multiple_of(2) || hex.len() > max * 2 {
|
||||
return None;
|
||||
}
|
||||
let bytes: Option<Vec<u8>> = (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok()).collect();
|
||||
String::from_utf8(bytes?).ok()
|
||||
}
|
||||
|
||||
/// One ink's plate: its ink amounts, one byte a pixel (0 is none, 255 is solid), row by row from
|
||||
/// the top.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct InkPlate {
|
||||
/// "Cyan", "Magenta", "Yellow", "Black", or a spot ink's name.
|
||||
pub name: String,
|
||||
/// The process inks the ink stands for (C, M, Y, K, 0..1): one process ink at 100% for a
|
||||
/// process plate.
|
||||
pub cmyk: [f32; 4],
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl InkPlate {
|
||||
/// Is it a spot ink's plate (not one of the four process inks)?
|
||||
pub fn spot(&self) -> bool {
|
||||
!PROCESS_PLATES.contains(&self.name.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// The plates of a separated image, all of one size.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Separated {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub plates: Vec<InkPlate>,
|
||||
}
|
||||
|
||||
impl Separated {
|
||||
/// `plates` as a `width` × `height` image; `None` when there are none or more than
|
||||
/// [`MAX_PLATES`], two have the same name, a name is empty or longer than [`MAX_NAME`], a plate
|
||||
/// doesn't hold that many pixels, an equivalent isn't within 0..1, or the image is empty, has
|
||||
/// more than [`MAX_CMYK_PIXELS`], or its plates together hold more than [`MAX_SAMPLES`]
|
||||
/// ([`Self::fits`]). A process plate's equivalent is its own ink.
|
||||
pub fn new(width: u32, height: u32, mut plates: Vec<InkPlate>) -> Option<Self> {
|
||||
let n = u64::from(width) * u64::from(height);
|
||||
if !Self::fits(width, height, plates.len()) {
|
||||
return None;
|
||||
}
|
||||
for p in plates.iter_mut() {
|
||||
if p.name.is_empty() || p.name.len() > MAX_NAME || p.data.len() as u64 != n {
|
||||
return None;
|
||||
}
|
||||
if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == p.name) {
|
||||
p.cmyk = [0.0; 4];
|
||||
p.cmyk[j] = 1.0;
|
||||
}
|
||||
if !p.cmyk.iter().all(|v| (0.0..=1.0).contains(v)) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
if !plates.iter().all(|p| names.insert(p.name.as_str())) {
|
||||
return None;
|
||||
}
|
||||
Some(Self { width, height, plates })
|
||||
}
|
||||
|
||||
/// May an image of `width` × `height` pixels hold `plates` plates? Not when it is empty, has
|
||||
/// more than [`MAX_CMYK_PIXELS`], has no plate or more than [`MAX_PLATES`], or the plates
|
||||
/// together would hold more than [`MAX_SAMPLES`].
|
||||
pub fn fits(width: u32, height: u32, plates: usize) -> bool {
|
||||
let n = u64::from(width) * u64::from(height);
|
||||
n > 0 && n <= MAX_CMYK_PIXELS && (1..=MAX_PLATES).contains(&plates) && n * plates as u64 <= MAX_SAMPLES
|
||||
}
|
||||
|
||||
/// The plates of spot inks.
|
||||
pub fn spots(&self) -> impl Iterator<Item = &InkPlate> {
|
||||
self.plates.iter().filter(|p| p.spot())
|
||||
}
|
||||
|
||||
/// The plates mixed into process inks: each plate's ink amount times its equivalent, the
|
||||
/// plates over one another as inks print (`1 − (1 − a)(1 − b)` for each process ink).
|
||||
pub fn composite(&self) -> Inks {
|
||||
let n = self.data_len();
|
||||
let mut data = vec![0u8; n * 4];
|
||||
for (i, px) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let mut clear = [1.0f32; 4];
|
||||
for p in &self.plates {
|
||||
let t = f32::from(p.data[i]) / 255.0;
|
||||
for (c, e) in clear.iter_mut().zip(p.cmyk) {
|
||||
*c *= 1.0 - t * e;
|
||||
}
|
||||
}
|
||||
for (o, c) in px.iter_mut().zip(clear) {
|
||||
*o = ((1.0 - c) * 255.0).round() as u8;
|
||||
}
|
||||
}
|
||||
Inks { width: self.width, height: self.height, data }
|
||||
}
|
||||
|
||||
/// The ink amounts that print on plate `plate` (a process ink's name or a spot ink's), one byte
|
||||
/// a pixel. A spot plate for which `own` is true prints on its own plate only; every other spot
|
||||
/// plate (the job prints no plate of that name) prints as its process equivalent, mixed as
|
||||
/// [`Self::composite`] mixes it. A plate name the image has no plate for, and a spot plate that
|
||||
/// prints as process, print nothing.
|
||||
pub fn coverage(&self, plate: &str, own: &dyn Fn(&str) -> bool) -> Vec<u8> {
|
||||
self.coverage_as(plate, own, &|p| p.cmyk)
|
||||
}
|
||||
|
||||
/// [`Self::coverage`], a spot plate that prints as process printing as the process inks
|
||||
/// `equivalent` gives it (the document's swatch of its ink, when there is one).
|
||||
pub fn coverage_as(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Vec<u8> {
|
||||
let n = self.data_len();
|
||||
if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == plate) {
|
||||
let mixed: Vec<(&InkPlate, f32)> = self
|
||||
.plates
|
||||
.iter()
|
||||
.filter(|p| !p.spot() || !own(&p.name))
|
||||
.map(|p| (p, if p.spot() { equivalent(p)[j].clamp(0.0, 1.0) } else { p.cmyk[j] }))
|
||||
.filter(|(_, e)| *e > 0.0)
|
||||
.collect();
|
||||
return (0..n)
|
||||
.map(|i| {
|
||||
let clear = mixed.iter().fold(1.0f32, |c, (p, e)| c * (1.0 - f32::from(p.data[i]) / 255.0 * e));
|
||||
((1.0 - clear) * 255.0).round() as u8
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
match self.plates.iter().find(|p| p.name == plate && p.spot() && own(&p.name)) {
|
||||
Some(p) => p.data.clone(),
|
||||
None => vec![0; n],
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::coverage_as`] as a grayscale PNG, black for solid ink and white for none, as a plate
|
||||
/// prints; `None` when it can't be written.
|
||||
pub fn plate_png(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Option<ImageBlob> {
|
||||
let gray: Vec<u8> = self.coverage_as(plate, own, equivalent).into_iter().map(|v| 255 - v).collect();
|
||||
let img = image::GrayImage::from_raw(self.width, self.height, gray)?;
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some(ImageBlob::png(png))
|
||||
}
|
||||
|
||||
fn data_len(&self) -> usize {
|
||||
self.width as usize * self.height as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// A plate's ImageDescription: the mark, its equivalent and its name in hexadecimal (TIFF text is
|
||||
/// ASCII).
|
||||
fn description(p: &InkPlate) -> String {
|
||||
let [c, m, y, k] = p.cmyk;
|
||||
format!("{MARK}{c} {m} {y} {k} {}", hex(&p.name))
|
||||
}
|
||||
|
||||
/// A plate's name and equivalent from its ImageDescription; `None` when it isn't one.
|
||||
fn parse_description(s: &str) -> Option<(String, [f32; 4])> {
|
||||
let rest = s.strip_prefix(MARK)?;
|
||||
let mut words = rest.split(' ');
|
||||
let mut cmyk = [0.0f32; 4];
|
||||
for v in &mut cmyk {
|
||||
*v = words.next()?.parse().ok().filter(|v: &f32| v.is_finite())?;
|
||||
}
|
||||
let name = unhex(words.next()?, MAX_NAME)?;
|
||||
words.next().is_none().then_some((name, cmyk))
|
||||
}
|
||||
|
||||
/// Longest plate file name kept (bytes).
|
||||
const MAX_FILE_NAME: usize = 4096;
|
||||
|
||||
/// The composite's ImageDescription line for `files`: the mark, then each file's name in
|
||||
/// hexadecimal, its size and its modification time.
|
||||
fn files_description(files: &[PlateFile]) -> String {
|
||||
let mut out = String::from(FILES_MARK);
|
||||
for f in files.iter().take(MAX_PLATES) {
|
||||
out.push_str(&format!(" {} {} {}", hex(&f.name), f.size, f.modified));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How the composite's ImageDescription line holding the clipping path starts.
|
||||
const CLIP_MARK: &str = "VectorCraft clip ";
|
||||
|
||||
/// Longest clipping path kept (bytes of its JSON).
|
||||
const MAX_CLIP: usize = 16 << 20;
|
||||
|
||||
/// The composite's ImageDescription line for clipping path `clip`: the mark, then the path's JSON
|
||||
/// in hexadecimal; `None` when it is longer than [`MAX_CLIP`].
|
||||
fn clip_description(clip: &PathData) -> Option<String> {
|
||||
let json = serde_json::to_string(clip).ok().filter(|j| j.len() <= MAX_CLIP)?;
|
||||
Some(format!("{CLIP_MARK}{}", hex(&json)))
|
||||
}
|
||||
|
||||
/// The plate files of a composite's ImageDescription; none when it isn't one.
|
||||
fn parse_files(s: &str) -> Vec<PlateFile> {
|
||||
let Some(rest) = s.lines().find_map(|l| l.strip_prefix(FILES_MARK)) else { return vec![] };
|
||||
let words: Vec<&str> = rest.split(' ').filter(|w| !w.is_empty()).collect();
|
||||
let file =
|
||||
|w: &[&str]| Some(PlateFile { name: unhex(w.first()?, MAX_FILE_NAME)?, size: w.get(1)?.parse().ok()?, modified: w.get(2)?.parse().ok()? });
|
||||
words.chunks(3).take(MAX_PLATES).filter_map(file).collect()
|
||||
}
|
||||
|
||||
impl ImageBlob {
|
||||
/// A TIFF of separated image `s`: its composite in CMYK, then its plates (Deflate-compressed),
|
||||
/// declaring the resolution `ppi` when it is given and both are finite and above 0, and noting
|
||||
/// `files`, the plate files of their own the plates were read from ([`Self::plate_files`]);
|
||||
/// `None` when it can't be written.
|
||||
pub fn separated_tiff(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile]) -> Option<Self> {
|
||||
Self::separated_tiff_clipped(s, ppi, files, None)
|
||||
}
|
||||
|
||||
/// [`Self::separated_tiff`], noting `clip` too, the clipping path its file draws it through, in
|
||||
/// its pixel space ([`Self::separated_clip`]).
|
||||
pub fn separated_tiff_clipped(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile], clip: Option<&PathData>) -> Option<Self> {
|
||||
use tiff::encoder::{Compression, Rational, TiffEncoder, colortype, compression::DeflateLevel};
|
||||
use tiff::tags::{ResolutionUnit, Tag};
|
||||
let ppi = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0));
|
||||
// Ten-thousandths of a pixel per inch.
|
||||
let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced));
|
||||
let mut img = enc.new_image::<colortype::CMYK8>(s.width, s.height).ok()?;
|
||||
if let Some((x, y)) = ppi {
|
||||
img.encoder().write_tag(Tag::XResolution, r(x)).ok()?;
|
||||
img.encoder().write_tag(Tag::YResolution, r(y)).ok()?;
|
||||
img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?;
|
||||
}
|
||||
// One line for the plate files, one for the clipping path.
|
||||
let lines: Vec<String> =
|
||||
[(!files.is_empty()).then(|| files_description(files)), clip.and_then(clip_description)].into_iter().flatten().collect();
|
||||
if !lines.is_empty() {
|
||||
img.encoder().write_tag(Tag::ImageDescription, lines.join("\n").as_str()).ok()?;
|
||||
}
|
||||
img.write_data(&s.composite().data).ok()?;
|
||||
for p in &s.plates {
|
||||
// White is no ink, so a viewer that shows a plate shows it as it prints.
|
||||
let mut img = enc.new_image::<colortype::Gray8>(s.width, s.height).ok()?;
|
||||
img.encoder().write_tag(Tag::ImageDescription, description(p).as_str()).ok()?;
|
||||
let inverted: Vec<u8> = p.data.iter().map(|v| 255 - v).collect();
|
||||
img.write_data(&inverted).ok()?;
|
||||
}
|
||||
Some(Self::new("image/tiff", out.into_inner()))
|
||||
}
|
||||
|
||||
/// Does the image hold plates ([`ImageBlob::separated_tiff`]), at most [`MAX_PLATES`] of them?
|
||||
/// One with more, or with more directories than its composite and [`MAX_PLATES`] plates, is the
|
||||
/// CMYK image of its composite only, as [`Self::separated`] refuses it. Reads only the TIFF's
|
||||
/// directories, at most [`MAX_DIRECTORIES`].
|
||||
pub fn is_separated(&self) -> bool {
|
||||
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return false };
|
||||
let (mut plates, mut directories) = (0usize, 1usize);
|
||||
while d.more_images() {
|
||||
directories += 1;
|
||||
if directories > MAX_DIRECTORIES || d.next_image().is_err() {
|
||||
return false;
|
||||
}
|
||||
if d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().is_some_and(|s| s.starts_with(MARK)) {
|
||||
plates += 1;
|
||||
if plates > MAX_PLATES {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
plates > 0
|
||||
}
|
||||
|
||||
/// The plate files of their own a separated image was read from, as they were then; none for
|
||||
/// other images. Reads only the TIFF's first directory.
|
||||
pub fn plate_files(&self) -> Vec<PlateFile> {
|
||||
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] };
|
||||
d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().map(parse_files).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The clipping path a separated image's file draws it through, in its pixel space, as
|
||||
/// [`Self::separated_tiff_clipped`] noted it; `None` for other images. Reads only the TIFF's
|
||||
/// first directory.
|
||||
pub fn separated_clip(&self) -> Option<PathData> {
|
||||
let (_, mut d) = crate::cmyk::tiff(&self.bytes)?;
|
||||
let text = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok()?;
|
||||
let json = unhex(text.lines().find_map(|l| l.strip_prefix(CLIP_MARK))?, MAX_CLIP)?;
|
||||
serde_json::from_str(&json).ok()
|
||||
}
|
||||
|
||||
/// The spot inks a separated image has plates for, each with its CMYK equivalent; none for
|
||||
/// other images. Reads only the TIFF's directories.
|
||||
pub fn spot_plates(&self) -> Vec<(String, [f32; 4])> {
|
||||
if !self.is_separated() {
|
||||
return vec![];
|
||||
}
|
||||
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] };
|
||||
let mut inks = vec![];
|
||||
while d.more_images() && inks.len() < MAX_PLATES {
|
||||
if d.next_image().is_err() {
|
||||
break;
|
||||
}
|
||||
let plate = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description);
|
||||
inks.extend(plate.filter(|(name, _)| !PROCESS_PLATES.contains(&name.as_str())));
|
||||
}
|
||||
inks
|
||||
}
|
||||
|
||||
/// The plates of a separated image; `None` for other images, and ones whose plates can't be
|
||||
/// read. The plates of the last image read are kept for the next call (print separates one
|
||||
/// image plate after plate).
|
||||
pub fn separated(&self) -> Option<Arc<Separated>> {
|
||||
thread_local! {
|
||||
static LAST: std::cell::RefCell<Option<(String, Arc<Separated>)>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
if !self.is_separated() {
|
||||
return None;
|
||||
}
|
||||
let key = self.content_key();
|
||||
LAST.with_borrow_mut(|last| match last {
|
||||
Some((k, s)) if *k == key => Some(s.clone()),
|
||||
_ => {
|
||||
let s = Arc::new(read_plates(&self.bytes)?);
|
||||
*last = Some((key, s.clone()));
|
||||
Some(s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The plates of TIFF `bytes`, each the size of its first image.
|
||||
fn read_plates(bytes: &[u8]) -> Option<Separated> {
|
||||
let (_, mut d) = crate::cmyk::tiff(bytes)?;
|
||||
let (w, h) = d.dimensions().ok()?;
|
||||
let n = usize::try_from(u64::from(w) * u64::from(h)).ok()?;
|
||||
let mut plates = vec![];
|
||||
// Every plate is read: a file with more than [`MAX_PLATES`] is refused ([`Separated::fits`]),
|
||||
// not cut short, and so is one with more than [`MAX_DIRECTORIES`] directories.
|
||||
let mut directories = 1usize;
|
||||
while d.more_images() {
|
||||
directories += 1;
|
||||
if directories > MAX_DIRECTORIES {
|
||||
return None;
|
||||
}
|
||||
d.next_image().ok()?;
|
||||
let Some((name, cmyk)) = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description) else {
|
||||
continue;
|
||||
};
|
||||
// Checked before the plate is decoded.
|
||||
if d.dimensions().ok()? != (w, h) || !matches!(d.colortype().ok()?, tiff::ColorType::Gray(8)) || !Separated::fits(w, h, plates.len() + 1) {
|
||||
return None;
|
||||
}
|
||||
let data = crate::cmyk::read_samples(&mut d, n, 1)?.into_iter().map(|v| 255 - v).collect();
|
||||
plates.push(InkPlate { name, cmyk, data });
|
||||
}
|
||||
Separated::new(w, h, plates)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn plate(name: &str, cmyk: [f32; 4], data: &[u8]) -> InkPlate {
|
||||
InkPlate { name: name.into(), cmyk, data: data.to_vec() }
|
||||
}
|
||||
|
||||
/// Two pixels: cyan 100% and a spot ink at 50% on the first, nothing on the second.
|
||||
fn two() -> Separated {
|
||||
let plates = vec![plate("Cyan", [0.0; 4], &[255, 0]), plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], &[128, 0])];
|
||||
Separated::new(2, 1, plates).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plates_mix_into_the_composite_as_inks_print() {
|
||||
let s = two();
|
||||
assert_eq!(s.plates[0].cmyk, [1.0, 0.0, 0.0, 0.0], "a process plate stands for its own ink");
|
||||
let c = s.composite();
|
||||
// Magenta: 0.6 × 128/255; yellow: 128/255.
|
||||
assert_eq!(&c.data[..4], &[255, 77, 128, 0]);
|
||||
assert_eq!(&c.data[4..], &[0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_plate_prints_on_its_own_plate_or_as_process() {
|
||||
let s = two();
|
||||
let own = |_: &str| true;
|
||||
assert_eq!(s.coverage("Spot Orange", &own), [128, 0]);
|
||||
assert_eq!(s.coverage("Magenta", &own), [0, 0], "nothing of the spot on a process plate");
|
||||
assert_eq!(s.coverage("Cyan", &own), [255, 0]);
|
||||
assert_eq!(s.coverage("Black", &own), [0, 0]);
|
||||
let process = |_: &str| false;
|
||||
assert_eq!(s.coverage("Spot Orange", &process), [0, 0]);
|
||||
assert_eq!(s.coverage("Magenta", &process), [77, 0]);
|
||||
assert_eq!(s.coverage("Yellow", &process), [128, 0]);
|
||||
assert_eq!(s.coverage("Other", &own), [0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tiff_keeps_every_plate_and_shows_the_composite() {
|
||||
let s = two();
|
||||
let files =
|
||||
[PlateFile { name: "pic (1).C".into(), size: 1234, modified: 1_700_000_000_000 }, PlateFile { name: "ü.K".into(), size: 0, modified: 0 }];
|
||||
let b = ImageBlob::separated_tiff(&s, Some((300.0, 300.0)), &files).unwrap();
|
||||
assert_eq!(b.plate_files(), files);
|
||||
assert!(ImageBlob::separated_tiff(&s, None, &[]).unwrap().plate_files().is_empty());
|
||||
assert!(b.is_separated());
|
||||
assert!(b.is_cmyk(), "readers of a CMYK TIFF see the composite");
|
||||
assert_eq!(b.cmyk(), Some(s.composite()));
|
||||
assert_eq!(*b.separated().unwrap(), s);
|
||||
assert_eq!(b.spot_plates(), [("Spot Orange".to_string(), [0.0, 0.6, 1.0, 0.0])]);
|
||||
assert!(ImageBlob::cmyk_tiff(&s.composite()).unwrap().spot_plates().is_empty());
|
||||
assert!(!ImageBlob::cmyk_tiff(&s.composite()).unwrap().is_separated());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tiff_keeps_the_clipping_path_beside_the_plate_files() {
|
||||
let s = two();
|
||||
let clip = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 1.5, 1.0));
|
||||
let files = [PlateFile { name: "a.C".into(), size: 1, modified: 2 }];
|
||||
let b = ImageBlob::separated_tiff_clipped(&s, None, &files, Some(&clip)).unwrap();
|
||||
assert_eq!(b.separated_clip(), Some(clip.clone()));
|
||||
assert_eq!(b.plate_files(), files);
|
||||
let alone = ImageBlob::separated_tiff_clipped(&s, None, &[], Some(&clip)).unwrap();
|
||||
assert_eq!(alone.separated_clip(), Some(clip));
|
||||
assert!(alone.plate_files().is_empty());
|
||||
assert_eq!(ImageBlob::separated_tiff(&s, None, &files).unwrap().separated_clip(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiff_with_more_plates_than_are_read_is_refused() {
|
||||
use tiff::encoder::{TiffEncoder, colortype};
|
||||
let tiff = |plates: usize| {
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let mut enc = TiffEncoder::new(&mut out).unwrap();
|
||||
enc.write_image::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
|
||||
for i in 0..plates {
|
||||
let mut img = enc.new_image::<colortype::Gray8>(1, 1).unwrap();
|
||||
img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate(&format!("S{i}"), [0.0; 4], &[0])).as_str()).unwrap();
|
||||
img.write_data(&[255]).unwrap();
|
||||
}
|
||||
ImageBlob::new("image/tiff", out.into_inner())
|
||||
};
|
||||
assert_eq!(tiff(MAX_PLATES).separated().map(|s| s.plates.len()), Some(MAX_PLATES));
|
||||
let over = tiff(MAX_PLATES + 1);
|
||||
assert!(over.separated().is_none(), "not cut short to the first {MAX_PLATES}");
|
||||
assert!(!over.is_separated() && over.spot_plates().is_empty(), "the CMYK image of its composite only");
|
||||
assert!(tiff(MAX_PLATES).is_separated());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiff_with_more_directories_than_a_composite_and_its_plates_is_refused() {
|
||||
use tiff::encoder::{TiffEncoder, colortype};
|
||||
let tiff = |others: usize| {
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let mut enc = TiffEncoder::new(&mut out).unwrap();
|
||||
enc.write_image::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
|
||||
let mut img = enc.new_image::<colortype::Gray8>(1, 1).unwrap();
|
||||
img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate("S", [0.0; 4], &[0])).as_str()).unwrap();
|
||||
img.write_data(&[255]).unwrap();
|
||||
// Directories that are not plates.
|
||||
for _ in 0..others {
|
||||
enc.write_image::<colortype::Gray8>(1, 1, &[255]).unwrap();
|
||||
}
|
||||
ImageBlob::new("image/tiff", out.into_inner())
|
||||
};
|
||||
let most = tiff(MAX_PLATES - 1);
|
||||
assert!(most.is_separated() && most.separated().is_some());
|
||||
let over = tiff(MAX_PLATES);
|
||||
assert!(!over.is_separated() && over.separated().is_none() && over.spot_plates().is_empty());
|
||||
assert!(read_plates(&over.bytes).is_none(), "read_plates stops at the limit too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_that_are_not_ascii_are_kept() {
|
||||
let s = Separated::new(1, 1, vec![plate("Grün 100 % (A)", [0.5, 0.0, 1.0, 0.0], &[9])]).unwrap();
|
||||
let b = ImageBlob::separated_tiff(&s, None, &[]).unwrap();
|
||||
assert_eq!(b.separated().unwrap().plates[0].name, "Grün 100 % (A)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_plates_are_refused() {
|
||||
assert!(Separated::new(2, 1, vec![]).is_none(), "no plates");
|
||||
assert!(Separated::new(2, 1, vec![plate("Cyan", [0.0; 4], &[1])]).is_none(), "too few pixels");
|
||||
assert!(Separated::new(1, 1, vec![plate("A", [0.0; 4], &[1]), plate("A", [0.0; 4], &[1])]).is_none(), "the same name twice");
|
||||
assert!(Separated::new(1, 1, vec![plate("", [0.0; 4], &[1])]).is_none(), "no name");
|
||||
assert!(Separated::new(1, 1, vec![plate("A", [2.0, 0.0, 0.0, 0.0], &[1])]).is_none(), "equivalent past 100%");
|
||||
assert!(Separated::new(0, 1, vec![plate("A", [0.0; 4], &[])]).is_none(), "empty");
|
||||
let many: Vec<InkPlate> = (0..=MAX_PLATES).map(|i| plate(&format!("S{i}"), [0.0; 4], &[1])).collect();
|
||||
assert!(Separated::new(1, 1, many).is_none(), "too many plates");
|
||||
assert!(Separated::fits(1 << 13, 1 << 13, 8), "512 MB of ink amounts");
|
||||
assert!(!Separated::fits(1 << 13, 1 << 13, 9), "more than 512 MB together");
|
||||
assert!(!Separated::fits(1 << 14, 1 << 13, 1), "more pixels than a CMYK image is decoded with");
|
||||
}
|
||||
}
|
||||
+159
-42
@@ -5,7 +5,7 @@
|
||||
//! tint (`Paint::Solid.swatch` / `.tint`, `GradientStop.swatch` / `.tint`); a tint swatch is a
|
||||
//! swatch whose own paint links to its base that way. [`Document::map_solid_paints`] rewrites
|
||||
//! those links (and colours) wherever art and swatches hold them, copying only the nodes that
|
||||
//! change.
|
||||
//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
@@ -124,6 +124,52 @@ impl Document {
|
||||
/// ([`Paint::map_links`]). Only nodes holding a changed paint (and the paths to them) are
|
||||
/// copied. Returns the number of changed paints.
|
||||
pub fn map_solid_paints(&mut self, f: &mut LinkFn) -> usize {
|
||||
let mut n = self.map_art_paints(&mut relink(f));
|
||||
for gs in &mut self.graphic_styles {
|
||||
for it in &mut gs.appearance.items {
|
||||
n += usize::from(item_paint_mut(it).map_links(f));
|
||||
}
|
||||
}
|
||||
for w in self.swatches_iter_mut() {
|
||||
n += usize::from(w.paint.map_links(f));
|
||||
}
|
||||
let mut g = relink(f);
|
||||
for def in &mut self.char_styles {
|
||||
for key in ["fill", "stroke"] {
|
||||
n += usize::from(map_style_paint(&mut def.attrs, key, &mut g));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Visit every paint in the places [`Document::map_solid_paints`] visits (fills, strokes, text
|
||||
/// runs, image colorize paints, dynamic symbol instances' own paints and graphs' stored series and
|
||||
/// label paints in the art, opacity masks included, symbol definitions, graph designs, pattern tiles and the tile that pattern
|
||||
/// editing's Cancel puts back; graphic styles; the swatches; character styles' fill and
|
||||
/// stroke), whatever its kind. `f(paint)` gives the paint to put in its place, or `None` to keep
|
||||
/// it. Only nodes holding a changed paint (and the paths to them) are copied. Returns the number
|
||||
/// of changed paints.
|
||||
pub fn map_paints(&mut self, f: &mut PaintFn) -> usize {
|
||||
let mut n = self.map_art_paints(f);
|
||||
for gs in &mut self.graphic_styles {
|
||||
for it in &mut gs.appearance.items {
|
||||
n += usize::from(replace_paint(item_paint_mut(it), f));
|
||||
}
|
||||
}
|
||||
for w in self.swatches_iter_mut() {
|
||||
n += usize::from(replace_paint(&mut w.paint, f));
|
||||
}
|
||||
for def in &mut self.char_styles {
|
||||
for key in ["fill", "stroke"] {
|
||||
n += usize::from(map_style_paint(&mut def.attrs, key, f));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// [`Document::map_paints`] limited to the node trees: the art, symbol definitions, graph
|
||||
/// designs, pattern tiles and the tile that pattern editing's Cancel puts back.
|
||||
fn map_art_paints(&mut self, f: &mut PaintFn) -> usize {
|
||||
let mut n = map_trees(&mut self.layers, f);
|
||||
for s in &mut self.symbols {
|
||||
n += map_tree(&mut s.art, f);
|
||||
@@ -134,19 +180,6 @@ impl Document {
|
||||
for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) {
|
||||
n += map_trees(&mut p.art, f);
|
||||
}
|
||||
for gs in &mut self.graphic_styles {
|
||||
for it in &mut gs.appearance.items {
|
||||
n += usize::from(item_paint_mut(it).map_links(f));
|
||||
}
|
||||
}
|
||||
for w in self.swatches_iter_mut() {
|
||||
n += usize::from(w.paint.map_links(f));
|
||||
}
|
||||
for def in &mut self.char_styles {
|
||||
for key in ["fill", "stroke"] {
|
||||
n += usize::from(map_style_paint(&mut def.attrs, key, f));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
@@ -156,9 +189,10 @@ impl Document {
|
||||
let roots: Vec<NodeId> =
|
||||
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
|
||||
let mut n = 0;
|
||||
let mut g = relink(f);
|
||||
for id in roots {
|
||||
let Some(node) = self.node(id) else { continue };
|
||||
if let Some((new, count)) = map_node(node, f)
|
||||
if let Some((new, count)) = map_node(node, &mut g)
|
||||
&& let Some(slot) = self.node_mut(id)
|
||||
{
|
||||
*slot = new;
|
||||
@@ -176,7 +210,7 @@ impl Document {
|
||||
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
|
||||
let mut tree = |n: &Node| {
|
||||
walk_with_masks(n, &mut |m| {
|
||||
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
|
||||
node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f);
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
|
||||
}
|
||||
@@ -258,14 +292,39 @@ impl FreeSwatchNames {
|
||||
/// true when it changed them.
|
||||
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
|
||||
|
||||
/// Apply `f` to the paint a character style's attribute `key` holds, as [`Paint::map_links`]
|
||||
/// does, and store the result in the attribute. True when it changed.
|
||||
fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut LinkFn) -> bool {
|
||||
let Some(value) = attrs.get_mut(key) else { return false };
|
||||
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { return false };
|
||||
if !paint.map_links(f) {
|
||||
return false;
|
||||
/// What [`Document::map_paints`] applies to each paint: the paint to put in its place, or `None`
|
||||
/// to keep it.
|
||||
pub type PaintFn<'a> = dyn FnMut(&Paint) -> Option<Paint> + 'a;
|
||||
|
||||
/// `f` as a [`PaintFn`]: a solid or gradient paint with `f` applied ([`Paint::map_links`]) when
|
||||
/// `f` changed it, `None` for every other paint.
|
||||
fn relink<'a>(f: &'a mut LinkFn<'_>) -> impl FnMut(&Paint) -> Option<Paint> + 'a {
|
||||
move |p| match p {
|
||||
Paint::Solid { .. } | Paint::Gradient(_) => {
|
||||
let mut q = p.clone();
|
||||
q.map_links(f).then_some(q)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `f(p)` in place of `p` when it gives a paint. True when it did.
|
||||
fn replace_paint(p: &mut Paint, f: &mut PaintFn) -> bool {
|
||||
match f(p) {
|
||||
Some(q) => {
|
||||
*p = q;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply `f` to the paint a character style's attribute `key` holds and store the result in the
|
||||
/// attribute. An attribute that is not a paint stays as it is. True when it changed.
|
||||
fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut PaintFn) -> bool {
|
||||
let Some(value) = attrs.get_mut(key) else { return false };
|
||||
let Ok(paint) = serde_json::from_value::<Paint>(value.clone()) else { return false };
|
||||
let Some(paint) = f(&paint) else { return false };
|
||||
match serde_json::to_value(&paint) {
|
||||
Ok(changed) => {
|
||||
*value = changed;
|
||||
@@ -323,6 +382,23 @@ pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
|
||||
}
|
||||
|
||||
/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its
|
||||
/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out.
|
||||
pub fn graph_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
let g = n.extras().graph.as_deref();
|
||||
let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten();
|
||||
let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten();
|
||||
series.chain(labels.flat_map(|st| [&st.fill, &st.stroke]))
|
||||
}
|
||||
|
||||
/// Mutable [`graph_paints`] of graph `g`, in the same order.
|
||||
fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mut Paint> {
|
||||
let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten();
|
||||
let l = &mut g.label_styles;
|
||||
let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten();
|
||||
series.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke]))
|
||||
}
|
||||
|
||||
/// Mutable [`node_paints`], in the same order.
|
||||
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
|
||||
let runs = match &mut n.kind {
|
||||
@@ -333,20 +409,11 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
|
||||
n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])).chain(colorize)
|
||||
}
|
||||
|
||||
/// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then
|
||||
/// nothing was copied). Also returns the number of changed paints.
|
||||
fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
|
||||
// Try each own solid or gradient paint on a scratch copy first, so unchanged nodes are never
|
||||
// cloned.
|
||||
let mut changes: Vec<(usize, Paint)> = vec![];
|
||||
for (i, p) in node_paints(n).enumerate() {
|
||||
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) {
|
||||
let mut q = p.clone();
|
||||
if q.map_links(f) {
|
||||
changes.push((i, q));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `n` with `f` applied to its subtree's paints, or `None` when nothing changed (then nothing was
|
||||
/// copied). Also returns the number of changed paints.
|
||||
fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> {
|
||||
// `f` gives each own paint's replacement first, so unchanged nodes are never cloned.
|
||||
let changes: Vec<(usize, Paint)> = node_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
|
||||
let mut count = changes.len();
|
||||
let mut out: Option<Node> = None;
|
||||
if !changes.is_empty() {
|
||||
@@ -366,15 +433,29 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
|
||||
let mut overrides = n.extras().symbol_overrides.clone();
|
||||
let mut k = 0;
|
||||
for p in overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
|
||||
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) && p.map_links(f) {
|
||||
k += 1;
|
||||
}
|
||||
k += usize::from(replace_paint(p, f));
|
||||
}
|
||||
if k > 0 {
|
||||
out.get_or_insert_with(|| n.clone()).extras_mut().symbol_overrides = overrides;
|
||||
count += k;
|
||||
}
|
||||
}
|
||||
// A graph's series and label paints, which its marks and labels take when it is drawn again.
|
||||
let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
|
||||
if !graph.is_empty() {
|
||||
count += graph.len();
|
||||
let m = out.get_or_insert_with(|| n.clone());
|
||||
if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
|
||||
let mut graph = graph.into_iter().peekable();
|
||||
for (i, p) in graph_paints_mut(spec).enumerate() {
|
||||
if graph.peek().is_some_and(|c| c.0 == i)
|
||||
&& let Some((_, q)) = graph.next()
|
||||
{
|
||||
*p = q;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children() {
|
||||
for (i, c) in ch.iter().enumerate() {
|
||||
if let Some((new, k)) = map_node(c, f) {
|
||||
@@ -415,6 +496,13 @@ pub fn walk_with_masks<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) {
|
||||
/// brush: `f` applied to the linkable colors of `n` and its subtree (opacity masks included). Only
|
||||
/// the nodes holding a changed paint are copied. Returns the number of changed paints.
|
||||
pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize {
|
||||
map_node_paints(n, &mut relink(f))
|
||||
}
|
||||
|
||||
/// [`Document::map_paints`] for art a document keeps outside its trees, such as the art of a brush:
|
||||
/// `f` applied to every paint of `n` and its subtree (opacity masks included). Only the nodes
|
||||
/// holding a changed paint are copied. Returns the number of changed paints.
|
||||
pub fn map_node_paints(n: &mut Node, f: &mut PaintFn) -> usize {
|
||||
match map_node(n, f) {
|
||||
Some((new, count)) => {
|
||||
*n = new;
|
||||
@@ -424,7 +512,7 @@ pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize {
|
||||
fn map_tree(n: &mut Arc<Node>, f: &mut PaintFn) -> usize {
|
||||
match map_node(n, f) {
|
||||
Some((new, count)) => {
|
||||
*n = Arc::new(new);
|
||||
@@ -434,7 +522,7 @@ fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
fn map_trees(v: &mut [Arc<Node>], f: &mut LinkFn) -> usize {
|
||||
fn map_trees(v: &mut [Arc<Node>], f: &mut PaintFn) -> usize {
|
||||
v.iter_mut().map(|n| map_tree(n, f)).sum()
|
||||
}
|
||||
|
||||
@@ -593,6 +681,35 @@ mod tests {
|
||||
assert_eq!(map_node_solid_paints(&mut loose, &mut to_blue), 0, "nothing left to change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_reaches_the_series_and_label_paints_a_graph_keeps() {
|
||||
let (mut d, a, _) = doc();
|
||||
let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand");
|
||||
let spec = crate::graph::GraphSpec {
|
||||
series_paints: vec![crate::SeriesPaint { fill: Some(red.clone()), stroke: Some(red.clone()), ..Default::default() }],
|
||||
label_styles: crate::graph::LabelStyles {
|
||||
legend: Some(crate::CharStyle { fill: red.clone(), stroke: Paint::None, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
|
||||
let mut seen = 0;
|
||||
d.visit_paints(&mut |p| seen += usize::from(*p == red));
|
||||
assert_eq!(seen, 4, "the fill and the graph's series fill, series stroke and legend fill");
|
||||
let blue = Color::rgb(0.0, 0.0, 1.0);
|
||||
let mut to_blue = |c: &mut Color, s: &mut Option<String>, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue;
|
||||
assert_eq!(d.map_solid_paints(&mut to_blue), 4);
|
||||
let g = d.node(a).unwrap().extras().graph.clone().unwrap();
|
||||
assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand")));
|
||||
assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand")));
|
||||
let legend = g.label_styles.legend.unwrap();
|
||||
assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None));
|
||||
let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None);
|
||||
assert_eq!(d.map_paints(&mut cleared), 4, "the fill and the graph's three");
|
||||
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_within_ids_visits_each_paint_once() {
|
||||
let (mut d, a, b) = doc();
|
||||
|
||||
@@ -17,7 +17,7 @@ mod wrap;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
|
||||
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics};
|
||||
pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
|
||||
CompositeParts,
|
||||
|
||||
@@ -34,6 +34,16 @@ pub struct CharStyle {
|
||||
/// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect.
|
||||
#[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub kerning_before: f64,
|
||||
/// Insert Aki Left (Character panel, East Asian options): space added before the character in
|
||||
/// reading order, in 1/1000 em as [`Self::tracking`], 0 to 1000. Before is on the left in
|
||||
/// left-to-right type, on the right in right-to-left type and above in vertical type. A
|
||||
/// cluster takes the value of its first character, and full justification leaves it as it is.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
#[serde(default, rename = "akiLeft", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub aki_left: f64,
|
||||
/// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`].
|
||||
#[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub aki_right: f64,
|
||||
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
|
||||
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub optical_kerning: bool,
|
||||
@@ -57,7 +67,9 @@ pub struct CharStyle {
|
||||
#[serde(default)]
|
||||
pub all_caps: bool,
|
||||
/// OpenType features that differ from the defaults (OpenType panel), as tags: `"dlig"` turns
|
||||
/// a feature on, `"-liga"` off.
|
||||
/// a feature on, `"-liga"` off, and `"salt=2"` turns a feature with alternates on at the font's
|
||||
/// alternate number 2 (the value the shaper gets; a plain `"salt"` is value 1). Runs that
|
||||
/// differ only in this list are shaped together, each with its own features.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub features: Vec<String>,
|
||||
/// Character style (Character Styles panel) these attributes come from; None = Normal.
|
||||
@@ -402,6 +414,9 @@ fn hundred() -> f64 {
|
||||
100.0
|
||||
}
|
||||
|
||||
/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em.
|
||||
pub const MAX_AKI: f64 = 1000.0;
|
||||
|
||||
pub(super) fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
@@ -418,6 +433,8 @@ impl Default for CharStyle {
|
||||
tracking: 0.0,
|
||||
kerning: None,
|
||||
kerning_before: 0.0,
|
||||
aki_left: 0.0,
|
||||
aki_right: 0.0,
|
||||
optical_kerning: false,
|
||||
baseline_shift: 0.0,
|
||||
h_scale: 100.0,
|
||||
@@ -466,7 +483,8 @@ impl CharStyle {
|
||||
/// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way)
|
||||
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
|
||||
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
|
||||
/// offsets are kept as the baseline shift is.
|
||||
/// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to
|
||||
/// [`MAX_AKI`], and one that is not a number becomes 0.
|
||||
pub fn keep_dimensions_in_range(&mut self) {
|
||||
let default = Self::default();
|
||||
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
|
||||
@@ -478,6 +496,9 @@ impl CharStyle {
|
||||
self.baseline_shift = shift(self.baseline_shift);
|
||||
self.tcy_up_down = shift(self.tcy_up_down);
|
||||
self.tcy_left_right = shift(self.tcy_left_right);
|
||||
let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) };
|
||||
self.aki_left = aki(self.aki_left);
|
||||
self.aki_right = aki(self.aki_right);
|
||||
}
|
||||
/// Do the characters draw a stroke (a paint and a positive weight)?
|
||||
pub fn has_stroke(&self) -> bool {
|
||||
|
||||
@@ -490,6 +490,8 @@ impl crate::Document {
|
||||
st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift);
|
||||
st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down);
|
||||
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
|
||||
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
|
||||
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
|
||||
st.keep_dimensions_in_range();
|
||||
let kept = [
|
||||
("size", Some(st.size)),
|
||||
@@ -498,6 +500,8 @@ impl crate::Document {
|
||||
("baseline_shift", Some(st.baseline_shift)),
|
||||
("tcyUpDown", Some(st.tcy_up_down)),
|
||||
("tcyLeftRight", Some(st.tcy_left_right)),
|
||||
("akiLeft", Some(st.aki_left)),
|
||||
("akiRight", Some(st.aki_right)),
|
||||
("leading", st.leading),
|
||||
];
|
||||
for (k, v) in kept {
|
||||
|
||||
@@ -237,6 +237,10 @@ pub struct ParaStyle {
|
||||
/// 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,
|
||||
/// Bunri-Kinshi (Paragraph panel menu): a line never breaks inside an inseparable pair (two em
|
||||
/// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept
|
||||
/// with kinsoku None, where it has no effect. Off by default.
|
||||
pub bunri_kinshi: bool,
|
||||
/// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and
|
||||
/// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses,
|
||||
/// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari.
|
||||
@@ -339,6 +343,8 @@ struct ParaStyleFile {
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
bunri_kinshi: bool,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
roman_hanging: bool,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kashida: Kashida,
|
||||
@@ -375,6 +381,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -401,6 +408,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -431,6 +439,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -456,6 +465,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -498,6 +508,21 @@ pub enum Mojikumi {
|
||||
/// Consecutive punctuation shares one half-em space (JLREQ 3.1.4), and a closing bracket,
|
||||
/// comma or full stop ending a line is set half width.
|
||||
LineEndHalf,
|
||||
/// YakumonoHankaku: every opening and closing bracket, comma and full stop is set half width,
|
||||
/// a middle dot loses a quarter em on each side, and a quarter em separates Japanese and Latin
|
||||
/// letters or digits.
|
||||
YakumonoHankaku,
|
||||
/// GyomatsuYakumonoHankaku: punctuation keeps its full width, except that an opening bracket
|
||||
/// starting a line is set flush with the line's start, a closing bracket, comma or full stop
|
||||
/// ending a line is set half width and a middle dot ending a line loses the quarter em after
|
||||
/// it; a quarter em separates Japanese and Latin letters or digits.
|
||||
GyomatsuYakumonoHankaku,
|
||||
/// GyomatsuYakumonoZenkaku: punctuation keeps its full width at a line's end too; a quarter em
|
||||
/// separates Japanese and Latin letters or digits.
|
||||
GyomatsuYakumonoZenkaku,
|
||||
/// YakumonoZenkaku: punctuation keeps its full width, with no added space between Japanese and
|
||||
/// Latin text.
|
||||
YakumonoZenkaku,
|
||||
}
|
||||
|
||||
impl Mojikumi {
|
||||
|
||||
@@ -357,7 +357,7 @@ impl ParaList {
|
||||
|
||||
/// The style the marker is set in: `first` (the style of the paragraph's first character)
|
||||
/// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning,
|
||||
/// tate-chu-yoko, underline and strikethrough.
|
||||
/// Insert Aki, tate-chu-yoko, underline and strikethrough.
|
||||
pub fn marker_style(first: &CharStyle) -> CharStyle {
|
||||
CharStyle {
|
||||
baseline_shift: 0.0,
|
||||
@@ -366,6 +366,8 @@ impl ParaList {
|
||||
tracking: 0.0,
|
||||
kerning: None,
|
||||
kerning_before: 0.0,
|
||||
aki_left: 0.0,
|
||||
aki_right: 0.0,
|
||||
optical_kerning: first.optical_kerning,
|
||||
tate_chu_yoko: false,
|
||||
underline: false,
|
||||
|
||||
@@ -92,6 +92,43 @@ fn font_height_reference_is_saved_only_when_not_the_em_box() {
|
||||
assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().font_height_reference, FontHeightReference::EmBox);
|
||||
}
|
||||
|
||||
/// Insert Aki Left and Right are 0 by default and saved only when not 0, each side on its own;
|
||||
/// styles written before them read as 0, and a value out of range from a file is kept from 0 to one
|
||||
/// em.
|
||||
#[test]
|
||||
fn insert_aki_is_saved_only_when_set() {
|
||||
let st = CharStyle::default();
|
||||
assert_eq!((st.aki_left, st.aki_right), (0.0, 0.0));
|
||||
let saved = serde_json::to_value(&st).unwrap();
|
||||
assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none());
|
||||
for set in [
|
||||
CharStyle { aki_left: 250.0, ..CharStyle::default() },
|
||||
CharStyle { aki_right: 500.0, ..CharStyle::default() },
|
||||
CharStyle { aki_left: 125.5, aki_right: 1000.0, ..CharStyle::default() },
|
||||
] {
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!(saved.get("akiLeft").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_left);
|
||||
assert_eq!(saved.get("akiRight").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_right);
|
||||
assert_eq!(saved.get("akiLeft").is_some(), set.aki_left != 0.0);
|
||||
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
|
||||
}
|
||||
let old = serde_json::to_value(&st).unwrap();
|
||||
let read = serde_json::from_value::<CharStyle>(old).unwrap();
|
||||
assert_eq!((read.aki_left, read.aki_right), (0.0, 0.0));
|
||||
let mut damaged = CharStyle { aki_left: -20.0, aki_right: 4000.0, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
|
||||
let mut damaged = CharStyle { aki_left: f64::NAN, aki_right: f64::INFINITY, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
|
||||
// A character style from a file is kept in range the same way.
|
||||
let mut d = crate::Document::new(100.0, 100.0);
|
||||
let attrs = serde_json::json!({"akiLeft": 5000, "akiRight": -1});
|
||||
d.char_styles.push(TextStyleDef { name: "Spaced".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
|
||||
d.keep_type_values_in_range();
|
||||
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
|
||||
}
|
||||
|
||||
/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its
|
||||
/// script's block; every system saves under its id, which reads back, and other names are refused.
|
||||
#[test]
|
||||
|
||||
@@ -15,6 +15,7 @@ vectorcraft-doc = { workspace = true }
|
||||
vectorcraft-pathops = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
vectorcraft-trace = { workspace = true }
|
||||
image = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
|
||||
@@ -26,3 +27,5 @@ serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
vectorcraft-color = { workspace = true }
|
||||
# A face built in code from the bundled Source Sans 3 (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
@@ -435,11 +435,19 @@ impl ColorVisitor for Live<'_, '_> {
|
||||
/// adjustments of an object `n` is the art of) on everything it paints. The adjustment effects
|
||||
/// are gone from the result; embedded images take the keys `images` gives. `swatches` tells the
|
||||
/// document's global and spot swatches apart ([`crate::addons::duotone::swatch_kind`]).
|
||||
pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images: &mut ImageHook<'_>) -> Option<Node> {
|
||||
/// `has_image` tells whether the document holds an image: an image whose color mask's pixels are
|
||||
/// missing is recoloured from its own pixels, as it is drawn without the adjustment.
|
||||
pub fn adjust(
|
||||
n: &Node,
|
||||
outer: Option<&ColorMap>,
|
||||
swatches: &SwatchKinds,
|
||||
images: &mut ImageHook<'_>,
|
||||
has_image: &dyn Fn(&str) -> bool,
|
||||
) -> Option<Node> {
|
||||
let mut m: Option<Node> = None;
|
||||
if let Some(ch) = n.children() {
|
||||
for (i, c) in ch.iter().enumerate() {
|
||||
if let Some(new) = adjust(c, None, swatches, images)
|
||||
if let Some(new) = adjust(c, None, swatches, images, has_image)
|
||||
&& let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i))
|
||||
{
|
||||
*slot = Arc::new(new);
|
||||
@@ -462,11 +470,57 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images
|
||||
if let Some(map) = map {
|
||||
let mm = m.get_or_insert_with(|| n.clone());
|
||||
mm.appearance.effects.retain(|e| !is_adjustment(&e.id));
|
||||
show_color_masks(mm, has_image);
|
||||
recolor_node(mm, Reach::ALL, &mut Live { map: &map, swatches, images });
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Whether `n` is an image that [`recolor_node`] recolours (embedded, not colorized, without
|
||||
/// pixels of its own) with a color mask made from its pixels.
|
||||
fn recoloured_with_mask(n: &Node) -> bool {
|
||||
match (&n.kind, Document::color_mask_of(n)) {
|
||||
(NodeKind::Image(im), Some(m)) => im.link.is_none() && n.extras().colorize.is_none() && m.made_for(im),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` is or holds an image [`recoloured_with_mask`] counts.
|
||||
fn holds_recoloured_with_mask(n: &Node) -> bool {
|
||||
recoloured_with_mask(n) || n.children().is_some_and(|ch| ch.iter().any(|c| holds_recoloured_with_mask(c)))
|
||||
}
|
||||
|
||||
/// Give each image in `n` that [`recoloured_with_mask`] counts its masked pixels as its own,
|
||||
/// without the mask, so [`recolor_node`] recolours the pixels it shows and the colors the mask
|
||||
/// hides stay hidden. An image whose masked pixels the document does not hold (`has_image`) is
|
||||
/// drawn from its own pixels ([`Document::shown_image`]): it keeps its key and loses the mask, so
|
||||
/// the recoloured copy is drawn the same way.
|
||||
fn show_color_masks(n: &mut Node, has_image: &dyn Fn(&str) -> bool) {
|
||||
if recoloured_with_mask(n)
|
||||
&& let Some(masked) = Document::color_mask_of(n).map(|m| m.key.clone())
|
||||
{
|
||||
if let NodeKind::Image(im) = &mut n.kind
|
||||
&& has_image(&masked)
|
||||
{
|
||||
im.key = masked;
|
||||
}
|
||||
n.extras_mut().color_mask = None;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if holds_recoloured_with_mask(c) {
|
||||
show_color_masks(Arc::make_mut(c), has_image);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys of the masked pixels of the color masks in `n` and its members.
|
||||
fn color_mask_keys<'a>(n: &'a Node, out: &mut Vec<&'a str>) {
|
||||
out.extend(Document::color_mask_of(n).map(|m| m.key.as_str()));
|
||||
for c in n.children().into_iter().flatten() {
|
||||
color_mask_keys(c, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in
|
||||
/// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art`
|
||||
/// when given, otherwise the symbol's art with the instance's own appearance changes.
|
||||
@@ -482,13 +536,16 @@ pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option<Node>)
|
||||
_ => n,
|
||||
};
|
||||
let kinds = crate::addons::duotone::swatch_kinds(d);
|
||||
let mut masked = vec![];
|
||||
color_mask_keys(src, &mut masked);
|
||||
masked.retain(|k| d.images.contains_key(*k));
|
||||
let mut hook = |key: &str, map: &ColorMap| -> Option<String> {
|
||||
let blob = d.images.get(key)?.map_rgb(|rgb| map.apply_rgb8(rgb))?;
|
||||
let k = blob.content_key();
|
||||
d.images.entry(k.clone()).or_insert(blob);
|
||||
Some(k)
|
||||
};
|
||||
adjust(src, None, &|name| kinds.get(name).copied(), &mut hook)
|
||||
adjust(src, None, &|name| kinds.get(name).copied(), &mut hook, &|key| masked.contains(&key))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -551,17 +608,17 @@ mod tests {
|
||||
let mut g = Node::group(NodeId(1), vec![leaf(2), leaf(3)]);
|
||||
g.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true });
|
||||
assert!(has_adjustment(&g));
|
||||
let out = adjust(&g, None, &|_| None, &mut |_, _| None).unwrap();
|
||||
let out = adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
|
||||
assert!(out.appearance.effects.is_empty());
|
||||
for c in out.children().unwrap() {
|
||||
assert_eq!(c.appearance.fill_paint().color().unwrap().to_hex(), "#00ff00");
|
||||
}
|
||||
// A hidden effect does nothing; a stroke's own effect recolours just that stroke.
|
||||
g.appearance.effects[0].visible = false;
|
||||
assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None).is_none());
|
||||
assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).is_none());
|
||||
let mut p = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
p.appearance.items[1].effects_mut().push(Effect { id: "adjust.levels".into(), params: json!({"outputBlack": 255}), visible: true });
|
||||
let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap();
|
||||
let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
|
||||
assert_eq!(out.appearance.items[1].paint().color().unwrap().to_hex(), "#ffffff");
|
||||
assert_eq!(out.appearance.items[0].paint(), p.appearance.items[0].paint());
|
||||
assert!(out.appearance.items[1].effects().is_empty());
|
||||
@@ -576,7 +633,7 @@ mod tests {
|
||||
let fill = Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0);
|
||||
let mut p = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill);
|
||||
p.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true });
|
||||
let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap();
|
||||
let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
|
||||
let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
// The points are what a freeform gradient draws from, not its stops.
|
||||
let hexes: Vec<String> = g.freeform.as_ref().unwrap().points.iter().map(|p| p.color.to_hex()).collect();
|
||||
|
||||
@@ -29,7 +29,7 @@ use crate::group::{has_own_paint, paints};
|
||||
use crate::reshape::{as_art, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
|
||||
use crate::{
|
||||
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
|
||||
has_item_geometry, has_pathfinder, is_geometry, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
|
||||
has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
|
||||
};
|
||||
|
||||
fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] {
|
||||
@@ -41,8 +41,8 @@ fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] {
|
||||
|
||||
fn clear_item_effects(item: &mut AppearanceItem) {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => f.effects.retain(|e| !is_geometry(&e.id)),
|
||||
AppearanceItem::Stroke(s) => s.effects.retain(|e| !is_geometry(&e.id)),
|
||||
AppearanceItem::Fill(f) => f.effects = crate::raster::without_geometry(&f.effects),
|
||||
AppearanceItem::Stroke(s) => s.effects = crate::raster::without_geometry(&s.effects),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,15 @@ fn path_kind(d: &mut Document, path: PathData, rule: FillRule) -> NodeKind {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// How many symbol instances deep [`bake_node`] is baking, through the art of instances whose
|
||||
/// effects reshape it.
|
||||
static INSTANCE_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// The objects of symbol art that [`bake_document`] has baked for instances inside the art of
|
||||
/// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`].
|
||||
static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged).
|
||||
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
|
||||
@@ -143,8 +152,27 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// Instances baked inside the art of others stop at the depth limit, or once their art
|
||||
// passes the objects one export bakes that way: an instance of a symbol whose art holds
|
||||
// instances of itself is kept as it is there.
|
||||
let instance = matches!(n.kind, NodeKind::SymbolInstance { .. });
|
||||
if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 {
|
||||
let count = symbol.as_ref().map_or(0, |a| a.count() as u64);
|
||||
let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count);
|
||||
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES {
|
||||
return None;
|
||||
}
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
}
|
||||
let m = reshape(Some(d), n, symbol.as_ref())?;
|
||||
return Some(bake_node(d, &m).unwrap_or(m));
|
||||
if instance {
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() + 1));
|
||||
}
|
||||
let baked = bake_node(d, &m);
|
||||
if instance {
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() - 1));
|
||||
}
|
||||
return Some(baked.unwrap_or(m));
|
||||
}
|
||||
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
|
||||
// patterns: each copy an object of its own, so its gradient fits it rather than spanning
|
||||
@@ -337,7 +365,7 @@ fn moved_type_group(n: &Node) -> Option<Node> {
|
||||
g.knockout = Knockout::Off;
|
||||
g.knockout_shape = n.knockout_shape;
|
||||
g.extras_mut().mask = n.extras().mask.clone();
|
||||
g.appearance.effects = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
|
||||
g.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
|
||||
Some(g)
|
||||
}
|
||||
|
||||
@@ -397,7 +425,8 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
return None;
|
||||
}
|
||||
reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d));
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id));
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
|
||||
m.appearance.items.clear();
|
||||
m.appearance.contents_index = None;
|
||||
Some(m)
|
||||
@@ -439,7 +468,9 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> {
|
||||
if carry.moves(&m.appearance) {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
m.appearance.effects.retain(|e| !is_geometry(&e.id));
|
||||
// The raster effects of its fills and strokes follow its Transform effects, as on the canvas.
|
||||
crate::raster::follow_items(&mut m);
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
Some((g, rule, ctx, m))
|
||||
}
|
||||
|
||||
@@ -528,7 +559,9 @@ fn hoist_transparency(mut p: Node) -> Node {
|
||||
}
|
||||
|
||||
/// [`expand_leaf`] every path and compound path in `n` (art made for Expand Appearance, such as a
|
||||
/// group's own fills and strokes or outlined type), in place.
|
||||
/// group's own fills and strokes or outlined type), in place. A group or layer in it with an
|
||||
/// appearance of its own ([`crate::has_container_appearance`]) is first made into the art that
|
||||
/// appearance paints ([`crate::evaluate_container`]).
|
||||
pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
|
||||
if matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
|
||||
if let Some(m) = expand_leaf(d, n, stroke_art) {
|
||||
@@ -536,6 +569,11 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if crate::has_container_appearance(n)
|
||||
&& let Some(m) = crate::evaluate_container(Some(&*d), n)
|
||||
{
|
||||
*n = m;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
expand_art(d, Arc::make_mut(c), stroke_art);
|
||||
}
|
||||
@@ -658,6 +696,7 @@ pub fn bake_document(doc: &Document) -> Option<Document> {
|
||||
};
|
||||
}
|
||||
let mut d = placed.into_owned();
|
||||
NESTED_NODES.with(|c| c.set(0));
|
||||
let layers = d.layers.clone();
|
||||
d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect();
|
||||
Some(d)
|
||||
|
||||
@@ -94,6 +94,8 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"stylize.glowingEdges" => always(&["edgeWidth", "smoothness"]),
|
||||
"brushStrokes.accentedEdges" => always(&["edgeWidth"]),
|
||||
"artistic.paletteKnife" => always(&["strokeSize"]),
|
||||
"artistic.coloredPencil" => always(&["pencilWidth"]),
|
||||
"artistic.paintDaubs" => always(&["brushSize"]),
|
||||
"brushStrokes.angledStrokes" | "brushStrokes.crosshatch" | "brushStrokes.inkOutlines" => always(&["strokeLength"]),
|
||||
"brushStrokes.spatter" => always(&["sprayRadius"]),
|
||||
"brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]),
|
||||
@@ -187,8 +189,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), 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), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), 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, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), 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), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), 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, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
|
||||
),
|
||||
g(
|
||||
INFLATE,
|
||||
@@ -201,8 +203,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
ROTATE,
|
||||
"Rotate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{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), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), 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, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
|
||||
"{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), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), 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, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_EXTRUDE,
|
||||
@@ -258,14 +260,14 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"distort.roughen",
|
||||
"Roughen…",
|
||||
DT,
|
||||
"{size: 0..100 (5), relative: bool (true: % of size; false: pt), detail: per inch 0..100 (10), points: \"smooth\"|\"corner\", seed: int (0)}",
|
||||
"{size: 0..100 (5; 0 keeps the outline and adds its points along it), relative: bool (true: % of size; false: pt), detail: per inch 0..100 (10), points: \"smooth\"|\"corner\", seed: int (0)}",
|
||||
json!({"size": 5.0, "relative": true, "detail": 10.0, "points": "smooth", "seed": 0}),
|
||||
),
|
||||
g(
|
||||
"distort.transform",
|
||||
"Transform…",
|
||||
DT,
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}",
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
|
||||
),
|
||||
g(
|
||||
@@ -294,7 +296,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"path.outlineObject",
|
||||
"Outline Object",
|
||||
PATH,
|
||||
"{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change",
|
||||
"{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change. On an image's own fill or stroke it gives the outline of the image's pixels that are at least half opaque (VectorCraft's own cutoff), and nothing when no pixel is; it gives the image's frame when the image has no transparency, its pixels can't be read, or the image or its outline is too large to trace",
|
||||
json!({}),
|
||||
),
|
||||
g(
|
||||
@@ -387,7 +389,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"artistic.paintDaubs",
|
||||
"Paint Daubs…",
|
||||
ARTISTIC,
|
||||
"{brushSize: 1..50 (10; dab centres farther apart), sharpness: 0..40 (25; harder dab edges), brushType: \"simple\"|\"lightRough\"|\"darkRough\"|\"wideSharp\"|\"wideBlurry\"|\"sparkle\" (\"simple\")} repaints the object with thick round brush dabs in the local colours, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.",
|
||||
"{brushSize: 1..50 (10; spacing of the dab centers in document units),sharpness: 0..40 (25; harder dab edges), brushType: \"simple\"|\"lightRough\"|\"darkRough\"|\"wideSharp\"|\"wideBlurry\"|\"sparkle\" (\"simple\")} repaints the object with thick round brush dabs in the local colours, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.",
|
||||
json!({"brushSize": 10.0, "sharpness": 25.0, "brushType": "simple"}),
|
||||
),
|
||||
r(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPath, Vec2};
|
||||
use vectorcraft_pathops::addons::pathtools::insert_at;
|
||||
|
||||
use crate::util::{catmull_rom, fit_piece, flag, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points};
|
||||
|
||||
@@ -79,7 +80,8 @@ const MAX_ROUGHEN_POINTS: usize = 2000;
|
||||
|
||||
/// Roughen: resample at `detail` points per inch and jitter each point by up to `size`. Where
|
||||
/// that would make more than `max` anchors, the points are spaced further apart until it doesn't
|
||||
/// (stacked Roughens multiply their points, #3578).
|
||||
/// (stacked Roughens multiply their points, #3578). At size 0 no point moves: each segment is
|
||||
/// split into its pieces, evenly along its length, and the outline stays as it is.
|
||||
pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
|
||||
let size = num(p, "size", 5.0).clamp(0.0, 1e4);
|
||||
let amp = if flag(p, "relative", true) { size / 100.0 * mean_size(b) } else { size };
|
||||
@@ -89,6 +91,23 @@ pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
|
||||
let lens: Vec<f64> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i).arclen(0.1))).collect();
|
||||
let spacing = fit_piece(&lens, spacing, MAX_ROUGHEN_POINTS, max.saturating_sub(path.anchor_count()));
|
||||
let mut lens = lens.iter();
|
||||
if amp == 0.0 {
|
||||
// Each segment's pieces, cut at equal lengths as `pathtools::add_points` cuts them.
|
||||
let mut subs = Vec::with_capacity(path.subpaths.len());
|
||||
for sp in &path.subpaths {
|
||||
let mut places = vec![];
|
||||
for (i, &coarse) in (0..sp.segment_count()).zip(&mut lens) {
|
||||
let k = pieces(coarse, spacing, MAX_ROUGHEN_POINTS);
|
||||
let c = sp.segment(i);
|
||||
let len = c.arclen(ROUGHEN_ARCLEN_ACCURACY);
|
||||
if len > 1e-9 && len.is_finite() {
|
||||
places.extend((1..k).map(|j| (i, c.inv_arclen(len * j as f64 / k as f64, ROUGHEN_ARCLEN_ACCURACY))));
|
||||
}
|
||||
}
|
||||
subs.push(insert_at(sp, &places).0);
|
||||
}
|
||||
return PathData::new(subs);
|
||||
}
|
||||
let smooth = smooth_points(p);
|
||||
let seed = seed(p);
|
||||
let mut subs = vec![];
|
||||
@@ -118,6 +137,8 @@ pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
|
||||
PathData::new(subs)
|
||||
}
|
||||
|
||||
const ROUGHEN_ARCLEN_ACCURACY: f64 = 1e-4;
|
||||
|
||||
/// The move and the number of copies of a Transform effect with params `p` that only moves what
|
||||
/// it applies to, as [`transform_map`] reads them; `None` when it also scales, rotates or reflects,
|
||||
/// or moves by a random share, or moves pattern paints along (Transform Patterns), or scales
|
||||
|
||||
@@ -257,6 +257,9 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
|
||||
if carry.moves(&m.appearance) {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
// So do the raster effects of its fills and strokes, by `n`'s Transform effects
|
||||
// ([`crate::follow_items`]).
|
||||
crate::raster::follow_items_of(&mut m, &n.appearance.effects);
|
||||
}
|
||||
without_geometry_effects(&mut m);
|
||||
m
|
||||
@@ -265,7 +268,7 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
|
||||
fn without_geometry_effects(n: &mut Node) {
|
||||
if n.appearance.effects.iter().any(|e| crate::is_geometry(&e.id)) {
|
||||
let mut ap = (*n.appearance).clone();
|
||||
ap.effects.retain(|e| !crate::is_geometry(&e.id));
|
||||
ap.effects = crate::raster::without_geometry(&ap.effects);
|
||||
n.appearance = ap.into();
|
||||
}
|
||||
}
|
||||
@@ -686,7 +689,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
|
||||
}
|
||||
|
||||
/// A path node of `id` on `path` (filled under `rule`) painted by `ap`.
|
||||
fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
|
||||
pub(crate) fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
|
||||
let mut n = Node::path(id, path, ap);
|
||||
if let NodeKind::Path { rule: r, .. } = &mut n.kind {
|
||||
*r = rule;
|
||||
@@ -794,7 +797,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
}
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !crate::is_geometry(&e.id));
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
|
||||
if paint {
|
||||
let shapes = member_shapes(doc, &m);
|
||||
let bounds = m.geometric_bounds();
|
||||
|
||||
@@ -690,6 +690,525 @@ fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A white 10 pt square with id `id` at the origin.
|
||||
fn white_square(id: u64) -> Node {
|
||||
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// `n` masked by `art`, linked or not.
|
||||
fn masked_by(mut n: Node, art: Node, linked: bool) -> Node {
|
||||
let mut mask = vectorcraft_doc::OpacityMask::new(art, true);
|
||||
mask.linked = linked;
|
||||
n.extras_mut().mask = Some(Box::new(mask));
|
||||
n
|
||||
}
|
||||
|
||||
/// The geometry effects that reshape a group's members, one at a time.
|
||||
fn reshaping_effects() -> Vec<Effect> {
|
||||
let fx = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true };
|
||||
let corners = serde_json::json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
|
||||
vec![
|
||||
fx("distort.transform", serde_json::json!({"moveH": 30})),
|
||||
fx("distort.transform", serde_json::json!({"rotate": 90})),
|
||||
fx("distort.twist", serde_json::json!({"angle": 90})),
|
||||
fx("distort.freeDistort", corners),
|
||||
fx("warp.arc", serde_json::json!({})),
|
||||
fx("distort.roughen", serde_json::json!({"size": 5, "seed": 3})),
|
||||
fx("distort.zigZag", serde_json::json!({})),
|
||||
fx("distort.puckerBloat", serde_json::json!({"amount": 50})),
|
||||
fx("distort.tweak", serde_json::json!({})),
|
||||
fx("path.offsetPath", serde_json::json!({"offset": 3})),
|
||||
fx("stylize.roundCorners", serde_json::json!({"radius": 3})),
|
||||
]
|
||||
}
|
||||
|
||||
/// A group's geometry effect reshapes the art of a member's linked opacity mask as it reshapes the
|
||||
/// member: a mask drawn over the member still covers it. An unlinked mask stays where it is.
|
||||
#[test]
|
||||
fn a_groups_geometry_effects_reshape_a_members_linked_mask_with_it() {
|
||||
let square = white_square(1);
|
||||
let original = square.path_data().cloned();
|
||||
for e in reshaping_effects() {
|
||||
for linked in [true, false] {
|
||||
let member = masked_by(square.clone(), white_square(4), linked);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = member.extras().mask.as_deref().unwrap();
|
||||
assert!(member.path_data().cloned() != original, "{}: the member is reshaped", e.id);
|
||||
let want = if linked { member.path_data().cloned() } else { original.clone() };
|
||||
assert_eq!(mask.art.path_data().cloned(), want, "{} (linked: {linked})", e.id);
|
||||
assert_eq!(mask.linked, linked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mask of a group inside the group, the mask of a path in it, a mask inside that mask's art and
|
||||
/// an inverted mask all take the outer group's effect with the paths they mask.
|
||||
#[test]
|
||||
fn a_groups_geometry_effects_reshape_nested_and_inverted_masks() {
|
||||
for e in reshaping_effects() {
|
||||
let innermost = masked_by(white_square(7), white_square(8), true);
|
||||
let path = masked_by(white_square(1), masked_by(white_square(6), innermost, true), true);
|
||||
let mut inner = masked_by(Node::group(NodeId(5), vec![Arc::new(path)]), white_square(4), true);
|
||||
if let Some(m) = inner.extras_if_any().and_then(|x| x.mask.as_mut()) {
|
||||
m.invert = true;
|
||||
}
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let path = &inner.children().unwrap()[0];
|
||||
let want = path.path_data().cloned();
|
||||
let mask_of = |n: &Node| n.extras().mask.as_deref().map(|m| (*m.art).clone()).unwrap();
|
||||
let (outer_mask, path_mask) = (mask_of(inner), mask_of(path));
|
||||
assert!(inner.extras().mask.as_deref().is_some_and(|m| m.invert));
|
||||
assert_eq!(outer_mask.path_data().cloned(), want, "{}: the inner group's inverted mask", e.id);
|
||||
assert_eq!(path_mask.path_data().cloned(), want, "{}: the path's mask", e.id);
|
||||
assert_eq!(mask_of(&path_mask).path_data().cloned(), want, "{}: the mask inside the mask's art", e.id);
|
||||
assert_eq!(mask_of(&mask_of(&path_mask)).path_data().cloned(), want, "{}: one level deeper", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect's copies of a path with a linked mask are objects of their own, each with the
|
||||
/// mask moved with it; the original keeps its mask where it was.
|
||||
#[test]
|
||||
fn each_transform_copy_of_a_masked_member_carries_its_mask() {
|
||||
let member = masked_by(white_square(1), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let copies = art.children().unwrap()[0].children().expect("the object and its copies are objects of their own");
|
||||
assert_eq!(copies.len(), 3);
|
||||
for c in copies {
|
||||
let mask = c.extras().mask.as_deref().unwrap();
|
||||
assert_eq!(mask.art.geometric_bounds(), c.geometric_bounds());
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect's copies of the paths of a member group give the group's linked mask the same
|
||||
/// copies: the mask covers each copy.
|
||||
#[test]
|
||||
fn a_member_groups_mask_takes_the_transform_copies_of_its_paths() {
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let want = inner.geometric_bounds();
|
||||
assert_eq!(want, Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "the path and its copy");
|
||||
assert_eq!(inner.extras().mask.as_deref().unwrap().art.geometric_bounds(), want);
|
||||
}
|
||||
|
||||
/// A mask's art of several objects takes Transform copies whole, as the art it masks does: each copy
|
||||
/// of the mask's art is a group of its objects, so the copies do not interleave object by object.
|
||||
#[test]
|
||||
fn a_masks_art_of_several_objects_is_copied_whole() {
|
||||
let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
let copies = mask.children().unwrap();
|
||||
assert_eq!(copies.len(), 2, "the mask's art and its copy");
|
||||
for c in copies {
|
||||
let ids: Vec<NodeId> = c.children().into_iter().flatten().map(|m| m.id).collect();
|
||||
assert_eq!(ids, [NodeId(4), NodeId(5)], "each copy holds the mask's objects");
|
||||
}
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)));
|
||||
}
|
||||
|
||||
/// The linked mask of a mask's art that is copied whole takes the same Transform copies.
|
||||
#[test]
|
||||
fn the_mask_of_a_masks_art_copied_whole_takes_its_copies() {
|
||||
let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let mask_art = masked_by(parts, white_square(6), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)), "the mask's art and its copy");
|
||||
let own = &mask.extras().mask.as_deref().expect("the mask's art keeps its own mask").art;
|
||||
assert_eq!(own.geometric_bounds(), Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "its mask covers the copy too");
|
||||
}
|
||||
|
||||
/// The mask of a mask's art copied whole stays in the budget while that art is copied: when the
|
||||
/// budget has no room for that mask's copy, the art keeps its shape with its masks.
|
||||
#[test]
|
||||
fn the_mask_of_a_masks_art_copied_whole_counts_against_the_budget() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true };
|
||||
let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let mask_art = masked_by(parts, white_square(6), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the four squares and the copies of three of them, not for the copy of the fourth.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 7 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
assert_eq!(inner.geometric_bounds(), square, "the path keeps its shape");
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 15.0, 10.0)), "and so does its mask");
|
||||
}
|
||||
|
||||
/// When a member group's linked mask can't take all the Transform copies its paths take (past the
|
||||
/// budget), the art keeps its shape under the effect, so the mask still covers the paths.
|
||||
#[test]
|
||||
fn art_whose_mask_would_take_fewer_copies_keeps_its_shape() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true };
|
||||
let member = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the path, its mask and a copy of the path, not for a copy of the mask.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 3 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let member = &art.children().unwrap()[0];
|
||||
let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
assert_eq!(member.geometric_bounds(), square, "the path keeps its shape");
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), square, "and so does its mask");
|
||||
}
|
||||
|
||||
/// The copies of a path with a linked mask count the art of the mask each copy carries against the
|
||||
/// budget: they stop where the masks would pass it.
|
||||
#[test]
|
||||
fn transform_copies_count_the_art_of_their_masks() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 2}), visible: true };
|
||||
let member = masked_by(white_square(1), white_square(4), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the path, its mask and one copy of both, not for a second copy.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 4 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let copies = art.children().unwrap()[0].children().expect("the object and its copy are objects of their own");
|
||||
assert_eq!(copies.len(), 2);
|
||||
for c in copies {
|
||||
assert_eq!(c.extras().mask.as_deref().unwrap().art.geometric_bounds(), c.geometric_bounds());
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect that scales strokes moves a group's paths as objects, their masks with them.
|
||||
/// The mask of a member group, whose art holds a path with a mask of its own, moves with the group's
|
||||
/// paths too.
|
||||
#[test]
|
||||
fn a_transform_that_moves_paths_as_objects_moves_a_member_groups_nested_mask() {
|
||||
let mask_art = masked_by(white_square(4), white_square(5), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(3, 20.0, Color::BLACK)]);
|
||||
let params = serde_json::json!({"moveH": 30, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let want = inner.children().unwrap()[0].geometric_bounds();
|
||||
assert_eq!(want, Some(Rect::new(30.0, 0.0, 40.0, 10.0)));
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), want, "the group's mask");
|
||||
assert_eq!(mask.extras().mask.as_deref().unwrap().art.geometric_bounds(), want, "the mask inside its art");
|
||||
}
|
||||
|
||||
/// A group's Transform effect moves an image member's linked opacity mask with the image, and its
|
||||
/// copies' masks with the copies; an unlinked mask stays.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_an_image_members_linked_mask() {
|
||||
for linked in [true, false] {
|
||||
for copies in [0, 2] {
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), white_square(4), linked);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": copies});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let first = &art.children().unwrap()[0];
|
||||
let images: Vec<&Node> = match first.children() {
|
||||
Some(ch) => ch.iter().map(|c| &**c).collect(),
|
||||
None => vec![first],
|
||||
};
|
||||
assert_eq!(images.len(), copies + 1);
|
||||
for im in images {
|
||||
let mask = im.extras().mask.as_deref().unwrap();
|
||||
let want = if linked { im.geometric_bounds() } else { Some(Rect::new(0.0, 0.0, 10.0, 10.0)) };
|
||||
assert_eq!(mask.art.geometric_bounds(), want, "linked {linked}, copies {copies}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When a path in a member's mask art would pass the effects' budget, the whole mask stays as it
|
||||
/// was, rather than part of its art moving with the member, and the member keeps its shape with it.
|
||||
#[test]
|
||||
fn a_mask_whose_art_passes_the_budget_stays_whole() {
|
||||
// Bloat bends a path's sides into curves drawn with more lines the larger they are: many more
|
||||
// on the mask's large square.
|
||||
let bloat = Effect { id: "distort.puckerBloat".into(), params: serde_json::json!({"amount": 50}), visible: true };
|
||||
let large = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0)), Appearance::default());
|
||||
let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), Arc::new(large.clone())]);
|
||||
let member = masked_by(white_square(1), mask_art.clone(), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
// Room for the member and the mask's small square to take the effect, not for the large one.
|
||||
let bounds = art.geometric_bounds().unwrap();
|
||||
let ctx = crate::GeomContext { seed: 10, ..crate::GeomContext::of(&art) };
|
||||
let square = white_square(1).path_data().cloned().unwrap();
|
||||
let made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), &square, bounds, &ctx)).lines;
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 2 * made + crate::Budget::of(large.path_data().unwrap()).lines };
|
||||
let large_made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), large.path_data().unwrap(), bounds, &ctx)).lines;
|
||||
assert!(large_made > crate::Budget::of(large.path_data().unwrap()).lines, "the large square's curves cost more lines");
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&bloat], budget, None);
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.path_data(), Some(&square), "the member keeps its shape with its mask");
|
||||
assert_eq!(*member.extras().mask.as_deref().unwrap().art, mask_art, "the mask stays whole");
|
||||
}
|
||||
|
||||
/// Live objects in a member's linked mask are evaluated before the group's geometry effects run
|
||||
/// over the mask's art, so the mask still covers the member: a Repeat in it moves and bends with
|
||||
/// the member.
|
||||
#[test]
|
||||
fn a_groups_effects_reshape_a_live_object_in_a_members_mask() {
|
||||
let mut grid = vectorcraft_doc::RepeatSpec::grid(vec![Arc::new(white_square(5))], 0.0, 0.0);
|
||||
if let vectorcraft_doc::RepeatKind::Grid { rows, cols, .. } = &mut grid.kind {
|
||||
(*rows, *cols) = (1, 1);
|
||||
}
|
||||
let repeat = Node::new(NodeId(4), NodeKind::Repeat(grid));
|
||||
let drawn: Vec<Node> = crate::expand_live(None, &repeat);
|
||||
let leaf = |n: &Node| {
|
||||
let mut found = None;
|
||||
n.walk(&mut |c| found = found.take().or_else(|| c.path_data().cloned()));
|
||||
found
|
||||
};
|
||||
assert_eq!(drawn.iter().find_map(leaf), white_square(1).path_data().cloned(), "the Repeat draws one square over the member");
|
||||
for e in [reshaping_effects()[0].clone(), reshaping_effects()[4].clone()] {
|
||||
let member = masked_by(white_square(1), repeat.clone(), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = &member.extras().mask.as_deref().unwrap().art;
|
||||
assert!(member.path_data() != white_square(1).path_data(), "{}: the member is reshaped", e.id);
|
||||
assert_eq!(leaf(mask), member.path_data().cloned(), "{}: the mask's square takes the effect with it", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Type in a member's linked mask is outlined before the group's Transform effect moves the mask's
|
||||
/// art with the member.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_type_in_a_members_mask() {
|
||||
if skip_without_craft_fonts() {
|
||||
return;
|
||||
}
|
||||
let member = masked_by(white_square(1), type_h(), true);
|
||||
let before = crate::reshape::outline_text(&type_h()).unwrap().geometric_bounds().unwrap();
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
let mut text = false;
|
||||
mask.walk(&mut |c| text |= matches!(c.kind, NodeKind::Text(_)));
|
||||
assert!(!text, "the type is outlined");
|
||||
let after = mask.geometric_bounds().unwrap();
|
||||
assert!((after.x0 - before.x0 - 30.0).abs() < 0.5 && (after.y0 - before.y0).abs() < 0.5, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
/// The linked mask of a compound path in a group, and of a path in a layer, takes the geometry
|
||||
/// effects with the art it masks.
|
||||
#[test]
|
||||
fn a_compound_paths_and_a_layers_members_masks_take_the_effects() {
|
||||
let geometry = |n: &Node| crate::reshape::leaf_geometry(n).map(|(p, _)| p);
|
||||
for e in reshaping_effects() {
|
||||
let square = white_square(1);
|
||||
let compound = Node::new(NodeId(1), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: FillRule::NonZero });
|
||||
let compound = masked_by(compound, white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(compound), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert!(geometry(member) != square.path_data().cloned(), "{}: the compound path is reshaped", e.id);
|
||||
assert_eq!(geometry(&member.extras().mask.as_deref().unwrap().art), geometry(member), "{}: compound path", e.id);
|
||||
|
||||
let mut layer = Node::layer(NodeId(10), "Layer", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
ch.extend([Arc::new(masked_by(square.clone(), white_square(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
}
|
||||
layer.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &layer).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert!(member.path_data() != square.path_data(), "{}: the layer's path is reshaped", e.id);
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.path_data(), member.path_data(), "{}: layer", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect moves a symbol instance member's linked mask with the instance.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_a_symbol_instance_members_linked_mask() {
|
||||
let instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(instance, white_square(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let instance = &art.children().unwrap()[0];
|
||||
let NodeKind::SymbolInstance { xf, .. } = &instance.kind else { panic!("an instance: {instance:?}") };
|
||||
assert!((xf.translation().x - 30.0).abs() < 1e-9, "the instance moves: {xf:?}");
|
||||
let mask = instance.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
|
||||
assert!((mask.x0 - 30.0).abs() < 1e-9 && (mask.x1 - 40.0).abs() < 1e-9, "its mask moves with it: {mask:?}");
|
||||
}
|
||||
|
||||
/// With Scale Strokes & Effects on, a group's Transform effect scales the stroke of an image
|
||||
/// member's linked mask as it scales that of a path member's mask.
|
||||
#[test]
|
||||
fn a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike() {
|
||||
let stroked =
|
||||
Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0));
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), stroked.clone(), true);
|
||||
let path = masked_by(white_square(2), stroked, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image), Arc::new(path)]);
|
||||
let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let width = |n: &Node| n.extras().mask.as_deref().unwrap().art.appearance.stroke().map(|s| s.width);
|
||||
let ch = art.children().unwrap();
|
||||
assert_eq!(width(&ch[1]), Some(4.0), "the path's mask");
|
||||
assert_eq!(width(&ch[0]), width(&ch[1]), "the image's mask");
|
||||
}
|
||||
|
||||
/// With Transform Objects off and Scale Strokes & Effects on, a group's Transform effect scales the
|
||||
/// strokes of a member's linked mask as it scales the member's, and moves neither.
|
||||
#[test]
|
||||
fn a_transform_of_strokes_only_scales_a_members_mask_strokes() {
|
||||
let stroked = |id: u64| {
|
||||
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0))
|
||||
};
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(stroked(1), stroked(4), true))]);
|
||||
let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = &member.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(member.appearance.stroke().map(|s| s.width), Some(4.0), "the member's stroke");
|
||||
assert_eq!(mask.appearance.stroke().map(|s| s.width), Some(4.0), "the mask's stroke");
|
||||
assert_eq!(mask.geometric_bounds(), member.geometric_bounds());
|
||||
}
|
||||
|
||||
/// The art of a member group's mask is copied as it was before the first effect: a mask of one
|
||||
/// path takes a second Transform effect's copies path by path, as the path it masks does, though
|
||||
/// the first effect (with Scale Strokes & Effects) made it a group of copies.
|
||||
#[test]
|
||||
fn a_masks_art_is_copied_as_it_was_before_the_first_effect() {
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
for strokes in [true, false] {
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2, "strokes": strokes});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), inner.geometric_bounds());
|
||||
let kinds = |n: &Node| n.children().unwrap().iter().map(|c| std::mem::discriminant(&c.kind)).collect::<Vec<_>>();
|
||||
let paths = &inner.children().unwrap()[0];
|
||||
assert_eq!(kinds(paths).len(), 3, "the first effect's three paths");
|
||||
assert!(paths.children().unwrap().iter().all(|c| matches!(c.kind, NodeKind::Compound { .. })), "each with its copies");
|
||||
assert_eq!(kinds(mask), kinds(paths), "the mask's art takes the copies as the paths do");
|
||||
}
|
||||
|
||||
/// A 10 × 10 image with id `id` at the origin.
|
||||
fn image_node(id: u64) -> Node {
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
Node::new(NodeId(id), NodeKind::Image(Box::new(im)))
|
||||
}
|
||||
|
||||
/// A linked mask whose art is an image moves with the path it masks under a group's Transform
|
||||
/// effect, and a member group's image mask takes the copies its paths take.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_a_linked_mask_whose_art_is_an_image() {
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(white_square(1), image_node(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.geometric_bounds(), Some(Rect::new(30.0, 0.0, 40.0, 10.0)));
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), member.geometric_bounds());
|
||||
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), image_node(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
assert_eq!(inner.geometric_bounds(), Some(Rect::new(0.0, 0.0, 70.0, 10.0)));
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), inner.geometric_bounds(), "the image and its copies");
|
||||
}
|
||||
|
||||
/// An image in a linked mask's art takes no geometry effect but Transform, so under a Warp effect
|
||||
/// the art keeps its shape with its mask.
|
||||
#[test]
|
||||
fn art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp() {
|
||||
let member = masked_by(white_square(1), Node::group(NodeId(3), vec![Arc::new(image_node(4))]), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[4].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.path_data(), white_square(1).path_data(), "the path keeps its shape");
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), Some(Rect::new(0.0, 0.0, 10.0, 10.0)));
|
||||
}
|
||||
|
||||
/// A Warp effect bends an image's pixels but not the art of its linked mask, so art with such an
|
||||
/// image keeps its shape under the warp, with the image and its mask.
|
||||
#[test]
|
||||
fn art_with_a_masked_image_keeps_its_shape_under_a_warp() {
|
||||
let image = masked_by(image_node(1), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image.clone()), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[4].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert_eq!(*ch[0], image, "the image and its mask");
|
||||
assert_eq!(ch[1].path_data(), sq(2, 20.0, Color::BLACK).path_data(), "the path keeps its shape");
|
||||
}
|
||||
|
||||
/// A symbol instance in perspective projects the linked masks of the objects in its art with them.
|
||||
#[test]
|
||||
fn perspective_projects_the_masks_in_a_symbols_art() {
|
||||
let art = Node::group(NodeId(20), vec![Arc::new(masked_by(white_square(21), white_square(22), true))]);
|
||||
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let mut at = vectorcraft_doc::PerspectiveAttachment::new("left", 0.0);
|
||||
at.projection = Some([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.01, 0.0, 1.0]);
|
||||
instance.extras_mut().perspective = Some(Box::new(at));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap();
|
||||
let mut masked = vec![];
|
||||
out.walk(&mut |c| masked.extend(c.extras().mask.as_deref().map(|m| (c.path_data().cloned(), m.art.path_data().cloned()))));
|
||||
let [(path, mask)] = masked.as_slice() else { panic!("one masked path: {masked:?}") };
|
||||
assert!(path != &white_square(21).path_data().cloned(), "the path is projected");
|
||||
assert_eq!(mask, path, "and so is its mask");
|
||||
}
|
||||
|
||||
/// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit
|
||||
/// pitch, each crossing every bar of the other direction: n² crossings.
|
||||
fn crossing_bars(n: usize, effect: &str) -> Node {
|
||||
@@ -762,6 +1281,23 @@ fn compound_shape(mode: ShapeMode) -> Node {
|
||||
g
|
||||
}
|
||||
|
||||
/// A compound shape's Transform effect turns its fill's drop shadow with the area it turns.
|
||||
#[test]
|
||||
fn a_compound_shapes_transform_turns_its_fills_shadow() {
|
||||
let mut shape = compound_shape(ShapeMode::Add);
|
||||
if let Some(item) = shape.appearance.items.first_mut() {
|
||||
*item.effects_mut() =
|
||||
vec![Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 10, "y": 0, "blur": 0}), visible: true }];
|
||||
}
|
||||
shape.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"rotate": 90}), visible: true });
|
||||
let art = shape_art(None, &shape, None).unwrap();
|
||||
let item = art.appearance.items.first().unwrap();
|
||||
match crate::raster_effects(item.effects()).first() {
|
||||
Some(crate::RasterFx::DropShadow { dx, dy, .. }) => assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9, "{dx} {dy}"),
|
||||
other => panic!("expected a drop shadow, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A compound shape draws the area its members' modes make, one unpainted path that its own
|
||||
/// appearance paints; evaluated, it is plain art painted with that appearance.
|
||||
#[test]
|
||||
|
||||
@@ -78,24 +78,30 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
|
||||
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 raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
|
||||
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects,
|
||||
has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
|
||||
};
|
||||
pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
};
|
||||
pub use solids::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES,
|
||||
classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_classic_three_d, is_three_d, solid_art, solid_art_in,
|
||||
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in,
|
||||
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, ROTATE, ROTATE_SURFACES,
|
||||
ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds,
|
||||
graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, solid_art, solid_art_in, takes_graphics, three_d_meshes,
|
||||
three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in,
|
||||
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, rename_appearance_graphic_symbol,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
pub use trap::TRAP;
|
||||
pub use vectorcraft_three_d::Mesh;
|
||||
pub use vectorcraft_three_d::PlanarFace;
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version};
|
||||
|
||||
mod catalog;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
//! Raster (painted) effects: descriptions for the renderer.
|
||||
|
||||
use serde_json::Value;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Color};
|
||||
use vectorcraft_doc::rastersettings::MAX_ADD_AROUND;
|
||||
use vectorcraft_doc::{Effect, RasterColorModel, RasterEffectsSettings};
|
||||
use vectorcraft_doc::{AppearanceItem, Effect, Node, RasterColorModel, RasterEffectsSettings};
|
||||
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use crate::merged_params;
|
||||
use crate::pixel::{self, PixelFx, PixelSpace};
|
||||
@@ -384,9 +386,10 @@ fn opacity(p: &Value) -> f32 {
|
||||
(num(p, "opacity", 75.0) / 100.0).clamp(0.0, 1.0) as f32
|
||||
}
|
||||
|
||||
/// The visible raster effects of `effects`, in stack order.
|
||||
/// The visible raster effects of `effects`, in stack order, each following the Transform effects
|
||||
/// listed after it ([`followed`]).
|
||||
pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
|
||||
effects
|
||||
followed(effects)
|
||||
.iter()
|
||||
.filter(|e| e.visible)
|
||||
.filter_map(|e| {
|
||||
@@ -426,6 +429,214 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `effects` with each raster effect following the visible Transform effects listed after it
|
||||
/// ([`follow_transform`]): effects apply in the order they are listed, so a Transform effect
|
||||
/// transforms what the raster effects before it paint, whatever its Scale Strokes & Effects says.
|
||||
/// A hidden raster effect follows too, so it draws the same when it is shown after the Transform
|
||||
/// effect has been expanded. A raster effect that a Transform effect making copies or moving at
|
||||
/// random follows stays as it is, as does one after the last Transform effect. Borrowed when
|
||||
/// nothing changes.
|
||||
pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> {
|
||||
if !effects.iter().any(|e| e.visible && e.id == "distort.transform") {
|
||||
return Cow::Borrowed(effects);
|
||||
}
|
||||
let mut out: Option<Vec<Effect>> = None;
|
||||
// The linear part of the Transform effects after the effect at hand, the last one outermost;
|
||||
// `None` once one of them makes copies or moves at random.
|
||||
let mut after = Some(Affine::IDENTITY);
|
||||
for (i, e) in effects.iter().enumerate().rev() {
|
||||
if e.id == "distort.transform" {
|
||||
after = after.and_then(|a| transform_step(e).map(|s| a * s));
|
||||
continue;
|
||||
}
|
||||
let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue };
|
||||
let list = out.get_or_insert_with(|| effects.to_vec());
|
||||
if let Some(e) = list.get_mut(i) {
|
||||
follow_transform(e, a);
|
||||
}
|
||||
}
|
||||
out.map_or(Cow::Borrowed(effects), Cow::Owned)
|
||||
}
|
||||
|
||||
/// `effects` without their geometry effects, each raster effect following the Transform effects
|
||||
/// it loses ([`followed`]): what an object, or a fill or stroke, keeps once its geometry effects
|
||||
/// are applied to its art.
|
||||
pub fn without_geometry(effects: &[Effect]) -> Vec<Effect> {
|
||||
followed(effects).iter().filter(|e| !crate::is_geometry(&e.id)).cloned().collect()
|
||||
}
|
||||
|
||||
/// Make the raster effects of `effects`, all listed before Transform effect `t`, follow `t` as
|
||||
/// [`followed`] makes them follow it, for art that applies its effects one at a time. `false`
|
||||
/// when `t` leaves them as they are.
|
||||
pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool {
|
||||
let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false };
|
||||
let mut changed = false;
|
||||
for e in effects.iter_mut().filter(|e| follows(&e.id)) {
|
||||
follow_transform(e, a);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The linear part of the visible Transform effects of `owner`, an object's or a container's own
|
||||
/// effects, in order: what they do to the raster effects of everything the object paints (its
|
||||
/// fills and strokes, and a container's members and theirs), which those effects transform with
|
||||
/// the rest of the art. `None` when they leave them as they are: no Transform effect moves the
|
||||
/// art, or one of them makes copies or moves at random ([`followed`]).
|
||||
pub(crate) fn contents_step(owner: &[Effect]) -> Option<Affine> {
|
||||
let a = owner.iter().filter(|e| e.visible && e.id == "distort.transform").try_fold(Affine::IDENTITY, |a, e| transform_step(e).map(|s| s * a))?;
|
||||
(a != Affine::IDENTITY).then_some(a)
|
||||
}
|
||||
|
||||
/// Make the raster effects of `effects`, the own effects of something inside an object (a fill's
|
||||
/// or stroke's, or a member's), follow `a`, the linear part of the object's Transform effects
|
||||
/// ([`contents_step`]), which apply after all of them. `outer` is what the Transform effects
|
||||
/// between them and `a` do to them (those of the fill's or stroke's object and of the groups that
|
||||
/// hold it inside the object). A raster effect that the Transform effects after it in `effects`
|
||||
/// move ([`followed`]) is set so that it draws as those effects, then `outer` and then `a`
|
||||
/// transform it, whichever of them is applied first. One that a Transform effect after it in
|
||||
/// `effects` holds back keeps its value through those effects, so it is set to draw as `outer` and
|
||||
/// then `a` transform it. `false` when nothing changed.
|
||||
pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine) -> bool {
|
||||
if a == Affine::IDENTITY || !effects.iter().any(|e| follows(&e.id)) {
|
||||
return false;
|
||||
}
|
||||
let mut changed = false;
|
||||
// The linear part of the Transform effects after the effect at hand, as `followed` reads it;
|
||||
// `None` once one of them holds the effect back, which they then leave as it is.
|
||||
let mut after = Some(Affine::IDENTITY);
|
||||
for e in effects.iter_mut().rev() {
|
||||
if e.id == "distort.transform" {
|
||||
after = after.and_then(|b| transform_step(e).map(|s| b * s));
|
||||
continue;
|
||||
}
|
||||
if !follows(&e.id) {
|
||||
continue;
|
||||
}
|
||||
let b = outer * after.unwrap_or(Affine::IDENTITY);
|
||||
// The effect is still to be mapped by `b` when it is drawn, so it takes b⁻¹·a·b now:
|
||||
// drawn, it is a·b of what it was. A `b` that flattens the art takes `a` alone.
|
||||
let det = b.determinant();
|
||||
let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b };
|
||||
if c.is_finite() {
|
||||
follow_transform(e, c);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Make the raster effects of the fills and strokes of `n` follow the Transform effects of its own
|
||||
/// effect list ([`contents_step`]), as they do while the object is drawn with them: for art that
|
||||
/// applies those effects and keeps the fills and strokes. `false` when nothing changed.
|
||||
pub fn follow_items(n: &mut Node) -> bool {
|
||||
let Some(a) = contents_step(&n.appearance.effects) else { return false };
|
||||
follow_items_by(n, a)
|
||||
}
|
||||
|
||||
/// [`follow_items`] for `n` holding the fills and strokes of an object whose own effects are
|
||||
/// `owner` (the area of a compound shape, which carries none of the shape's effects).
|
||||
pub(crate) fn follow_items_of(n: &mut Node, owner: &[Effect]) -> bool {
|
||||
let Some(a) = contents_step(owner) else { return false };
|
||||
follow_items_by(n, a)
|
||||
}
|
||||
|
||||
/// Make the raster effects of the fills and strokes of `n` follow `a` ([`follow_contents`]).
|
||||
fn follow_items_by(n: &mut Node, a: Affine) -> bool {
|
||||
if !n.appearance.items.iter().any(|i| i.effects().iter().any(|e| follows(&e.id))) {
|
||||
return false;
|
||||
}
|
||||
let mut changed = false;
|
||||
for item in &mut n.appearance.items {
|
||||
changed |= follow_contents(item.effects_mut(), a, Affine::IDENTITY);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Make the raster effects of `items`, the fills and strokes of an object whose own effects are
|
||||
/// `owner`, follow the Transform effects of `owner` ([`follow_contents`]): for art that applies
|
||||
/// those effects to the object's path and draws each fill and stroke on it as a node of its own.
|
||||
pub(crate) fn follow_paints(items: &mut [AppearanceItem], owner: &[Effect]) {
|
||||
let Some(a) = contents_step(owner) else { return };
|
||||
for item in items {
|
||||
follow_contents(item.effects_mut(), a, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
|
||||
/// `effects`, those of a fill or stroke of an object whose own effects are `owner`, with each
|
||||
/// raster effect following the Transform effects of `owner` as well ([`follow_contents`]): the
|
||||
/// list to draw that fill's or stroke's raster effects from ([`raster_effects`]). Borrowed when
|
||||
/// nothing changes.
|
||||
pub fn item_effects_in<'a>(owner: &[Effect], effects: &'a [Effect]) -> Cow<'a, [Effect]> {
|
||||
let Some(a) = contents_step(owner) else { return Cow::Borrowed(effects) };
|
||||
if !effects.iter().any(|e| follows(&e.id)) {
|
||||
return Cow::Borrowed(effects);
|
||||
}
|
||||
let mut out = effects.to_vec();
|
||||
if follow_contents(&mut out, a, Affine::IDENTITY) { Cow::Owned(out) } else { Cow::Borrowed(effects) }
|
||||
}
|
||||
|
||||
/// How many of the effects of `effects` that [`without_geometry`] keeps no longer follow the
|
||||
/// Transform effects listed after `effects` ([`followed`]): those before the last visible Transform
|
||||
/// effect among them that makes copies or moves at random.
|
||||
pub(crate) fn held_back(effects: &[Effect]) -> usize {
|
||||
let Some(last) = effects.iter().rposition(|e| transform_step(e).is_none()) else { return 0 };
|
||||
effects.get(..last).unwrap_or_default().iter().filter(|e| !crate::is_geometry(&e.id)).count()
|
||||
}
|
||||
|
||||
/// Does `e` stop the raster effects listed before it from following the Transform effects after
|
||||
/// it ([`followed`]): is it a visible Transform effect that makes copies or moves at random?
|
||||
pub(crate) fn holds_back(e: &Effect) -> bool {
|
||||
transform_step(e).is_none()
|
||||
}
|
||||
|
||||
/// What `e` does to the raster effects listed before it ([`followed`]): the linear part of its map
|
||||
/// when it is a visible Transform effect that moves the art once, the identity when it is no
|
||||
/// Transform effect, is hidden or has Transform Objects off (the art stays where it is), and `None`
|
||||
/// when it makes copies or moves at random.
|
||||
fn transform_step(e: &Effect) -> Option<Affine> {
|
||||
if e.id != "distort.transform" || !e.visible {
|
||||
return Some(Affine::IDENTITY);
|
||||
}
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
if !flag(&p, "objects", true) {
|
||||
return Some(Affine::IDENTITY);
|
||||
}
|
||||
let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0);
|
||||
(copies == 0 && !flag(&p, "random", false)).then(|| map.with_translation(Vec2::ZERO))
|
||||
}
|
||||
|
||||
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
|
||||
/// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room
|
||||
/// around the art.
|
||||
pub(crate) fn follows(id: &str) -> bool {
|
||||
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
|
||||
}
|
||||
|
||||
/// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as
|
||||
/// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean
|
||||
/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with
|
||||
/// `a`. Effects that [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
if !follows(&e.id) {
|
||||
return;
|
||||
}
|
||||
let offset = (e.id == "stylize.dropShadow").then(|| {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0))
|
||||
});
|
||||
if let Some(k) = vectorcraft_doc::Scaling::factor(a) {
|
||||
crate::scale_effect(e, k);
|
||||
}
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Map::new());
|
||||
}
|
||||
e.params["x"] = json!(o.x);
|
||||
e.params["y"] = json!(o.y);
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the visible raster effects of `effects` paint beyond `bounds`, the (effected)
|
||||
/// geometry's, in document units. Geometry effects are accounted for by evaluating them.
|
||||
pub fn outset(effects: &[Effect], bounds: Rect) -> f64 {
|
||||
|
||||
+924
-110
File diff suppressed because it is too large.
Load diff
+118
-16
@@ -8,7 +8,9 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, L
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve};
|
||||
|
||||
use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, resolve_for, solid_paints, union_bounds};
|
||||
use crate::solids::{
|
||||
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
|
||||
};
|
||||
use crate::util::{flag, num, text};
|
||||
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
|
||||
|
||||
@@ -507,6 +509,60 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
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
|
||||
/// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for
|
||||
/// each member, about one shared axis. The swatches and patterns named by a live-effect plug-in
|
||||
/// after a fill's or stroke's Revolve are looked up in `doc`.
|
||||
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
|
||||
let faces = |path: &PathData, b: Rect, options: Revolve| -> Result<Vec<PathData>, String> {
|
||||
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect())
|
||||
};
|
||||
if is_container(n) {
|
||||
let index = n
|
||||
.appearance
|
||||
.effects
|
||||
.iter()
|
||||
.position(|e| e.visible && is_revolve(&e.id))
|
||||
.ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
|
||||
let mut shapes = members(n, "Revolve")?;
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
|
||||
let options = shared_options(&shapes, fx_options(fx))?;
|
||||
let mut out = vec![];
|
||||
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
|
||||
out.extend(faces(&s.path, b, options)?);
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
|
||||
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
|
||||
if surface_item(&solid_paints(n)).is_none() {
|
||||
return Err("the revolved object has no fill or stroke".into());
|
||||
}
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
return faces(&path, b, fx_options(fx));
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id))
|
||||
&& let Some(fx) = item.effects().get(index)
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&p, b, fx_options(fx))?;
|
||||
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
|
||||
fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let index = n
|
||||
@@ -538,7 +594,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
if is_container(n) {
|
||||
return group_art(n, expand);
|
||||
}
|
||||
let (path, _) = profile(n)?;
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let mut children = vec![];
|
||||
let mut copies = 0;
|
||||
@@ -558,23 +614,23 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
}
|
||||
children.push(Arc::new(surface));
|
||||
// Later geometry acts on the projected art as a whole through container evaluation.
|
||||
remaining = n
|
||||
.appearance
|
||||
.effects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, e)| !is_revolve(&e.id) && (!is_geometry(&e.id) || *i > index))
|
||||
.map(|(_, e)| e.clone())
|
||||
.collect();
|
||||
remaining = past_effect(&n.appearance.effects, index);
|
||||
remaining.retain(|e| !is_revolve(&e.id));
|
||||
} else {
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
remaining.retain(|e| !is_geometry(&e.id));
|
||||
remaining = crate::without_geometry(&remaining);
|
||||
// The object's Transform effects, applied to the path above, transform the items' raster
|
||||
// effects too. Each copy keeps its item beside it, which plug-in effects are told they sit
|
||||
// on.
|
||||
let originals: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).collect();
|
||||
let mut items: Vec<AppearanceItem> = originals.iter().map(|i| (*i).clone()).collect();
|
||||
crate::raster::follow_paints(&mut items, &n.appearance.effects);
|
||||
// Every item's shadow goes behind every item's art.
|
||||
let mut shadows = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
for (original, item) in originals.into_iter().zip(&items) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let fx = item.effects().get(index)?;
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
@@ -586,7 +642,8 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
}
|
||||
children.push(Arc::new(art));
|
||||
} else {
|
||||
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
|
||||
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
|
||||
}
|
||||
}
|
||||
children.splice(0..0, shadows);
|
||||
@@ -835,8 +892,7 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> {
|
||||
// One shadow for every member's surface, behind them all.
|
||||
let mut children = children;
|
||||
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?);
|
||||
let remaining =
|
||||
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
|
||||
let remaining = past_effect(&n.appearance.effects, index);
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children, clip: false };
|
||||
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
|
||||
@@ -969,6 +1025,52 @@ mod tests {
|
||||
assert!(surface.children().unwrap().iter().all(|c| c.opacity == 1.0 && !has_revolve(c)));
|
||||
}
|
||||
#[test]
|
||||
fn a_fill_without_the_revolve_keeps_the_even_odd_hole() {
|
||||
use vectorcraft_geom::FillRule;
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
// Two nested squares drawn in the same direction: only the even-odd rule leaves a hole.
|
||||
let [outer, inner] = [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((lo, lo));
|
||||
b.line_to((hi, lo));
|
||||
b.line_to((hi, hi));
|
||||
b.line_to((lo, hi));
|
||||
b.close_path();
|
||||
PathData::from_bezpath(&b)
|
||||
});
|
||||
let flat = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.1, 0.3, 0.9))));
|
||||
for id in [REVOLVE, CLASSIC_REVOLVE] {
|
||||
let mut top = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.8, 0.2, 0.1))));
|
||||
top.effects_mut().push(crate::new_effect(id, &json!({})).unwrap());
|
||||
let appearance = Appearance { items: vec![flat.clone(), top], ..Default::default() };
|
||||
let members = vec![
|
||||
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
|
||||
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
|
||||
];
|
||||
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
|
||||
compound.appearance = appearance.clone().into();
|
||||
let both = PathData::new(outer.subpaths.iter().chain(&inner.subpaths).cloned().collect());
|
||||
let path = crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance);
|
||||
for (n, shape) in [(compound, "compound path"), (path, "path")] {
|
||||
for (art, how) in [(revolve_art(&n), "live"), (expand_revolve_art(&n), "expanded")] {
|
||||
let what = format!("{id} on the top fill of a {shape}, {how}");
|
||||
let art = art.unwrap_or_else(|| panic!("{what}"));
|
||||
let children = art.children().unwrap();
|
||||
let plain: Vec<usize> = (0..children.len())
|
||||
.filter(|&i| children[i].appearance.items == [flat.clone()] && children[i].path_data().is_some())
|
||||
.collect();
|
||||
let [index] = plain[..] else { panic!("{what}: one flat child, got {plain:?}") };
|
||||
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
|
||||
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
|
||||
let bez = path.to_bezpath();
|
||||
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
|
||||
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
|
||||
assert!(index + 1 < children.len(), "{what}: the revolved art is drawn above");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn export_bakes_faces_with_unique_ids_and_no_revolve_effects() {
|
||||
let mut d = Document::new(300.0, 300.0);
|
||||
let mut n = profile_node();
|
||||
|
||||
+318
-36
@@ -6,7 +6,7 @@ use serde_json::Value;
|
||||
use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, PlanarFace, View};
|
||||
|
||||
#[cfg(test)]
|
||||
use vectorcraft_doc::color::Color;
|
||||
@@ -20,8 +20,20 @@ pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLO
|
||||
mod source;
|
||||
pub(crate) use source::{resolve, resolve_for};
|
||||
|
||||
mod graphics;
|
||||
pub use graphics::{
|
||||
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
|
||||
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
|
||||
};
|
||||
pub use graphics::{
|
||||
MAX_OFFSET as GRAPHIC_MAX_OFFSET, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, rename_appearance_graphic_symbol,
|
||||
};
|
||||
|
||||
pub(crate) mod shadow;
|
||||
|
||||
pub(crate) mod wireframe;
|
||||
pub use wireframe::three_d_wireframe_in;
|
||||
|
||||
pub const EXTRUDE: &str = "threeD.extrude";
|
||||
pub const INFLATE: &str = "threeD.inflate";
|
||||
pub const ROTATE: &str = "threeD.rotate";
|
||||
@@ -67,6 +79,12 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A plane has only a front, so graphics on the back cap are dropped.
|
||||
if to == ROTATE
|
||||
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
|
||||
{
|
||||
list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id()));
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
@@ -209,6 +227,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
}
|
||||
crate::lighting::validate(p)?;
|
||||
shadow::validate(p)?;
|
||||
graphics::validate(id, p)?;
|
||||
if let Some(v) = p.get("bevel")
|
||||
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
|
||||
{
|
||||
@@ -238,6 +257,9 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
/// `item`, whose shadow is cast by that item's solid alone.
|
||||
fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, item: Option<usize>) -> Result<(), String> {
|
||||
validate_solid_params(id, p)?;
|
||||
if let Some(doc) = doc {
|
||||
graphics::validate_symbols(doc, p)?;
|
||||
}
|
||||
let label = label_of(id);
|
||||
let n = &*source::resolve_for(doc, n, label, is_plane(id))?;
|
||||
if is_container(n) {
|
||||
@@ -431,6 +453,7 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
|
||||
/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]).
|
||||
pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
graphics::validate(id, p)?;
|
||||
if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) }
|
||||
}
|
||||
|
||||
@@ -446,6 +469,7 @@ pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usi
|
||||
/// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a
|
||||
/// blend and a clipping group take a 3D effect as groups do: on the object itself.
|
||||
pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
|
||||
graphics::validate(id, p)?;
|
||||
match at {
|
||||
Some(_) if is_container(n) || source::resolves(n) => {
|
||||
Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into())
|
||||
@@ -460,6 +484,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va
|
||||
/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does
|
||||
/// not need to fit.
|
||||
pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
graphics::validate(id, p)?;
|
||||
if crate::revolve::is_revolve(id) { crate::revolve::validate_params_of(id, p) } else { validate_solid_params(id, p) }
|
||||
}
|
||||
|
||||
@@ -709,8 +734,8 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
|
||||
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
|
||||
/// off), to be drawn behind every surface of the object, and the surfaces.
|
||||
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
|
||||
let art = surfaces_for(n, fx, shapes)?;
|
||||
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
|
||||
let art = surfaces_for(doc, n, fx, shapes)?;
|
||||
// A shadow past the limits draws the source path, as a solid past them does; commands report
|
||||
// the error ([`validate_solid_in`]).
|
||||
let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? {
|
||||
@@ -786,8 +811,141 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
/// its member's scopes and ink ([`cast_shadow`]).
|
||||
type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>);
|
||||
|
||||
/// [`art_for`] without the shadow: the solids' surfaces.
|
||||
fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
/// The graphics of a 3D effect with parameters `p`, drawn on its faces ([`graphics::face_art`]):
|
||||
/// for each planar face with a graphic, the art and the face. `caps` are the faces the viewer sees
|
||||
/// of the ends of the object's solids, each with its end; `bounds` are the bounds the solids were
|
||||
/// built with; `opacity` is the opacity of the fill or stroke those solids are painted with, which
|
||||
/// the graphics take too. `elements` is the effect's count of drawn path elements, shared by every
|
||||
/// call for one effect ([`graphics::face_art`]).
|
||||
fn graphic_art(
|
||||
doc: Option<&Document>,
|
||||
id: NodeId,
|
||||
(effect, p): (&str, &Value),
|
||||
bounds: Rect,
|
||||
caps: &[&Facet],
|
||||
opacity: f32,
|
||||
elements: &mut usize,
|
||||
) -> Vec<(PlanarFace, Arc<Node>)> {
|
||||
let list = graphics::mapped_graphics(p);
|
||||
if list.is_empty() || !takes_graphics(effect) {
|
||||
return vec![];
|
||||
}
|
||||
let view = view_options(p);
|
||||
PlanarFace::ALL
|
||||
.into_iter()
|
||||
.filter_map(|face| {
|
||||
let on: Vec<&Facet> = caps.iter().copied().filter(|f| f.end == Some(face)).collect();
|
||||
let map = if effect == ROTATE {
|
||||
vectorcraft_three_d::plane_face_map(bounds, view)
|
||||
} else {
|
||||
vectorcraft_three_d::extrude_face_map(bounds, extrude_options(p), view, face)
|
||||
}?;
|
||||
graphics::face_art(doc, id, &list, (face, &map), bounds.center(), &on, elements).map(|mut art| {
|
||||
art.opacity *= opacity;
|
||||
(face, Arc::new(art))
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A solid (a fill's or a stroke's) with ends the viewer sees: the index of its surface, its
|
||||
/// member, the ends, the opacity and blending mode of its fill or stroke, and whether its surface
|
||||
/// carries an opacity mask (a gradient's transparency under a colored light, [`surface`]).
|
||||
struct Filled {
|
||||
at: usize,
|
||||
member: usize,
|
||||
caps: Vec<Facet>,
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
masked: bool,
|
||||
}
|
||||
|
||||
/// Does a surface in `paint` carry an opacity mask ([`surface`])?
|
||||
fn masks_surface(paint: &Paint, colored: bool) -> bool {
|
||||
colored && crate::lighting::opaque_paint(paint).1.is_some()
|
||||
}
|
||||
|
||||
/// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is
|
||||
/// drawn right after (the last of those solids holding its face) and its face. Solids in a run
|
||||
/// with the same opacity and blending mode share their graphics. With `per_member`
|
||||
/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get
|
||||
/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes.
|
||||
/// All the groups share one limit on the path elements drawn: once it is reached, later groups
|
||||
/// draw no graphics.
|
||||
fn placed_graphics(
|
||||
doc: Option<&Document>,
|
||||
id: NodeId,
|
||||
effect: (&str, &Value),
|
||||
bounds: Rect,
|
||||
filled: &[Filled],
|
||||
per_member: bool,
|
||||
) -> Vec<(usize, PlanarFace, Arc<Node>)> {
|
||||
let mut groups: Vec<Vec<&Filled>> = vec![];
|
||||
for f in filled {
|
||||
// Solids whose fills or strokes differ in opacity or blending mode get graphics of their
|
||||
// own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask
|
||||
// gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the
|
||||
// group of the solid before it, so a graphic is never drawn past a solid painted between.
|
||||
let joins = |first: &Filled| {
|
||||
(!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked
|
||||
};
|
||||
match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) {
|
||||
Some(g) => g.push(f),
|
||||
None => groups.push(vec![f]),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
let mut elements = 0usize;
|
||||
for group in groups {
|
||||
let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect();
|
||||
let opacity = group.first().map_or(1.0, |f| f.opacity);
|
||||
let blend = group.first().map_or(BlendMode::Normal, |f| f.blend);
|
||||
for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) {
|
||||
if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) {
|
||||
Arc::make_mut(&mut art).blend = blend;
|
||||
out.push((f.at, face, art));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One solid's surface as [`surfaces_for`] builds it: its faces' depths, its art, its member's
|
||||
/// scopes, and for each face the end of a solid it is, when the viewer sees it.
|
||||
type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>);
|
||||
|
||||
/// [`with_graphics`] of built surfaces, each drawn whole.
|
||||
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts)
|
||||
}
|
||||
|
||||
/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each
|
||||
/// right after its surface, with that surface's scopes and its opacity mask (a gradient's
|
||||
/// transparency), so a graphic is hidden where its cap is.
|
||||
fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc<Node>)>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
let mut out = Vec::with_capacity(surfaces.len() + arts.len());
|
||||
for (k, (scopes, s)) in surfaces.into_iter().enumerate() {
|
||||
let mask = s.extras().mask.clone();
|
||||
out.push((scopes, s));
|
||||
out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| {
|
||||
let mut art = art.clone();
|
||||
if let Some(mask) = &mask {
|
||||
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
|
||||
}
|
||||
(scopes, art)
|
||||
}));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The ends of `f` the viewer sees, for a fill's solid or a stroke's: where its graphics go.
|
||||
fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
|
||||
f.iter().filter(|f| f.end.is_some() && !f.away)
|
||||
}
|
||||
|
||||
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
|
||||
/// faces drawn right after the last of the solids' surfaces that holds that face.
|
||||
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
let b = union_bounds(shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
|
||||
@@ -795,11 +953,14 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
let masks = has_masks(shapes);
|
||||
// The paint copies of every solid together: past the allowance the source path is drawn.
|
||||
let mut paint_bytes = 0usize;
|
||||
// The caps are copied only when the effect has graphics to draw on them.
|
||||
let graphics_on = !classic && takes_graphics(&fx.id) && !mapped_graphics(&p).is_empty();
|
||||
if is_plane(&fx.id) {
|
||||
// Every part turns about the centre of the object's own bounds (a group's members about
|
||||
// the centre of theirs), so they stay together.
|
||||
let mut out = vec![];
|
||||
for s in shapes {
|
||||
let mut filled = vec![];
|
||||
for (member, s) in shapes.iter().enumerate() {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, blend) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
@@ -807,10 +968,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
|
||||
return None;
|
||||
}
|
||||
if graphics_on {
|
||||
let caps: Vec<Facet> = seen_ends(&f).cloned().collect();
|
||||
if !caps.is_empty() {
|
||||
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) };
|
||||
out.push((s.scopes.as_slice(), Arc::new(art)));
|
||||
}
|
||||
}
|
||||
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
|
||||
let out = with_graphics(out, &arts);
|
||||
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
@@ -842,36 +1011,56 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
let (_, opacity, blend) = paint_of(item, *member);
|
||||
opacity >= 1.0 && blend == BlendMode::Normal
|
||||
});
|
||||
let surfaces: Vec<(Vec<Placed>, Node, &[Scope])> = solids
|
||||
let arts = if !graphics_on {
|
||||
vec![]
|
||||
} else {
|
||||
let filled: Vec<Filled> = solids
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(at, (item, member, _, f, shape))| {
|
||||
let caps: Vec<Facet> = seen_ends(f).cloned().collect();
|
||||
let (paint, opacity, blend) = paint_of(item, *member);
|
||||
let masked = masks_surface(&paint, colored);
|
||||
(!caps.is_empty()).then_some(Filled { at, member: *shape, caps, opacity, blend, masked })
|
||||
})
|
||||
.collect();
|
||||
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
|
||||
};
|
||||
let surfaces: Vec<BuiltSurface> = solids
|
||||
.into_iter()
|
||||
.map(|(item, member, scopes, f, shape)| {
|
||||
let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed));
|
||||
let paints = Paints::of(item, closed);
|
||||
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
|
||||
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
|
||||
let (paint, opacity, blend) = paint_of(item, member);
|
||||
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
|
||||
(depths, art, scopes)
|
||||
(depths, art, scopes, ends)
|
||||
})
|
||||
.collect();
|
||||
if masks {
|
||||
return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect()));
|
||||
return Some(masked(n.id, whole_surfaces(surfaces, &arts)));
|
||||
}
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. With
|
||||
// colored lights a surface can instead be one clipped composite of all its facets. A composite
|
||||
// has no faces to order, so when any surface is one, every surface of the solid, masked ones
|
||||
// included, draws whole in member order.
|
||||
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
|
||||
if !opaque || !plain {
|
||||
return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect());
|
||||
}
|
||||
let plain =
|
||||
surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
|
||||
// A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs
|
||||
// ([`in_runs`]), and each run carries the mask.
|
||||
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect();
|
||||
let (mut placed, mut faces) = (vec![], vec![]);
|
||||
for (surface, (depths, s, _)) in surfaces.into_iter().enumerate() {
|
||||
// ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole,
|
||||
// each graphic right after its surface.
|
||||
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
|
||||
let masked_faces = masks.iter().any(Option::is_some);
|
||||
if !opaque || !plain || (masked_faces && !arts.is_empty()) {
|
||||
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
|
||||
}
|
||||
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
|
||||
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
|
||||
if let NodeKind::Group { children, .. } = s.kind {
|
||||
placed.extend(depths);
|
||||
faces.extend(children.into_iter().map(|face| Some((surface, face))));
|
||||
ends.extend(e);
|
||||
}
|
||||
}
|
||||
let sealed = match fx.id.as_str() {
|
||||
@@ -880,8 +1069,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
_ => extrude_options(&p).cap,
|
||||
};
|
||||
let order = draw_order(&placed, sealed);
|
||||
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
|
||||
let children = if masks.iter().all(Option::is_none) { faces.into_iter().map(|(_, face)| face).collect() } else { in_runs(n.id, faces, &masks) };
|
||||
if masked_faces {
|
||||
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
|
||||
return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]);
|
||||
}
|
||||
// Each face's graphics go right after the last of the faces they are drawn on.
|
||||
let last: Vec<Option<usize>> =
|
||||
arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect();
|
||||
let mut children = Vec::with_capacity(order.len() + arts.len());
|
||||
for (at, k) in order.into_iter().enumerate() {
|
||||
children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face));
|
||||
children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone()));
|
||||
}
|
||||
Some(vec![Arc::new(Node::group(n.id, children))])
|
||||
}
|
||||
|
||||
@@ -966,7 +1165,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
let n = &*resolve(doc, n, "").ok()?;
|
||||
if is_container(n) {
|
||||
return group_solid_art(n);
|
||||
return group_solid_art(doc, n);
|
||||
}
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
@@ -975,26 +1174,23 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
let remaining: Vec<Effect>;
|
||||
if let Some((index, fx)) = solid(&n.appearance.effects) {
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
let (shadow, surfaces) = art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
|
||||
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
|
||||
children.extend(shadow.into_iter().chain(surfaces));
|
||||
// Later geometry effects act on the projected art as a whole.
|
||||
remaining = n
|
||||
.appearance
|
||||
.effects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index))
|
||||
.map(|(_, e)| e.clone())
|
||||
.collect();
|
||||
remaining = past_effect(&n.appearance.effects, index);
|
||||
} else {
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
remaining = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
|
||||
remaining = crate::without_geometry(&n.appearance.effects);
|
||||
// The object's Transform effects, applied to the path above, transform the items' raster
|
||||
// effects too.
|
||||
let mut paints = paints;
|
||||
crate::raster::follow_paints(&mut paints, &n.appearance.effects);
|
||||
// Every item's shadow goes behind every item's art.
|
||||
let mut shadows = vec![];
|
||||
for item in &paints {
|
||||
if let Some((index, fx)) = solid(item.effects()) {
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
|
||||
let (shadow, surfaces) = art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
|
||||
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
|
||||
let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
|
||||
let with_later = |mut art: Arc<Node>| {
|
||||
Arc::make_mut(&mut art).appearance.effects = later.clone();
|
||||
@@ -1003,7 +1199,8 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
shadows.extend(shadow.into_iter().map(with_later));
|
||||
children.extend(surfaces.into_iter().map(with_later));
|
||||
} else {
|
||||
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
|
||||
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
|
||||
}
|
||||
}
|
||||
children.splice(0..0, shadows);
|
||||
@@ -1018,20 +1215,105 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
/// geometry effects before it reshape the members, those after it bend the result as a whole; the
|
||||
/// group's own fills and strokes are not drawn. `None` when the effect is only on one of the
|
||||
/// group's own fills or strokes, or when its members can't become solids.
|
||||
fn group_solid_art(n: &Node) -> Option<Node> {
|
||||
fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
let (index, fx) = solid(&n.appearance.effects)?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let (shadow, surfaces) = art_for(n, fx, &shapes)?;
|
||||
let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?;
|
||||
let children = shadow.into_iter().chain(surfaces).collect();
|
||||
let remaining =
|
||||
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
|
||||
let remaining = past_effect(&n.appearance.effects, index);
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children, clip: false };
|
||||
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its
|
||||
/// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their
|
||||
/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or
|
||||
/// Rotate there, or its art can't be built.
|
||||
pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option<usize>) -> Option<graphics::GraphicFrame> {
|
||||
frame_of(doc, n, item, &solid)
|
||||
}
|
||||
|
||||
/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude &
|
||||
/// Bevel or Rotate.
|
||||
pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<graphics::GraphicFrame> {
|
||||
frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && SOLIDS.contains(&e.id.as_str())).map(|e| (index, e)))
|
||||
}
|
||||
|
||||
/// Does a visible geometry effect come after the 3D effect at `index` in the effects of `n` (on the
|
||||
/// object itself with `item` `None`, else on its fill or stroke `item`)? Such an effect moves or
|
||||
/// bends the drawn art, graphics included, while [`graphic_frame_at`] places the graphics on the
|
||||
/// art before it.
|
||||
pub fn graphics_reshaped_after(n: &Node, item: Option<usize>, index: usize) -> bool {
|
||||
n.appearance.effects_at(item).and_then(|fx| fx.get(index + 1..)).is_some_and(crate::has_geometry)
|
||||
}
|
||||
|
||||
/// Finds a 3D effect in a list of effects, with its index there.
|
||||
type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p;
|
||||
|
||||
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
|
||||
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
|
||||
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![] }])
|
||||
}
|
||||
}
|
||||
};
|
||||
if !takes_graphics(&fx.id) {
|
||||
return None;
|
||||
}
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let b = union_bounds(&shapes)?;
|
||||
let view = view_options(&p);
|
||||
if fx.id == ROTATE {
|
||||
let plane = vectorcraft_three_d::plane_face_map(b, view);
|
||||
return Some(graphics::GraphicFrame::new(b, plane, None));
|
||||
}
|
||||
let (_, bounds) = solid_parts(&shapes, b);
|
||||
let options = extrude_options(&p);
|
||||
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
|
||||
Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)))
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// `effects` without the 3D effect at `index` and the geometry effects before it, which shape the
|
||||
/// art it projects. Each raster effect before it follows the Transform effects among those
|
||||
/// ([`crate::without_geometry`]), unless a Transform effect after it makes copies or moves at
|
||||
/// random ([`crate::raster::holds_back`]); the effects after it stay as they are.
|
||||
pub(crate) fn past_effect(effects: &[Effect], index: usize) -> Vec<Effect> {
|
||||
let (before, after) = effects.split_at(index.min(effects.len()));
|
||||
let after = after.get(1..).unwrap_or_default();
|
||||
let kept: Vec<Effect> = if after.iter().any(crate::raster::holds_back) {
|
||||
before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect()
|
||||
} else {
|
||||
crate::without_geometry(before)
|
||||
};
|
||||
kept.into_iter().chain(after.iter().cloned()).collect()
|
||||
}
|
||||
|
||||
/// One solid of a 3D object as a mesh, with the color it is painted.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SolidMesh {
|
||||
|
||||
@@ -0,0 +1,631 @@
|
||||
//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials ›
|
||||
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a
|
||||
//! plane, turned, foreshortened and shaded with that face and clipped to it.
|
||||
//!
|
||||
//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale,
|
||||
//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of
|
||||
//! the object's bounds in the face's own plane (points, x to the right and y down as the face is
|
||||
//! seen from the front of that face), its size as a share of the symbol's own, and its turn
|
||||
//! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from
|
||||
//! behind, so the graphic reads the right way round there.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol};
|
||||
use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath};
|
||||
use vectorcraft_three_d::{FaceMap, Facet, PlanarFace};
|
||||
|
||||
/// The effect parameter that holds the graphics.
|
||||
pub const GRAPHICS: &str = "graphics";
|
||||
|
||||
/// The most graphics one 3D effect maps.
|
||||
pub const MAX_GRAPHICS: usize = 64;
|
||||
|
||||
/// The most fills and stroke outlines the art of one symbol draws as a graphic.
|
||||
const MAX_PIECES: usize = 4096;
|
||||
|
||||
/// The most path elements the graphics of one 3D effect draw together, after a perspective cuts
|
||||
/// their curves.
|
||||
const MAX_ELEMENTS: usize = 400_000;
|
||||
|
||||
/// The pieces each curve of a graphic is cut into under a perspective map, which bends it.
|
||||
const PERSPECTIVE_PIECES: usize = 8;
|
||||
|
||||
/// How deep symbol instances in a graphic's art may nest.
|
||||
const MAX_NESTING: usize = 8;
|
||||
|
||||
/// How deep the objects of a graphic's art may be, counting groups and the art of the symbols it
|
||||
/// places: as deep as an object may be drawn.
|
||||
const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH;
|
||||
|
||||
/// The size range of a graphic, as a percentage of its symbol's own size.
|
||||
pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0);
|
||||
|
||||
/// How far a graphic's center may be from the center of its object, in points.
|
||||
pub const MAX_OFFSET: f64 = 1e6;
|
||||
|
||||
/// One graphic mapped onto a face of a 3D object.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MappedGraphic {
|
||||
pub symbol: String,
|
||||
pub face: PlanarFace,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
/// Percent of the symbol's own size.
|
||||
pub scale: f64,
|
||||
/// Degrees, counterclockwise.
|
||||
pub rotation: f64,
|
||||
}
|
||||
|
||||
impl MappedGraphic {
|
||||
pub fn to_value(&self) -> Value {
|
||||
json!({"symbol": self.symbol, "face": self.face.id(), "x": self.x, "y": self.y, "scale": self.scale, "rotation": self.rotation})
|
||||
}
|
||||
|
||||
/// The graphic `v` describes. Only `symbol` is required: `face` defaults to front, the offsets
|
||||
/// and the rotation to 0 and the scale to 100.
|
||||
pub fn from_value(v: &Value) -> Result<Self, String> {
|
||||
let Value::Object(m) = v else { return Err(format!("each of `{GRAPHICS}` must be an object")) };
|
||||
if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "symbol" | "face" | "x" | "y" | "scale" | "rotation")) {
|
||||
return Err(format!("`{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}`"));
|
||||
}
|
||||
let symbol = match m.get("symbol") {
|
||||
Some(Value::String(s)) if !s.trim().is_empty() => s.clone(),
|
||||
_ => return Err(format!("each of `{GRAPHICS}` needs `symbol`, the name of a symbol")),
|
||||
};
|
||||
let face = match m.get("face") {
|
||||
None => PlanarFace::Front,
|
||||
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?,
|
||||
};
|
||||
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!("`{GRAPHICS}` {key} must be a number from {lo} to {hi}")),
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
symbol,
|
||||
face,
|
||||
x: number("x", 0.0, (-MAX_OFFSET, MAX_OFFSET))?,
|
||||
y: number("y", 0.0, (-MAX_OFFSET, MAX_OFFSET))?,
|
||||
scale: number("scale", 100.0, SCALE_RANGE)?,
|
||||
rotation: number("rotation", 0.0, (-360.0, 360.0))?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the graphic's art goes in the face's plane, for symbol art whose bounds are `art` on an
|
||||
/// object whose bounds have center `center`.
|
||||
fn placement(&self, art: Rect, center: Point) -> Affine {
|
||||
let place = Affine::translate((center.x + self.x, center.y + self.y))
|
||||
* Affine::rotate(-self.rotation.to_radians())
|
||||
* Affine::scale(self.scale / 100.0)
|
||||
* Affine::translate(-art.center().to_vec2());
|
||||
match self.face {
|
||||
PlanarFace::Front => place,
|
||||
// Seen from behind, the back's right is the front's left.
|
||||
PlanarFace::Back => {
|
||||
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D effects that take graphics: Extrude & Bevel (its caps) and Rotate (the plane), the two
|
||||
/// object types of the 3D and Materials panel with planar faces.
|
||||
pub fn takes_graphics(id: &str) -> bool {
|
||||
id == super::EXTRUDE || id == super::ROTATE
|
||||
}
|
||||
|
||||
/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold
|
||||
/// anything; commands check every entry with [`validate`]).
|
||||
pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
|
||||
match p.get(GRAPHICS) {
|
||||
Some(Value::Array(list)) => list.iter().take(MAX_GRAPHICS).filter_map(|v| MappedGraphic::from_value(v).ok()).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel and Rotate take
|
||||
/// graphics, and a plane has only a front.
|
||||
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
let list = match p.get(GRAPHICS) {
|
||||
None => return Ok(()),
|
||||
Some(Value::Array(list)) => list,
|
||||
Some(_) => return Err(format!("`{GRAPHICS}` must be an array")),
|
||||
};
|
||||
if list.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if !takes_graphics(id) {
|
||||
return Err("Graphics map onto planar faces: use the Extrude or Plane object type".into());
|
||||
}
|
||||
if list.len() > MAX_GRAPHICS {
|
||||
return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics"));
|
||||
}
|
||||
for v in list {
|
||||
let g = MappedGraphic::from_value(v)?;
|
||||
if id == super::ROTATE && g.face == PlanarFace::Back {
|
||||
return Err("A plane has one face: map its graphics onto the front".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first symbol the graphics in `p` name that `doc` does not have, leaving out the symbols the
|
||||
/// 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))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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 pieces = pieces_of(doc, symbol)?;
|
||||
elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum());
|
||||
if elements > MAX_ELEMENTS {
|
||||
return Err("The graphics are too complex: simplify the symbols' art".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 {
|
||||
let segments = |s: &SubPath| (0..s.segment_count()).map(|i| if s.segment_is_line(i) { 1 } else { curve }).sum::<usize>();
|
||||
path.subpaths.iter().map(|s| 1 + usize::from(s.closed) + segments(s)).sum()
|
||||
}
|
||||
|
||||
/// One area of a graphic's art, drawn with one paint: a fill, or a stroke's outline.
|
||||
struct Piece {
|
||||
path: PathData,
|
||||
rule: FillRule,
|
||||
paint: Paint,
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
}
|
||||
|
||||
/// The areas the art of `symbol` paints, back to front, at the symbol's natural size: the fills of
|
||||
/// its paths, compound paths and type (as outlines), and its strokes' outlines, through the symbol
|
||||
/// instances it holds (with their changes to dynamic symbols, and through 9-slice guides). Hidden objects, guides, clipping paths and images are left out, and clipping
|
||||
/// groups draw their art unclipped.
|
||||
fn pieces_of(doc: &Document, symbol: &Symbol) -> Result<Vec<Piece>, String> {
|
||||
fn walk(doc: &Document, n: &Node, outer: f32, xf: Affine, (depth, level): (usize, usize), out: &mut Vec<Piece>) -> Result<(), String> {
|
||||
if !n.visible || n.is_guide() {
|
||||
return Ok(());
|
||||
}
|
||||
if level > MAX_LEVELS {
|
||||
return Err(format!("A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art"));
|
||||
}
|
||||
let opacity = outer * n.opacity;
|
||||
let shape = match &n.kind {
|
||||
NodeKind::Path { path, rule, clipping: false, .. } => Some((path.clone(), *rule)),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
Some((PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule))
|
||||
}
|
||||
NodeKind::Text(_) => {
|
||||
if let Some(mut outlined) = crate::outline_text(n) {
|
||||
// The outlines take the type's place, with its opacity.
|
||||
outlined.visible = true;
|
||||
outlined.opacity = n.opacity;
|
||||
walk(doc, &outlined, outer, xf, (depth, level + 1), out)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, xf: at } => {
|
||||
if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) {
|
||||
if depth >= MAX_NESTING {
|
||||
return Err(format!("A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art"));
|
||||
}
|
||||
// The instance shows its own changes to a dynamic symbol's art, and a symbol
|
||||
// with 9-slice guides is placed through them, as the canvas draws it. The
|
||||
// pieces are not clipped, so paths that cross a guide are cut at it.
|
||||
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n);
|
||||
if doc.symbol_slice_map(symbol, *at).is_some() {
|
||||
let Some(placed) = doc.place_symbol_art_unclipped(symbol, &art, *at) else {
|
||||
return Err("A graphic's art holds too many objects: simplify the symbol's art".into());
|
||||
};
|
||||
walk(doc, &placed, opacity, xf, (depth + 1, level + 1), out)?;
|
||||
} else {
|
||||
walk(doc, &art, opacity, xf * *at, (depth + 1, level + 1), out)?;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
_ => {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(doc, c, opacity, xf, (depth, level + 1), out)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
let Some((path, rule)) = shape else { return Ok(()) };
|
||||
// Symbol art keeps its strokes' widths as drawn while its geometry is scaled to the
|
||||
// symbol's square, so a stroke is outlined after the art takes its size.
|
||||
let path = path.transformed(xf);
|
||||
for item in n.appearance.items.iter().filter(|i| i.visible()) {
|
||||
let (area, rule, paint, item_opacity, blend) = match item {
|
||||
AppearanceItem::Fill(f) => (path.clone(), rule, f.paint.clone(), f.opacity, f.blend),
|
||||
AppearanceItem::Stroke(s) if s.width > 0.0 && s.width.is_finite() => {
|
||||
(crate::stroke::outline_region(&path, rule, s), FillRule::EvenOdd, s.paint.clone(), s.opacity, s.blend)
|
||||
}
|
||||
AppearanceItem::Stroke(_) => continue,
|
||||
};
|
||||
if matches!(paint, Paint::None) || area.bounds().is_none() {
|
||||
continue;
|
||||
}
|
||||
if out.len() >= MAX_PIECES {
|
||||
return Err(format!("A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art"));
|
||||
}
|
||||
// A placed gradient or pattern takes the same size and place as its path.
|
||||
let mut paint = paint;
|
||||
match &mut paint {
|
||||
Paint::Gradient(g) => g.transform(xf),
|
||||
Paint::Pattern { xf: placed, .. } => *placed = xf * *placed,
|
||||
Paint::None | Paint::Solid { .. } => {}
|
||||
}
|
||||
out.push(Piece { path: area, rule, paint, opacity: opacity * item_opacity, blend });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(doc, &symbol.art, 1.0, doc.symbol_natural_xf(&symbol.name), (0, 1), &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `path` through `map`: exactly for an affine map, otherwise with each curve cut into
|
||||
/// [`PERSPECTIVE_PIECES`] pieces whose control points go through it (straight lines stay straight
|
||||
/// under a perspective). Fails when part of it has no page point, or when it takes more than `room`
|
||||
/// elements.
|
||||
fn map_path(path: &PathData, map: &FaceMap, affine: Option<Affine>, room: usize) -> Result<BezPath, NotMapped> {
|
||||
let bp = path.to_bezpath();
|
||||
if let Some(a) = affine {
|
||||
return if bp.elements().len() <= room { Ok(a * bp) } else { Err(NotMapped::Full) };
|
||||
}
|
||||
let to = |p: Point| map.to_page(p).ok_or(NotMapped::Behind);
|
||||
let mut out = BezPath::new();
|
||||
let mut at = Point::ZERO;
|
||||
for el in bp.elements() {
|
||||
if out.elements().len() > room {
|
||||
return Err(NotMapped::Full);
|
||||
}
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
out.move_to(to(p)?);
|
||||
at = p;
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
out.line_to(to(p)?);
|
||||
at = p;
|
||||
}
|
||||
PathEl::QuadTo(c, p) => {
|
||||
cubic_to(&mut out, vectorcraft_geom::kurbo::QuadBez::new(at, c, p).raise(), map).ok_or(NotMapped::Behind)?;
|
||||
at = p;
|
||||
}
|
||||
PathEl::CurveTo(c1, c2, p) => {
|
||||
cubic_to(&mut out, CubicBez::new(at, c1, c2, p), map).ok_or(NotMapped::Behind)?;
|
||||
at = p;
|
||||
}
|
||||
PathEl::ClosePath => out.close_path(),
|
||||
}
|
||||
}
|
||||
if out.elements().len() <= room { Ok(out) } else { Err(NotMapped::Full) }
|
||||
}
|
||||
|
||||
/// Why [`map_path`] drew nothing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum NotMapped {
|
||||
/// Part of the path has no page point: it is at or behind the eye.
|
||||
Behind,
|
||||
/// The path takes more elements than it has room for.
|
||||
Full,
|
||||
}
|
||||
|
||||
/// Curve `c` through `map`, cut into [`PERSPECTIVE_PIECES`] pieces. A piece that lies in front of
|
||||
/// the eye while a control point does not is split further ([`piece_to`]). `None` when part of a
|
||||
/// piece has no page point.
|
||||
fn cubic_to(out: &mut BezPath, c: CubicBez, map: &FaceMap) -> Option<()> {
|
||||
for k in 0..PERSPECTIVE_PIECES {
|
||||
let (t0, t1) = (k as f64 / PERSPECTIVE_PIECES as f64, (k + 1) as f64 / PERSPECTIVE_PIECES as f64);
|
||||
let s = c.subsegment(t0..t1);
|
||||
if !map.maps_curve([s.p0, s.p1, s.p2, s.p3]) {
|
||||
return None;
|
||||
}
|
||||
piece_to(out, s, map, MAX_SPLITS)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// How many times [`piece_to`] halves a piece whose control points are behind the eye.
|
||||
const MAX_SPLITS: usize = 4;
|
||||
|
||||
/// Piece `s`, which lies in front of the eye, through `map`: halved until the control points of
|
||||
/// each half have page points, at most `splits` times, and drawn straight past that.
|
||||
fn piece_to(out: &mut BezPath, s: CubicBez, map: &FaceMap, splits: usize) -> Option<()> {
|
||||
let end = map.to_page(s.p3)?;
|
||||
match (map.to_page(s.p1), map.to_page(s.p2)) {
|
||||
(Some(c1), Some(c2)) => out.curve_to(c1, c2, end),
|
||||
_ if splits == 0 => out.line_to(end),
|
||||
_ => {
|
||||
let (a, b) = s.subdivide();
|
||||
piece_to(out, a, map, splits - 1)?;
|
||||
piece_to(out, b, map, splits - 1)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The graphics `graphics` lists for `face`, drawn on caps `caps` (the faces of that end of the
|
||||
/// object's solids that the viewer sees) through `map`, for an object whose bounds have
|
||||
/// center `center`: one clipping group of every such graphic, shaded with the first cap's light.
|
||||
/// Pattern tiles keep their colors: the document's pattern draws them. A graphic whose symbol
|
||||
/// `doc` does not have draws nothing. `elements` counts the path elements
|
||||
/// the effect's graphics have drawn so far, after a perspective cuts their curves, and is shared by
|
||||
/// every call for one effect. `None` when there is nothing to draw or that count passes
|
||||
/// [`MAX_ELEMENTS`].
|
||||
pub(super) fn face_art(
|
||||
doc: Option<&Document>,
|
||||
id: NodeId,
|
||||
graphics: &[MappedGraphic],
|
||||
(face, map): (PlanarFace, &FaceMap),
|
||||
center: Point,
|
||||
caps: &[&Facet],
|
||||
elements: &mut usize,
|
||||
) -> Option<Node> {
|
||||
let doc = doc?;
|
||||
let light = caps.first()?.illumination;
|
||||
let affine = map.local_affine(center).filter(|_| map.is_affine());
|
||||
let mut children = vec![];
|
||||
for g in graphics.iter().filter(|g| g.face == face) {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
|
||||
// A symbol past the limits is left out; the other graphics still draw.
|
||||
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
|
||||
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
|
||||
let place = g.placement(bounds, center);
|
||||
// Gradients follow the face's map as it is near the graphic's center.
|
||||
let middle = place * bounds.center();
|
||||
// When the center is at or behind the eye, they follow it near the middle of the part that
|
||||
// is in front; a graphic with no part in front is left out.
|
||||
let local = map.local_affine(middle).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 { continue };
|
||||
let gradient_map = local * place;
|
||||
for piece in pieces {
|
||||
let placed = piece.path.transformed(place);
|
||||
// Each anchor draws at least one element. A perspective cuts curves into more, and
|
||||
// straight lines stay one each: the path may take what is left of the limit, and is
|
||||
// counted as it is drawn. Past the limit, the face draws nothing.
|
||||
let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum();
|
||||
let before = *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,
|
||||
};
|
||||
*elements = before.saturating_add(mapped.elements().len());
|
||||
let mut paint = piece.paint;
|
||||
vectorcraft_doc::recolor::map_paint(&mut paint, &|c| crate::lighting::shade(c, light));
|
||||
// A pattern's tiles follow the graphic onto the face, as its gradients do below.
|
||||
if let Paint::Pattern { xf, .. } = &mut paint {
|
||||
*xf = gradient_map * *xf;
|
||||
}
|
||||
let mut fill = FillLayer::new(paint);
|
||||
fill.opacity = piece.opacity;
|
||||
fill.blend = piece.blend;
|
||||
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
|
||||
appearance.transform_gradients(gradient_map);
|
||||
let mut node = Node::path(id, PathData::from_bezpath(&mapped), appearance);
|
||||
if let NodeKind::Path { rule: r, .. } = &mut node.kind {
|
||||
*r = rule;
|
||||
}
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
}
|
||||
if children.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut clip = BezPath::new();
|
||||
for cap in caps {
|
||||
// A cap'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 = cap.path().to_bezpath();
|
||||
if outline.area() < 0.0 {
|
||||
outline = outline.reverse_subpaths();
|
||||
}
|
||||
clip.extend(outline.iter());
|
||||
}
|
||||
let clip = Node::path(id, PathData::from_bezpath(&clip), Appearance::default());
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
|
||||
}
|
||||
|
||||
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
|
||||
pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
|
||||
let symbol = doc.symbols.iter().find(|s| s.name == name)?;
|
||||
pieces_of(doc, symbol).ok()?.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
|
||||
/// offsets are from their center) and the maps of its front and back faces, when it has them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct GraphicFrame {
|
||||
pub bounds: Rect,
|
||||
front: Option<FaceMap>,
|
||||
back: Option<FaceMap>,
|
||||
}
|
||||
|
||||
impl GraphicFrame {
|
||||
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
|
||||
Self { bounds, front, back }
|
||||
}
|
||||
|
||||
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
|
||||
match face {
|
||||
PlanarFace::Front => self.front.as_ref(),
|
||||
PlanarFace::Back => self.back.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The point of `face`'s plane that offset `(x, y)` names, as [`MappedGraphic`] places a
|
||||
/// graphic's center.
|
||||
fn art_point(&self, face: PlanarFace, (x, y): (f64, f64)) -> Point {
|
||||
let c = self.bounds.center();
|
||||
match face {
|
||||
PlanarFace::Front => Point::new(c.x + x, c.y + y),
|
||||
PlanarFace::Back => Point::new(c.x - x, c.y + y),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
|
||||
/// viewer. `None` when the object has no such face or the point has no page point.
|
||||
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
|
||||
let map = self.map(g.face)?;
|
||||
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
|
||||
}
|
||||
|
||||
/// The offset of a graphic on `face` whose center lands on page point `page`.
|
||||
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
|
||||
let art = self.map(face)?.to_art(page)?;
|
||||
let c = self.bounds.center();
|
||||
let (x, y) = match face {
|
||||
PlanarFace::Front => (art.x - c.x, art.y - c.y),
|
||||
PlanarFace::Back => (c.x - art.x, art.y - c.y),
|
||||
};
|
||||
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
|
||||
}
|
||||
|
||||
/// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most
|
||||
/// 100: where a newly mapped graphic starts.
|
||||
pub fn fitting_scale(&self, art: Rect) -> f64 {
|
||||
let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9));
|
||||
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes').
|
||||
pub fn graphic_symbols(n: &Node) -> Vec<String> {
|
||||
appearance_graphic_symbols(&n.appearance)
|
||||
}
|
||||
|
||||
/// The symbols the graphics of the 3D effects in `appearance` name, as [`graphic_symbols`]: for a
|
||||
/// graphic style's appearance.
|
||||
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)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Makes the graphics of `n`'s 3D effects that name symbol `from` name `to` instead. Returns
|
||||
/// whether any changed.
|
||||
pub fn rename_graphic_symbol(n: &mut Node, from: &str, to: &str) -> bool {
|
||||
// Checked first, so an appearance that names another symbol is not copied.
|
||||
graphic_symbols(n).iter().any(|s| s == from) && rename_appearance_graphic_symbol(&mut n.appearance, from, to)
|
||||
}
|
||||
|
||||
/// [`rename_graphic_symbol`] for the 3D effects in `appearance`: for a graphic style's appearance.
|
||||
pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, to: &str) -> bool {
|
||||
if !appearance_graphic_symbols(appearance).iter().any(|s| s == from) {
|
||||
return false;
|
||||
}
|
||||
let mut lists: Vec<&mut Vec<vectorcraft_doc::Effect>> = vec![];
|
||||
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 g in list.iter_mut() {
|
||||
if g.get("symbol").and_then(Value::as_str) == Some(from) {
|
||||
g["symbol"] = json!(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Does `n` or any object in it, opacity masks included, have a graphic that names symbol `from`?
|
||||
pub fn names_graphic_symbol(n: &Node, from: &str) -> bool {
|
||||
let mut found = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= graphic_symbols(c).iter().any(|s| s == from));
|
||||
found
|
||||
}
|
||||
|
||||
/// [`rename_graphic_symbol`] for `n` and every object in it, at any depth, opacity masks included.
|
||||
/// Only the parts that name `from` are copied. Returns whether any changed.
|
||||
pub fn rename_graphic_symbol_in(n: &mut Node, from: &str, to: &str) -> bool {
|
||||
let names = names_graphic_symbol;
|
||||
let mut changed = rename_graphic_symbol(n, from, to);
|
||||
if let Some(mask) = n.extras_if_any().and_then(|x| x.mask.as_deref_mut()).filter(|m| names(&m.art, from)) {
|
||||
changed |= rename_graphic_symbol_in(Arc::make_mut(&mut mask.art), from, to);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut().filter(|c| names(c, from)) {
|
||||
changed |= rename_graphic_symbol_in(Arc::make_mut(c), from, to);
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// `p` with graphic `g` added at the end of its list.
|
||||
pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
|
||||
let mut out = p.as_object().cloned().unwrap_or_else(Map::new);
|
||||
let mut list = match out.get(GRAPHICS) {
|
||||
Some(Value::Array(list)) => list.clone(),
|
||||
_ => vec![],
|
||||
};
|
||||
list.push(g.to_value());
|
||||
out.insert(GRAPHICS.into(), Value::Array(list));
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests_graphics.rs"]
|
||||
mod tests;
|
||||
@@ -8,7 +8,7 @@ use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
|
||||
use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints};
|
||||
@@ -24,6 +24,19 @@ const MAX_DEPTH: usize = 64;
|
||||
/// many steps.
|
||||
pub(super) const MAX_WORK: usize = 1 << 18;
|
||||
|
||||
/// The most times resolving one 3D effect's art may cut an image's frame to a clipping path to
|
||||
/// learn whether the clip shows any of it ([`Resolver::hidden`]).
|
||||
pub(super) const MAX_IMAGE_CUTS: usize = 1024;
|
||||
|
||||
/// The area, in square points, under which what a clip shows of an image's frame counts as nothing:
|
||||
/// the sliver left where the frame only touches the clipping path.
|
||||
const SHOWN_AREA: f64 = 1e-9;
|
||||
|
||||
/// The precision an image's frame is cut to a clipping path with: the cut drops pieces narrower
|
||||
/// than this, so it is far below [`po::DEFAULT_PRECISION`], and a strip of the image much
|
||||
/// narrower than a hundredth of a point still counts as shown.
|
||||
const CUT_PRECISION: f64 = 1e-6;
|
||||
|
||||
/// The error for an image a 3D effect is asked to build from.
|
||||
pub(crate) fn image_refusal(label: &str) -> String {
|
||||
format!("{label} can't build a solid from an image: trace it first with Object › Image Trace › Make.")
|
||||
@@ -66,7 +79,7 @@ pub(crate) fn resolve_for<'a>(doc: Option<&Document>, n: &'a Node, label: &str,
|
||||
if !needs(n) {
|
||||
return Ok(Cow::Borrowed(n));
|
||||
}
|
||||
let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, shown: None };
|
||||
let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, cuts: 0, shown: None };
|
||||
let children = r.content(n, 0);
|
||||
#[cfg(test)]
|
||||
WORK.with(|w| w.set(r.work));
|
||||
@@ -90,8 +103,18 @@ struct Resolver<'a> {
|
||||
leaves: usize,
|
||||
/// The objects visited or made so far, counted against [`MAX_WORK`].
|
||||
work: usize,
|
||||
/// Inside clipping groups, the box of what their clipping paths show together.
|
||||
shown: Option<Rect>,
|
||||
/// The image frames cut to clipping paths so far, counted against [`MAX_IMAGE_CUTS`].
|
||||
cuts: usize,
|
||||
/// Inside clipping groups, what their clipping paths show together.
|
||||
shown: Option<Shown>,
|
||||
}
|
||||
|
||||
/// The clipping paths around the art being listed, outermost first, with the box of what they
|
||||
/// show together.
|
||||
#[derive(Clone)]
|
||||
struct Shown {
|
||||
bounds: Rect,
|
||||
clips: Vec<Arc<(PathData, FillRule)>>,
|
||||
}
|
||||
|
||||
impl Resolver<'_> {
|
||||
@@ -111,15 +134,52 @@ impl Resolver<'_> {
|
||||
/// `f` run on the art of `c`. The effects of an object or group can move its art into a clip,
|
||||
/// so inside one with effects no image is left out for lying outside the clip ([`Self::shown`]).
|
||||
fn inside<T>(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
|
||||
let outer = self.shown;
|
||||
if has_effects(c) {
|
||||
self.shown = None;
|
||||
if !has_effects(c) {
|
||||
return f(self);
|
||||
}
|
||||
let outer = self.shown.take();
|
||||
let out = f(self);
|
||||
self.shown = outer;
|
||||
out
|
||||
}
|
||||
|
||||
/// Does the plain image `c` lie wholly outside what the clips around it show together, each
|
||||
/// clipping path with its own fill rule? Its frame, the pixel rectangle as its transform places
|
||||
/// it, is cut to each clip in turn until nothing is left. An error when a cut fails or the cuts
|
||||
/// pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out.
|
||||
fn hidden(&mut self, c: &Node) -> Result<bool, String> {
|
||||
let Some(shown) = &self.shown else { return Ok(false) };
|
||||
let NodeKind::Image(im) = &c.kind else { return Ok(false) };
|
||||
let Some(b) = c.visual_bounds() else { return Ok(true) };
|
||||
if b.intersect(shown.bounds).area() <= 0.0 {
|
||||
return Ok(true);
|
||||
}
|
||||
let (w, h) = (f64::from(im.width), f64::from(im.height));
|
||||
let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| im.xf * Point::new(x, y));
|
||||
if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
|
||||
return Err(image_refusal(self.label));
|
||||
}
|
||||
let clips = shown.clips.clone();
|
||||
let mut left = PathData::single(SubPath::polyline(&corners, true));
|
||||
for clip in clips {
|
||||
let Some(here) = clip.0.bounds() else { return Ok(true) };
|
||||
if left.bounds().is_none_or(|l| l.intersect(here).area() <= 0.0) {
|
||||
return Ok(true);
|
||||
}
|
||||
self.cuts += 1;
|
||||
if self.cuts > MAX_IMAGE_CUTS {
|
||||
return Err(self.too_much_work());
|
||||
}
|
||||
self.spend(1)?;
|
||||
left =
|
||||
po::try_boolean(&left, FillRule::NonZero, &clip.0, clip.1, po::BoolOp::Intersect, CUT_PRECISION).map_err(|_| self.too_complex())?;
|
||||
if left.subpaths.iter().all(|s| s.area().abs() <= SHOWN_AREA) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// The art `n`, a symbol instance, a blend, a clipping group or layer, or a group holding one,
|
||||
/// shows, as the members of a plain group.
|
||||
fn content(&mut self, n: &Node, depth: usize) -> Result<Vec<Arc<Node>>, String> {
|
||||
@@ -162,11 +222,15 @@ impl Resolver<'_> {
|
||||
if clip_nested_past(first, MAX_DEPTH.saturating_sub(depth)) {
|
||||
return Err(self.too_deep());
|
||||
}
|
||||
let clip = clip_area(first);
|
||||
// An image wholly outside every clip around it shows nothing and is left out.
|
||||
let outer = self.shown;
|
||||
let clip = Arc::new(clip_area(first));
|
||||
// An image wholly outside what the clips around it show together draws nothing and
|
||||
// is left out.
|
||||
let here = clip.0.bounds().unwrap_or(Rect::ZERO);
|
||||
self.shown = Some(outer.map_or(here, |o| o.intersect(here)));
|
||||
let outer = self.shown.take();
|
||||
let mut inner_shown = outer.clone().unwrap_or(Shown { bounds: here, clips: vec![] });
|
||||
inner_shown.bounds = inner_shown.bounds.intersect(here);
|
||||
inner_shown.clips.push(clip.clone());
|
||||
self.shown = Some(inner_shown);
|
||||
let listed = self.list(rest, depth + 1);
|
||||
self.shown = outer;
|
||||
let (inner, _) = listed?;
|
||||
@@ -198,8 +262,7 @@ impl Resolver<'_> {
|
||||
// Only an image with no effects or fills and strokes of its own is measured by its
|
||||
// frame; any other one may draw inside the clip.
|
||||
let plain = !has_effects(c) && c.appearance.items.iter().all(|i| !i.visible());
|
||||
let hidden = plain && self.shown.is_some_and(|k| c.visual_bounds().is_none_or(|b| b.intersect(k).area() <= 0.0));
|
||||
if hidden {
|
||||
if plain && self.hidden(c)? {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -457,6 +457,68 @@ fn transparency_stays_on_the_whole_surface_and_items_take_their_own_effect() {
|
||||
assert!(matches!(surfaces[1].kind, NodeKind::Path { .. }));
|
||||
}
|
||||
|
||||
/// Two nested squares drawn in the same direction, so only the even-odd rule leaves a hole.
|
||||
fn nested_squares() -> [PathData; 2] {
|
||||
[(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((lo, lo));
|
||||
b.line_to((hi, lo));
|
||||
b.line_to((hi, hi));
|
||||
b.line_to((lo, hi));
|
||||
b.close_path();
|
||||
PathData::from_bezpath(&b)
|
||||
})
|
||||
}
|
||||
|
||||
/// The nested squares as an even-odd compound path and as one even-odd path, painted by `items`.
|
||||
fn even_odd_shapes(items: Vec<AppearanceItem>) -> [Node; 2] {
|
||||
let [outer, inner] = nested_squares();
|
||||
let appearance = Appearance { items, ..Default::default() };
|
||||
let children = vec![
|
||||
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
|
||||
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
|
||||
];
|
||||
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd });
|
||||
compound.appearance = appearance.clone().into();
|
||||
let both = PathData::new(outer.subpaths.into_iter().chain(inner.subpaths).collect());
|
||||
[compound, crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance)]
|
||||
}
|
||||
|
||||
/// Check that `art` draws `item` as one flat child: an even-odd path with a hole in the middle,
|
||||
/// below the 3D art after it.
|
||||
fn assert_flat_item_keeps_the_hole(art: &Node, item: &AppearanceItem, what: &str) {
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
let children = art.children().unwrap();
|
||||
let flat: Vec<usize> =
|
||||
(0..children.len()).filter(|&i| children[i].appearance.items == [item.clone()] && children[i].path_data().is_some()).collect();
|
||||
let [index] = flat[..] else { panic!("{what}: one flat child, got {flat:?}") };
|
||||
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
|
||||
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
|
||||
let bez = path.to_bezpath();
|
||||
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
|
||||
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
|
||||
assert!(index + 1 < children.len(), "{what}: the 3D art is drawn above");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole() {
|
||||
let red = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(RED)));
|
||||
let blue = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(BLUE)));
|
||||
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 4.0));
|
||||
for id in SOLIDS {
|
||||
// The top fill and then the top stroke take the effect; the fill below stays flat.
|
||||
for (top, on) in [(&red, "fill"), (&stroke, "stroke")] {
|
||||
let mut lifted = top.clone();
|
||||
lifted.effects_mut().push(fx(id, json!({})));
|
||||
for (n, shape) in even_odd_shapes(vec![blue.clone(), lifted]).into_iter().zip(["compound path", "path"]) {
|
||||
let what = format!("{id} on the top {on} of a {shape}");
|
||||
let art = solid_art(&n).unwrap_or_else(|| panic!("{what}"));
|
||||
assert_flat_item_keeps_the_hole(&art, &blue, &what);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_and_expand_bake_faces_with_their_own_ids() {
|
||||
for id in SOLIDS {
|
||||
|
||||
@@ -0,0 +1,694 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::color::Color;
|
||||
use vectorcraft_doc::{StrokeLayer, Symbol};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use super::super::{EXTRUDE, INFLATE, ROTATE, graphic_frame, solid_art_in, three_d_params_as, validate_three_d_in, validate_three_d_params};
|
||||
use super::*;
|
||||
|
||||
fn red() -> Color {
|
||||
Color::rgb(1.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
fn square(id: u64, r: Rect, paint: Paint) -> Node {
|
||||
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// A document with symbol "Mark": a red 10 × 10 square.
|
||||
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), Paint::solid(red()))),
|
||||
});
|
||||
d
|
||||
}
|
||||
|
||||
/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view
|
||||
/// straight on.
|
||||
fn object(id: &str, params: Value) -> Node {
|
||||
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
|
||||
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), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
|
||||
n.appearance.effects.push(crate::new_effect(id, &p).unwrap());
|
||||
n
|
||||
}
|
||||
|
||||
/// The graphics clip groups in `art`, in drawing order: each one's mapped paths.
|
||||
fn graphics_in(art: &Node) -> Vec<Vec<(PathData, Paint)>> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if let NodeKind::Group { children, clip: true } = &n.kind
|
||||
&& let [_, inner] = children.as_slice()
|
||||
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
|
||||
{
|
||||
let paths: Vec<(PathData, Paint)> = paths
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let fill = p.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => Some(f.paint.clone()),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
})?;
|
||||
Some((p.path_data()?.clone(), fill))
|
||||
})
|
||||
.collect();
|
||||
if paths.iter().any(|(_, p)| p.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3)) {
|
||||
out.push(paths);
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn bounds_of(paths: &[(PathData, Paint)]) -> 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)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
|
||||
let d = document();
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let found = graphics_in(&art);
|
||||
assert_eq!(found.len(), 1);
|
||||
// Straight on, the front cap is the art: a 20 × 20 square centered 20 right of and 10 above (50, 50).
|
||||
assert!(close(bounds_of(&found[0]), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds_of(&found[0]));
|
||||
// Turned 45°, the square's corners reach out to its half diagonal.
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "rotation": 45.0}]}));
|
||||
let b = bounds_of(&graphics_in(&solid_art_in(Some(&d), &n).unwrap())[0]);
|
||||
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_document_or_its_symbol_nothing_is_drawn() {
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
|
||||
let art = solid_art_in(None, &n).unwrap();
|
||||
assert!(graphics_in(&art).is_empty());
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Gone"}]}));
|
||||
assert!(graphics_in(&solid_art_in(Some(&document()), &n).unwrap()).is_empty());
|
||||
// Without graphics, the art is the same as before they existed.
|
||||
let plain = object(EXTRUDE, json!({}));
|
||||
assert_eq!(solid_art_in(Some(&document()), &plain), solid_art_in(None, &plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_graphic_is_shaded_with_its_face() {
|
||||
let d = document();
|
||||
let n = object(EXTRUDE, json!({"shade": true, "lightIntensity": 0.0, "ambient": 50.0, "graphics": [{"symbol": "Mark"}]}));
|
||||
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
|
||||
let c = found[0][0].1.color().unwrap().to_rgb();
|
||||
assert!((c[0] - 0.5).abs() < 1e-3 && c[1].abs() < 1e-6 && c[2].abs() < 1e-6, "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_graphic_goes_right_after_its_cap_and_is_clipped_to_it() {
|
||||
let d = document();
|
||||
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 25.0, "graphics": [{"symbol": "Mark", "scale": 2000.0}]}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let NodeKind::Group { children, .. } = &art.kind else { panic!("a group") };
|
||||
let NodeKind::Group { children: faces, .. } = &children.last().unwrap().kind else { panic!("the ordered faces") };
|
||||
let last = faces.last().unwrap();
|
||||
assert!(matches!(&last.kind, NodeKind::Group { clip: true, .. }), "the graphic is drawn last, over the front cap");
|
||||
let NodeKind::Group { children: parts, .. } = &last.kind else { panic!() };
|
||||
let clip = parts[0].path_data().unwrap().bounds().unwrap();
|
||||
let cap = faces[faces.len() - 2].path_data().unwrap().bounds().unwrap();
|
||||
assert!(close(clip, cap), "clipped to the cap: {clip:?} against {cap:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_back_cap_reads_the_right_way_round_from_behind() {
|
||||
let d = document();
|
||||
let behind = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0}]});
|
||||
let n = object(EXTRUDE, behind);
|
||||
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
|
||||
assert_eq!(found.len(), 1);
|
||||
let b = bounds_of(&found[0]);
|
||||
// Seen from behind, x runs to the right on the page too.
|
||||
assert!((b.center().x - 70.0).abs() < 1e-6, "{b:?}");
|
||||
let frame = graphic_frame(Some(&d), &n, None).unwrap();
|
||||
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 20.0})).unwrap();
|
||||
let (at, visible) = frame.handle(&g).unwrap();
|
||||
assert!(visible && (at.x - 70.0).abs() < 1e-6);
|
||||
let (x, y) = frame.offset_at(PlanarFace::Back, Point::new(40.0, 55.0)).unwrap();
|
||||
assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6);
|
||||
// From the front the back cap is hidden, and so is its graphic.
|
||||
let front = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "face": "back"}]}));
|
||||
assert!(graphics_in(&solid_art_in(Some(&d), &front).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_perspective_foreshortens_the_graphic_with_its_face() {
|
||||
let d = document();
|
||||
let params = json!({"rotationX": -30.0, "rotationY": 35.0, "perspectiveAngle": 100.0, "graphics": [{"symbol": "Mark", "scale": 400.0}]});
|
||||
let n = object(EXTRUDE, params);
|
||||
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
|
||||
let frame = graphic_frame(Some(&d), &n, None).unwrap();
|
||||
let map = frame.map(PlanarFace::Front).unwrap();
|
||||
// The corners of the 40 × 40 square centered on the object land where the face's map takes them.
|
||||
let path = &found[0][0].0;
|
||||
let corners: Vec<Point> = [(30.0, 30.0), (70.0, 30.0), (70.0, 70.0), (30.0, 70.0)].map(|(x, y)| map.to_page(Point::new(x, y)).unwrap()).into();
|
||||
for c in corners {
|
||||
let near = path.subpaths.iter().flat_map(|s| &s.anchors).map(|a| a.p.distance(c)).fold(f64::INFINITY, f64::min);
|
||||
assert!(near < 1e-6, "{c:?} is {near} from the drawn graphic");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_behind_the_eye_leaves_the_others_drawn() {
|
||||
let d = document();
|
||||
let view = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0});
|
||||
let n = object(EXTRUDE, view.clone());
|
||||
let frame = graphic_frame(Some(&d), &n, None).unwrap();
|
||||
let map = frame.map(PlanarFace::Front).unwrap();
|
||||
let c = frame.bounds.center();
|
||||
// An offset whose point of the front's plane is at or behind the eye.
|
||||
let y = [1.0, -1.0]
|
||||
.into_iter()
|
||||
.flat_map(|s| (1..60).map(move |k| s * 10f64.powf(f64::from(k) / 10.0)))
|
||||
.find(|y| map.local_affine(Point::new(c.x, c.y + y)).is_none())
|
||||
.expect("an offset behind the eye");
|
||||
let mut params = view;
|
||||
params["graphics"] = json!([{"symbol": "Mark"}, {"symbol": "Mark", "y": y}]);
|
||||
let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap());
|
||||
assert_eq!(found.len(), 1, "the graphic that projects is still drawn");
|
||||
// A graphic centered there but large enough to reach over the cap draws the part in front.
|
||||
let mut params = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0});
|
||||
params["graphics"] = json!([{"symbol": "Mark", "y": y, "scale": (20.0 * (y.abs() + 50.0)).clamp(1.0, 10_000.0)}]);
|
||||
let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap());
|
||||
assert_eq!(found.len(), 1, "the part in front is drawn (offset {y})");
|
||||
assert!(!found[0].is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_graphic_takes_the_opacity_of_its_fill() {
|
||||
let d = document();
|
||||
for id in [EXTRUDE, ROTATE] {
|
||||
let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = 0.25;
|
||||
}
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let mut opacities = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
|
||||
opacities.push(c.opacity);
|
||||
}
|
||||
});
|
||||
assert_eq!(opacities, vec![0.25], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_graphic_takes_the_blending_mode_of_its_fill() {
|
||||
let d = document();
|
||||
for id in [EXTRUDE, ROTATE] {
|
||||
let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.blend = BlendMode::Multiply;
|
||||
}
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let mut blends = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
|
||||
blends.push(c.blend);
|
||||
}
|
||||
});
|
||||
assert_eq!(blends, vec![BlendMode::Multiply], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_fill_of_a_plane_gives_its_graphic_its_own_opacity() {
|
||||
let d = document();
|
||||
let mut n = object(ROTATE, json!({"graphics": [{"symbol": "Mark"}]}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = 0.25;
|
||||
}
|
||||
let mut second = FillLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)));
|
||||
second.opacity = 0.75;
|
||||
n.appearance.items.push(AppearanceItem::Fill(second));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let mut opacities = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
|
||||
opacities.push(c.opacity);
|
||||
}
|
||||
});
|
||||
opacities.sort_by(f32::total_cmp);
|
||||
assert_eq!(opacities, vec![0.25, 0.75]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbols_gradient_takes_the_size_of_its_art() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let mut d = document();
|
||||
// Symbol art kept in its 20 × 20 square, drawn 40 × 20.
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)]));
|
||||
g.geom = Some(GradientGeom { start: Point::new(-10.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None });
|
||||
let art = square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::Gradient(Box::new(g)));
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Ramp".into(), art: Arc::new(art) });
|
||||
d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({"Ramp": [40.0, 20.0]}));
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ramp"}]}));
|
||||
let out = solid_art_in(Some(&d), &n).unwrap();
|
||||
let mut found = None;
|
||||
out.walk(&mut |c| {
|
||||
if let (Some(p), Some(AppearanceItem::Fill(f))) = (c.path_data(), c.appearance.items.first())
|
||||
&& let Paint::Gradient(g) = &f.paint
|
||||
{
|
||||
found = Some((p.bounds().unwrap(), g.geom.unwrap()));
|
||||
}
|
||||
});
|
||||
let (bounds, geom) = found.unwrap();
|
||||
assert!(close(bounds, Rect::new(30.0, 40.0, 70.0, 60.0)), "{bounds:?}");
|
||||
assert!(geom.start.distance(Point::new(30.0, 50.0)) < 1e-6 && geom.end.distance(Point::new(70.0, 50.0)) < 1e-6, "{geom:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbols_pattern_follows_the_graphic() {
|
||||
let mut d = document();
|
||||
let tiles = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Tiles".into(), art: Arc::new(square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), tiles)) });
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Tiles", "scale": 200.0}]}));
|
||||
let out = solid_art_in(Some(&d), &n).unwrap();
|
||||
let mut found = None;
|
||||
out.walk(&mut |c| {
|
||||
if let Some(AppearanceItem::Fill(f)) = c.appearance.items.first()
|
||||
&& let Paint::Pattern { xf, .. } = &f.paint
|
||||
{
|
||||
found = Some((c.path_data().unwrap().bounds().unwrap(), *xf));
|
||||
}
|
||||
});
|
||||
let (bounds, xf) = found.unwrap();
|
||||
// The 20 × 20 art drawn 40 × 40 on the middle of the front: its tiles go with it.
|
||||
assert!(close(bounds, Rect::new(30.0, 30.0, 70.0, 70.0)), "{bounds:?}");
|
||||
assert!((xf * Point::new(-10.0, -10.0)).distance(Point::new(30.0, 30.0)) < 1e-6, "{xf:?}");
|
||||
assert!((xf * Point::new(10.0, 10.0)).distance(Point::new(70.0, 70.0)) < 1e-6, "{xf:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_in_front_of_the_eye_maps_though_its_control_points_do_not() {
|
||||
let bounds = Rect::new(10.0, 20.0, 70.0, 60.0);
|
||||
let view = vectorcraft_three_d::View { rotation_x: -89.0, rotation_y: 40.0, rotation_z: 10.0, perspective: 160.0, ..Default::default() };
|
||||
let map = vectorcraft_three_d::plane_face_map(bounds, view).unwrap();
|
||||
// Where the page map stops along the line x = `x`, between the center and a point it does not map.
|
||||
let edge = |x: f64| {
|
||||
let inside = Point::new(x, bounds.center().y);
|
||||
let far = [Point::new(x, -1e6), Point::new(x, 1e6)].into_iter().find(|p| map.to_page(*p).is_none()).unwrap();
|
||||
let (mut a, mut b) = (inside, far);
|
||||
for _ in 0..200 {
|
||||
let m = a.midpoint(b);
|
||||
if map.to_page(m).is_some() { a = m } else { b = m }
|
||||
}
|
||||
a
|
||||
};
|
||||
let (b1, b2) = (edge(40.0), edge(60.0));
|
||||
let u = (b2 - b1).normalize();
|
||||
let mut n = vectorcraft_geom::Vec2::new(-u.y, u.x);
|
||||
if map.to_page(b1 + n * 10.0).is_none() {
|
||||
n = -n;
|
||||
}
|
||||
// Ends 219.17 in front of that line and control points 100 and 42 past it: the curve stays
|
||||
// about 1 in front, while a control point of one of the pieces it is cut into falls behind.
|
||||
let at = |s: f64, t: f64| b1 + n * s + u * t;
|
||||
let mut curve = BezPath::new();
|
||||
curve.move_to(at(219.17, 0.0));
|
||||
curve.curve_to(at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0));
|
||||
let c = CubicBez::new(at(219.17, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0));
|
||||
assert!((0..=1000).all(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_some()), "the curve itself is in front");
|
||||
let pieces = (0..PERSPECTIVE_PIECES).map(|k| c.subsegment(k as f64 / 8.0..(k + 1) as f64 / 8.0));
|
||||
assert!(pieces.flat_map(|s| [s.p1, s.p2]).any(|p| map.to_page(p).is_none()), "a piece's control point is behind");
|
||||
let mapped = map_path(&PathData::from_bezpath(&curve), &map, None, usize::MAX).expect("the curve maps");
|
||||
// The split pieces count toward the room the path is given: without room, the path is full,
|
||||
// not behind the eye, so it is not clipped.
|
||||
assert!(mapped.elements().len() > 1 + PERSPECTIVE_PIECES);
|
||||
assert_eq!(map_path(&PathData::from_bezpath(&curve), &map, None, PERSPECTIVE_PIECES + 1).err(), Some(NotMapped::Full));
|
||||
assert!(mapped.elements().iter().all(|e| e.end_point().is_none_or(|p| p.x.is_finite() && p.y.is_finite())));
|
||||
// That piece is split until its halves' control points map, so it stays a curve.
|
||||
assert!(mapped.elements().iter().all(|e| !matches!(e, PathEl::LineTo(_))), "{mapped:?}");
|
||||
// With its ends at 214.25 instead, the curve dips about 0.24 behind the line between the ends
|
||||
// of two pieces, which still map: it has no page point there, and is left to the clipping.
|
||||
let c = CubicBez::new(at(214.25, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(214.25, 20.0));
|
||||
assert!((0..=PERSPECTIVE_PIECES).all(|k| map.to_page(c.eval(k as f64 / 8.0)).is_some()));
|
||||
assert!((0..=1000).any(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_none()));
|
||||
let mut dips = BezPath::new();
|
||||
dips.move_to(c.p0);
|
||||
dips.curve_to(c.p1, c.p2, c.p3);
|
||||
assert_eq!(map_path(&PathData::from_bezpath(&dips), &map, None, usize::MAX).err(), Some(NotMapped::Behind));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_with_their_own_blending_get_graphics_of_their_own() {
|
||||
let d = document();
|
||||
let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
|
||||
let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
|
||||
b.blend = BlendMode::Multiply;
|
||||
let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]);
|
||||
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 1000.0}]});
|
||||
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
|
||||
let art = solid_art_in(Some(&d), &group).unwrap();
|
||||
let found = graphics_in(&art);
|
||||
// One graphic clipped to each member's cap: the second stays inside the member's Multiply group.
|
||||
assert_eq!(found.len(), 2);
|
||||
let mut blended = 0;
|
||||
art.walk(&mut |c| {
|
||||
if c.blend == BlendMode::Multiply {
|
||||
blended += graphics_in(c).len();
|
||||
}
|
||||
});
|
||||
assert_eq!(blended, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_stays_under_a_solid_painted_after_its_own() {
|
||||
let d = document();
|
||||
let member = |id: u64, r: Rect, color: Color, opacity: f32| {
|
||||
let mut n = square(id, r, Paint::solid(color));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = opacity;
|
||||
}
|
||||
Arc::new(n)
|
||||
};
|
||||
let gray = Color::rgb(0.5, 0.5, 0.5);
|
||||
// A and C share their fill's opacity; B, painted between them, has its own and covers part of A.
|
||||
let a = member(1, Rect::new(0.0, 0.0, 60.0, 100.0), gray, 1.0);
|
||||
let b = member(2, Rect::new(40.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0), 0.5);
|
||||
let c = member(4, Rect::new(200.0, 0.0, 260.0, 100.0), gray, 1.0);
|
||||
let mut group = Node::group(NodeId(3), vec![a, b, c]);
|
||||
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 3000.0}]});
|
||||
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
|
||||
let art = solid_art_in(Some(&d), &group).unwrap();
|
||||
// In drawing order: 'G' for a graphic, 'B' for a face of B's solid.
|
||||
let mut order = String::new();
|
||||
art.walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Group { clip: true, .. }) && !graphics_in(n).is_empty() {
|
||||
order.push('G');
|
||||
} else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first()
|
||||
&& f.paint.color().is_some_and(|c| c.to_rgb()[2] > 0.9 && c.to_rgb()[0] < 0.1)
|
||||
{
|
||||
order.push('B');
|
||||
}
|
||||
});
|
||||
// A's graphic is drawn right after A, under B; C's is drawn after B.
|
||||
assert_eq!(graphics_in(&art).len(), 3, "{order}");
|
||||
assert!(order.starts_with('G'), "{order}");
|
||||
}
|
||||
|
||||
/// [`document`] with symbol "Dense" too: a red polygon of 30,000 sides, straight or `curved`.
|
||||
fn dense_document(curved: bool) -> Document {
|
||||
let mut d = document();
|
||||
let mut poly = BezPath::new();
|
||||
let mut last = Point::ZERO;
|
||||
for k in 0..30_000 {
|
||||
let a = k as f64 / 30_000.0 * std::f64::consts::TAU;
|
||||
let p = Point::new(5.0 + 5.0 * a.cos(), 5.0 + 5.0 * a.sin());
|
||||
if k == 0 {
|
||||
poly.move_to(p);
|
||||
} else if curved {
|
||||
poly.curve_to(last.lerp(p, 1.0 / 3.0), last.lerp(p, 2.0 / 3.0), p);
|
||||
} else {
|
||||
poly.line_to(p);
|
||||
}
|
||||
last = p;
|
||||
}
|
||||
poly.close_path();
|
||||
let art = Node::path(NodeId(0), PathData::from_bezpath(&poly), Appearance::basic(Paint::solid(red()), Paint::None, 0.0));
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(art) });
|
||||
d
|
||||
}
|
||||
|
||||
/// The graphics drawn on a group of two members, each with its own graphic of symbol "Dense"
|
||||
/// ([`dense_document`]), seen under a perspective.
|
||||
fn dense_graphics_drawn(curved: bool) -> usize {
|
||||
let d = dense_document(curved);
|
||||
let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
|
||||
let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
|
||||
b.blend = BlendMode::Multiply;
|
||||
let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]);
|
||||
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "perspectiveAngle": 60.0, "shade": false, "graphics": [{"symbol": "Dense", "scale": 1000.0}]});
|
||||
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
|
||||
graphics_in(&solid_art_in(Some(&d), &group).unwrap()).len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_with_graphics_of_their_own_share_one_element_limit() {
|
||||
// A perspective cuts each of the 30,000 curves into 8: one copy fits the limit, two do not.
|
||||
// The first member's graphic is drawn; the second would pass the limit, so it draws none.
|
||||
assert_eq!(dense_graphics_drawn(true), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn straight_sides_count_once_under_a_perspective() {
|
||||
// A perspective keeps each of the 30,000 straight sides one element: both copies fit the limit.
|
||||
assert_eq!(dense_graphics_drawn(false), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_symbol_check_counts_what_the_view_draws() {
|
||||
// Two graphics of the 30,000-sided polygon under a perspective: straight, they fit the limit;
|
||||
// curved, they do not.
|
||||
let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]});
|
||||
let n = object(EXTRUDE, two.clone());
|
||||
assert!(validate_three_d_in(Some(&dense_document(false)), &n, EXTRUDE, &two).is_ok());
|
||||
let e = validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &two).unwrap_err();
|
||||
assert!(e.contains("too complex"), "{e}");
|
||||
// Without a perspective each curve draws once: curved, they fit too.
|
||||
let flat = json!({"perspectiveAngle": 0.0, "graphics": two["graphics"].clone()});
|
||||
assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plane_and_a_hollow_solid() {
|
||||
let d = document();
|
||||
let plane = object(ROTATE, json!({"rotationY": 30.0, "graphics": [{"symbol": "Mark"}]}));
|
||||
assert_eq!(graphics_in(&solid_art_in(Some(&d), &plane).unwrap()).len(), 1);
|
||||
let hollow = object(EXTRUDE, json!({"cap": false, "graphics": [{"symbol": "Mark"}]}));
|
||||
assert!(graphics_in(&solid_art_in(Some(&d), &hollow).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroked_graphic_draws_its_stroke_as_an_outline() {
|
||||
let mut d = document();
|
||||
let mut ring = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::None);
|
||||
ring.appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(red()), 2.0))], ..Default::default() }.into();
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Ring".into(), art: Arc::new(ring) });
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ring"}]}));
|
||||
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
|
||||
// The 10 × 10 square's 2 pt stroke reaches 1 pt outside it.
|
||||
assert!(close(bounds_of(&found[0]), Rect::new(44.0, 44.0, 56.0, 56.0)), "{:?}", bounds_of(&found[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_are_checked() {
|
||||
let n = object(EXTRUDE, json!({}));
|
||||
let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics}));
|
||||
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok());
|
||||
assert!(check(EXTRUDE, json!([])).is_ok());
|
||||
for bad in [
|
||||
json!("Mark"),
|
||||
json!([{"face": "front"}]),
|
||||
json!([{"symbol": ""}]),
|
||||
json!([{"symbol": "Mark", "face": "side"}]),
|
||||
json!([{"symbol": "Mark", "scale": 0.0}]),
|
||||
json!([{"symbol": "Mark", "rotation": 400.0}]),
|
||||
json!([{"symbol": "Mark", "x": "1"}]),
|
||||
json!([{"symbol": "Mark", "repeat": true}]),
|
||||
json!(vec![json!({"symbol": "Mark"}); MAX_GRAPHICS + 1]),
|
||||
] {
|
||||
assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
|
||||
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
|
||||
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
|
||||
// A loaded file's invalid entries are left out when drawn.
|
||||
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frame_at_an_index_is_that_effects() {
|
||||
let d = document();
|
||||
let mut n = object(EXTRUDE, json!({}));
|
||||
n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap());
|
||||
// The first 3D effect is the Extrude & Bevel, with a back cap; the second is a plane, without.
|
||||
assert!(graphic_frame(Some(&d), &n, None).unwrap().map(PlanarFace::Back).is_some());
|
||||
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 0).unwrap().map(PlanarFace::Back).is_some());
|
||||
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 1).unwrap().map(PlanarFace::Back).is_none());
|
||||
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 2).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_to_a_plane_drops_the_back_caps_graphics() {
|
||||
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]});
|
||||
let plane = three_d_params_as(EXTRUDE, &p, ROTATE);
|
||||
assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
|
||||
assert!(validate_three_d_params(ROTATE, &plane).is_ok());
|
||||
// Back to Extrude & Bevel, the front's graphic stays.
|
||||
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroked_solid_carries_its_graphic_too() {
|
||||
let d = document();
|
||||
let mut n = Node::path(
|
||||
NodeId(7),
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)),
|
||||
Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 20.0),
|
||||
);
|
||||
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]});
|
||||
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
|
||||
assert_eq!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_nested_too_deep_is_refused_and_not_drawn() {
|
||||
let mut d = document();
|
||||
let mut art = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()));
|
||||
for k in 0..=MAX_LEVELS {
|
||||
art = Node::group(NodeId(k as u64 + 1), vec![Arc::new(art)]);
|
||||
}
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(art) });
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
|
||||
let e = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Deep"}]})).unwrap_err();
|
||||
assert!(e.contains("nested"), "{e}");
|
||||
assert!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).is_empty());
|
||||
// A loaded file draws its other graphics.
|
||||
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
|
||||
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_nested_too_deep_are_refused_and_not_drawn() {
|
||||
let mut d = document();
|
||||
// Symbol `N{k}` holds an instance of `N{k-1}`, and `N0` is a square.
|
||||
d.symbols.push(Symbol { dynamic: false, name: "N0".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) });
|
||||
for k in 1..=MAX_NESTING + 1 {
|
||||
let instance = Node::new(NodeId(k as u64), NodeKind::SymbolInstance { symbol: format!("N{}", k - 1), xf: Affine::IDENTITY });
|
||||
d.symbols.push(Symbol { dynamic: false, name: format!("N{k}"), art: Arc::new(instance) });
|
||||
}
|
||||
let deepest = format!("N{MAX_NESTING}");
|
||||
let p = json!({"graphics": [{"symbol": deepest}]});
|
||||
assert!(validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).is_ok());
|
||||
assert_eq!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).len(), 1);
|
||||
let past = format!("N{}", MAX_NESTING + 1);
|
||||
let p = json!({"graphics": [{"symbol": past}]});
|
||||
let e = validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).unwrap_err();
|
||||
assert!(e.contains("nest"), "{e}");
|
||||
assert!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let d = document();
|
||||
let mut stop = GradientStop::new(1.0, red());
|
||||
stop.opacity = 0.25;
|
||||
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
|
||||
// Under a colored light the faces are drawn opaque and masked by the gradient's transparency.
|
||||
let mut n = object(EXTRUDE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Gradient(Box::new(gradient));
|
||||
}
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let mut masked = false;
|
||||
art.walk(&mut |c| masked |= c.extras().mask.is_some());
|
||||
assert!(masked);
|
||||
assert_eq!(graphics_in(&art).len(), 1);
|
||||
// Each graphic clip group in `art`, in drawing order: whether it carries an opacity mask.
|
||||
let masks = |art: &Node| {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind
|
||||
&& let [_, inner] = children.as_slice()
|
||||
&& matches!(inner.kind, NodeKind::Group { clip: false, .. })
|
||||
{
|
||||
out.push(c.extras().mask.is_some());
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
// The graphic carries the cap's mask, so it is hidden where the gradient is transparent.
|
||||
assert_eq!(masks(&art), vec![true]);
|
||||
// With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own
|
||||
// and the stroke's outline gets an unmasked one.
|
||||
n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0)));
|
||||
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() {
|
||||
let d = document();
|
||||
let outer = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
|
||||
let hole = shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)).to_bezpath().reverse_subpaths();
|
||||
let mut ring = outer;
|
||||
ring.extend(hole.iter());
|
||||
for flip in [false, true] {
|
||||
let ring = if flip { ring.reverse_subpaths() } else { ring.clone() };
|
||||
let mut n =
|
||||
Node::path(NodeId(7), PathData::from_bezpath(&ring), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0));
|
||||
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]});
|
||||
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let mut clips = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind {
|
||||
clips.push(children[0].path_data().unwrap().to_bezpath());
|
||||
}
|
||||
});
|
||||
assert_eq!(clips.len(), 1, "flip {flip}");
|
||||
assert_ne!(clips[0].winding(Point::new(10.0, 10.0)), 0, "flip {flip}: the ring is inside the clip");
|
||||
assert_eq!(clips[0].winding(Point::new(50.0, 50.0)), 0, "flip {flip}: the hole is outside it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_starts_inside_its_object() {
|
||||
let d = document();
|
||||
let frame = graphic_frame(Some(&d), &object(EXTRUDE, json!({})), None).unwrap();
|
||||
assert_eq!(frame.fitting_scale(Rect::new(0.0, 0.0, 10.0, 10.0)), 100.0);
|
||||
assert!((frame.fitting_scale(Rect::new(0.0, 0.0, 400.0, 200.0)) - 25.0).abs() < 1e-9);
|
||||
assert_eq!(super::super::graphic_bounds(&d, "Mark"), Some(Rect::new(500.0, 500.0, 510.0, 510.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() {
|
||||
let mut d = document();
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
// A dynamic symbol whose instance in "Changed" fills its square blue instead of red.
|
||||
d.symbols.push(Symbol { dynamic: true, name: "Dynamic".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) });
|
||||
let mut changed = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "Dynamic".into(), xf: Affine::IDENTITY });
|
||||
changed.extras_mut().symbol_overrides =
|
||||
vec![vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(blue.clone()), ..Default::default() }];
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Changed".into(), art: Arc::new(changed) });
|
||||
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Changed").unwrap()).unwrap();
|
||||
assert_eq!(pieces.iter().map(|p| p.paint.clone()).collect::<Vec<_>>(), [blue]);
|
||||
// A symbol with 9-slice guides, a 100 × 100 square with a 10 × 10 one in its corner, placed
|
||||
// three times as wide: the corner keeps its width while the rest stretches.
|
||||
let corner = square(2, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()));
|
||||
let whole = square(3, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(red()));
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(4), vec![Arc::new(whole), Arc::new(corner)])) });
|
||||
d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let wide = Node::new(NodeId(5), NodeKind::SymbolInstance { symbol: "Sliced".into(), xf: Affine::scale_non_uniform(3.0, 1.0) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Wide".into(), art: Arc::new(wide) });
|
||||
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Wide").unwrap()).unwrap();
|
||||
let widths: Vec<f64> = pieces.iter().map(|p| p.path.bounds().unwrap().width()).collect();
|
||||
assert_eq!(widths.len(), 2);
|
||||
assert!((widths[1] / widths[0] - 1.0 / 30.0).abs() < 1e-6, "{widths:?}");
|
||||
// With a gradient, the square crossing the guides is cut at them: its pieces cover the
|
||||
// placed 300 × 100 once, not one whole copy for each cell.
|
||||
use vectorcraft_doc::color::{Gradient, GradientPaint};
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
let shaded = square(6, Rect::new(0.0, 0.0, 100.0, 100.0), gradient);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Shaded".into(), art: Arc::new(Node::group(NodeId(7), vec![Arc::new(shaded)])) });
|
||||
d.set_symbol_nine_slice("Shaded", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let wide = Node::new(NodeId(8), NodeKind::SymbolInstance { symbol: "Shaded".into(), xf: Affine::scale_non_uniform(3.0, 1.0) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "WideShaded".into(), art: Arc::new(wide) });
|
||||
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "WideShaded").unwrap()).unwrap();
|
||||
let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum();
|
||||
assert!((area - 30_000.0).abs() < 1e-3, "{area}");
|
||||
}
|
||||
@@ -317,6 +317,86 @@ fn images_are_refused_alone_and_in_a_group_with_image_trace_named() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A clipping group: `art` inside a clipping path of `path` filled under `rule`.
|
||||
fn shaped_clip_group(id: u64, path: PathData, rule: FillRule, art: Vec<Node>) -> Node {
|
||||
let mut clipping = Node::path(NodeId(id + 1), path, Appearance::default());
|
||||
if let NodeKind::Path { clipping: c, rule: r, .. } = &mut clipping.kind {
|
||||
*c = true;
|
||||
*r = rule;
|
||||
}
|
||||
let children = std::iter::once(clipping).chain(art).map(Arc::new).collect();
|
||||
Node::new(NodeId(id), NodeKind::Group { children, clip: true })
|
||||
}
|
||||
|
||||
/// An image `width` by `height` pixels placed by `xf`.
|
||||
fn placed(id: u64, width: u32, height: u32, xf: Affine) -> Node {
|
||||
let mut img = image(id);
|
||||
if let NodeKind::Image(i) = &mut img.kind {
|
||||
i.width = width;
|
||||
i.height = height;
|
||||
i.xf = xf;
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_inside_a_clips_box_but_outside_its_shape_is_left_out() {
|
||||
let d = document();
|
||||
let circle = || shapes::ellipse(Rect::new(100.0, 100.0, 200.0, 200.0));
|
||||
let square = || shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 150.0));
|
||||
let at = |x: f64, y: f64| Affine::translate((x, y));
|
||||
// Two circles inside each other's clips: they show together only the lens between them.
|
||||
let lens = |art: Vec<Node>| {
|
||||
let inner = shaped_clip_group(70, shapes::ellipse(Rect::new(120.0, 100.0, 220.0, 200.0)), FillRule::NonZero, art);
|
||||
shaped_clip_group(80, shapes::ellipse(Rect::new(80.0, 100.0, 180.0, 200.0)), FillRule::NonZero, vec![inner])
|
||||
};
|
||||
let mut ring = shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0));
|
||||
ring.subpaths.extend(shapes::rectangle(Rect::new(130.0, 130.0, 170.0, 170.0)).subpaths);
|
||||
// Turned 45° about its center at (156, 156): its box reaches into the square's corner, and its
|
||||
// frame does not.
|
||||
let turned = at(156.0, 156.0) * Affine::rotate(std::f64::consts::FRAC_PI_4) * at(-5.0, -5.0);
|
||||
// A shown rectangle and an image `w` by `h` at `xf` inside the clipping path `path`.
|
||||
let clipped = |path: PathData, rule: FillRule, shown: Rect, (w, h, xf): (u32, u32, Affine)| {
|
||||
shaped_clip_group(60, path, rule, vec![rect(62, shown.x0, shown.y0, shown.x1, shown.y1, 0.0), placed(63, w, h, xf)])
|
||||
};
|
||||
let middle = Rect::new(140.0, 140.0, 160.0, 160.0);
|
||||
let band = Rect::new(100.0, 100.0, 110.0, 200.0);
|
||||
let left_out = [
|
||||
// In the corner of the circle's box, outside the circle.
|
||||
("a circle's corner", clipped(circle(), FillRule::NonZero, middle, (10, 10, at(100.0, 100.0)))),
|
||||
("a turned frame", clipped(square(), FillRule::NonZero, Rect::new(110.0, 110.0, 140.0, 140.0), (10, 10, turned))),
|
||||
// Above the lens: inside each circle, outside both at once.
|
||||
("two clips' shared area", lens(vec![rect(62, 145.0, 140.0, 155.0, 160.0, 0.0), placed(63, 8, 3, at(146.0, 100.0))])),
|
||||
("an even-odd hole", clipped(ring.clone(), FillRule::EvenOdd, band, (10, 10, at(140.0, 140.0)))),
|
||||
];
|
||||
let shown = [
|
||||
("part of the circle", clipped(circle(), FillRule::NonZero, middle, (10, 10, at(145.0, 145.0)))),
|
||||
("a non-zero hole", clipped(ring, FillRule::NonZero, band, (10, 10, at(140.0, 140.0)))),
|
||||
// A strip 0.005 pt wide inside the square still shows.
|
||||
("a narrow strip", clipped(square(), FillRule::NonZero, Rect::new(110.0, 110.0, 140.0, 140.0), (10, 10, at(149.995, 120.0)))),
|
||||
("the lens", lens(vec![rect(62, 145.0, 140.0, 155.0, 160.0, 0.0), placed(63, 8, 3, at(146.0, 108.0))])),
|
||||
];
|
||||
for id in TYPES {
|
||||
for (what, g) in &left_out {
|
||||
let n = with(g.clone(), id, json!({}));
|
||||
assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}: {what}");
|
||||
assert!(art(&d, &n, id).is_some(), "{id}: {what} draws");
|
||||
assert!(three_d_meshes_in(Some(&d), &n).is_ok_and(|m| !m.is_empty()), "{id}: {what} exports");
|
||||
}
|
||||
for (what, g) in &shown {
|
||||
let n = with(g.clone(), id, json!({}));
|
||||
assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}: {what}");
|
||||
assert!(art(&d, &n, id).is_none(), "{id}: {what}");
|
||||
}
|
||||
}
|
||||
// Each frame cut to a clip counts: past the limit the art is refused, never left out unchecked.
|
||||
let many: Vec<Node> = std::iter::once(rect(62, 140.0, 140.0, 160.0, 160.0, 0.0))
|
||||
.chain((0..=source::MAX_IMAGE_CUTS as u64).map(|i| placed(100 + i, 10, 10, at(100.0, 100.0))))
|
||||
.collect();
|
||||
let n = with(shaped_clip_group(60, circle(), FillRule::NonZero, many), ROTATE, front());
|
||||
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("too many objects")));
|
||||
}
|
||||
|
||||
/// Symbols `L0` to `L{levels}`: `L0` holds `leaf`, each later one `fan` instances of the one
|
||||
/// before it.
|
||||
fn nested_symbols(levels: usize, fan: usize, leaf: Node) -> Document {
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
//! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that
|
||||
//! can be edited on their own.
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
|
||||
use vectorcraft_three_d::Facet;
|
||||
|
||||
use super::{
|
||||
INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_plane, is_three_d, label_of, members, object_profile,
|
||||
region, reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds, view_options,
|
||||
};
|
||||
use crate::{GeomContext, is_geometry};
|
||||
|
||||
/// The most distinct edges one object's wireframe may have.
|
||||
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
|
||||
|
||||
/// The grid points are rounded to before edges are compared, in points: two faces that share an
|
||||
/// edge give it once.
|
||||
const GRID: f64 = 1.0 / 1024.0;
|
||||
|
||||
const NO_EFFECT: &str = "the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)";
|
||||
|
||||
/// The wireframe of `n`'s 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D
|
||||
/// (Classic) forms), in document coordinates: the edges of every face the effect draws for the object as
|
||||
/// it is turned and projected, each edge once. Edges that meet end to end are joined into one path;
|
||||
/// a run that comes back to where it started is closed. A curved edge stays a curve. The geometry
|
||||
/// effects after the object's 3D effect reshape the wireframe as they reshape the drawn art. On a
|
||||
/// group or layer, the edges of the solids of all its members. An error when `n` has no visible 3D
|
||||
/// effect, when its solids can't be built, when the canvas draws the source art in their place, when
|
||||
/// they draw no face, or past [`MAX_WIRE_EDGES`] edges.
|
||||
pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
|
||||
if !crate::has_revolve(n) && !has_solid(n) {
|
||||
return Err(NO_EFFECT.into());
|
||||
}
|
||||
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
|
||||
// The faces come from the effect whose art the canvas draws (Revolve first, as the canvas tries
|
||||
// it first). When neither draws, past their limits, the canvas shows the source art and there
|
||||
// is no surface to expand.
|
||||
let revolve = crate::has_revolve(n) && crate::revolve_art_in(doc, n).is_some();
|
||||
if !revolve && !(has_solid(n) && super::solid_art_in(doc, n).is_some()) {
|
||||
// The builders' own error says why, when there is one. Revolve's art is cut for Revolve,
|
||||
// as the canvas cuts it.
|
||||
if crate::has_revolve(n) {
|
||||
crate::revolve::revolve_face_paths(doc, &*resolve_for(doc, n, label, false)?)?;
|
||||
} else {
|
||||
solid_face_paths(doc, &*resolve(doc, n, label)?)?;
|
||||
}
|
||||
return Err(format!("{label} draws the source art for this object instead of its 3D surface"));
|
||||
}
|
||||
// Revolve's art is cut for Revolve whatever other 3D effect the object carries, as the canvas
|
||||
// cuts it ([`crate::revolve_art_in`]).
|
||||
let n = &*if revolve { resolve_for(doc, n, label, false)? } else { resolve(doc, n, label)? };
|
||||
let faces = if revolve { crate::revolve::revolve_face_paths(doc, n)? } else { solid_face_paths(doc, n)? };
|
||||
let faces = after_geometry(doc, n, faces, revolve);
|
||||
let wire = edges(&faces)?;
|
||||
if wire.is_empty() {
|
||||
return Err(format!("{label} draws no faces for this object"));
|
||||
}
|
||||
Ok(wire)
|
||||
}
|
||||
|
||||
/// `faces` reshaped by the visible geometry effects after the 3D effect of `n`'s own that drew them
|
||||
/// ([`reshaped`]): its first visible Revolve when `revolve` is set, else its first visible Extrude &
|
||||
/// Bevel, Inflate or Rotate.
|
||||
fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<PathData>, revolve: bool) -> Vec<PathData> {
|
||||
let fx = &n.appearance.effects;
|
||||
let drawn = if revolve { fx.iter().position(|e| e.visible && crate::revolve::is_revolve(&e.id)) } else { solid(fx).map(|(i, _)| i) };
|
||||
let Some(index) = drawn else { return faces };
|
||||
reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) })
|
||||
}
|
||||
|
||||
/// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), as
|
||||
/// they reshape the faces of the drawn surface ([`crate::reshape::reshape_leaves`]): each effect
|
||||
/// reshapes each face on its own, about the bounds all the faces have before it, and the faces keep
|
||||
/// to one budget of anchors together. `ctx` gives the object's id, the seed of a random Transform,
|
||||
/// and the document.
|
||||
pub(crate) fn reshaped(faces: Vec<PathData>, later: &[Effect], ctx: &GeomContext) -> Vec<PathData> {
|
||||
let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
if after.is_empty() {
|
||||
return faces;
|
||||
}
|
||||
let id = NodeId(ctx.seed);
|
||||
let fill = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
|
||||
let mut art = Node::group(id, faces.into_iter().map(|f| Arc::new(Node::path(id, f, fill.clone()))).collect());
|
||||
crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc);
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |c| out.extend(c.path_data().cloned()));
|
||||
out
|
||||
}
|
||||
|
||||
/// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect
|
||||
/// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer,
|
||||
/// the solids of its members, about one shared axis. The swatches and patterns named by a live-effect
|
||||
/// plug-in after a fill's or stroke's 3D effect are looked up in `doc`.
|
||||
fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
|
||||
if is_container(n) {
|
||||
let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
|
||||
let mut shapes = members(n, label_of(&fx.id))?;
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
return facet_paths(fx, &shapes);
|
||||
}
|
||||
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
|
||||
let (path, rule) = object_profile(n, label)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let paints = solid_paints(n);
|
||||
if let Some((index, fx)) = solid(&n.appearance.effects) {
|
||||
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
|
||||
return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]);
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
for item in &paints {
|
||||
if let Some((index, fx)) = solid(item.effects()) {
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
let faces = facet_paths(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
|
||||
out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and
|
||||
/// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's
|
||||
/// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out,
|
||||
/// as it is left out of the drawn art.
|
||||
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String> {
|
||||
let label = label_of(&fx.id);
|
||||
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let mut out = vec![];
|
||||
if is_plane(&fx.id) {
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(Facet::path));
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let built: Vec<Result<Vec<Facet>, String>> = if fx.id == INFLATE {
|
||||
let shapes: Vec<(&PathData, vectorcraft_geom::FillRule)> = parts.iter().map(|(_, _, area, rule, ..)| (area, *rule)).collect();
|
||||
vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p))
|
||||
} else {
|
||||
parts.iter().map(|(_, _, area, rule, ..)| facets(&fx.id, area, *rule, bounds, &p)).collect()
|
||||
};
|
||||
for ((item, ..), f) in parts.iter().zip(built) {
|
||||
match f {
|
||||
Ok(f) => out.extend(f.iter().map(Facet::path)),
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A point on the [`GRID`].
|
||||
type Snap = (i64, i64);
|
||||
|
||||
fn snap(p: Point) -> Snap {
|
||||
((p.x / GRID).round() as i64, (p.y / GRID).round() as i64)
|
||||
}
|
||||
|
||||
fn reversed(c: CubicBez) -> CubicBez {
|
||||
CubicBez::new(c.p3, c.p2, c.p1, c.p0)
|
||||
}
|
||||
|
||||
/// The edges of `faces`, each once, joined end to end into paths ([`three_d_wireframe_in`]).
|
||||
pub(crate) fn edges(faces: &[PathData]) -> Result<Vec<PathData>, String> {
|
||||
let mut seen: HashSet<[Snap; 4]> = HashSet::new();
|
||||
let mut segments: Vec<CubicBez> = vec![];
|
||||
for sp in faces.iter().flat_map(|f| &f.subpaths) {
|
||||
for i in 0..sp.segment_count() {
|
||||
let mut c = sp.segment(i);
|
||||
if sp.segment_is_line(i) {
|
||||
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
|
||||
}
|
||||
if [c.p0, c.p1, c.p2, c.p3].iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let key = [c.p0, c.p1, c.p2, c.p3].map(snap);
|
||||
// A segment that starts and ends on one grid point with its handles there too draws nothing.
|
||||
if key.iter().all(|k| *k == key[0]) {
|
||||
continue;
|
||||
}
|
||||
let back = [key[3], key[2], key[1], key[0]];
|
||||
if seen.contains(&back) || !seen.insert(key) {
|
||||
continue;
|
||||
}
|
||||
if segments.len() >= MAX_WIRE_EDGES {
|
||||
return Err(format!("the wireframe has more than {MAX_WIRE_EDGES} edges"));
|
||||
}
|
||||
segments.push(c);
|
||||
}
|
||||
}
|
||||
Ok(chain(&segments))
|
||||
}
|
||||
|
||||
/// `segments` joined end to end: each path starts at the first segment not yet used and takes in
|
||||
/// the unused segments that meet its ends until none is left at either end, or it closes.
|
||||
fn chain(segments: &[CubicBez]) -> Vec<PathData> {
|
||||
let mut at: HashMap<Snap, Vec<usize>> = HashMap::new();
|
||||
for (i, c) in segments.iter().enumerate() {
|
||||
at.entry(snap(c.p0)).or_default().push(i);
|
||||
if snap(c.p3) != snap(c.p0) {
|
||||
at.entry(snap(c.p3)).or_default().push(i);
|
||||
}
|
||||
}
|
||||
let mut used = vec![false; segments.len()];
|
||||
// The next unused segment at `point`, turned to leave it (`leave`) or to arrive at it.
|
||||
let mut take = |used: &mut Vec<bool>, point: Snap, leave: bool| -> Option<CubicBez> {
|
||||
let list = at.get_mut(&point)?;
|
||||
while let Some(&i) = list.last() {
|
||||
if used.get(i).copied().unwrap_or(true) {
|
||||
list.pop();
|
||||
continue;
|
||||
}
|
||||
if let Some(u) = used.get_mut(i) {
|
||||
*u = true;
|
||||
}
|
||||
let c = *segments.get(i)?;
|
||||
let starts = snap(c.p0) == point;
|
||||
return Some(if starts == leave { c } else { reversed(c) });
|
||||
}
|
||||
None
|
||||
};
|
||||
let mut out = vec![];
|
||||
for (i, first) in segments.iter().enumerate() {
|
||||
if used.get(i).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
if let Some(u) = used.get_mut(i) {
|
||||
*u = true;
|
||||
}
|
||||
let mut run: VecDeque<CubicBez> = VecDeque::from([*first]);
|
||||
// A path of one anchor has no segment (`SubPath::segment_count`), so a run of one segment
|
||||
// that comes back to its start stays open, with its two ends on one point.
|
||||
let closes = |run: &VecDeque<CubicBez>| run.len() > 1 && run.front().zip(run.back()).is_some_and(|(f, b)| snap(f.p0) == snap(b.p3));
|
||||
while !closes(&run) {
|
||||
let Some(end) = run.back().map(|c| snap(c.p3)) else { break };
|
||||
let Some(c) = take(&mut used, end, true) else { break };
|
||||
run.push_back(c);
|
||||
}
|
||||
while !closes(&run) {
|
||||
let Some(start) = run.front().map(|c| snap(c.p0)) else { break };
|
||||
let Some(c) = take(&mut used, start, false) else { break };
|
||||
run.push_front(c);
|
||||
}
|
||||
out.push(PathData::single(subpath(&run, closes(&run))));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `run`, segments that meet end to end, as one subpath; a closed one ends at its first anchor.
|
||||
fn subpath(run: &VecDeque<CubicBez>, closed: bool) -> SubPath {
|
||||
let mut anchors: Vec<Anchor> = vec![];
|
||||
if let Some(first) = run.front() {
|
||||
let h_in = if closed { run.back().map_or(first.p0, |b| b.p2) } else { first.p0 };
|
||||
anchors.push(Anchor::with_handles(first.p0, h_in, first.p1));
|
||||
}
|
||||
for (k, c) in run.iter().enumerate() {
|
||||
let h_out = run.get(k + 1).map_or(c.p3, |next| next.p1);
|
||||
anchors.push(Anchor::with_handles(c.p3, c.p2, h_out));
|
||||
}
|
||||
// A closed run's last anchor is its first, whose in handle already comes from the last segment.
|
||||
if closed {
|
||||
anchors.pop();
|
||||
}
|
||||
SubPath::new(anchors, closed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,235 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId};
|
||||
use vectorcraft_geom::{BezPath, Rect};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn square(x: f64, y: f64, size: f64) -> PathData {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((x, y));
|
||||
b.line_to((x + size, y));
|
||||
b.line_to((x + size, y + size));
|
||||
b.line_to((x, y + size));
|
||||
b.close_path();
|
||||
PathData::from_bezpath(&b)
|
||||
}
|
||||
|
||||
/// A filled 100 pt square without a stroke, with effect `id` and `params`.
|
||||
fn solid_square(id: &str, params: Value) -> Node {
|
||||
let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap());
|
||||
n
|
||||
}
|
||||
|
||||
/// Every segment of `wire`, each as its two ends on the grid.
|
||||
fn segments(wire: &[PathData]) -> Vec<(Snap, Snap)> {
|
||||
wire.iter()
|
||||
.flat_map(|p| &p.subpaths)
|
||||
.flat_map(|sp| (0..sp.segment_count()).map(move |i| sp.segment(i)))
|
||||
.map(|c| (snap(c.p0), snap(c.p3)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bounds(paths: &[PathData]) -> Rect {
|
||||
paths.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
|
||||
}
|
||||
|
||||
/// The paths of the faces `art` draws (every leaf of the art).
|
||||
fn face_paths(art: &Node) -> Vec<PathData> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |c| out.extend(c.path_data().cloned()));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_faces_that_share_an_edge_give_it_once() {
|
||||
let wire = edges(&[square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)]).unwrap();
|
||||
let segs = segments(&wire);
|
||||
assert_eq!(segs.len(), 7, "{segs:?}");
|
||||
for (i, a) in segs.iter().enumerate() {
|
||||
for b in segs.iter().skip(i + 1) {
|
||||
assert!(a != b && (a.1, a.0) != *b, "{a:?} twice");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_of_edges_is_one_closed_path_and_a_curve_stays_a_curve() {
|
||||
let wire = edges(&[square(0.0, 0.0, 10.0)]).unwrap();
|
||||
assert_eq!(wire.len(), 1);
|
||||
assert!(wire[0].subpaths[0].closed);
|
||||
assert_eq!(wire[0].subpaths[0].anchors.len(), 4);
|
||||
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 0.0));
|
||||
b.curve_to((0.0, 10.0), (10.0, 10.0), (10.0, 0.0));
|
||||
b.close_path();
|
||||
let wire = edges(&[PathData::from_bezpath(&b)]).unwrap();
|
||||
let curved = wire.iter().flat_map(|p| &p.subpaths).any(|sp| (0..sp.segment_count()).any(|i| !sp.segment_is_line(i)));
|
||||
assert!(curved, "{wire:?}");
|
||||
}
|
||||
|
||||
/// A single curve that comes back to its start keeps its segment: it stays open, with two anchors on
|
||||
/// one point, since a path of one anchor has no segment.
|
||||
#[test]
|
||||
fn a_single_curve_that_comes_back_to_its_start_keeps_its_segment() {
|
||||
let p = Point::new(0.0, 0.0);
|
||||
let anchors = vec![Anchor::with_handles(p, p, Point::new(0.0, 10.0)), Anchor::with_handles(p, Point::new(10.0, 10.0), p)];
|
||||
let face = PathData::single(SubPath::new(anchors, false));
|
||||
assert_eq!(face.subpaths[0].segment_count(), 1);
|
||||
let wire = edges(&[face]).unwrap();
|
||||
assert_eq!(wire.len(), 1);
|
||||
let sp = &wire[0].subpaths[0];
|
||||
assert_eq!(sp.segment_count(), 1, "{sp:?}");
|
||||
assert!(!sp.segment_is_line(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_without_length_or_with_non_finite_points_are_left_out() {
|
||||
let point = PathData::single(SubPath::polyline(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0)], false));
|
||||
let bad = PathData::single(SubPath::polyline(&[Point::new(f64::NAN, 0.0), Point::new(1.0, 1.0)], false));
|
||||
assert!(edges(&[point, bad]).unwrap().is_empty());
|
||||
assert!(edges(&[]).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_turned_off_axis_shows_the_nine_edges_of_its_three_faces() {
|
||||
let n = solid_square(super::super::EXTRUDE, json!({}));
|
||||
let wire = three_d_wireframe_in(None, &n).unwrap();
|
||||
assert_eq!(segments(&wire).len(), 9, "{wire:?}");
|
||||
// The wireframe covers what the effect draws, in the same place.
|
||||
let art = super::super::solid_art(&n).unwrap();
|
||||
let (w, a) = (bounds(&wire), bounds(&face_paths(&art)));
|
||||
for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] {
|
||||
assert!((x - y).abs() < 1e-6, "{w:?} {a:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_classic_wireframe_surface_expands_to_all_twelve_edges() {
|
||||
let n = solid_square(super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"}));
|
||||
assert_eq!(segments(&three_d_wireframe_in(None, &n).unwrap()).len(), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_inflate_and_rotate_expand_too() {
|
||||
for id in [crate::REVOLVE, super::super::INFLATE, ROTATE] {
|
||||
let wire = three_d_wireframe_in(None, &solid_square(id, json!({}))).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
assert!(!wire.is_empty(), "{id}");
|
||||
assert!(wire.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.anchors).all(|a| a.p.x.is_finite() && a.p.y.is_finite()), "{id}");
|
||||
}
|
||||
// Rotate is one flat face: its outline.
|
||||
let plane = three_d_wireframe_in(None, &solid_square(ROTATE, json!({}))).unwrap();
|
||||
assert_eq!(segments(&plane).len(), 4);
|
||||
}
|
||||
|
||||
/// Revolve (Classic) and Rotate (Classic) expand to the edges of the faces they draw, in the same
|
||||
/// place.
|
||||
#[test]
|
||||
fn revolve_classic_and_rotate_classic_expand_too() {
|
||||
let n = solid_square(crate::CLASSIC_REVOLVE, json!({}));
|
||||
let wire = three_d_wireframe_in(None, &n).unwrap();
|
||||
assert!(!wire.is_empty());
|
||||
let art = crate::revolve_art(&n).unwrap();
|
||||
let (w, a) = (bounds(&wire), bounds(&face_paths(&art)));
|
||||
for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] {
|
||||
assert!((x - y).abs() < 1e-6, "{w:?} {a:?}");
|
||||
}
|
||||
// On a fill, with a geometry effect after it.
|
||||
let mut n = solid_square(crate::CLASSIC_REVOLVE, json!({}));
|
||||
let fx = n.appearance.effects.remove(0);
|
||||
for item in &mut n.appearance.items {
|
||||
if matches!(item, AppearanceItem::Fill(_)) {
|
||||
item.effects_mut().push(fx.clone());
|
||||
}
|
||||
}
|
||||
let plain = bounds(&three_d_wireframe_in(None, &n).unwrap());
|
||||
for item in &mut n.appearance.items {
|
||||
if matches!(item, AppearanceItem::Fill(_)) {
|
||||
item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
|
||||
}
|
||||
}
|
||||
let moved = bounds(&three_d_wireframe_in(None, &n).unwrap());
|
||||
assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{plain:?} {moved:?}");
|
||||
// Rotate (Classic) is one flat face: its outline.
|
||||
let plane = three_d_wireframe_in(None, &solid_square(super::super::CLASSIC_ROTATE, json!({}))).unwrap();
|
||||
assert_eq!(segments(&plane).len(), 4);
|
||||
}
|
||||
|
||||
/// The geometry effects after a 3D effect reshape each face on its own, as they reshape each face
|
||||
/// of the drawn surface: two faces that touch stay two outlines.
|
||||
#[test]
|
||||
fn later_geometry_effects_reshape_each_face_on_its_own() {
|
||||
let n = solid_square(super::super::EXTRUDE, json!({}));
|
||||
let fx = [crate::new_effect("path.offsetPath", &json!({"offset": 1.0})).unwrap()];
|
||||
let out = reshaped(vec![square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)], &fx, &GeomContext::of(&n));
|
||||
assert_eq!(out.len(), 2, "{out:?}");
|
||||
let (a, b) = (out[0].bounds().unwrap(), out[1].bounds().unwrap());
|
||||
assert!((a.x0 + 1.0).abs() < 1e-3 && (a.x1 - 11.0).abs() < 1e-3, "{a:?}");
|
||||
assert!((b.x0 - 9.0).abs() < 1e-3 && (b.x1 - 21.0).abs() < 1e-3, "{b:?}");
|
||||
}
|
||||
|
||||
/// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface.
|
||||
#[test]
|
||||
fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() {
|
||||
for id in [super::super::EXTRUDE, crate::REVOLVE] {
|
||||
let mut n = solid_square(id, json!({}));
|
||||
let fx = n.appearance.effects.remove(0);
|
||||
for item in &mut n.appearance.items {
|
||||
if matches!(item, AppearanceItem::Fill(_)) {
|
||||
item.effects_mut().push(fx.clone());
|
||||
}
|
||||
}
|
||||
let plain = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}")));
|
||||
for item in &mut n.appearance.items {
|
||||
if matches!(item, AppearanceItem::Fill(_)) {
|
||||
item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
|
||||
}
|
||||
}
|
||||
let moved = bounds(&three_d_wireframe_in(None, &n).unwrap());
|
||||
assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{id}: {plain:?} {moved:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With two 3D effects, a geometry effect between them reshapes the faces of the one drawn only
|
||||
/// once: Revolve is drawn, so a Transform before it moves its profile and not its faces again.
|
||||
#[test]
|
||||
fn a_geometry_effect_before_the_drawn_3d_effect_is_not_applied_again() {
|
||||
let mut n = solid_square(crate::REVOLVE, json!({}));
|
||||
n.appearance.effects.insert(0, crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
|
||||
let alone = bounds(&three_d_wireframe_in(None, &n).unwrap());
|
||||
n.appearance.effects.insert(0, crate::new_effect(super::super::EXTRUDE, &json!({})).unwrap());
|
||||
let both = bounds(&three_d_wireframe_in(None, &n).unwrap());
|
||||
assert!((both.x0 - alone.x0).abs() < 1e-6 && (both.x1 - alone.x1).abs() < 1e-6, "{alone:?} {both:?}");
|
||||
}
|
||||
|
||||
/// A clipping group with Revolve and Rotate draws Revolve, which cuts the art's fills as one piece
|
||||
/// in the top fill's place. Its wireframe is cut the same way, so art with more fills than a 3D
|
||||
/// effect takes members still expands, to the edges of Revolve alone.
|
||||
#[test]
|
||||
fn a_clipping_group_with_revolve_and_rotate_expands_the_art_revolve_cuts() {
|
||||
let mut art = Node::path(NodeId(3), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = art.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap();
|
||||
art.appearance.items = vec![fill; super::super::MAX_MEMBERS + 4];
|
||||
let mut clip = Node::path(NodeId(2), square(100.0, 100.0, 50.0), Appearance::default());
|
||||
if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let mut n = Node::new(NodeId(1), vectorcraft_doc::NodeKind::Group { children: vec![Arc::new(clip), Arc::new(art)], clip: true });
|
||||
n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({})).unwrap());
|
||||
let alone = segments(&three_d_wireframe_in(None, &n).unwrap());
|
||||
n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap());
|
||||
assert!(crate::revolve_art_in(None, &n).is_some(), "the canvas draws Revolve");
|
||||
let both = segments(&three_d_wireframe_in(None, &n).unwrap());
|
||||
assert_eq!(both, alone);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_without_a_visible_3d_effect_is_an_error() {
|
||||
let mut n = solid_square(super::super::EXTRUDE, json!({}));
|
||||
n.appearance.effects[0].visible = false;
|
||||
assert!(three_d_wireframe_in(None, &n).unwrap_err().contains("no 3D effect"));
|
||||
n.appearance.effects.clear();
|
||||
assert!(three_d_wireframe_in(None, &n).is_err());
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
//! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
|
||||
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
|
||||
//! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset
|
||||
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]).
|
||||
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are
|
||||
//! custom heads, whose stroke ends halfway along their length.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -37,8 +38,14 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a>
|
||||
let last = subs.last().filter(|s| !s.1).map(|s| s.0.clone());
|
||||
let cap = cap_extent(st.cap, st.width);
|
||||
let (hw0, hw1) = (st.arrow_weight(false), st.arrow_weight(true));
|
||||
let start = st.start_arrow.zip(first).map(|(k, r)| (k, r, inset(k, hw0, cap)));
|
||||
let end = st.end_arrow.zip(last).map(|(k, r)| (k, r, inset(k, hw1, cap)));
|
||||
let start = st.start_arrow.clone().zip(first).map(|(k, r)| {
|
||||
let i = inset(&k, hw0, cap);
|
||||
(k, r, i)
|
||||
});
|
||||
let end = st.end_arrow.clone().zip(last).map(|(k, r)| {
|
||||
let i = inset(&k, hw1, cap);
|
||||
(k, r, i)
|
||||
});
|
||||
if start.is_none() && end.is_none() {
|
||||
return StrokePieces { line: Cow::Borrowed(bp), heads: vec![] };
|
||||
}
|
||||
@@ -56,7 +63,8 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a>
|
||||
} else {
|
||||
(end_pt + outward * inset, outward)
|
||||
};
|
||||
heads.push(Arrow { kind, outline: shape(kind, tip, dir, hw), tip, dir, inset });
|
||||
let outline = shape(&kind, tip, dir, hw);
|
||||
heads.push(Arrow { kind, outline, tip, dir, inset });
|
||||
};
|
||||
if let Some((k, r, i)) = start {
|
||||
place(k, r, true, i, hw0);
|
||||
@@ -181,12 +189,12 @@ pub(super) fn trims(st: &StrokeLayer) -> (f64, f64) {
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
let cap = cap_extent(st.cap, st.width);
|
||||
let inset_of = |kind: Option<Arrowhead>, end: bool| kind.map_or(0.0, |k| inset(k, st.arrow_weight(end), cap));
|
||||
(inset_of(st.start_arrow, false), inset_of(st.end_arrow, true))
|
||||
let inset_of = |kind: &Option<Arrowhead>, end: bool| kind.as_ref().map_or(0.0, |k| inset(k, st.arrow_weight(end), cap));
|
||||
(inset_of(&st.start_arrow, false), inset_of(&st.end_arrow, true))
|
||||
}
|
||||
|
||||
/// Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end.
|
||||
fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
|
||||
fn inset(kind: &Arrowhead, hw: f64, cap: f64) -> f64 {
|
||||
let l = len(hw);
|
||||
// Solid heads: halfway in, far enough that the cap stays behind the tip.
|
||||
let solid = |back: f64| (back / 2.0).max(cap);
|
||||
@@ -199,6 +207,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
|
||||
Arrowhead::TriangleOpen | Arrowhead::CircleOpen | Arrowhead::SquareOpen => hollow(l),
|
||||
// The inner corner of the chevron: arm / sin(half angle).
|
||||
Arrowhead::ArrowOpen => (arm(hw) * (l * l + l * l / 4.0).sqrt() / (l / 2.0)).max(cap),
|
||||
Arrowhead::Custom(c) => (c.stop() * hw).max(cap),
|
||||
_ => match local_stop(kind) {
|
||||
Stop::At(u) => (u * hw).max(cap),
|
||||
Stop::Wall(back) => hollow(back * hw),
|
||||
@@ -207,7 +216,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// Outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along `dir`.
|
||||
fn shape(kind: Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
|
||||
fn shape(kind: &Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
|
||||
let n = Vec2::new(-dir.y, dir.x);
|
||||
let l = len(hw);
|
||||
let half = l / 2.0;
|
||||
@@ -265,7 +274,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2;
|
||||
const LOCAL_TOL: f64 = 1e-3;
|
||||
|
||||
/// Where the stroke ends under a head drawn in local units ([`local`]), in those units.
|
||||
fn local_stop(kind: Arrowhead) -> Stop {
|
||||
fn local_stop(kind: &Arrowhead) -> Stop {
|
||||
match kind {
|
||||
Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0),
|
||||
Arrowhead::HexagonOpen => Stop::Wall(HEX),
|
||||
@@ -288,8 +297,8 @@ fn local_stop(kind: Arrowhead) -> Stop {
|
||||
/// The outline of a head added after the first ten, in local units: x from the tip (0) back
|
||||
/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2,
|
||||
/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape
|
||||
/// is generated here.
|
||||
fn local(kind: Arrowhead) -> BezPath {
|
||||
/// is generated here, and a custom head's outline is its own.
|
||||
fn local(kind: &Arrowhead) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>());
|
||||
let ring_poly = |p: &mut BezPath, pts: &[(f64, f64)]| ring_polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>(), ring(1.0));
|
||||
@@ -385,6 +394,7 @@ fn local(kind: Arrowhead) -> BezPath {
|
||||
let t = FRAC_1_SQRT_2;
|
||||
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
|
||||
}
|
||||
Arrowhead::Custom(c) => p = c.path.to_bezpath(),
|
||||
// The first ten are drawn by `shape`.
|
||||
Arrowhead::Triangle
|
||||
| Arrowhead::TriangleOpen
|
||||
|
||||
@@ -134,6 +134,10 @@ impl Plan {
|
||||
|
||||
fn fitted(mut segs: Vec<PathSeg>, mut lens: Vec<f64>, closed: bool, period: f64) -> Self {
|
||||
let n = segs.len();
|
||||
// A subpath with no segments (a lone moveto) has no runs to fit.
|
||||
if n == 0 {
|
||||
return Self::exact(segs, lens, closed, period);
|
||||
}
|
||||
// Corners: where segments with length meet at a kink (zero-length ones have no direction).
|
||||
let live: Vec<usize> = (0..n).filter(|&i| lens[i] > EPS).collect();
|
||||
let mut corners: Vec<usize> = live.windows(2).filter(|w| kink(&segs[w[0]], &segs[w[1]])).map(|w| w[1]).collect();
|
||||
|
||||
@@ -32,6 +32,12 @@ const SHARP: f64 = 1.25;
|
||||
const HAIRPIN: f64 = 4.0;
|
||||
/// Rows of a mesh across the stroke (more where the gradient has stops).
|
||||
const MESH_ROWS: usize = 16;
|
||||
/// The most stops of the gradient [`gradient_meshes`] puts rows or columns at
|
||||
/// ([`Gradient::fitted`]: past it, the stops that change the colors least are left out).
|
||||
pub(crate) const MAX_MESH_STOPS: usize = 1024;
|
||||
/// The most points of one mesh [`gradient_meshes`] makes, unless a single pair of ribs needs more:
|
||||
/// a subpath with more ribs than leave room for a row at each stop becomes several meshes.
|
||||
pub(crate) const MAX_MESH_POINTS: usize = 1 << 20;
|
||||
/// The most of a subpath one column of a mesh along the stroke spans.
|
||||
const MESH_STEP: f64 = 1.0 / 32.0;
|
||||
/// The most of a subpath one slice spans while a width profile shapes the across gradient.
|
||||
@@ -367,9 +373,12 @@ pub struct Slice {
|
||||
}
|
||||
|
||||
impl Slice {
|
||||
/// The slice's paint: its piece of `g` as a linear gradient placed from `from` to `to`.
|
||||
pub fn paint(&self, g: &Gradient) -> Paint {
|
||||
let gradient = g.span(self.span.0 as f32, self.span.1 as f32);
|
||||
/// The slice's paint: its piece of `unrolled` as a linear gradient placed from `from` to `to`.
|
||||
/// `unrolled` is the stroke's gradient as [`Gradient::unrolled`] gives it (unrolled once for
|
||||
/// all the slices), so one that repeats or reflects runs its stops that many times along (or
|
||||
/// across) the stroke.
|
||||
pub fn paint(&self, unrolled: &Gradient) -> Paint {
|
||||
let gradient = unrolled.span(self.span.0 as f32, self.span.1 as f32);
|
||||
let end = if self.from.distance(self.to) > 1e-9 { self.to } else { self.from + Vec2::new(1.0, 0.0) };
|
||||
let geom = GradientGeom { start: self.from, end, aspect: 1.0, focal: None };
|
||||
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle: geom.angle_deg(), ..GradientPaint::new(gradient) }))
|
||||
@@ -471,40 +480,72 @@ pub fn written_slices(bp: &BezPath, rule: FillRule, st: &StrokeLayer, outlines:
|
||||
_ => vectorcraft_pathops::stroke_region(outlines).to_bezpath(),
|
||||
};
|
||||
let grow = if g.stops.iter().all(|s| s.opacity >= 1.0) { SLICE_GROW } else { 0.0 };
|
||||
let unrolled = g.unrolled();
|
||||
let slices = gradient_slices(bp, rule, st, SLICE_TOL, SLICE_MARGIN, grow)
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
let paint = s.paint(g);
|
||||
let paint = s.paint(&unrolled);
|
||||
(s.shape, paint)
|
||||
})
|
||||
.collect();
|
||||
Some(WrittenSlices { clip, slices })
|
||||
}
|
||||
|
||||
/// How far before and after a sharp step between two colors (two stops at one offset, as a
|
||||
/// gradient that repeats has where one run meets the next) [`mesh_marks`] puts a mesh row or
|
||||
/// column, as a fraction of the gradient's length.
|
||||
const STEP_GAP: f64 = 1e-4;
|
||||
|
||||
/// Where along gradient `g` (0 to 1) Outline Stroke's mesh puts a row or column for its stops
|
||||
/// ([`Gradient::expanded_stops`]): at each stop, and for two stops at one offset (a sharp step,
|
||||
/// or where a reflecting gradient turns back) also [`STEP_GAP`] before and after it, so the mesh
|
||||
/// takes the color on each side.
|
||||
fn mesh_marks(g: &Gradient) -> Vec<f64> {
|
||||
let offsets: Vec<f64> = g.expanded_stops().iter().map(|s| f64::from(s.0)).collect();
|
||||
let shared = |i: usize| {
|
||||
let t = offsets.get(i).copied().unwrap_or(0.0);
|
||||
let near = |j: Option<usize>| j.and_then(|j| offsets.get(j)).is_some_and(|&u| (u - t).abs() < 1e-6);
|
||||
near(i.checked_sub(1)) || near(i.checked_add(1))
|
||||
};
|
||||
let mut out = Vec::with_capacity(offsets.len() + 2);
|
||||
for (i, &t) in offsets.iter().enumerate() {
|
||||
out.push(t);
|
||||
if shared(i) {
|
||||
out.extend([(t - STEP_GAP).max(0.0), (t + STEP_GAP).min(1.0)]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Outline Stroke of stroke `st` of `bp` (filled with `rule`) whose gradient `g` runs along or
|
||||
/// across it: a gradient mesh per subpath over all the stroke can paint there (clip it to the
|
||||
/// stroke's outline), coloured as [`gradient_slices`] paint it.
|
||||
/// stroke's outline), coloured as [`gradient_slices`] paint it. The gradient's stops are fitted to
|
||||
/// [`MAX_MESH_STOPS`], and a subpath whose mesh would hold more than [`MAX_MESH_POINTS`] points is
|
||||
/// split into meshes of fewer ribs ([`rib_pieces`]).
|
||||
pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec<GradientMesh> {
|
||||
let fitted = g.fitted(MAX_MESH_STOPS);
|
||||
let across = st.gradient_mode == StrokeGradientMode::Across;
|
||||
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
|
||||
// Along: a column at each stop (colours are linear between columns), close enough to look smooth.
|
||||
let marks: Vec<f64> = if across { vec![] } else { g.expanded_stops().iter().map(|s| s.0 as f64).collect() };
|
||||
let marks: Vec<f64> = if across { vec![] } else { mesh_marks(&fitted) };
|
||||
let max_dt = match (across, st.profile.is_some()) {
|
||||
(false, _) => MESH_STEP,
|
||||
(true, true) => PROFILE_STEP,
|
||||
(true, false) => 1.0,
|
||||
};
|
||||
// Rows across: the strip's edges, then (across) the band's left edge to its right edge with a row at each stop.
|
||||
let mut us: Vec<f64> = if across {
|
||||
(0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(g.expanded_stops().iter().map(|s| s.0 as f64)).collect()
|
||||
} else {
|
||||
vec![0.5]
|
||||
};
|
||||
let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(mesh_marks(&fitted)).collect() } else { vec![0.5] };
|
||||
us.sort_by(f64::total_cmp);
|
||||
us.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
|
||||
let us = &us;
|
||||
let g = &*fitted;
|
||||
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
|
||||
// A mesh is a point for each row (and its two edges) on each rib: a strip with more ribs than
|
||||
// that leaves room for is split into meshes of fewer ribs.
|
||||
let per_mesh = MAX_MESH_POINTS / (us.len() + 2);
|
||||
strips(bp, rule, st, SLICE_TOL, SLICE_MARGIN, &marks, max_dt)
|
||||
.into_iter()
|
||||
.filter(|ribs| ribs.len() > 1)
|
||||
.flat_map(|ribs| rib_pieces(ribs.len(), per_mesh).into_iter().map(move |r| ribs.get(r).unwrap_or_default().to_vec()))
|
||||
.map(|ribs| {
|
||||
let (rows, cols) = (us.len() + 1, ribs.len() - 1);
|
||||
// Each level across: a point on each rib and the gradient position there.
|
||||
@@ -541,3 +582,11 @@ pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradi
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The ribs (index ranges of `n`, at least two) of each mesh [`gradient_meshes`] makes of a strip:
|
||||
/// at most `per_mesh` ribs each (at least two), each starting on the last rib of the one before,
|
||||
/// so the meshes meet without a gap.
|
||||
pub(crate) fn rib_pieces(n: usize, per_mesh: usize) -> Vec<std::ops::Range<usize>> {
|
||||
let per_mesh = per_mesh.max(2);
|
||||
(0..n.saturating_sub(1)).step_by(per_mesh - 1).map(|start| start..(start + per_mesh).min(n)).collect()
|
||||
}
|
||||
@@ -280,7 +280,7 @@ fn no_heads_borrows_the_path_and_closed_paths_get_none() {
|
||||
#[test]
|
||||
fn tip_mode_shortens_the_stroke_by_the_head_and_puts_the_tip_on_the_end_point() {
|
||||
for kind in Arrowhead::ALL {
|
||||
let st = arrows(kind, ArrowAlign::Tip, LineCap::Butt);
|
||||
let st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Butt);
|
||||
let l = line(0.0, 100.0);
|
||||
let p = stroke_pieces(&l, &st);
|
||||
let [h] = &p.heads[..] else { panic!("one head") };
|
||||
@@ -335,7 +335,7 @@ fn extend_mode_keeps_the_path_and_overhangs_by_the_inset() {
|
||||
#[test]
|
||||
fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() {
|
||||
for (kind, cap) in [(Arrowhead::CircleOpen, LineCap::Round), (Arrowhead::SquareOpen, LineCap::Square), (Arrowhead::TriangleOpen, LineCap::Butt)] {
|
||||
let st = arrows(kind, ArrowAlign::Tip, cap);
|
||||
let st = arrows(kind.clone(), ArrowAlign::Tip, cap);
|
||||
let l = line(0.0, 100.0);
|
||||
let p = stroke_pieces(&l, &st);
|
||||
let h = &p.heads[0];
|
||||
@@ -361,7 +361,7 @@ fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() {
|
||||
fn round_caps_never_poke_past_the_tip() {
|
||||
for kind in Arrowhead::ALL {
|
||||
for scale in [10.0, 100.0, 300.0] {
|
||||
let mut st = arrows(kind, ArrowAlign::Tip, LineCap::Round);
|
||||
let mut st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Round);
|
||||
st.arrow_scale = (scale, scale);
|
||||
let l = line(0.0, 100.0);
|
||||
let p = stroke_pieces(&l, &st);
|
||||
@@ -403,8 +403,8 @@ fn degenerate_paths_and_patterns_neither_panic_nor_hang() {
|
||||
for pat in patterns {
|
||||
for off in [0.0, -7.0, 1e12, f64::INFINITY] {
|
||||
let st = stroke(2.0, |s| {
|
||||
s.start_arrow = Some(kind);
|
||||
s.end_arrow = Some(kind);
|
||||
s.start_arrow = Some(kind.clone());
|
||||
s.end_arrow = Some(kind.clone());
|
||||
s.arrow_align = align;
|
||||
s.cap = cap;
|
||||
s.dash = Some(dashed(pat, off));
|
||||
|
||||
@@ -50,7 +50,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
|
||||
let (o, d) = (Point::ORIGIN, Point::new(2.0, 2.0));
|
||||
assert!(cross((o, d), (Point::new(0.0, 2.0), Point::new(2.0, 0.0))) && !cross((o, d), (d, Point::new(4.0, 0.0))), "the check itself");
|
||||
for kind in Arrowhead::ALL {
|
||||
let h = head(kind);
|
||||
let h = head(kind.clone());
|
||||
assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn");
|
||||
let b = h.outline.bounding_box();
|
||||
let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width());
|
||||
@@ -73,7 +73,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
|
||||
#[test]
|
||||
fn the_stroke_ends_inside_every_head() {
|
||||
for kind in Arrowhead::ALL {
|
||||
let h = head(kind);
|
||||
let h = head(kind.clone());
|
||||
// Just in front of where the line stops, on its centre line.
|
||||
let end = h.tip - h.dir * (h.inset - 0.1);
|
||||
assert_ne!(h.outline.winding(end), 0, "{kind:?}: the line ends outside the head (inset {})", h.inset);
|
||||
@@ -112,3 +112,30 @@ fn half_arrows_barb_on_their_own_side() {
|
||||
assert!(head(Arrowhead::HalfArrowLeft).outline.bounding_box().y1 < 1.5);
|
||||
assert!(head(Arrowhead::HalfArrowRight).outline.bounding_box().y1 > 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_heads_draw_their_own_art_at_the_tip() {
|
||||
use vectorcraft_doc::CustomArrowhead;
|
||||
use vectorcraft_geom::{PathData, SubPath};
|
||||
// From the tip back 3 units, 2 to the right of the line and 1 to the left.
|
||||
let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
|
||||
let kind = Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), wedge)));
|
||||
let h = head(kind.clone());
|
||||
// Weight 2: drawn back to x 94, right of +x is +y on a y-down page.
|
||||
let b = h.outline.bounding_box();
|
||||
assert!((b.x0 - 94.0).abs() < 1e-9 && (b.x1 - 100.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.y1 - 4.0).abs() < 1e-9, "{b:?}");
|
||||
assert_eq!(h.outline.winding(Point::new(95.0, 1.0)), h.outline.winding(Point::new(95.0, 0.5)));
|
||||
assert_ne!(h.outline.winding(Point::new(95.0, 1.0)), 0);
|
||||
// The line stops halfway along the head.
|
||||
assert!((h.inset - 3.0).abs() < 1e-9, "inset {}", h.inset);
|
||||
// Extended, the tip sits the inset past the end point, and scaling scales the art.
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
(st.start_arrow, st.arrow_scale) = (Some(kind), (200.0, 100.0));
|
||||
let mut l = BezPath::new();
|
||||
l.move_to((0.0, 0.0));
|
||||
l.line_to((100.0, 0.0));
|
||||
let p = stroke_pieces(&l, &st);
|
||||
let [s] = &p.heads[..] else { panic!("one head") };
|
||||
assert!((s.tip.x + 6.0).abs() < 1e-9 && s.dir.x < 0.0, "tip {:?}", s.tip);
|
||||
assert!((s.outline.bounding_box().width() - 12.0).abs() < 1e-9);
|
||||
}
|
||||
@@ -37,6 +37,20 @@ fn near(a: f64, b: f64, tol: f64) -> bool {
|
||||
|
||||
// ---------------------------------------------------------------- dashes fitted to corners
|
||||
|
||||
/// A subpath with no segments (a lone moveto, as an HP-GL wedge of almost no radius gives) is
|
||||
/// dashed fitted to corners without a panic, and the other subpaths keep their dashes.
|
||||
#[test]
|
||||
fn fitted_dashes_take_a_subpath_with_no_segments() {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((5.0, 5.0));
|
||||
b.extend(line(100.0));
|
||||
let d = dash(&b, &fitted(&[10.0, 5.0], 0.0)).expect("dashed");
|
||||
assert!(moves(&d.path) > 1 && length(&d.path) > 0.0, "{:?}", d.path);
|
||||
let mut lone = BezPath::new();
|
||||
lone.move_to((0.0, 0.0));
|
||||
assert!(dash(&lone, &fitted(&[10.0, 5.0], 0.0)).is_some_and(|d| d.path.elements().is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_corner_of_a_rectangle_falls_mid_dash() {
|
||||
// 100 × 50 with 12/6: the long sides hold 6 periods (scaled by 100/108), the short ones 3
|
||||
|
||||
@@ -286,6 +286,94 @@ fn a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone() {
|
||||
assert_covered(&hairpin, &st);
|
||||
}
|
||||
|
||||
/// A gradient along or across a stroke that repeats or reflects runs its stops that many times
|
||||
/// along (or across) it: a slice's paint, and Outline Stroke's meshes, give each point the color
|
||||
/// the spread gives its place.
|
||||
#[test]
|
||||
fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false);
|
||||
for (mode, spread) in [StrokeGradientMode::Along, StrokeGradientMode::Across]
|
||||
.into_iter()
|
||||
.flat_map(|m| [GradientSpread::Reflect, GradientSpread::Repeat].map(|s| (m, s)))
|
||||
{
|
||||
let mut st = stroke(10.0, mode);
|
||||
let g = Gradient { spread, repeats: 3, ..Gradient::default() };
|
||||
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
|
||||
for s in slices(&bp, &st) {
|
||||
let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") };
|
||||
let geom = p.geom.unwrap();
|
||||
for u in [0.1, 0.5, 0.9] {
|
||||
let at = s.from + (s.to - s.from) * u;
|
||||
let t = s.span.0 + (s.span.1 - s.span.0) * u;
|
||||
// Where two runs meet, Repeat's color is the next run's start or the last one's end.
|
||||
if (t * 3.0 - (t * 3.0).round()).abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(geom.param_at(vectorcraft_color::GradientKind::Linear, at) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-3), "{mode:?} at {t}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
// Outline Stroke: the mesh comes back to white where each run starts again, and reaches
|
||||
// black where each run ends, on both sides of a sharp step between runs.
|
||||
let count = |g: &Gradient, hex: &str| {
|
||||
gradient_meshes(&bp, FillRule::NonZero, &st, g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == hex).count()
|
||||
};
|
||||
for hex in ["#ffffff", "#000000"] {
|
||||
let (spread, pad) = (count(&g, hex), count(&Gradient::default(), hex));
|
||||
assert!(spread > pad, "{mode:?} {:?} {hex}: {spread} vs {pad}", g.spread);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a reflecting gradient turns back past a narrow last stop, Outline Stroke's mesh keeps that
|
||||
/// stop's color.
|
||||
#[test]
|
||||
fn a_narrow_peak_where_a_reflecting_gradient_turns_back_stays_in_the_mesh() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false);
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.995, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
|
||||
let mut st = stroke(10.0, mode);
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops.clone()) };
|
||||
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
|
||||
let whites =
|
||||
gradient_meshes(&bp, FillRule::NonZero, &st, &g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == "#ffffff").count();
|
||||
// The gradient turns back at white 50 times.
|
||||
assert!(whites >= 50, "{mode:?}: {whites}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline Stroke's mesh across a stroke of many ribs, with a gradient of many stops repeated 100
|
||||
/// times: each mesh holds at most so many points, and every run still starts on its first color.
|
||||
#[test]
|
||||
fn a_mesh_across_many_ribs_and_stops_stays_bounded() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let pts: Vec<(f64, f64)> = (0..1200).map(|i| (i as f64 * 10.0, if i % 2 == 0 { 0.0 } else { 10.0 })).collect();
|
||||
let bp = poly(&pts, false);
|
||||
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(1.0 - i as f32 / 199.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops) };
|
||||
let mut st = stroke(4.0, StrokeGradientMode::Across);
|
||||
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
|
||||
let meshes = gradient_meshes(&bp, FillRule::NonZero, &st, &g);
|
||||
assert!(!meshes.is_empty());
|
||||
for m in &meshes {
|
||||
assert!(m.points.len() <= super::gradient::MAX_MESH_POINTS, "{} points", m.points.len());
|
||||
// A row at the start of each of the 100 runs, on every rib, is white.
|
||||
let light = m.points.iter().filter(|p| p.color.to_rgb()[0] > 0.97).count();
|
||||
assert!(light >= 100 * (m.cols as usize + 1), "{light} light points of {}", m.points.len());
|
||||
}
|
||||
// A strip of more ribs than one mesh has room for is split into meshes that share their end
|
||||
// ribs, every rib in one of them.
|
||||
use super::gradient::rib_pieces;
|
||||
assert_eq!(rib_pieces(5, 3), [0..3, 2..5]);
|
||||
assert_eq!(rib_pieces(4, 3), [0..3, 2..4]);
|
||||
let one = rib_pieces(2, 1000);
|
||||
assert_eq!((one.len(), one.first()), (1, Some(&(0..2))));
|
||||
assert_eq!(rib_pieces(3, 0), [0..2, 1..3]);
|
||||
}
|
||||
|
||||
/// #5960: with dashes, the ribs reach as far as the stroke gets wide within a cap's length along
|
||||
/// the path, however many points lie that far: not as far as it is wide anywhere when more than
|
||||
/// 256 do.
|
||||
|
||||
@@ -78,6 +78,35 @@ fn a_butt_capped_open_path_is_measured_where_it_paints() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn beveled_corners_are_measured_where_they_paint() {
|
||||
let mut tip = BezPath::new();
|
||||
tip.move_to((0.0, 100.0));
|
||||
tip.line_to((20.0, 0.0));
|
||||
tip.line_to((40.0, 100.0));
|
||||
tip.close_path();
|
||||
let mut chevron = BezPath::new();
|
||||
chevron.move_to((0.0, 100.0));
|
||||
chevron.line_to((20.0, 0.0));
|
||||
chevron.line_to((40.0, 100.0));
|
||||
// A rectangle with no width turns back at its top and bottom.
|
||||
let flat = vectorcraft_geom::shapes::rectangle(Rect::new(3.0, 100.0, 3.0, 150.0)).to_bezpath();
|
||||
let ps = paths();
|
||||
for (name, bp) in [("tip", &tip), ("chevron", &chevron), ("zigzag", &ps[1]), ("triangle", &ps[2]), ("flat", &flat)] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
for (join, limit) in [(LineJoin::Bevel, 10.0), (LineJoin::Miter, 1.0), (LineJoin::Miter, 2.0), (LineJoin::Miter, 10.0)] {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 20.0);
|
||||
(st.cap, st.join, st.miter_limit) = (cap, join, limit);
|
||||
let painted = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, &st).to_bezpath().bounding_box();
|
||||
let bounds = st.bounds_on(bp, bp.bounding_box());
|
||||
for (got, want) in [(bounds.x0, painted.x0), (bounds.y0, painted.y0), (bounds.x1, painted.x1), (bounds.y1, painted.y1)] {
|
||||
assert!((got - want).abs() < 0.05, "{name} {cap:?} {join:?} {limit}: measured {bounds:?}, paints {painted:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_clicks_cover_what_every_stroke_paints() {
|
||||
let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })];
|
||||
@@ -99,14 +128,27 @@ fn bounds_and_clicks_cover_what_every_stroke_paints() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom heads: one wholly behind its tip, and a long one reaching as far in front of its tip as
|
||||
/// behind it (its tip sits halfway along it past the end point with Extend).
|
||||
fn custom_heads() -> Vec<Arrowhead> {
|
||||
use vectorcraft_geom::{Point as P, SubPath};
|
||||
let head = |name: &str, pts: &[(f64, f64)]| {
|
||||
let pts: Vec<P> = pts.iter().map(|&(x, y)| P::new(x, y)).collect();
|
||||
let path = PathData::single(SubPath::polyline(&pts, true));
|
||||
Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(name.into(), path)))
|
||||
};
|
||||
vec![head("Wedge", &[(0.0, 0.0), (3.0, 2.0), (3.0, -1.0)]), head("Spindle", &[(-10.0, 0.0), (0.0, 2.0), (10.0, 0.0), (0.0, -2.0)])]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_clicks_cover_every_arrowhead() {
|
||||
let bp = &paths()[0];
|
||||
for kind in Arrowhead::ALL {
|
||||
for kind in Arrowhead::ALL.into_iter().chain(custom_heads()) {
|
||||
for align in [ArrowAlign::Extend, ArrowAlign::Tip] {
|
||||
for (scale, cap) in [(50.0, LineCap::Round), (100.0, LineCap::Butt), (300.0, LineCap::Square)] {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0);
|
||||
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) = (Some(kind), Some(kind), align, (scale, scale), cap);
|
||||
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) =
|
||||
(Some(kind.clone()), Some(kind.clone()), align, (scale, scale), cap);
|
||||
check(bp, &st, &format!("{kind:?} {align:?} {scale}%"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes};
|
||||
|
||||
use super::*;
|
||||
|
||||
mod imageoutline;
|
||||
mod rasterfollow;
|
||||
mod scale;
|
||||
mod transformfx;
|
||||
|
||||
@@ -885,6 +887,108 @@ fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Under a Warp effect a hidden path in a layer that keeps its shape past the budget does not hold
|
||||
/// the layer's gradient in place either: it moves and scales from the layer's bounds to the warped
|
||||
/// square's bounds, as the art and inside the art.
|
||||
#[test]
|
||||
fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_follow_a_warp() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, LayerColor, NodeId, NodeKind, color::Paint};
|
||||
let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)];
|
||||
let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
|
||||
let ends = |ap: &Appearance| match ap.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom.map(|g| (g.start, g.end)),
|
||||
_ => None,
|
||||
};
|
||||
let oval = || shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
// A layer with a visible square and a hidden circle, both 0..100, and a gradient fill of its own.
|
||||
let layer = || {
|
||||
let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()));
|
||||
let mut circle = Node::path(NodeId(4), oval(), Appearance::default());
|
||||
circle.visible = false;
|
||||
let mut layer = Node::layer(NodeId(2), "Layer 1", LayerColor::Preset(0));
|
||||
if let NodeKind::Layer { children, .. } = &mut layer.kind {
|
||||
*children = vec![square, Arc::new(circle)];
|
||||
}
|
||||
layer.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone())));
|
||||
layer
|
||||
};
|
||||
// The box map from the layer's bounds (the square's) to `b`: (0, 50) and (100, 50) go to the
|
||||
// middles of b's sides.
|
||||
let near = |got: Option<(Point, Point)>, b: Rect| {
|
||||
let mid = (b.y0 + b.y1) / 2.0;
|
||||
got.is_some_and(|(s, e)| s.distance(Point::new(b.x0, mid)) < 1e-6 && e.distance(Point::new(b.x1, mid)) < 1e-6)
|
||||
};
|
||||
for style in ["arc", "inflate", "flag"] {
|
||||
let warp = fx(&format!("warp.{style}"), json!({"bend": 40.0, "horizontal": 20.0}));
|
||||
// Room for the warped square beside the circle as it was, and not for the warped circle
|
||||
// beside the warped square: the paths take the budget in turn, so the circle keeps its shape.
|
||||
let mut probe = layer();
|
||||
crate::reshape::reshape_leaves_within(&mut probe, &[&warp], Budget::EFFECTS, None);
|
||||
let warped = |k: usize| util::line_estimate(probe.children().unwrap()[k].path_data().unwrap());
|
||||
let circle = util::line_estimate(&oval());
|
||||
assert!(warped(1) > circle, "warp.{style}: the warped circle is drawn with more lines");
|
||||
let budget = Budget { anchors: usize::MAX, lines: warped(0) + circle };
|
||||
let mut art = layer();
|
||||
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None);
|
||||
assert_eq!(art.children().unwrap()[1].path_data(), Some(&oval()), "{}: the hidden circle keeps its shape", warp.id);
|
||||
let square = art.children().unwrap()[0].geometric_bounds().unwrap();
|
||||
assert!(square != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the square takes the effect: {square:?}", warp.id);
|
||||
let mut own = Appearance::clone(&art.appearance);
|
||||
carry.apply(&mut own);
|
||||
assert!(near(ends(&own), square), "{}: the layer's gradient, as the art: {:?} for {square:?}", warp.id, ends(&own));
|
||||
let mut art = Node::group(NodeId(9), vec![Arc::new(layer())]);
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None);
|
||||
let got = ends(&art.children().unwrap()[0].appearance);
|
||||
assert!(near(got, square), "{}: the layer's gradient, inside the art: {got:?} for {square:?}", warp.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A freeform gradient whose points were edited moves its points with a Warp effect from the
|
||||
/// bounds before the warp to the bounds after it, on a path, on a group inside the art and on the
|
||||
/// art itself, as a placed gradient does.
|
||||
#[test]
|
||||
fn edited_freeform_points_follow_a_warp() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint};
|
||||
let mut ramp = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Gradient::default() });
|
||||
let pt = |x: f64, c| FreeformPoint::new(Point::new(x, 50.0), c);
|
||||
ramp.set_freeform(Freeform { points: vec![pt(0.0, Color::BLACK), pt(100.0, Color::WHITE)], ..Default::default() });
|
||||
assert!(ramp.geom.is_none() && !ramp.is_placed());
|
||||
let freeform = Paint::Gradient(Box::new(ramp));
|
||||
let points = |ap: &Appearance| match ap.fill_paint() {
|
||||
Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points.iter().map(|p| p.at).collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
};
|
||||
let square = |ap: Appearance| Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap));
|
||||
// The box map from the square's bounds to `b`: (0, 50) and (100, 50) go to the middles of b's sides.
|
||||
let near = |got: Option<Vec<Point>>, b: Rect| {
|
||||
let mid = (b.y0 + b.y1) / 2.0;
|
||||
got.is_some_and(|p| p.len() == 2 && p[0].distance(Point::new(b.x0, mid)) < 1e-6 && p[1].distance(Point::new(b.x1, mid)) < 1e-6)
|
||||
};
|
||||
for style in ["arc", "inflate", "rise"] {
|
||||
let e = fx(&format!("warp.{style}"), json!({"bend": 40.0, "vertical": 20.0}));
|
||||
let mut inner = Node::group(NodeId(2), vec![square(Appearance::default())]);
|
||||
inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
|
||||
let mut art = Node::group(NodeId(9), vec![square(Appearance::basic(freeform.clone(), Paint::None, 0.0)), Arc::new(inner)]);
|
||||
art.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
|
||||
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&e], Budget::EFFECTS, None);
|
||||
let b = art.geometric_bounds().unwrap();
|
||||
assert!(b != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the warp changes the bounds: {b:?}", e.id);
|
||||
let members = art.children().unwrap();
|
||||
assert!(near(points(&members[0].appearance), b), "{}: the path's points {:?} for {b:?}", e.id, points(&members[0].appearance));
|
||||
assert!(near(points(&members[1].appearance), b), "{}: the inner group's points {:?} for {b:?}", e.id, points(&members[1].appearance));
|
||||
let mut own = Appearance::clone(&art.appearance);
|
||||
carry.apply(&mut own);
|
||||
assert!(near(points(&own), b), "{}: the art's own points {:?} for {b:?}", e.id, points(&own));
|
||||
}
|
||||
}
|
||||
|
||||
/// A freeform gradient whose points were edited (its vector still fitted to the bounds) moves its
|
||||
/// points with a Transform effect and Free Distort, on a path, on a group inside the art and on the
|
||||
/// art itself, as a placed gradient does.
|
||||
@@ -1251,6 +1355,96 @@ fn roughen_smooth_makes_no_cusps() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly() {
|
||||
use vectorcraft_geom::AnchorKind;
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
|
||||
let (a, b) = (Point::new(0.0, 0.0), Point::new(300.0, 0.0));
|
||||
let curve = PathData::single(SubPath::new(
|
||||
vec![
|
||||
vectorcraft_geom::Anchor::with_handles(a, a, Point::new(10.0, 40.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(b, Point::new(100.0, 200.0), b),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let ellipse = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 50.0));
|
||||
// Two subpaths with lines and curves: a closed one whose last segment is a line, and an open
|
||||
// one that ends with a line.
|
||||
let (c, d, e, f) = (Point::new(100.0, 100.0), Point::new(200.0, 0.0), Point::new(300.0, 0.0), Point::new(300.0, 100.0));
|
||||
let mixed = PathData::new(vec![
|
||||
SubPath::new(
|
||||
vec![
|
||||
vectorcraft_geom::Anchor::corner(a),
|
||||
vectorcraft_geom::Anchor::with_handles(Point::new(100.0, 0.0), Point::new(100.0, 0.0), Point::new(160.0, 20.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(c, Point::new(160.0, 80.0), c),
|
||||
],
|
||||
true,
|
||||
),
|
||||
SubPath::new(
|
||||
vec![
|
||||
vectorcraft_geom::Anchor::with_handles(d, d, Point::new(220.0, 60.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(e, Point::new(280.0, 60.0), e),
|
||||
vectorcraft_geom::Anchor::corner(f),
|
||||
],
|
||||
false,
|
||||
),
|
||||
]);
|
||||
for path in [square(), ellipse, curve, mixed] {
|
||||
let all: Vec<_> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i))).collect();
|
||||
let off = |q: Point| all.iter().map(|c| c.nearest(q, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt();
|
||||
for params in
|
||||
[json!({"size": 0}), json!({"size": 0, "points": "corner"}), json!({"size": 0, "relative": false, "points": "corner", "seed": 7})]
|
||||
{
|
||||
let out = run("distort.roughen", params.clone(), &path);
|
||||
assert!(out.anchor_count() > path.anchor_count(), "{params}: the points are added");
|
||||
assert_eq!(out.subpaths.len(), path.subpaths.len(), "{params}");
|
||||
for (sp, got) in path.subpaths.iter().zip(&out.subpaths) {
|
||||
assert_eq!(got.closed, sp.closed);
|
||||
// Walk the result one original segment at a time: its pieces end on the segment's end anchor.
|
||||
let mut at = 0;
|
||||
for i in 0..sp.segment_count() {
|
||||
let (orig, end) = (sp.segment(i), sp.anchors[(i + 1) % sp.anchors.len()]);
|
||||
let start = got.anchors[at];
|
||||
let was = sp.anchors[i];
|
||||
assert_eq!((start.p, start.kind, start.has_in(), start.has_out()), (was.p, was.kind, was.has_in(), was.has_out()), "{params}");
|
||||
let mut pieces = vec![];
|
||||
loop {
|
||||
let piece = got.segment(at);
|
||||
for j in 0..=8 {
|
||||
let q = piece.eval(j as f64 / 8.0);
|
||||
assert!(off(q) < 1e-6, "{params}: {q:?} is {} off the outline", off(q));
|
||||
}
|
||||
pieces.push(piece.arclen(1e-6));
|
||||
at += 1;
|
||||
if piece.p3.distance(end.p) < 1e-9 {
|
||||
break;
|
||||
}
|
||||
// A point the effect added: a corner without handles on a line, a smooth
|
||||
// point whose handles follow the curve.
|
||||
let added = got.anchors[at];
|
||||
if sp.segment_is_line(i) {
|
||||
assert_eq!((added.kind, added.has_in(), added.has_out()), (AnchorKind::Corner, false, false), "{params}");
|
||||
} else {
|
||||
assert_eq!(added.kind, AnchorKind::Smooth, "{params}");
|
||||
let (hi, ho) = (added.h_in - added.p, added.h_out - added.p);
|
||||
assert!(hi.cross(ho).abs() < 1e-6 * hi.hypot() * ho.hypot() && hi.dot(ho) < 0.0, "{params}: {added:?}");
|
||||
}
|
||||
}
|
||||
assert!(pieces.len() > 1, "{params}: segment {i} is split");
|
||||
assert!(close(pieces.iter().sum::<f64>(), orig.arclen(1e-6), 1e-3), "{params}: {pieces:?}");
|
||||
let (lo, hi) = pieces.iter().fold((f64::INFINITY, 0.0f64), |(lo, hi), &l| (lo.min(l), hi.max(l)));
|
||||
assert!(hi - lo < 1e-3, "{params}: segment {i}'s pieces from {lo} to {hi}");
|
||||
}
|
||||
assert_eq!(at, got.segment_count(), "{params}");
|
||||
if !sp.closed {
|
||||
let (last, was) = (got.anchors[at], sp.anchors[sp.anchors.len() - 1]);
|
||||
assert_eq!((last.p, last.kind, last.has_in(), last.has_out()), (was.p, was.kind, was.has_in(), was.has_out()), "{params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zigzag_ridge_count_and_amplitude() {
|
||||
let out = run("distort.zigZag", json!({"ridges": 4, "points": "corner", "size": 10}), &square());
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Outline Object on an image's own fill or stroke: the outline of the image's opaque area, for
|
||||
//! every pixel format with alpha, and the frame for one without.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Effect, FillLayer, ImageBlob, ImageObject, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn fx(id: &str) -> Effect {
|
||||
Effect { id: id.into(), params: json!({}), visible: true }
|
||||
}
|
||||
|
||||
/// `img` encoded as `format`.
|
||||
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle.
|
||||
fn disc() -> image::DynamicImage {
|
||||
image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 100, |x, y| {
|
||||
let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0);
|
||||
image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }])
|
||||
}))
|
||||
}
|
||||
|
||||
/// A document holding the encoded image `bytes` (key "img") and an image object of 100×100 pixels
|
||||
/// placed at (50, 50) with the appearance items `items`, the image's own row at `contents`.
|
||||
/// → (document, the image's node).
|
||||
fn image_doc(bytes: Vec<u8>, items: Vec<AppearanceItem>, contents: usize) -> (Document, Node) {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.images.insert("img".into(), ImageBlob::new("image/png", bytes));
|
||||
let mut n = Node::new(
|
||||
NodeId(0),
|
||||
NodeKind::Image(Box::new(ImageObject {
|
||||
key: "img".into(),
|
||||
width: 100,
|
||||
height: 100,
|
||||
xf: Affine::translate((50.0, 50.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
})),
|
||||
);
|
||||
n.id = d.alloc_id();
|
||||
n.appearance.items = items;
|
||||
n.appearance.set_contents_at(contents);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n.clone()).unwrap();
|
||||
(d, n)
|
||||
}
|
||||
|
||||
/// A PNG of `w × h` pixels with the color type `color` at `depth` bits, the chunks `extra` before
|
||||
/// its pixels, and the filtered rows `rows` stored without compression.
|
||||
fn png(w: u32, h: u32, color: u8, depth: u8, extra: &[(&[u8; 4], Vec<u8>)], rows: &[u8]) -> Vec<u8> {
|
||||
fn crc(data: &[u8]) -> u32 {
|
||||
let mut c = !0u32;
|
||||
for &b in data {
|
||||
c ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
}
|
||||
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
let mut chunk = |kind: &[u8; 4], data: &[u8]| {
|
||||
let mut body = kind.to_vec();
|
||||
body.extend_from_slice(data);
|
||||
out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes());
|
||||
out.extend_from_slice(&body);
|
||||
out.extend_from_slice(&crc(&body).to_be_bytes());
|
||||
};
|
||||
let mut ihdr = [w.to_be_bytes(), h.to_be_bytes()].concat();
|
||||
ihdr.extend([depth, color, 0, 0, 0]);
|
||||
chunk(b"IHDR", &ihdr);
|
||||
for (kind, data) in extra {
|
||||
chunk(kind, data);
|
||||
}
|
||||
// A zlib stream of stored blocks.
|
||||
let mut z = vec![0x78, 0x01];
|
||||
let blocks: Vec<&[u8]> = if rows.is_empty() { vec![rows] } else { rows.chunks(65_535).collect() };
|
||||
for (i, block) in blocks.iter().enumerate() {
|
||||
let len = u16::try_from(block.len()).unwrap();
|
||||
z.push(u8::from(i + 1 == blocks.len()));
|
||||
z.extend(len.to_le_bytes());
|
||||
z.extend((!len).to_le_bytes());
|
||||
z.extend_from_slice(block);
|
||||
}
|
||||
let (mut a, mut b) = (1u32, 0u32);
|
||||
for &byte in rows {
|
||||
a = (a + u32::from(byte)) % 65_521;
|
||||
b = (b + a) % 65_521;
|
||||
}
|
||||
z.extend(((b << 16) | a).to_be_bytes());
|
||||
chunk(b"IDAT", &z);
|
||||
chunk(b"IEND", &[]);
|
||||
out
|
||||
}
|
||||
|
||||
fn stroke(effects: Vec<Effect>) -> AppearanceItem {
|
||||
let mut s = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
|
||||
s.effects = effects;
|
||||
AppearanceItem::Stroke(s)
|
||||
}
|
||||
|
||||
/// The bounds of the paths the image's own fills and strokes paint, below it first.
|
||||
fn row_bounds(d: &Document, n: &Node) -> Vec<Rect> {
|
||||
let art = reshape::reshape(Some(d), n, None).unwrap();
|
||||
let mut out = vec![];
|
||||
for c in art.children().unwrap() {
|
||||
if matches!(c.kind, NodeKind::Path { .. }) {
|
||||
out.push(c.geometric_bounds().unwrap());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn near(r: Rect, want: [f64; 4], tol: f64) -> bool {
|
||||
[r.x0 - want[0], r.y0 - want[1], r.x1 - want[2], r.y1 - want[3]].iter().all(|d| d.abs() < tol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() {
|
||||
let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8());
|
||||
let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16());
|
||||
for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] {
|
||||
let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let rows = row_bounds(&d, &n);
|
||||
assert_eq!(rows.len(), 1, "{name}");
|
||||
// The disc runs from 70 to 130; the frame from 50 to 150.
|
||||
assert!(near(rows[0], [70.0, 70.0, 130.0, 130.0], 0.5), "{name}: {:?}", rows[0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_object_follows_the_frame_of_an_image_without_transparency() {
|
||||
let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255])));
|
||||
let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200])));
|
||||
let formats = [
|
||||
("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)),
|
||||
("rgb png", encoded(opaque, image::ImageFormat::Png)),
|
||||
("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)),
|
||||
];
|
||||
for (name, bytes) in formats {
|
||||
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let rows = row_bounds(&d, &n);
|
||||
assert!(rows.len() == 1 && near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{name}: {rows:?}");
|
||||
}
|
||||
// Pixels that can't be read keep the frame too.
|
||||
let (d, n) = image_doc(b"not an image".to_vec(), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
assert!(near(row_bounds(&d, &n)[0], [50.0, 50.0, 150.0, 150.0], 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_shape_keeps_the_frame_beside_outline_object() {
|
||||
// Below the image: a fill with Convert to Shape, then a stroke with Outline Object; above it
|
||||
// a stroke with Convert to Shape before Outline Object, which starts from the frame.
|
||||
let rect = Effect { id: "convertToShape.rectangle".into(), params: json!({"relative": true, "extraW": 0, "extraH": 0}), visible: true };
|
||||
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
fill.effects = vec![rect.clone()];
|
||||
let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])];
|
||||
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2);
|
||||
let rows = row_bounds(&d, &n);
|
||||
assert_eq!(rows.len(), 3, "{rows:?}");
|
||||
assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
|
||||
assert!(near(rows[1], [70.0, 70.0, 130.0, 130.0], 0.5), "{rows:?}");
|
||||
assert!(near(rows[2], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
|
||||
// The image keeps its place between them.
|
||||
let art = reshape::reshape(Some(&d), &n, None).unwrap();
|
||||
assert!(matches!(art.children().unwrap()[2].kind, NodeKind::Image(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transparent_image_gives_outline_object_nothing_to_paint() {
|
||||
let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100])));
|
||||
let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
assert!(row_bounds(&d, &n).is_empty());
|
||||
let art = reshape::reshape(Some(&d), &n, None).unwrap();
|
||||
assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_outline_follows_the_images_own_pixels_and_placement() {
|
||||
// Pixels kept on the image itself (art made outside a document), placed at half size.
|
||||
let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png))));
|
||||
im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5);
|
||||
}
|
||||
let art = reshape::reshape(None, &n, None).unwrap();
|
||||
let b = art.children().unwrap()[0].geometric_bounds().unwrap();
|
||||
// The disc runs from 20 to 80 pixels: half that, moved by (10, 20).
|
||||
assert!(near(b, [20.0, 30.0, 50.0, 60.0], 0.3), "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels() {
|
||||
// A 120×60 image whose opaque area is the rectangle from (12, 6) to (40, 24), its pixels a
|
||||
// copy at half size (as a linked image's preview is), turned a quarter and reflected.
|
||||
let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| {
|
||||
image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }])
|
||||
}));
|
||||
let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0);
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
(im.width, im.height, im.xf) = (120, 60, xf);
|
||||
}
|
||||
let rows = row_bounds(&d, &n);
|
||||
let want = xf.transform_rect_bbox(Rect::new(12.0, 6.0, 40.0, 24.0));
|
||||
// The rectangle runs from (76, 0) to (94, 28); a flip in either direction, or the copy's
|
||||
// width and height swapped, would move it.
|
||||
assert!(near(want, [76.0, 0.0, 94.0, 28.0], 1e-9), "{want:?}");
|
||||
assert!(rows.len() == 1 && near(rows[0], [want.x0, want.y0, want.x1, want.y1], 0.5), "{rows:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_in_a_group_exports_with_its_outline() {
|
||||
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let l = d.layers[0].id;
|
||||
d.remove(n.id).unwrap();
|
||||
let g = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(n)])).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let mut paths = vec![];
|
||||
for layer in &baked.layers {
|
||||
layer.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 {
|
||||
paths.push(c.geometric_bounds().unwrap());
|
||||
}
|
||||
});
|
||||
}
|
||||
assert!(matches!(paths.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{paths:?}");
|
||||
}
|
||||
|
||||
/// The bounds of the paths stroked 4 pt in `d` with its effects baked, as exports write it.
|
||||
fn baked_strokes(d: &Document) -> Vec<Rect> {
|
||||
let baked = bake_document(d).unwrap();
|
||||
let mut paths = vec![];
|
||||
for layer in &baked.layers {
|
||||
layer.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 {
|
||||
paths.push(c.geometric_bounds().unwrap());
|
||||
}
|
||||
});
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() {
|
||||
let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5));
|
||||
// Under a clipping mask that covers the whole image.
|
||||
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let l = d.layers[0].id;
|
||||
d.remove(n.id).unwrap();
|
||||
let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
|
||||
let g = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(n)], clip: true })).unwrap();
|
||||
let paths = baked_strokes(&d);
|
||||
assert!(disc_outline(&paths), "{paths:?}");
|
||||
// With an opacity mask.
|
||||
let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
|
||||
white.appearance.set_fill(Paint::solid(Color::WHITE));
|
||||
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true)));
|
||||
let id = n.id;
|
||||
*d.node_mut(id).unwrap() = n;
|
||||
let paths = baked_strokes(&d);
|
||||
assert!(disc_outline(&paths), "{paths:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() {
|
||||
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
fill.effects = vec![fx("path.outlineObject")];
|
||||
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1);
|
||||
let rows = row_bounds(&d, &n);
|
||||
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
|
||||
// A palette image whose first color is transparent (a tRNS chunk).
|
||||
let mut rows = vec![];
|
||||
for y in 0..100 {
|
||||
rows.push(0);
|
||||
for x in 0..100 {
|
||||
let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0);
|
||||
rows.push(u8::from(r <= 30.0));
|
||||
}
|
||||
}
|
||||
let palette = png(100, 100, 3, 8, &[(b"PLTE", vec![0, 0, 0, 255, 0, 0]), (b"tRNS", vec![0, 255])], &rows);
|
||||
let (d, n) = image_doc(palette, vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let rows = row_bounds(&d, &n);
|
||||
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() {
|
||||
// 72 megapixels at 8 bits a channel, and 42 at 16: refused before their pixels are read.
|
||||
for (w, h, depth) in [(9000, 8000, 8), (7000, 6000, 16)] {
|
||||
let bytes = png(w, h, 6, depth, &[], &[]);
|
||||
assert!(matches!(vectorcraft_trace::decode_alpha(&bytes), Err(vectorcraft_trace::TraceError::TooLarge { .. })), "{w}×{h}");
|
||||
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)), "{w}×{h}");
|
||||
}
|
||||
// A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points.
|
||||
let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }]));
|
||||
let (d, n) =
|
||||
image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
|
||||
let traces = || reshape::TRACES.with(std::cell::Cell::get);
|
||||
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("not an image") };
|
||||
let before = traces();
|
||||
let first = reshape::opaque_area(&[Some(&d)], im).unwrap();
|
||||
assert_eq!(traces(), before + 1);
|
||||
for _ in 0..3 {
|
||||
row_bounds(&d, &n);
|
||||
}
|
||||
assert_eq!(reshape::opaque_area(&[Some(&d)], im).unwrap(), first);
|
||||
assert_eq!(traces(), before + 1);
|
||||
let pixels = Arc::downgrade(&d.images.get(&im.key).unwrap().bytes);
|
||||
assert!(reshape::keeps_outline(&pixels));
|
||||
// Once the document and its pixels are gone, the next trace drops their entry.
|
||||
drop(d);
|
||||
assert!(pixels.upgrade().is_none());
|
||||
let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1);
|
||||
reshape::opaque_area(&[Some(&other)], im).unwrap();
|
||||
assert_eq!(traces(), before + 2);
|
||||
assert!(!reshape::keeps_outline(&pixels));
|
||||
}
|
||||
@@ -0,0 +1,652 @@
|
||||
//! Raster effects listed before a Transform effect follow it: the Transform effect transforms
|
||||
//! what they paint.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use crate::{RasterFx, bake_document, expand_outlined, raster_effects};
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
}
|
||||
|
||||
fn shadow(x: f64, y: f64, blur: f64) -> Effect {
|
||||
fx("stylize.dropShadow", json!({"x": x, "y": y, "blur": blur}))
|
||||
}
|
||||
|
||||
fn transform(params: Value) -> Effect {
|
||||
fx("distort.transform", params)
|
||||
}
|
||||
|
||||
/// The offset and blur of the first Drop Shadow `effects` draw.
|
||||
fn drawn_shadow(effects: &[Effect]) -> (f64, f64, f64) {
|
||||
match raster_effects(effects).first() {
|
||||
Some(RasterFx::DropShadow { dx, dy, blur, .. }) => (*dx, *dy, *blur),
|
||||
other => panic!("expected a drop shadow, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: (f64, f64, f64), b: (f64, f64, f64)) -> bool {
|
||||
(a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9 && (a.2 - b.2).abs() < 1e-9
|
||||
}
|
||||
|
||||
/// A 50 pt red square with `effects`.
|
||||
fn square(id: u64, effects: Vec<Effect>) -> Node {
|
||||
let mut n = Node::path(
|
||||
NodeId(id),
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)),
|
||||
Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0),
|
||||
);
|
||||
n.appearance.effects = effects;
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transform_after_a_drop_shadow_scales_its_offset_and_blur() {
|
||||
for strokes in [false, true] {
|
||||
let effects = [shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200, "strokes": strokes}))];
|
||||
assert!(close(drawn_shadow(&effects), (20.0, 20.0, 8.0)), "Scale Strokes & Effects {strokes}: {:?}", drawn_shadow(&effects));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_shadow_after_a_transform_keeps_its_offset() {
|
||||
let effects = [transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 10.0, 4.0)];
|
||||
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{:?}", drawn_shadow(&effects));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offset_follows_an_uneven_scale_a_rotation_and_a_reflection() {
|
||||
let uneven = [shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 100}))];
|
||||
assert!(close(drawn_shadow(&uneven), (20.0, 10.0, 4.0 * 2f64.sqrt())), "{:?}", drawn_shadow(&uneven));
|
||||
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
|
||||
let turned = [shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90}))];
|
||||
let (dx, dy, blur) = drawn_shadow(&turned);
|
||||
assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9 && (blur - 4.0).abs() < 1e-9, "{dx} {dy} {blur}");
|
||||
let reflected = [shadow(10.0, 0.0, 4.0), transform(json!({"reflectX": true}))];
|
||||
assert!(close(drawn_shadow(&reflected), (-10.0, 0.0, 4.0)), "{:?}", drawn_shadow(&reflected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforms_after_the_shadow_apply_in_order() {
|
||||
let effects = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"rotate": 90}))];
|
||||
let (dx, dy, _) = drawn_shadow(&effects);
|
||||
assert!(dx.abs() < 1e-9 && (dy + 20.0).abs() < 1e-9, "{dx} {dy}");
|
||||
// Only the Transform after a shadow moves it.
|
||||
let between = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), shadow(0.0, 10.0, 0.0)];
|
||||
let drawn = raster_effects(&between);
|
||||
let offsets: Vec<(f64, f64)> = drawn
|
||||
.iter()
|
||||
.filter_map(|r| match r {
|
||||
RasterFx::DropShadow { dx, dy, .. } => Some((*dx, *dy)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(offsets, vec![(20.0, 0.0), (0.0, 10.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforms_that_leave_the_art_or_copy_it_leave_the_shadow() {
|
||||
for params in [
|
||||
json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}),
|
||||
json!({"scaleH": 200, "scaleV": 200, "copies": 1}),
|
||||
json!({"scaleH": 200, "scaleV": 200, "random": true}),
|
||||
] {
|
||||
let effects = [shadow(10.0, 10.0, 4.0), transform(params.clone())];
|
||||
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{params}: {:?}", drawn_shadow(&effects));
|
||||
}
|
||||
let mut hidden = transform(json!({"scaleH": 200, "scaleV": 200}));
|
||||
hidden.visible = false;
|
||||
let effects = [shadow(10.0, 10.0, 4.0), hidden];
|
||||
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{:?}", drawn_shadow(&effects));
|
||||
}
|
||||
|
||||
/// A hidden shadow kept when the Transform effect is applied (Expand Appearance) draws as it would
|
||||
/// have before, once it is shown.
|
||||
#[test]
|
||||
fn a_hidden_shadow_follows_the_transform_it_loses() {
|
||||
let mut hidden = shadow(10.0, 10.0, 4.0);
|
||||
hidden.visible = false;
|
||||
let kept = crate::raster::without_geometry(&[hidden, transform(json!({"scaleH": 200, "scaleV": 200}))]);
|
||||
assert_eq!(kept.len(), 1);
|
||||
let mut shown = kept[0].clone();
|
||||
shown.visible = true;
|
||||
assert!(close(drawn_shadow(&[shown]), (20.0, 20.0, 8.0)));
|
||||
}
|
||||
|
||||
/// Rasterize keeps its room around the art: its image keeps its own pixel grid.
|
||||
#[test]
|
||||
fn rasterize_before_a_transform_keeps_its_options() {
|
||||
let rasterize = fx(crate::RASTERIZE, json!({"addAround": 6}));
|
||||
let effects = [rasterize.clone(), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
assert_eq!(crate::raster::followed(&effects)[0], rasterize);
|
||||
assert_eq!(crate::raster::without_geometry(&effects), vec![rasterize]);
|
||||
}
|
||||
|
||||
/// An SVG filter keeps its options: it paints in its own user space.
|
||||
#[test]
|
||||
fn an_svg_filter_before_a_transform_keeps_its_options() {
|
||||
let filter = fx(crate::SVG_FILTER, json!({"origin": [10, 10]}));
|
||||
let effects = [filter.clone(), transform(json!({"scaleH": 200, "scaleV": 200, "rotate": 90}))];
|
||||
assert_eq!(crate::raster::followed(&effects)[0], filter);
|
||||
assert_eq!(crate::raster::without_geometry(&effects), vec![filter]);
|
||||
}
|
||||
|
||||
/// The offset of every Drop Shadow drawn on `n` and the nodes under it, from the object's effects
|
||||
/// and from each fill's and stroke's.
|
||||
fn shadows_in(n: &Node) -> Vec<(f64, f64)> {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
for list in lists {
|
||||
for r in raster_effects(list) {
|
||||
if let RasterFx::DropShadow { dx, dy, .. } = r {
|
||||
out.push((dx, dy));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// A square whose fill carries `effects` of its own.
|
||||
fn fill_square(id: u64, effects: Vec<Effect>) -> Node {
|
||||
let mut n = square(id, vec![]);
|
||||
if let Some(item) = n.appearance.items.first_mut() {
|
||||
*item.effects_mut() = effects;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// A fill's own Transform effect transforms the fill's raster effects before it: drawn as they are
|
||||
/// (no options), drawn through the art the Transform Patterns or Scale Strokes & Effects option
|
||||
/// makes, expanded and baked. Scale Strokes & Effects does not scale a shadow that follows the
|
||||
/// Transform effect a second time.
|
||||
#[test]
|
||||
fn a_fills_shadow_follows_the_fills_own_transform() {
|
||||
let cases = [
|
||||
(json!({"rotate": 90}), (0.0, -10.0)),
|
||||
(json!({"rotate": 90, "strokes": true}), (0.0, -10.0)),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "strokes": true}), (20.0, 0.0)),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "patterns": true}), (20.0, 0.0)),
|
||||
(json!({"reflectX": true, "patterns": true}), (-10.0, 0.0)),
|
||||
];
|
||||
for (params, want) in cases {
|
||||
let n = fill_square(11, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
|
||||
// Drawn and expanded through its art when an option makes some.
|
||||
if crate::has_transform_art(&n) {
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[want]), "{params}: drawn {:?}", shadows_in(&art));
|
||||
let expanded = expand_outlined(None, &n, None).unwrap();
|
||||
assert!(near(&shadows_in(&expanded), &[want]), "{params}: expanded {:?}", shadows_in(&expanded));
|
||||
} else {
|
||||
assert!(near(&shadows_in(&n), &[want]), "{params}: drawn {:?}", shadows_in(&n));
|
||||
}
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let b = baked.node(NodeId(11)).unwrap();
|
||||
assert!(near(&shadows_in(b), &[want]), "{params}: baked {:?}", shadows_in(b));
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect after a fill's own Transform effect with Scale Strokes & Effects on turns the
|
||||
/// shadow between them, which the first one leaves as it is; a Transform effect that moves at random
|
||||
/// holds the shadow before it back from the Transform effects after it.
|
||||
#[test]
|
||||
fn a_fills_later_transform_turns_the_shadow_after_its_first() {
|
||||
let n = fill_square(
|
||||
12,
|
||||
vec![transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90}))],
|
||||
);
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[(0.0, -10.0)]), "{:?}", shadows_in(&art));
|
||||
let held = fill_square(
|
||||
13,
|
||||
vec![
|
||||
shadow(10.0, 0.0, 0.0),
|
||||
transform(json!({"scaleH": 200, "scaleV": 200, "random": true, "strokes": true})),
|
||||
transform(json!({"rotate": 90})),
|
||||
],
|
||||
);
|
||||
let art = crate::reshape(None, &held, None).unwrap();
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(drawn.len() == 1 && drawn[0].0 > 0.0 && drawn[0].1.abs() < 1e-9, "{drawn:?}");
|
||||
}
|
||||
|
||||
/// A fill's own Transform effect with Transform Patterns or Scale Strokes & Effects on leaves the
|
||||
/// fill's raster effects after it as they are: they paint around the transformed art, its copies
|
||||
/// included. With Transform Objects off it leaves the raster effects before it as they are too.
|
||||
/// Drawn, expanded and baked alike.
|
||||
#[test]
|
||||
fn a_fills_own_transform_leaves_the_shadow_after_it() {
|
||||
let cases = [
|
||||
vec![transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 0.0, 0.0)],
|
||||
vec![transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true, "strokes": true})), shadow(10.0, 0.0, 0.0)],
|
||||
vec![transform(json!({"scaleH": 200, "scaleV": 200, "moveH": 120, "copies": 1, "strokes": true})), shadow(10.0, 0.0, 0.0)],
|
||||
vec![transform(json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true})), shadow(10.0, 0.0, 0.0)],
|
||||
vec![shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}))],
|
||||
// A later Transform effect with an option leaves the shadow after it as well.
|
||||
vec![
|
||||
transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true})),
|
||||
transform(json!({"scaleH": 150, "scaleV": 150, "strokes": true})),
|
||||
shadow(10.0, 0.0, 0.0),
|
||||
],
|
||||
];
|
||||
for effects in cases {
|
||||
let n = fill_square(18, effects.clone());
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{effects:?}: drawn {drawn:?}");
|
||||
let expanded = shadows_in(&expand_outlined(None, &n, None).unwrap());
|
||||
assert!(!expanded.is_empty() && near(&expanded, &vec![(10.0, 0.0); expanded.len()]), "{effects:?}: expanded {expanded:?}");
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let b = shadows_in(baked.node(NodeId(18)).unwrap());
|
||||
assert!(!b.is_empty() && near(&b, &vec![(10.0, 0.0); b.len()]), "{effects:?}: baked {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A geometry effect after a fill's own Transform effect with Scale Strokes & Effects on reshapes
|
||||
/// the transformed art by its own distance, as it does after an object's Transform effect.
|
||||
#[test]
|
||||
fn a_fills_own_transform_leaves_the_offset_after_it() {
|
||||
let offset = fx("path.offsetPath", json!({"offset": 5}));
|
||||
let scaled = transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
|
||||
let n = fill_square(19, vec![scaled.clone(), offset.clone()]);
|
||||
let on_fill = crate::reshape(None, &n, None).unwrap();
|
||||
let on_object = crate::reshape(None, &square(20, vec![scaled, offset]), None).unwrap();
|
||||
let (fill, object) = (on_fill.geometric_bounds().unwrap(), on_object.geometric_bounds().unwrap());
|
||||
// The 50 pt square scaled to 100 pt about its center, then offset by 5 pt on each side.
|
||||
assert!((fill.width() - 110.0).abs() < 1e-6 && (fill.height() - 110.0).abs() < 1e-6, "{fill:?}");
|
||||
assert!((fill.width() - object.width()).abs() < 1e-6 && (fill.x0 - object.x0).abs() < 1e-6, "{fill:?} {object:?}");
|
||||
let expanded = expand_outlined(None, &n, None).unwrap().geometric_bounds().unwrap();
|
||||
assert!((expanded.width() - 110.0).abs() < 1e-6 && (expanded.x0 - fill.x0).abs() < 1e-6, "expanded {expanded:?}");
|
||||
}
|
||||
|
||||
/// The SVG filters on `n` and the nodes under it, from the object's effects and from each fill's
|
||||
/// and stroke's.
|
||||
fn filters_in(n: &Node) -> Vec<Effect> {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
out.extend(lists.flatten().filter(|e| e.id == crate::SVG_FILTER).cloned());
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// An SVG filter after a fill's own Transform effect with Scale Strokes & Effects on keeps its
|
||||
/// scale and the origin of its user space, as it does after the same Transform effect without
|
||||
/// options and after an object's own Transform effect.
|
||||
#[test]
|
||||
fn a_fills_own_transform_leaves_the_svg_filter_after_it() {
|
||||
let filter = fx(crate::SVG_FILTER, json!({"scale": 1.0, "origin": [10.0, 10.0]}));
|
||||
for params in [
|
||||
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "strokes": true}),
|
||||
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "patterns": true}),
|
||||
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}),
|
||||
json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}),
|
||||
] {
|
||||
let art = crate::reshape(None, &fill_square(21, vec![transform(params.clone()), filter.clone()]), None).unwrap();
|
||||
let drawn = filters_in(&art);
|
||||
assert!(!drawn.is_empty() && drawn.iter().all(|e| *e == filter), "{params}: {drawn:?}");
|
||||
}
|
||||
let object = square(22, vec![transform(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "strokes": true})), filter.clone()]);
|
||||
let art = crate::reshape(None, &object, None).unwrap();
|
||||
assert!(!filters_in(&art).is_empty() && filters_in(&art).iter().all(|e| *e == filter), "{:?}", filters_in(&art));
|
||||
}
|
||||
|
||||
/// The 3D effects keep the shadow before a Transform effect that shapes the art they project, the
|
||||
/// object's and its fill's 3D effect alike.
|
||||
#[test]
|
||||
fn a_shadow_before_a_transform_follows_it_into_3d_art() {
|
||||
let before = vec![shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
|
||||
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
|
||||
let mut on_object = before.clone();
|
||||
on_object.push(fx(three_d, json!({})));
|
||||
let projected = art(&square(14, on_object)).unwrap();
|
||||
assert!(near(&shadows_in(&projected), &[(20.0, 0.0)]), "{three_d} on the object: {:?}", shadows_in(&projected));
|
||||
let mut on_fill = square(15, before.clone());
|
||||
if let Some(item) = on_fill.appearance.items.first_mut() {
|
||||
*item.effects_mut() = vec![fx(three_d, json!({}))];
|
||||
}
|
||||
let projected = art(&on_fill).unwrap();
|
||||
assert!(near(&shadows_in(&projected), &[(20.0, 0.0)]), "{three_d} on the fill: {:?}", shadows_in(&projected));
|
||||
}
|
||||
}
|
||||
|
||||
/// An object's Transform effect transforms the raster effects of its fills when only a fill has a
|
||||
/// 3D effect: the shadow after that fill's 3D effect and another fill's shadow, as it does without
|
||||
/// the 3D effect.
|
||||
#[test]
|
||||
fn an_objects_transform_moves_its_fills_shadows_beside_a_fills_3d_effect() {
|
||||
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
|
||||
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
|
||||
let mut n = fill_square(18, vec![fx(three_d, json!({})), shadow(10.0, 10.0, 0.0)]);
|
||||
let mut other = n.appearance.items[0].clone();
|
||||
*other.effects_mut() = vec![shadow(10.0, 10.0, 0.0)];
|
||||
n.appearance.items.push(other);
|
||||
n.appearance.effects = vec![transform(json!({"scaleH": 200, "scaleV": 100}))];
|
||||
let drawn = shadows_in(&art(&n).unwrap());
|
||||
assert!(drawn.len() > 1 && near(&drawn, &vec![(20.0, 10.0); drawn.len()]), "{three_d}: {drawn:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glows_blurs_and_feathers_scale_with_the_transform_after_them() {
|
||||
let effects = [
|
||||
fx("stylize.outerGlow", json!({"blur": 5})),
|
||||
fx("stylize.innerGlow", json!({"blur": 5})),
|
||||
fx("stylize.feather", json!({"radius": 5})),
|
||||
fx("blur.gaussian", json!({"radius": 5})),
|
||||
transform(json!({"scaleH": 50, "scaleV": 50})),
|
||||
];
|
||||
let sizes: Vec<f64> = raster_effects(&effects)
|
||||
.iter()
|
||||
.map(|r| match r {
|
||||
RasterFx::OuterGlow { blur, .. } | RasterFx::InnerGlow { blur, .. } => *blur,
|
||||
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } => *radius,
|
||||
other => panic!("unexpected {other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(sizes, vec![2.5; 4]);
|
||||
// How far the shadow paints past the object follows too.
|
||||
let shadowed = [shadow(10.0, 10.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
assert_eq!(crate::outset(&shadowed, Rect::new(0.0, 0.0, 100.0, 100.0)), 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_filter_sizes_scale_with_the_transform_after_them() {
|
||||
let effects = [
|
||||
fx("artistic.coloredPencil", json!({"pencilWidth": 5})),
|
||||
fx("artistic.paintDaubs", json!({"brushSize": 10})),
|
||||
transform(json!({"scaleH": 200, "scaleV": 200})),
|
||||
];
|
||||
let drawn = raster_effects(&effects);
|
||||
assert!(matches!(drawn.first(), Some(RasterFx::Pixel(crate::PixelFx::ColoredPencil { width, .. })) if (width - 10.0).abs() < 1e-9), "{drawn:?}");
|
||||
assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}");
|
||||
}
|
||||
|
||||
/// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow
|
||||
/// before the 3D effect, as it does without the 3D effect.
|
||||
#[test]
|
||||
fn a_copying_transform_after_3d_holds_the_shadow_back() {
|
||||
for later in [json!({"copies": 1}), json!({"scaleH": 150, "scaleV": 150, "random": true})] {
|
||||
let plain = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(later.clone())];
|
||||
assert!(close(drawn_shadow(&plain), (10.0, 0.0, 0.0)), "{later}: {:?}", drawn_shadow(&plain));
|
||||
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
|
||||
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
|
||||
let effects = vec![plain[0].clone(), plain[1].clone(), fx(three_d, json!({})), plain[2].clone()];
|
||||
let projected = art(&square(16, effects)).unwrap();
|
||||
let drawn = shadows_in(&projected);
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{three_d} {later}: {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In a fill's own effects, a Transform effect that makes copies after a Transform effect with
|
||||
/// Transform Patterns on holds back the shadow before both, and before a Transform effect between
|
||||
/// them.
|
||||
#[test]
|
||||
fn a_fills_copying_transform_holds_back_the_shadow_before_an_earlier_transform() {
|
||||
let patterns = transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true}));
|
||||
let copies = transform(json!({"copies": 1}));
|
||||
let lists = [
|
||||
vec![shadow(10.0, 0.0, 0.0), patterns.clone(), copies.clone()],
|
||||
vec![shadow(10.0, 0.0, 0.0), patterns, transform(json!({"rotate": 90})), copies],
|
||||
];
|
||||
for effects in lists {
|
||||
let n = fill_square(17, effects.clone());
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{} effects: {drawn:?}", effects.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expanded_and_exported_objects_keep_the_shadow_the_canvas_draws() {
|
||||
let effects = vec![shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
// A path drawn through its art (Scale Strokes & Effects on), expanded.
|
||||
let mut with_options = effects.clone();
|
||||
with_options[1] = transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
|
||||
let n = square(7, with_options);
|
||||
let expanded = expand_outlined(None, &n, None).unwrap();
|
||||
assert!(close(drawn_shadow(&expanded.appearance.effects), (20.0, 20.0, 8.0)), "{:?}", expanded.appearance.effects);
|
||||
// A path and a group, baked for export.
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, square(8, effects.clone())).unwrap();
|
||||
let mut g = Node::group(NodeId(9), vec![std::sync::Arc::new(square(10, vec![]))]);
|
||||
g.appearance.effects = effects.clone();
|
||||
d.insert(Some(layer), 1, g).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
for id in [8, 9] {
|
||||
let b = baked.node(NodeId(id)).unwrap();
|
||||
assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{id}: {:?}", b.appearance.effects);
|
||||
assert!(close(drawn_shadow(&b.appearance.effects), (20.0, 20.0, 8.0)), "{id}: {:?}", b.appearance.effects);
|
||||
}
|
||||
}
|
||||
|
||||
/// A group of `members` with `effects` of its own.
|
||||
fn group(id: u64, members: Vec<Node>, effects: Vec<Effect>) -> Node {
|
||||
let mut g = Node::group(NodeId(id), members.into_iter().map(std::sync::Arc::new).collect());
|
||||
g.appearance.effects = effects;
|
||||
g
|
||||
}
|
||||
|
||||
/// The node with `id` under `n`.
|
||||
fn node_in(n: &Node, id: u64) -> Node {
|
||||
let mut found = None;
|
||||
n.walk(&mut |m| {
|
||||
if m.id == NodeId(id) && found.is_none() {
|
||||
found = Some(m.clone());
|
||||
}
|
||||
});
|
||||
found.unwrap_or_else(|| panic!("no node {id}"))
|
||||
}
|
||||
|
||||
/// The offset of the Drop Shadow that the first fill of `n` draws, its own effects and `n`'s
|
||||
/// Transform effects applied ([`crate::item_effects_in`]).
|
||||
fn fill_shadow(n: &Node) -> (f64, f64) {
|
||||
let item = n.appearance.items.first().unwrap();
|
||||
match raster_effects(&crate::item_effects_in(&n.appearance.effects, item.effects())).first() {
|
||||
Some(RasterFx::DropShadow { dx, dy, .. }) => (*dx, *dy),
|
||||
other => panic!("expected a drop shadow, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect transforms the raster effects of what the group holds with the art,
|
||||
/// whatever its options: a member's own shadow, a member's fill's shadow and a nested group's own
|
||||
/// shadow, drawn (the group's art) and baked.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_its_members_shadows() {
|
||||
let cases = [
|
||||
(json!({"scaleH": 200, "scaleV": 200}), (20.0, 20.0)),
|
||||
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
|
||||
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
|
||||
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
|
||||
];
|
||||
for (params, want) in cases {
|
||||
let members = vec![
|
||||
square(21, vec![shadow(10.0, 10.0, 0.0)]),
|
||||
fill_square(22, vec![shadow(10.0, 10.0, 0.0)]),
|
||||
group(23, vec![square(24, vec![])], vec![shadow(10.0, 10.0, 0.0)]),
|
||||
];
|
||||
let g = group(20, members, vec![transform(params.clone())]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[want; 3]), "{params}: drawn {:?}", shadows_in(&art));
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, g).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
for id in [21, 22, 23] {
|
||||
let b = baked.node(NodeId(id)).unwrap();
|
||||
assert!(near(&shadows_in(b), &[want]), "{params}: {id} baked {:?}", shadows_in(b));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect that makes copies or moves at random leaves its members' shadows as
|
||||
/// they are, as it leaves the shadows listed before it in its own effects.
|
||||
#[test]
|
||||
fn a_groups_copying_transform_leaves_its_members_shadows() {
|
||||
for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] {
|
||||
let g = group(25, vec![square(26, vec![shadow(10.0, 10.0, 0.0)]), square(27, vec![])], vec![transform(params.clone())]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 10.0); drawn.len()]), "{params}: {drawn:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Transform effects inside a group apply before the group's: a member's own turn of 90°
|
||||
/// applies to its shadow before the group's uneven scale does, for the member's own shadow, its
|
||||
/// fill's shadow, and the shadow of a member of a nested group that has the turn.
|
||||
#[test]
|
||||
fn a_groups_transform_applies_after_its_members_own() {
|
||||
let turn = || transform(json!({"rotate": 90}));
|
||||
let uneven = || transform(json!({"scaleH": 200, "scaleV": 100}));
|
||||
// Turned first, (10, 0) goes to (0, -10), which the scale leaves; scaled first, it would be (0, -20).
|
||||
let want = (0.0, -10.0);
|
||||
let own = group(30, vec![square(31, vec![shadow(10.0, 0.0, 0.0), turn()])], vec![uneven()]);
|
||||
let art = crate::evaluate_container(None, &own).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[want]), "own: {:?}", shadows_in(&art));
|
||||
let mut on_fill = fill_square(33, vec![shadow(10.0, 0.0, 0.0)]);
|
||||
on_fill.appearance.effects = vec![turn()];
|
||||
let art = crate::evaluate_container(None, &group(32, vec![on_fill], vec![uneven()])).unwrap();
|
||||
assert!(near(&[fill_shadow(&node_in(&art, 33))], &[want]), "fill: {:?}", fill_shadow(&node_in(&art, 33)));
|
||||
let nested = group(34, vec![group(35, vec![square(36, vec![shadow(10.0, 0.0, 0.0)])], vec![turn()])], vec![uneven()]);
|
||||
let art = crate::evaluate_container(None, &nested).unwrap();
|
||||
let inner = crate::evaluate_container(None, &node_in(&art, 35)).unwrap();
|
||||
assert!(near(&shadows_in(&inner), &[want]), "nested: {:?}", shadows_in(&inner));
|
||||
}
|
||||
|
||||
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
|
||||
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that
|
||||
/// makes copies leaves them.
|
||||
#[test]
|
||||
fn an_objects_transform_moves_its_fills_shadows() {
|
||||
let cases = [
|
||||
(json!({"scaleH": 200, "scaleV": 100}), (20.0, 10.0)),
|
||||
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
|
||||
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
|
||||
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)),
|
||||
];
|
||||
for (params, want) in cases {
|
||||
let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]);
|
||||
n.appearance.effects = vec![transform(params.clone())];
|
||||
if crate::has_transform_art(&n) {
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: drawn {drawn:?}");
|
||||
} else {
|
||||
assert!(near(&[fill_shadow(&n)], &[want]), "{params}: drawn {:?}", fill_shadow(&n));
|
||||
}
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let drawn = shadows_in(baked.node(NodeId(40)).unwrap());
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: baked {drawn:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A 10 pt image at the origin with `effects`.
|
||||
fn image(id: u64, effects: Vec<Effect>) -> Node {
|
||||
let mut n = Node::new(
|
||||
NodeId(id),
|
||||
vectorcraft_doc::NodeKind::Image(Box::new(vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
})),
|
||||
);
|
||||
n.appearance.effects = effects;
|
||||
n
|
||||
}
|
||||
|
||||
/// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster
|
||||
/// effects that a member's own Transform effect with copies holds back: they keep their value
|
||||
/// through the member's effect and transform with the group's. That holds for a shadow listed
|
||||
/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow
|
||||
/// of a member of a nested group with such an effect, and an image's shadow.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() {
|
||||
let copies = || transform(json!({"moveH": 60, "copies": 1}));
|
||||
// Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5).
|
||||
let want = (5.0, -5.0);
|
||||
for strokes in [false, true] {
|
||||
let mut on_fill = fill_square(73, vec![shadow(10.0, 10.0, 0.0)]);
|
||||
on_fill.appearance.effects = vec![copies()];
|
||||
let members = vec![
|
||||
square(71, vec![shadow(10.0, 10.0, 0.0), copies()]),
|
||||
square(72, vec![copies(), shadow(10.0, 10.0, 0.0)]),
|
||||
on_fill,
|
||||
group(74, vec![square(75, vec![shadow(10.0, 10.0, 0.0)])], vec![copies()]),
|
||||
image(76, vec![shadow(10.0, 10.0, 0.0)]),
|
||||
];
|
||||
let g = group(70, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
for id in [71, 72, 73, 75, 76] {
|
||||
let drawn = shadows_in(&node_in(&art, id));
|
||||
assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect transforms the raster effects in the art of a member's linked opacity
|
||||
/// mask with the member, a path's or an image's, with Scale Strokes & Effects off or on.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_the_shadow_in_a_members_mask() {
|
||||
let masked = |mut n: Node, id: u64| {
|
||||
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(square(id, vec![shadow(10.0, 10.0, 0.0)]), true)));
|
||||
n
|
||||
};
|
||||
for strokes in [false, true] {
|
||||
let params = json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes});
|
||||
let g = group(80, vec![masked(square(81, vec![]), 82), masked(image(83, vec![]), 84)], vec![transform(params)]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
for id in [81, 83] {
|
||||
let member = node_in(&art, id);
|
||||
let mask = member.extras().mask.as_deref().unwrap();
|
||||
assert!(near(&shadows_in(&mask.art), &[(5.0, -5.0)]), "Scale Strokes & Effects {strokes}: {id} {:?}", shadows_in(&mask.art));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect transforms the shadows of its members' fills that carry a Transform
|
||||
/// effect of their own with Scale Strokes & Effects on, with the group's Scale Strokes & Effects off
|
||||
/// or on: a shadow listed after the fill's Transform effect keeps its value through that effect and
|
||||
/// transforms with the group's, and one listed before it follows the fill's Transform effect and
|
||||
/// then the group's. Drawn through each member's art.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform() {
|
||||
let scaled = || transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
|
||||
// Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5); doubled first by
|
||||
// the fill's own Transform effect, it goes to (10, -10).
|
||||
let cases = [(91, vec![scaled(), shadow(10.0, 10.0, 0.0)], (5.0, -5.0)), (92, vec![shadow(10.0, 10.0, 0.0), scaled()], (10.0, -10.0))];
|
||||
for strokes in [false, true] {
|
||||
let members = cases.iter().map(|(id, effects, _)| fill_square(*id, effects.clone())).collect();
|
||||
let g = group(90, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
for (id, _, want) in &cases {
|
||||
let member = node_in(&art, *id);
|
||||
let drawn = shadows_in(&crate::reshape(None, &member, None).unwrap());
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![*want; drawn.len()]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -222,7 +222,7 @@ fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects() {
|
||||
fn a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects() {
|
||||
let mut n = stroke_with_effect(json!({}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.effects.push(transform(json!({"scaleH": 300, "scaleV": 300, "strokes": true})));
|
||||
@@ -231,10 +231,10 @@ fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let fill = leaves(&art).into_iter().find(|p| p.appearance.stroke().is_none()).unwrap();
|
||||
let AppearanceItem::Fill(f) = &fill.appearance.items[0] else { panic!("not a fill") };
|
||||
// The Offset Path, scaled from 5 to 15, applies to the transformed fill's path.
|
||||
// The Offset Path applies to the transformed fill's path at its own 5 pt.
|
||||
assert!(f.effects.is_empty(), "{:?}", f.effects);
|
||||
let w = fill.geometric_bounds().unwrap().width();
|
||||
assert!(close(w, 330.0), "{w}");
|
||||
assert!(close(w, 310.0), "{w}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -6,20 +6,38 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_geom::{Point, Rect, Shape};
|
||||
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
|
||||
|
||||
/// The largest distance between the edges of `a` and `b`.
|
||||
fn off(a: Rect, b: Rect) -> f64 {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
|
||||
}
|
||||
|
||||
/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or
|
||||
/// system fonts.
|
||||
fn type_in_test_face() -> TextObject {
|
||||
assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads");
|
||||
TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() })
|
||||
}
|
||||
|
||||
/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph.
|
||||
fn outline_box(t: &TextObject) -> Rect {
|
||||
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let outlines: Vec<Rect> = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect();
|
||||
assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline");
|
||||
outlines.into_iter().reduce(|a, b| a.union(b)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() {
|
||||
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
|
||||
let t = type_in_test_face();
|
||||
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
|
||||
let laid = n.geometric_bounds().unwrap();
|
||||
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
|
||||
let ink = outline_box(&t);
|
||||
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
|
||||
let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap();
|
||||
assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {ink:?}");
|
||||
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
|
||||
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ pub mod actionset;
|
||||
mod addons;
|
||||
mod apiref;
|
||||
pub(crate) mod appearance;
|
||||
pub mod arrowheads;
|
||||
mod artboardalign;
|
||||
mod assets;
|
||||
mod attributes;
|
||||
pub mod brushlib;
|
||||
@@ -80,7 +82,7 @@ pub mod rasterfx;
|
||||
mod recolor;
|
||||
pub mod recovery;
|
||||
pub mod scripts;
|
||||
mod select;
|
||||
pub(crate) mod select;
|
||||
pub(crate) mod shaper;
|
||||
pub mod shortcutset;
|
||||
pub(crate) mod slices;
|
||||
@@ -105,6 +107,7 @@ mod variablecmds;
|
||||
pub(crate) mod views;
|
||||
pub mod wand;
|
||||
pub mod webexport;
|
||||
mod wireframe;
|
||||
mod xform;
|
||||
|
||||
use serde::Serialize;
|
||||
@@ -297,6 +300,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
// Split out of `paint` (M3.8); kept next to it so lists in registry order (the command
|
||||
// palette, `engine.commands`) show them where they always were.
|
||||
v.extend(stroke::specs());
|
||||
v.extend(arrowheads::specs());
|
||||
v.extend(appearance::specs());
|
||||
v.extend(style::specs());
|
||||
v.extend(swatch::specs());
|
||||
@@ -308,6 +312,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(draw2::specs());
|
||||
v.extend(xform::specs());
|
||||
v.extend(effectcmd::specs());
|
||||
v.extend(wireframe::specs());
|
||||
v.extend(pathops::specs());
|
||||
v.extend(compoundshape::specs());
|
||||
v.extend(typecmd::specs());
|
||||
@@ -334,6 +339,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(variablecmds::specs());
|
||||
v.extend(docinfo::specs());
|
||||
v.extend(panelcmds::specs());
|
||||
v.extend(artboardalign::specs());
|
||||
v.extend(buildcmds::specs());
|
||||
v.extend(shaper::specs());
|
||||
v.extend(brushsym::specs());
|
||||
@@ -420,8 +426,13 @@ pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 {
|
||||
p.get(key).and_then(Value::as_f64).unwrap_or(default)
|
||||
}
|
||||
/// The number `p` gives for `key`. A missing key or null is "missing number `{key}`"; any other
|
||||
/// value, such as `"40"`, is "`{key}` must be a number, not {v}", as [`number_or`] words it.
|
||||
pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
|
||||
p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`")))
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Err(bad(cmd, format!("missing number `{key}`"))),
|
||||
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
}
|
||||
}
|
||||
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other
|
||||
/// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}".
|
||||
@@ -766,11 +777,12 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
|
||||
/// The most presets one presets file imports: each is looked up among the saved ones.
|
||||
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use addons::DecodedImages;
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub use plugin_call::{Location, key_location, location_in, location_keys};
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
|
||||
@@ -14,7 +14,7 @@ mod select;
|
||||
mod shapes;
|
||||
mod typetools;
|
||||
|
||||
pub(crate) use image::DecodedImages;
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
|
||||
use super::CommandSpec;
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, Para
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
|
||||
|
||||
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
|
||||
use crate::cmd::fonts::{art_texts_of, edit_art_texts_of};
|
||||
use crate::cmd::textedit::{editing_range, editing_story};
|
||||
use crate::cmd::typecmd::refresh_bounds;
|
||||
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Missing Fonts…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
|
||||
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in its opacity masks and in the art of its symbols and patterns included, hidden or locked type and disabled masks too) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
|
||||
has_doc,
|
||||
replace_fonts
|
||||
),
|
||||
@@ -982,8 +982,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
});
|
||||
}
|
||||
// The type in the symbols' art too, which exports name when its font is missing.
|
||||
if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) {
|
||||
// The type in opacity masks and in the art of symbols and patterns too, hidden or locked type
|
||||
// included, which exports name when its font is missing.
|
||||
if ids.is_empty() && !art_texts_of(d).into_iter().any(|(_, t, _)| lacks(t)) {
|
||||
return Err(EngineError::Other("No fonts are missing".into()));
|
||||
}
|
||||
let runs = s.edit("Replace Missing Fonts", |d, _| {
|
||||
@@ -1008,7 +1009,7 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
replace(t);
|
||||
}
|
||||
}
|
||||
edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace);
|
||||
edit_art_texts_of(d, &lacks, &mut replace);
|
||||
Ok(runs)
|
||||
})?;
|
||||
Ok(json!({ "runs": runs, "font": family }))
|
||||
|
||||
@@ -415,3 +415,53 @@ fn replace_missing_fonts_reaches_the_type_in_symbols() {
|
||||
s.execute("symbol.exitEditing", &json!({})).unwrap();
|
||||
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
|
||||
}
|
||||
|
||||
/// Replace Missing Fonts reaches the type in opacity masks (of a hidden object, disabled, in a
|
||||
/// symbol's art) and in a pattern swatch nothing paints with, and the export warning, the missing
|
||||
/// fonts list and Find Font name that type's font until it is replaced.
|
||||
#[test]
|
||||
fn replace_missing_fonts_reaches_the_type_in_masks_and_patterns() {
|
||||
let mut s = session();
|
||||
let mask = |s: &mut Session, owner: NodeId, art: NodeId| {
|
||||
s.edit("Mask", |d, _| {
|
||||
let art = d.remove(art)?;
|
||||
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
let lost = |s: &mut Session| text(s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"}));
|
||||
let rect =
|
||||
|s: &mut Session| NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let (hidden, disabled, in_symbol) = (rect(&mut s), rect(&mut s), rect(&mut s));
|
||||
for owner in [hidden, disabled, in_symbol] {
|
||||
let t = lost(&mut s);
|
||||
mask(&mut s, owner, t);
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [disabled.0]})).unwrap();
|
||||
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
|
||||
let t = lost(&mut s);
|
||||
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
|
||||
select(&mut s, &[t]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let mut on_layers = 0;
|
||||
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
|
||||
assert_eq!(on_layers, 0, "the type is only in masks, a symbol and a pattern");
|
||||
let missing = |s: &Session| crate::cmd::fontfiles::missing_fonts(&s.doc().unwrap().doc).into_iter().map(|f| f.family).collect::<Vec<_>>();
|
||||
assert_eq!(missing(&s), ["No Such Font Family"]);
|
||||
assert!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc).is_some_and(|w| w.contains("No Such Font Family")));
|
||||
let listed = s.execute("text.fonts", &json!({})).unwrap();
|
||||
assert_eq!((listed[0]["family"].as_str(), listed[0]["objects"].as_u64()), (Some("No Such Font Family"), Some(4)), "{listed}");
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap();
|
||||
assert_eq!(r["runs"].as_u64(), Some(4), "{r}");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
assert!(missing(&s).is_empty());
|
||||
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
|
||||
assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
}
|
||||
@@ -137,7 +137,7 @@ fn legend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let parent = st.target_parent()?;
|
||||
let text_size = (size / 7.0).clamp(4.0, 12.0);
|
||||
let pad = (size / 12.0).clamp(1.0, 8.0);
|
||||
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }));
|
||||
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?;
|
||||
let count = swatches.len();
|
||||
// Each chip's fill links to its swatch, as paint.setFill {swatch} links art: editing a global or
|
||||
// spot swatch then recolours the legend too.
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! Cutting Tools (`addon.cutting.*`), a built-in add-on that prepares art for cutting. Stencil
|
||||
//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together
|
||||
//! ([`stencil`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialog are the UI's.
|
||||
//! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art
|
||||
//! for vinyl cutting ([`weed`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are
|
||||
//! the UI's.
|
||||
|
||||
mod stencil;
|
||||
mod weed;
|
||||
|
||||
use super::super::CommandSpec;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
stencil::specs()
|
||||
let mut v = stencil::specs();
|
||||
v.extend(weed::specs());
|
||||
v
|
||||
}
|
||||
@@ -89,7 +89,12 @@ fn bridges(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
|
||||
let spec = BridgeSpec { width, count: count as usize, direction };
|
||||
let bridged = stencil_bridges(&refs, spec).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let bridged = stencil_bridges(&refs, spec).map_err(|e| match e {
|
||||
vectorcraft_pathops::PathOpsError::TooComplex => {
|
||||
EngineError::Other("Stencil Bridges: the selected art is too large or too detailed to bridge".into())
|
||||
}
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
(bridged, style_of(&top), roots)
|
||||
};
|
||||
let summary = |id: Option<NodeId>, original: Option<NodeId>| {
|
||||
|
||||
@@ -277,6 +277,34 @@ fn bad_params_are_refused() {
|
||||
assert!(s.execute("addon.cutting.bridges", &json!({"width": 4})).is_ok(), "good params run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_too_detailed_to_bridge_is_refused_with_a_message_that_says_so() {
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().target_parent().unwrap();
|
||||
let id = s
|
||||
.edit("dense", |d, sel| {
|
||||
// More anchors than Stencil Bridges measures.
|
||||
let mut zigzag = kurbo::BezPath::new();
|
||||
zigzag.move_to((100.0, 100.0));
|
||||
for i in 1..=vectorcraft_pathops::addons::stencil::MAX_STENCIL_SEGMENTS {
|
||||
zigzag.line_to((100.0 + i as f64 * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 }));
|
||||
}
|
||||
zigzag.close_path();
|
||||
let huge = vectorcraft_geom::PathData::from_bezpath(&zigzag);
|
||||
let n = vectorcraft_doc::Node::path(d.alloc_id(), huge, vectorcraft_doc::Appearance::default());
|
||||
let id = n.id;
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let steps = undo_steps(&s);
|
||||
let e = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap_err().to_string();
|
||||
assert!(e.contains("Stencil Bridges: the selected art is too large or too detailed to bridge"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_objects_without_outlines_stay_where_they_are() {
|
||||
for keep in [true, false] {
|
||||
|
||||
Loaded 100 of 664 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user