diff --git a/AGENTS.md b/AGENTS.md index bac119a742..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets`, `cargo xtask test` or `cargo nextest run -p `. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`. ### Paths and conventions -- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. +- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it. - Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. diff --git a/Cargo.lock b/Cargo.lock index be4b734a08..65c0466fa9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,30 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "acadrust" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8923c99ea1f151cb7fc17ce2fc14f8b1e330fa22611e535602d985c0cc3c89a2" +dependencies = [ + "anyhow", + "bitflags 2.13.2", + "byteorder", + "encoding_rs", + "flate2", + "foldhash 0.2.0", + "indexmap", + "itoa", + "memmap2", + "nom 7.1.3", + "oem_cp", + "once_cell", + "rayon", + "ryu", + "thiserror 2.0.21", + "web-time", +] + [[package]] name = "accesskit" version = "0.25.2" @@ -1231,13 +1255,14 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-automation", "craft-behavior", "craft-browse", "craft-cms", "craft-color-ui", + "craft-control", "craft-dialogs", "craft-draw", "craft-font-catalog", @@ -1272,7 +1297,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "crc32fast", "flate2", @@ -1280,10 +1305,20 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1330,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1338,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1363,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1399,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1408,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "egui", ] @@ -1381,7 +1416,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "md-5", "rayon", @@ -1390,12 +1425,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,10 +1450,15 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ + "craft-ai-agents", + "craft-atomic", "craft-control-protocol", + "craft-flags", "craft-platform", + "dirs", + "log", "serde", "serde_json", ] @@ -1426,7 +1466,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1476,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "rayon", ] @@ -1444,7 +1484,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1510,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1526,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "serde", ] @@ -1494,7 +1534,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1510,10 +1550,19 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-dwg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" +dependencies = [ + "acadrust", + "log", +] + [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "serde", "serde_json", @@ -1535,12 +1584,22 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" + +[[package]] +name = "craft-flags" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" +dependencies = [ + "craft-atomic", + "dirs", + "toml_edit", +] [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1614,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1633,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1642,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1665,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "gif", ] @@ -1619,7 +1678,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "flate2", ] @@ -1627,7 +1686,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1699,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1729,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1756,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1774,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1782,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1808,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1822,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1840,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1852,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1863,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1873,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1882,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1898,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1848,7 +1907,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "flate2", "serde", @@ -1859,7 +1918,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1871,7 +1930,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "async-channel", "async-io", @@ -1904,7 +1963,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1913,7 +1972,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -1937,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1948,7 +2007,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-eps", "flate2", @@ -1962,7 +2021,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "encoding_rs", "flate2", @@ -1973,7 +2032,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "dispatch2", "egui", @@ -1983,10 +2042,19 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-raster3d" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2005,7 +2073,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-atomic", "craft-host", @@ -2022,7 +2090,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "fax", "hayro-ccitt", @@ -2033,7 +2101,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2054,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-keymap", @@ -2066,7 +2134,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2091,7 +2159,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "thiserror 2.0.21", ] @@ -2099,7 +2167,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2114,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-atomic", "craft-behavior", @@ -2129,7 +2197,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "serde", "thiserror 2.0.21", @@ -2139,7 +2207,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "serde", "thiserror 2.0.21", @@ -2148,7 +2216,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-keymap", @@ -2163,12 +2231,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2182,7 +2250,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2199,7 +2267,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "accesskit", "craft-behavior", @@ -2237,7 +2305,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2248,7 +2316,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -2266,7 +2334,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -2287,7 +2355,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -2308,7 +2376,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-behavior", "craft-host", @@ -2327,7 +2395,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "base64 0.22.1", "chrono", @@ -2359,7 +2427,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "flate2", "serde", @@ -2370,7 +2438,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2380,7 +2448,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "js-sys", "serde_json", @@ -2391,7 +2459,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "winsafe", ] @@ -2399,7 +2467,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "craft-appkit", "craft-atomic", @@ -2431,7 +2499,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3791,7 +3859,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3800,7 +3868,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3818,7 +3886,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3836,12 +3904,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "flate2", "hayro-ccitt", @@ -4824,7 +4892,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4981,7 +5049,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -5865,6 +5933,15 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oem_cp" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7959d3349f484aec36462f98226983578bf7d33f9b034c32967489c7000e1f" +dependencies = [ + "phf 0.11.3", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -6037,6 +6114,15 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared 0.11.3", +] + [[package]] name = "phf" version = "0.13.1" @@ -6104,6 +6190,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.13.1" @@ -7520,8 +7615,7 @@ dependencies = [ [[package]] name = "skrifa" version = "0.44.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97" dependencies = [ "bytemuck", "read-fonts 0.41.0", @@ -8619,6 +8713,7 @@ dependencies = [ name = "vectorcraft-cad" version = "0.25.1" dependencies = [ + "craft-dwg", "craft-dxf", "craft-image-codecs", "craft-plotter", @@ -8632,12 +8727,15 @@ dependencies = [ "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", "vectorcraft-text", + "web-time", ] [[package]] name = "vectorcraft-cli" version = "0.25.1" dependencies = [ + "craft", + "craft-dwg", "log", "objc2-core-foundation", "objc2-core-text", @@ -8700,6 +8798,7 @@ name = "vectorcraft-effects" version = "0.25.1" dependencies = [ "craft-image-codecs", + "craft-raster3d", "craft-svg", "image", "kurbo 0.13.1", @@ -8727,6 +8826,7 @@ dependencies = [ "craft-codepage", "craft-doc", "craft-docpath", + "craft-dwg", "craft-font-catalog", "craft-font-store", "craft-image-codecs", @@ -9005,6 +9105,7 @@ dependencies = [ name = "vectorcraft-render" version = "0.25.1" dependencies = [ + "bytemuck", "craft-gif", "craft-image-codecs", "craft-psd", @@ -9173,6 +9274,7 @@ dependencies = [ "bytemuck", "chrono", "craft", + "craft-dwg", "craft-image-codecs", "egui", "egui_extras", diff --git a/Cargo.toml b/Cargo.toml index 7dab0c8895..03de727454 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,53 +10,57 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. -craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps. +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -196,13 +200,15 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } +# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa). +skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } diff --git a/NOTICE b/NOTICE index 4d7c813796..4790c330bc 100644 --- a/NOTICE +++ b/NOTICE @@ -35,6 +35,12 @@ based in part on the work of the Independent JPEG Group. WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is under the Apache License 2.0 with the LLVM exception. +DWG drawings are read by the acadrust crate 0.6.6 (https://crates.io/crates/acadrust/0.6.6), through +craft-dwg from https://github.com/storytold/craft-libs. acadrust is used unmodified under the Mozilla +Public License 2.0; its source is available at that address. Its license text and its third-party +notices (code adapted from ACadSharp, Copyright (c) 2021 Albert Domenech, MIT License) are in +licenses/acadrust-0.6.6/. + The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part diff --git a/README.md b/README.md index 3280824dc8..df83d9e9dd 100644 --- a/README.md +++ b/README.md @@ -316,6 +316,8 @@ RISC-V (riscv64) packages are `vectorcraft--linux-riscv64.deb`, ### FreeBSD +Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds. + | Build | File | |---|---| | x86_64 | `vectorcraft--freebsd-x86_64.tar.gz` | diff --git a/ROADMAP.md b/ROADMAP.md index 8b29a40471..616e6eea9d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,7 +124,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log -- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged. +- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged. - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. @@ -271,6 +271,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-26 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; the link watcher scans them in the background, so turning it on never waits on a file; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Scores and estimates unchanged. | | 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. | | 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. | | 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). | diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 25cffe599e..fc781c31c0 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -25,6 +25,8 @@ vectorcraft-render = { workspace = true } vectorcraft-text = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# The agent settings and the desktop app to start for plain `mcp` (the shared `src/agent_settings.rs`). +craft = { workspace = true, features = ["automation-agents"] } # `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this # process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT), @@ -47,11 +49,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" [dev-dependencies] tempfile = "3" vectorcraft-testkit = { workspace = true } +# DWG files for the `info` test, written from DXF by craft-dwg. +craft-dwg = { workspace = true } serde_json = { workspace = true } # The files of other crates that this crate compiles or its tests read, for CI's test selection. [package.metadata.craft] reads = [ + "apps/vectorcraft/src/agent_settings.rs", "apps/vectorcraft/src/mac_fonts.rs", "apps/vectorcraft/src/prefs_dir.rs", "apps/vectorcraft/src/profile.rs", diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 51d2aec7b6..8855d3f9e3 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -2,7 +2,7 @@ //! //! ```text //! vectorcraft-cli --safe-mode SUBCOMMAND ... -//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... +//! vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... //! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] //! vectorcraft-cli commands //! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] @@ -39,6 +39,10 @@ macro_rules! out { }}; } +/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the +/// closed-app choice and the agent folders the app saved. +#[path = "../../vectorcraft/src/agent_settings.rs"] +mod agent_settings; /// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts. #[cfg(target_os = "macos")] #[path = "../../vectorcraft/src/mac_fonts.rs"] @@ -56,9 +60,11 @@ mod system_fonts; #[path = "../../vectorcraft/src/windows_cores.rs"] mod windows_cores; +use craft::automation::agents::WhenAppClosed; use serde_json::{Value, json}; use vectorcraft_engine::file_access::{self, AutomationRoots}; -use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server}; +use vectorcraft_mcp::agents::{LiveBackend, LiveConfig}; +use vectorcraft_mcp::{Backend, Headless, Remote, Server}; /// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly, as /// ripgrep does; any other write error is reported. @@ -79,9 +85,18 @@ USAGE: Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and does not take --connect. - vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants] - Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979 - (vectorcraft --control 7979), falling back to a headless in-process session. + vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants] + Run the MCP server on stdio. Every tool call goes to the open VectorCraft window while AI + agents may use it (ArtCraft Launcher › Settings › AI agents), found through the connection + file the window publishes in the settings folder: no port or token to configure, and an app + opened after the session started is found too. Otherwise the call runs in a session without + a window. While agents may use VectorCraft but it is closed, the choice in Preferences › AI + Integrations applies (open VectorCraft, a session without a window in the agent folders, or + an error); --when-closed overrides it. Files of the open window's agent requests stay in the + agent folders set there (Documents/ArtCraft/Agents/VectorCraft when none is set); the + agent_folders tool names them. --headless always runs without a window. + --connect ADDR (deprecated, removed in a later release) drives an app started with + vectorcraft --control PORT and its VECTORCRAFT_CONTROL_TOKEN. --automation-read-root / --automation-write-root confine the files the agent's commands read (open, place, relink, library loads…) and write (save, export, package, library saves…) to DIR, links followed; each may be given more than once, a path inside any of its folders being @@ -209,6 +224,12 @@ fn help() -> Result<(), String> { } fn main() -> ExitCode { + // A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits. + if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() { + std::process::exit(code); + } + // DWG drawings open through that copy, so a damaged file can't end this process. + vectorcraft_engine::dwg::use_own_worker(); // Before the first render: the cores the process may run on. #[cfg(windows)] windows_cores::install(); @@ -280,6 +301,20 @@ fn with_stores(mut h: Headless) -> Headless { h } +/// Plain `mcp`'s window lookup: the agent settings in `dir`, the closed-app choice (`--when-closed` +/// overrides the saved one), the desktop app beside this CLI to start, and headless sessions with +/// the user's stores, or confined to the agent folders without them. +fn live_config(dir: std::path::PathBuf, when_closed: Option) -> LiveConfig { + let mut cfg = LiveConfig::new(dir, agent_settings::read_settings); + cfg.when_closed = when_closed; + cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, vectorcraft_mcp::agents::APP_EXE)); + cfg.headless = Box::new(|roots| match roots { + Some(roots) => Headless::with_document().with_automation_roots(Some(roots)), + None => with_stores(Headless::with_document()), + }); + cfg +} + /// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`). fn accepting_grants(mut h: Headless, allow: bool) -> Headless { if allow { @@ -288,26 +323,34 @@ fn accepting_grants(mut h: Headless, allow: bool) -> Headless { h } -/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own -/// plug-ins, so `--connect` is refused and the default does not connect. +/// The stderr line `mcp --connect` prints: the flag works for one more release. +const CONNECT_DEPRECATED: &str = "vectorcraft-cli: --connect is deprecated and will be removed in a later release; plain `vectorcraft-cli mcp` finds the open VectorCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents"; + +/// `mcp`: the open VectorCraft window while the person lets agents use it (the ArtCraft Launcher's +/// switch), found through its connection file on every tool call, otherwise a headless session +/// (`vectorcraft_mcp::agents`). `--headless`, the automation roots, `--allow-plugin-grants` and +/// `--safe-mode` (`safe_mode`: a running app loads its own plug-ins) always run headless. +/// `--connect ADDR` drives an app started with `vectorcraft --control PORT` (deprecated). fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { - if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) { + if help_requested(args, &["--connect", "--when-closed", "--automation-read-root", "--automation-write-root"]) { return help(); } let mut connect: Option = None; let mut headless = false; + let mut when_closed: Option = None; let mut allow_grants = false; let (mut read_roots, mut write_roots): (Vec, Vec) = (vec![], vec![]); let mut it = args.iter(); while let Some(a) = it.next() { // The roots also come as `--flag=DIR`, as the other Craft apps take them. let (flag, inline) = match a.split_once('=') { - Some((f, v)) if f.starts_with("--automation-") => (f, Some(v.to_string())), + Some((f, v)) if f.starts_with("--automation-") || f == "--when-closed" => (f, Some(v.to_string())), _ => (a.as_str(), None), }; match flag { "--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?), "--headless" => headless = true, + "--when-closed" => when_closed = Some(inline.or_else(|| it.next().cloned()).ok_or("--when-closed needs launch, headless or error")?), "--allow-plugin-grants" => allow_grants = true, "--automation-read-root" | "--automation-write-root" => { let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?; @@ -328,6 +371,16 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { if safe_mode && connect.is_some() { return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control `".into()); } + let when_closed = match when_closed.as_deref() { + None => None, + Some(choice) => { + let parsed = WhenAppClosed::parse(choice).ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?; + if connect.is_some() || headless || safe_mode || allow_grants || !(read_roots.is_empty() && write_roots.is_empty()) { + return Err("--when-closed is for the open window of plain `mcp`; --connect, --headless, --safe-mode, --allow-plugin-grants and the automation roots never use it".into()); + } + Some(parsed) + } + }; let read: Vec<&Path> = read_roots.iter().map(Path::new).collect(); let write: Vec<&Path> = write_roots.iter().map(Path::new).collect(); let roots = AutomationRoots::new(&read, &write)?; @@ -343,13 +396,18 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { } else if headless || safe_mode || allow_grants { Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants)) } else if let Some(addr) = connect { + eprintln!("{CONNECT_DEPRECATED}"); // Explicit address: fail loudly if the app isn't there. let token = vectorcraft_mcp::control_token()?; Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?) } else { - // No token or no app listening: the headless session answers instead. - match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) { - Some(r) => Box::new(r), + match prefs_dir::prefs_dir() { + Some(dir) => Box::new(LiveBackend::new(live_config(dir, when_closed))), + // No settings folder (no home folder): no window can be found either, so `--when-closed error` + // refuses rather than answering from a session the agent didn't ask for. + None if when_closed == Some(WhenAppClosed::Error) => { + return Err("VectorCraft's settings folder can't be found (no home folder), so its window can't be either: open VectorCraft, or run `mcp` without `--when-closed error`".into()); + } None => Box::new(with_stores(Headless::with_document())), } }; @@ -616,6 +674,8 @@ fn thumbnail(args: &[String]) -> Result<(), String> { } } let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?; + // A DWG worker ends by then too, so the exit below leaves no conversion running. + vectorcraft_engine::dwg::use_own_worker_for(THUMBNAIL_TIME); // The process ends when the time is up, wherever the work is: OUT is written whole or not at all. std::thread::spawn(|| { std::thread::sleep(THUMBNAIL_TIME); diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index 0b1c560901..dc96dd69b8 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -836,3 +836,20 @@ fn runs_without_preferences_remember_nothing() { let r = run_in(&config, &[("pdf.preset.list", json!({}))]); assert!(r[0]["presets"].as_array().unwrap().iter().all(|p| p["builtIn"] == true)); } + +/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one +/// release but says it is deprecated before it connects. +#[test] +fn mcp_when_closed_and_the_deprecated_connect() { + let fails = |args: &[&str], why: &str| { + let out = Command::new(crate::bin()).args(args).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success() && err.contains(why), "{args:?}: {err}"); + err.into_owned() + }; + fails(&["mcp", "--when-closed", "later"], "--when-closed must be launch, headless or error"); + fails(&["mcp", "--when-closed", "launch", "--headless"], "--when-closed is for the open window"); + fails(&["mcp", "--when-closed=error", "--connect", "127.0.0.1:1"], "--when-closed is for the open window"); + let err = fails(&["mcp", "--connect", "127.0.0.1:1"], "--connect is deprecated"); + assert!(err.contains("cannot connect") || err.contains("no control token"), "{err}"); +} diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 9593d2630e..fee790b65b 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -378,3 +378,70 @@ fn convert_and_run_write_ait_templates() { assert!(!one.status.success()); assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr)); } + +/// A DWG drawing opens through a worker copy of the program, so a damaged one ends in an error from +/// `info`, never in a crash. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on +/// aarch64. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() { + let dxf = tmp("plan.dxf"); + make(&dxf, 120, 80); + craft_dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&std::fs::read(&dxf).unwrap(), "AC1018").unwrap(); + let good = tmp("plan.dwg"); + std::fs::write(&good, &dwg).unwrap(); + // The DWG comes in as the DXF it was written from. + let (v, from) = (info(&good), info(&dxf)); + assert!(v["kinds"]["Path"].as_u64().is_some_and(|n| n > 0), "{v}"); + assert_eq!((&v["kinds"], &v["artboards"][0]["rect"]), (&from["kinds"], &from["artboards"][0]["rect"]), "{v}\n{from}"); + + let n = dwg.len(); + let mut damaged = vec![dwg[..n / 3].to_vec(), dwg[..2 * n / 3].to_vec(), dwg[..16].to_vec()]; + let mut overwritten = dwg.clone(); + overwritten[n / 2..(n / 2 + 64).min(n)].fill(0xFF); + damaged.push(overwritten); + let mut flipped = dwg.clone(); + flipped.iter_mut().skip(32).step_by(97).for_each(|b| *b ^= 0xA5); + damaged.push(flipped); + for (i, bytes) in damaged.iter().enumerate() { + let path = tmp(&format!("damaged-{i}.dwg")); + std::fs::write(&path, bytes).unwrap(); + let out = Command::new(crate::bin()).args(["info", &path]).output().unwrap(); + // A process ended by a signal has no exit code. + assert!(out.status.code().is_some(), "damaged file {i}: {:?}", out.status); + // The file cut to a third and the one cut to its header can't be read; the reader may + // recover the others. + if i == 0 || i == 2 { + assert!(!out.status.success(), "damaged file {i} is refused: {}", String::from_utf8_lossy(&out.stdout)); + } + if !out.status.success() { + assert!(String::from_utf8_lossy(&out.stderr).contains("DWG"), "damaged file {i}: {}", String::from_utf8_lossy(&out.stderr)); + } + } +} + +/// A DWG worker started with a deadline (as `thumbnail` starts one) exits with code 1 once the +/// deadline passes, even while it still waits for its drawing, and at once when it has already +/// passed, so `thumbnail`'s exit leaves no conversion running. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() { + let now = std::time::SystemTime::now(); + for until in [now + std::time::Duration::from_secs(1), now - std::time::Duration::from_secs(1)] { + let millis = until.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis().to_string(); + let mut worker = Command::new(crate::bin()) + .args(["--dwg-worker", "--dwg-worker-until", &millis]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + // Its input stays open, so the worker never gets the whole request. + let input = worker.stdin.take(); + let out = worker.wait_with_output().unwrap(); + drop(input); + assert_eq!(out.status.code(), Some(1), "{:?}", out.status); + // It stops without answering, so no partial drawing reaches the caller. + assert!(out.stdout.is_empty(), "{} bytes written", out.stdout.len()); + } +} diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 70aae32f73..0d227adb15 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 64a596e5ba..519056ba0c 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option AgentSettings { + let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() }; + let mut text = String::new(); + if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE { + return AgentSettings::default(); + } + let Ok(Value::Object(saved)) = serde_json::from_str::(&text) else { return AgentSettings::default() }; + let mut settings = AgentSettings::default(); + for (key, value) in saved { + let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue }; + if one.contains_key(&key) { + one.insert(key, value); + if let Ok(next) = serde_json::from_value(Value::Object(one)) { + settings = next; + } + } + } + settings +} + +/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a +/// `vectorcraft-cli mcp` reading it at the same time sees the old or the new settings, never half. +// The desktop writes the settings; `vectorcraft-cli` includes this file and only reads them. +#[allow(dead_code)] +pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?; + let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id())); + std::fs::write(&partial, text)?; + std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| { + let _ = std::fs::remove_file(&partial); + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use craft::automation::agents::WhenAppClosed; + + // Settings saved by the app read back in the CLI, and a damaged file or value never fails it. + #[test] + fn saved_settings_read_back_and_bad_values_reset_alone() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(read_settings(dir.path()), AgentSettings::default()); + let mut settings = AgentSettings::default(); + settings.read_root = "/in".into(); + settings.when_app_closed = WhenAppClosed::Headless; + write_settings(dir.path(), &settings).unwrap(); + assert_eq!(read_settings(dir.path()), settings); + std::fs::write(dir.path().join(SETTINGS_FILE), "not json").unwrap(); + assert_eq!(read_settings(dir.path()), AgentSettings::default()); + std::fs::write(dir.path().join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap(); + let read = read_settings(dir.path()); + assert_eq!(read.when_app_closed, WhenAppClosed::Error); + assert_eq!(read.read_root, ""); + } +} diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 4b1c77e0f1..d772397ce3 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -27,6 +27,7 @@ //! how the window's frames reach the display (`presentation`). #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] +mod agent_settings; mod automation_args; #[cfg(test)] mod build_channel; @@ -516,6 +517,30 @@ fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec, launched: Option<&Listening>) -> Option { + use craft::automation::agents::{AgentSwitch, remove_stale_connection}; + use vectorcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn}; + let dir = prefs_dir::prefs_dir()?; + remove_stale_connection(&dir); + let switch = AgentSwitch::watch(LAUNCHER_APP_ID, { + let ctx = ctx.clone(); + move || ctx.request_repaint() + }); + let save_dir = dir.clone(); + let save: SaveFn = Box::new(move |settings| { + agent_settings::write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display())) + }); + let version = format!("VectorCraft {}", env!("VECTORCRAFT_BUILT_VERSION")); + let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save); + // The port it listens on (the one the system picked for `--control 0`), none when it couldn't. + Some(if control_port.is_some() { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents }) +} + /// The control channel's port, and the token's notice with the token itself. type ControlChannel = (Option, Option<(String, String)>); @@ -573,10 +598,17 @@ fn finish_pending_update(nightly: bool) { } fn main() -> std::process::ExitCode { + // A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits, + // before the launch profile, the logger or any window. + if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() { + std::process::exit(code); + } // The launch profile first: a nightly build self-isolates or uses the Launcher's profile here, // before the update helper, the logger, fonts or any saved state, and `--version` is answered // here too. let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS }; + // DWG drawings open through that copy, so a damaged file can't end this process. + vectorcraft_engine::dwg::use_own_worker(); let nightly = launch_profile::current().is_nightly(); #[cfg(windows)] finish_pending_update(nightly); @@ -857,8 +889,6 @@ fn main() -> std::process::ExitCode { Some(pen) => spec.pen(pen), None => spec, }; - embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?; - egui_extras::install_image_loaders(ctx); let folders = settings.lock().get().ui.last_folders.clone(); let wake = { let ctx = ctx.clone(); @@ -875,7 +905,6 @@ fn main() -> std::process::ExitCode { .settings(Arc::new(settings.clone())) .files(files.clone()) .build(); - host.clone().install(ctx); let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); @@ -900,12 +929,16 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_proof_setups(&mut session); prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(winit_window.clone())); + load_prefs(&mut app, &settings); + let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, app.ui_language(), None); + embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?; + egui_extras::install_image_loaders(ctx); + host.clone().install(ctx); app.host = Arc::new(host); app.adopt_context(&cc.egui_ctx); // A nightly is updated by the Launcher: it never checks for a stable release, which // would install this program's own updater over the nightly build. app.set_startup_update_check(!nightly); - load_prefs(&mut app, &settings); safe_mode::after_start(&mut app, stopped); // Loads started later (a preference change, the end of Safe Mode) are waited for, // after the launch's own. @@ -1048,6 +1081,12 @@ fn main() -> std::process::ExitCode { } } } + if !nightly + && prefs_enabled() + && let Some(agents) = agents_link(&cc.egui_ctx, control_port, control_server.as_ref()) + { + app = app.with_agents(agents); + } #[cfg(target_os = "macos")] { open_documents::set_ui(&cc.egui_ctx); diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 651be6f6a3..ba5b6a3a18 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -180,7 +180,8 @@ mod system { let sockets = local_sockets(); // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, // so its sizes come from the server. - if scheduler_is_local(named.as_deref(), &sockets, real_path) { + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + if named_scheduler_is_local(named.as_deref(), port, |s| std::path::Path::new(s).exists(), &sockets, real_path) { const PPD_CAP: u64 = 16 << 20; let mut bytes = Vec::new(); let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); @@ -199,7 +200,6 @@ mod system { return papers; } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. - let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; @@ -286,10 +286,19 @@ mod system { } } /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or - /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` + /// `/etc/cups/client.conf`; `None` when none is named, where CUPS uses its domain socket when one exists and + /// `localhost` on `IPP_PORT` otherwise ([`named_scheduler_is_local`] resolves that case). macOS does not read `ServerName` /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. + /// A server named without a port gets the one `IPP_PORT` sets, so `localhost` with `IPP_PORT=8631` is a second + /// scheduler rather than the local one. #[cfg(not(windows))] fn cups_server() -> Option { + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + named_cups_server().map(|server| vectorcraft_ui_egui::print::server_with_ipp_port(&server, port)) + } + /// The scheduler `cups_server` names, as written. + #[cfg(not(windows))] + fn named_cups_server() -> Option { if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) { return Some(server.trim().to_string()); } @@ -304,8 +313,26 @@ mod system { client_conf_server_name(&text) }) } + /// Whether the scheduler CUPS uses runs on this machine, given the server `cups_server` names, the `IPP_PORT` + /// port, whether a path exists, the local scheduler's domain `sockets` and a socket path's real path. With no + /// server named, CUPS uses its domain socket when one exists, which is local, and otherwise `localhost` on the + /// `IPP_PORT` port, which is local only on port 631. + #[cfg(not(windows))] + pub(super) fn named_scheduler_is_local( + named: Option<&str>, + port: Option, + exists: impl Fn(&str) -> bool, + sockets: &[String], + resolve: impl Fn(&str) -> Option, + ) -> bool { + match named { + Some(server) => scheduler_is_local(Some(server), sockets, resolve), + None if CUPS_SOCKETS.iter().any(|s| exists(s)) => true, + None => scheduler_is_local(Some(&vectorcraft_ui_egui::print::server_with_ipp_port("localhost", port)), sockets, resolve), + } + } /// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain - /// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. + /// `sockets`, or `localhost`, `127.0.0.1` or `[::1]` with no port or port 631, each with an optional `/version=` suffix. /// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder /// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket. #[cfg(not(windows))] @@ -320,6 +347,10 @@ mod system { rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':'))) } else if server.matches(':').count() == 1 { server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port))) + } else if let Some((host, port)) = server.rsplit_once(':').filter(|(_, port)| port.starts_with(|c: char| c.is_ascii_digit())) { + // CUPS (`cupsSetServer`) reads the digits after the last `:` of an unbracketed name as its port, so `::1` is + // host `:` on port 1. + (host, Some(port)) } else { (server, None) }; @@ -646,7 +677,21 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local}; + use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, named_scheduler_is_local, scheduler_is_local}; + + #[test] + fn with_no_server_named_the_implicit_scheduler_decides_locality() { + let none = |_: &str| false; + let socket = |s: &str| s == "/run/cups/cups.sock"; + let real = |_: &str| None; + let own = cupsd_listen_sockets(""); + assert!(!named_scheduler_is_local(None, Some(8631), none, &own, real), "localhost:8631 is a second scheduler"); + assert!(named_scheduler_is_local(None, Some(631), none, &own, real)); + assert!(named_scheduler_is_local(None, None, none, &own, real)); + assert!(named_scheduler_is_local(None, Some(8631), socket, &own, real), "CUPS's socket is the local scheduler"); + assert!(!named_scheduler_is_local(Some("print.example.com"), None, socket, &own, real)); + assert!(named_scheduler_is_local(Some("localhost:631"), Some(8631), none, &own, real)); + } #[test] fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { @@ -700,7 +745,6 @@ mod client_conf_tests { Some("LocalHost:631"), Some("localhost:631"), Some("127.0.0.1:631"), - Some("::1"), Some("[::1]:631"), Some("[::1]"), Some("localhost/version=1.1"), @@ -714,6 +758,7 @@ mod client_conf_tests { "192.0.2.7", "[2001:db8::1]:631", "2001:db8::1", + "::1", "localhost.example.com", "print.example.com:631/version=1.1", "localhost:8631", @@ -727,6 +772,23 @@ mod client_conf_tests { } } + #[test] + fn a_loopback_server_on_another_ipp_port_is_not_local() { + use vectorcraft_ui_egui::print::server_with_ipp_port; + let own = cupsd_listen_sockets(""); + let real = |_: &str| None; + for named in ["localhost", "127.0.0.1", "[::1]", "localhost/version=1.1"] { + assert!(!scheduler_is_local(Some(&server_with_ipp_port(named, Some(8631))), &own, real), "{named}"); + assert!(scheduler_is_local(Some(&server_with_ipp_port(named, Some(631))), &own, real), "{named}"); + } + // CUPS reads an unbracketed `::1` as host `:` on port 1, so it is not the local scheduler on any `IPP_PORT`. + for port in [None, Some(631), Some(8631)] { + assert!(!scheduler_is_local(Some(&server_with_ipp_port("::1", port)), &own, real), "::1 with {port:?}"); + } + assert!(scheduler_is_local(Some(&server_with_ipp_port("localhost:631", Some(8631))), &own, real), "a port in the server name wins"); + assert!(scheduler_is_local(Some(&server_with_ipp_port("/run/cups/cups.sock", Some(8631))), &own, real)); + } + #[test] fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com")); diff --git a/assets/cursors/cursor-pen-convert.svg b/assets/cursors/cursor-pen-convert.svg index fa78f562ef..79e29af75d 100644 --- a/assets/cursors/cursor-pen-convert.svg +++ b/assets/cursors/cursor-pen-convert.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-curvature.svg b/assets/cursors/cursor-pen-curvature.svg index 94ba1708b5..b8d4bd3650 100644 --- a/assets/cursors/cursor-pen-curvature.svg +++ b/assets/cursors/cursor-pen-curvature.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-join.svg b/assets/cursors/cursor-pen-join.svg index 3dd7ce7f6e..05a020bb12 100644 --- a/assets/cursors/cursor-pen-join.svg +++ b/assets/cursors/cursor-pen-join.svg @@ -1 +1,6 @@ - + + + + + + diff --git a/assets/cursors/cursor-pen-new.svg b/assets/cursors/cursor-pen-new.svg index 6690b1ffd6..a27dc0ddae 100644 --- a/assets/cursors/cursor-pen-new.svg +++ b/assets/cursors/cursor-pen-new.svg @@ -1 +1,8 @@ - + + + + + + + + diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index e14c1439a7..1a69aeed48 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,6 +1,7 @@ //! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so //! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub use craft_affinity::*; diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index cff749e84f..e78cde4ecb 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -18,6 +18,7 @@ //! //! The crate knows no command and depends on no other VectorCraft crate. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use std::fmt; diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 85dfc8e084..fffdd4f797 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -9,6 +9,7 @@ //! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it //! returns (caching them per node) and `object.expandBrush` inserts them as real objects. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod calli; mod colorize; diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 1cbf8dc431..c09eb31879 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -3,13 +3,14 @@ name = "vectorcraft-cad" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer" +description = "VectorCraft CAD interchange: DXF export through craft-dxf, DXF and DWG import, and an HP-GL/2 plot file reader and writer" [lints] workspace = true [dependencies] craft-dxf = { workspace = true } +craft-dwg = { workspace = true } craft-plotter = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } @@ -21,6 +22,7 @@ vectorcraft-text = { workspace = true } kurbo = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } +web-time = "1" [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs new file mode 100644 index 0000000000..b6e4b545c4 --- /dev/null +++ b/crates/cad/src/dwg.rs @@ -0,0 +1,278 @@ +//! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result. +//! +//! The conversion runs in a child process once the program has called [`use_own_worker`] (and +//! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort +//! ends that process, not VectorCraft. Without a worker the conversion is refused, unless +//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there. + +use std::hash::BuildHasher; +use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak}; +use std::time::Duration; + +use web_time::Instant; + +pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; + +/// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch +/// ([`use_own_worker_for`]). +const WORKER_UNTIL_ARG: &str = "--dwg-worker-until"; + +/// Serve one conversion and return the exit code if this process was started as a worker. A +/// worker started by [`use_own_worker_for`] exits with code 1 once its time is up, wherever the +/// conversion is. +pub fn serve_if_asked() -> Option { + let mut args = std::env::args_os().skip(1); + if args.next()? != WORKER_ARG { + return None; + } + if args.next().is_some_and(|a| a == WORKER_UNTIL_ARG) + && let Some(millis) = args.next().and_then(|s| s.to_str()?.parse::().ok()) + && let Some(until) = std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_millis(millis)) + { + if until <= std::time::SystemTime::now() { + return Some(1); + } + std::thread::spawn(move || { + std::thread::sleep(until.duration_since(std::time::SystemTime::now()).unwrap_or_default()); + std::process::exit(1); + }); + } + craft_dwg::serve_if_asked() +} + +/// [`use_own_worker`], each worker exiting once `limit` from this call is up (a deadline passed to it +/// in milliseconds since the UNIX epoch), however late it starts, so a program that ends after +/// `limit` leaves no conversion running. If this program's path can't be found, or the deadline +/// can't be written, the worker setting does not change. Web builds have no worker. +pub fn use_own_worker_for(limit: std::time::Duration) { + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + if let Ok(program) = std::env::current_exe() + && let Some(until) = std::time::SystemTime::now().checked_add(limit).and_then(|until| until.duration_since(std::time::UNIX_EPOCH).ok()) + && let Ok(millis) = u64::try_from(until.as_millis()) + { + craft_dwg::worker::use_worker(program, vec![WORKER_ARG.into(), WORKER_UNTIL_ARG.into(), millis.to_string().into()]); + } + #[cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))] + let _ = limit; +} + +/// The largest DXF rendition kept for the next read of the same drawing (128 MiB). +const MAX_KEPT: usize = 128 << 20; + +/// Is `bytes` a DWG drawing (an `AC10nn` version code first)? +pub fn is_dwg(bytes: &[u8]) -> bool { + craft_dwg::is_dwg(bytes) +} + +/// A DWG drawing as DXF bytes, and what the conversion left out. +#[derive(Debug, PartialEq)] +pub(crate) struct Converted { + pub dxf: Vec, + pub notes: Vec, +} + +type Outcome = Result, String>; + +/// The outcome of the last drawing converted, by a hash of its bytes and its length, and the +/// conversions a [`Held`] keeps. Open reads a drawing's layouts, draws a preview of each in its +/// dialog and then opens it, and each of those reads the same file; a file the conversion refused +/// (or whose worker stopped) is refused again without another conversion for [`FAILURE_KEPT`], +/// after which the next read converts it again. +#[derive(Default)] +struct Kept { + hasher: std::collections::hash_map::RandomState, + /// The last outcome, by key, and when it was kept. + last: Option<((u64, usize), Outcome, Instant)>, + /// The conversions handed out by [`hold`], while a [`Held`] for each exists. + held: Vec<((u64, usize), Weak)>, +} + +impl Kept { + fn key(&self, bytes: &[u8]) -> (u64, usize) { + (self.hasher.hash_one(bytes), bytes.len()) + } + + fn get(&self, key: (u64, usize), now: Instant) -> Option { + let fresh = |outcome: &Outcome, at: &Instant| outcome.is_ok() || now.saturating_duration_since(*at) < FAILURE_KEPT; + if let Some((_, outcome, _)) = self.last.as_ref().filter(|(k, outcome, at)| *k == key && fresh(outcome, at)) { + return Some(outcome.clone()); + } + self.held.iter().filter(|(k, _)| *k == key).find_map(|(_, c)| c.upgrade()).map(Ok) + } + + fn hold(&mut self, key: (u64, usize), converted: &Arc) { + self.held.retain(|(_, c)| c.strong_count() > 0); + self.held.push((key, Arc::downgrade(converted))); + } + + fn keep(&mut self, key: (u64, usize), outcome: &Outcome, now: Instant) { + if outcome.as_ref().is_ok_and(|c| c.dxf.len() > MAX_KEPT) { + self.last = None; + } else { + self.last = Some((key, outcome.clone(), now)); + } + } +} + +/// How long a failed conversion is returned again for the same bytes. A worker can fail for a +/// passing cause (memory, its deadline, a failed start), so a later read converts the drawing again. +const FAILURE_KEPT: Duration = Duration::from_secs(10); + +/// The conversion of `bytes` that `kept` holds, else `convert`'s, which `kept` then holds. The +/// lock is not held while `convert` runs, so another drawing can be converted at the same time. +fn through(kept: &Mutex, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result) -> Outcome { + through_at(kept, bytes, &Instant::now, convert) +} + +/// [`through`] with the time read from `now`; an outcome is kept from when `convert` returned. +fn through_at(kept: &Mutex, bytes: &[u8], now: &dyn Fn() -> Instant, convert: impl FnOnce(&[u8]) -> Result) -> Outcome { + let key = { + let kept = kept.lock().unwrap_or_else(PoisonError::into_inner); + let key = kept.key(bytes); + if let Some(outcome) = kept.get(key, now()) { + return outcome; + } + key + }; + let outcome = convert(bytes).map(Arc::new); + kept.lock().unwrap_or_else(PoisonError::into_inner).keep(key, &outcome, now()); + outcome +} + +/// [`through`], and the conversion stays where `kept` finds it while the [`Held`] lasts. +fn hold_in(kept: &Mutex, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result) -> Result { + let converted = through(kept, bytes, convert)?; + let mut kept = kept.lock().unwrap_or_else(PoisonError::into_inner); + let key = kept.key(bytes); + kept.hold(key, &converted); + Ok(Held { _converted: converted }) +} + +static KEPT: LazyLock> = LazyLock::new(Mutex::default); + +/// `bytes` (a DWG drawing) as DXF, within craft-dwg's default limits (512 MiB of DWG, 1 GiB of DXF). +pub(crate) fn to_dxf(bytes: &[u8]) -> Outcome { + through(&KEPT, bytes, convert) +} + +/// A DWG drawing's conversion, kept for every read of the same bytes ([`crate::info`], +/// [`crate::import`]) while this value exists, whatever other drawings are converted meanwhile and +/// however large its DXF is. +#[derive(Debug, Clone)] +pub struct Held { + _converted: Arc, +} + +/// Convert `bytes` (a DWG drawing), or take the conversion already kept, and keep it while the +/// returned [`Held`] exists → the conversion's error when it fails. +pub fn hold(bytes: &[u8]) -> Result { + hold_in(&KEPT, bytes, convert) +} + +fn convert(bytes: &[u8]) -> Result { + let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?; + Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() }) +} + +/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one. +fn worded(message: &str) -> String { + message + .replace("accepted by this bridge", "VectorCraft opens") + .replace("types this bridge can't preserve", "types VectorCraft can't read") + .replace("; saving over the original file would lose them", "") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn counting<'a>(calls: &'a std::cell::Cell, dxf: &'a [u8]) -> impl FnOnce(&[u8]) -> Result + 'a { + move |_| { + calls.set(calls.get() + 1); + Ok(Converted { dxf: dxf.to_vec(), notes: vec![] }) + } + } + + #[test] + fn the_same_drawing_is_converted_once_and_another_drawing_again() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let a = through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + let again = through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap(); + assert_eq!(calls.get(), 1); + assert_eq!(again.dxf, a.dxf); + through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 2); + // The first drawing is no longer held. + through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 3); + } + + #[test] + fn a_refused_file_is_refused_again_without_converting_and_an_oversized_rendition_is_not_kept() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let start = Instant::now(); + let at_start = move || start; + assert_eq!(through_at(&kept, b"AC1015 bad", &at_start, |_| Err("DWG: no".to_string())).unwrap_err(), "DWG: no"); + let again = through_at(&kept, b"AC1015 bad", &at_start, counting(&calls, b"0\nEOF\n")); + assert_eq!((again.unwrap_err().as_str(), calls.get()), ("DWG: no", 0)); + let big = vec![b' '; MAX_KEPT + 1]; + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + assert_eq!(calls.get(), 2, "a rendition over MAX_KEPT is converted again"); + } + + #[test] + fn a_failed_conversion_is_tried_again_once_its_time_is_up() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let clock = std::cell::Cell::new(Instant::now()); + let now = || clock.get(); + // The worker fails after running for longer than FAILURE_KEPT: the failure is kept from then. + let slow_failure = |_: &[u8]| { + clock.set(clock.get() + FAILURE_KEPT * 2); + Err("DWG: stopped".to_string()) + }; + assert!(through_at(&kept, b"AC1015 bad", &now, slow_failure).is_err()); + clock.set(clock.get() + FAILURE_KEPT / 2); + let within = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n")); + assert_eq!((within.unwrap_err().as_str(), calls.get()), ("DWG: stopped", 0)); + clock.set(clock.get() + FAILURE_KEPT / 2); + let later = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n")); + assert_eq!((later.unwrap().dxf.as_slice(), calls.get()), (b"0\nEOF\n".as_slice(), 1)); + // A conversion that worked is kept whatever the time. + clock.set(clock.get() + FAILURE_KEPT * 100); + through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"other")).unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn a_held_drawing_is_not_converted_again_until_its_hold_is_dropped() { + let kept = Mutex::new(Kept::default()); + let calls = std::cell::Cell::new(0); + let big = vec![b' '; MAX_KEPT + 1]; + let one = hold_in(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + let large = hold_in(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap(); + assert_eq!(calls.get(), 3); + // Another drawing converted since, and a rendition over MAX_KEPT, are still found. + through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap(); + assert_eq!(through(&kept, b"AC1015 big", counting(&calls, b"other")).unwrap().dxf.len(), big.len()); + assert_eq!(calls.get(), 3); + drop((one, large)); + through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap(); + through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap(); + assert_eq!(calls.get(), 5, "a dropped hold no longer keeps its conversion"); + let refused = hold_in(&kept, b"AC1015 bad", |_| Err("DWG: no".to_string())); + assert_eq!(refused.unwrap_err(), "DWG: no"); + } + + #[test] + fn messages_name_what_vectorcraft_does() { + let m = worded("DWG: the file is 9.9 MB, larger than the 1.0 MB accepted by this bridge"); + assert_eq!(m, "DWG: the file is 9.9 MB, larger than the 1.0 MB VectorCraft opens"); + let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them"); + assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)"); + } +} diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 9216c57c29..5a5582efe1 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -1,4 +1,5 @@ -//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. +//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. A DWG drawing comes +//! in the same way, converted to DXF first ([`crate::dwg`]). //! //! The drawing's model space (or a paper layout) comes in at a ratio (1 unit of the art = N //! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred @@ -102,11 +103,24 @@ pub fn is_dxf(bytes: &[u8]) -> bool { false } -/// The tags of a DXF file and where it is damaged (DWG files are refused). -fn tags(bytes: &[u8]) -> Result<(Vec, Option), String> { - if bytes.starts_with(b"AC10") || bytes.starts_with(b"AC1.") { - return Err("this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that".into()); +/// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read +/// left out: where the file is damaged, and what the DWG conversion couldn't read. +fn tags(bytes: &[u8]) -> Result<(Vec, Vec), String> { + if crate::dwg::is_dwg(bytes) { + let converted = crate::dwg::to_dxf(bytes)?; + let (tags, mut notes) = dxf_tags(&converted.dxf)?; + notes.extend(converted.notes.iter().cloned()); + return Ok((tags, notes)); } + // R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number. + if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) { + return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into()); + } + dxf_tags(bytes) +} + +/// The tags of a DXF file and where it is damaged. +fn dxf_tags(bytes: &[u8]) -> Result<(Vec, Vec), String> { let (tags, damaged) = craft_dxf::parse_recovering(bytes).map_err(|e| match e { craft_dxf::DxfError::TooLarge { .. } => "the drawing is too large to open".to_string(), _ if bytes.starts_with(reader::BINARY_SENTINEL) => "this binary DXF file is damaged or cut short".to_string(), @@ -115,7 +129,7 @@ fn tags(bytes: &[u8]) -> Result<(Vec, Option), String> { if tags.is_empty() { return Err("not a DXF drawing".into()); } - Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")))) + Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")).into_iter().collect())) } /// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it. @@ -182,7 +196,7 @@ pub fn info(bytes: &[u8]) -> Result { }) } -/// Import a DXF drawing with `o`. +/// Import a DXF or DWG drawing with `o`. pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { let (w, h) = o.fit_to; if !(w > 0.0 && h > 0.0 && w.max(h) <= build::MAX_EXTENT) { @@ -193,7 +207,7 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { { return Err(format!("scale must be a number from {} to {}, not {s}", SCALE_RANGE.start(), SCALE_RANGE.end())); } - let (tags, damaged) = tags(bytes)?; + let (tags, notes) = tags(bytes)?; let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags)); if d.sections == 0 { return Err("not a DXF drawing".into()); @@ -214,10 +228,12 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { }; let (mut document, mut warnings) = build::Build::new(&d, o).run(layout, natural, ratio)?; document.units = if o.fit { unit } else { o.unit.unwrap_or(unit) }; - warnings.extend(damaged); + warnings.extend(notes); document.limit_depth_noting(&mut warnings); Ok(Imported { document, warnings }) } #[cfg(test)] mod tests; +#[cfg(test)] +mod tests_dwg; diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index 309a4ea228..9d147b08cf 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -178,7 +178,7 @@ pub(crate) struct Converter { const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries"; const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour"; -const MESHES: &str = "3D polygon meshes and polyface meshes are left out"; +const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out"; const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; const FAR_AWAY: &str = "entities with coordinates out of range are left out"; @@ -233,14 +233,20 @@ impl Converter { path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?) } model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs), - model::EntityKind::Polyline(p) => self.polyline(p, ocs), + model::EntityKind::Polyline(p) => self.polyline(p, &g, ocs), model::EntityKind::Spline(s) => path(spline(s)?), model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => { let [a, b, c, d] = corners.map(point); // The corners zigzag: the outline runs 1, 2, 4, 3. Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 }) } - model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))), + model::EntityKind::Face3d { corners, hidden_edges } => { + // Bit n of group 70 hides the edge from corner n. + let corners: Vec<(Point, bool)> = corners.iter().enumerate().map(|(i, c)| (point(*c), hidden_edges & (1 << i) == 0)).collect(); + let mut bp = BezPath::new(); + face(&mut bp, &corners); + (!bp.elements().is_empty()).then_some(bp).and_then(path) + } model::EntityKind::Hatch(h) => self.hatch(h, ocs), model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text), model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text), @@ -253,10 +259,11 @@ impl Converter { } } - fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option { - if p.is_mesh() || p.is_polyface() { - self.warn(MESHES); - return None; + fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option { + // Meshes are in world coordinates, seen from above. + if p.is_polyface() || p.is_mesh() { + let bp = if p.is_polyface() { self.polyface(p) } else { self.mesh(p, g) }?; + return Some(Geom::Path { bp, fill: false, width: 0.0 }); } // Spline frame control points and polyface faces aren't on the line. let verts: Vec = @@ -267,6 +274,60 @@ impl Converter { Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) }) } + /// A polyface mesh's faces: each one's visible edges, closed when all of them are. + fn polyface(&mut self, p: &model::Polyline) -> Option { + let points: Vec = p.vertices.iter().filter(|v| !v.is_face()).map(|v| point(v.location)).collect(); + let mut bp = BezPath::new(); + for f in p.vertices.iter().filter(|v| v.is_face()) { + // Vertex numbers count from 1, negative when the edge from that vertex is hidden; + // 0 ends a triangle's list. + let corners: Option> = f + .face + .iter() + .take_while(|n| **n != 0) + .map(|n| { + let i = usize::try_from(n.unsigned_abs()).ok()?.checked_sub(1)?; + Some((*points.get(i)?, *n > 0)) + }) + .collect(); + match corners { + Some(corners) => face(&mut bp, &corners), + None => self.warn(MESH_VERTICES), + } + } + (!bp.elements().is_empty()).then_some(bp) + } + + /// A polygon mesh as its M lines and N lines. Its vertices go row by row (N to a row); a + /// smoothed mesh holds its surface's vertices (groups 73 and 74 count them) after the frame. + fn mesh(&mut self, p: &model::Polyline, g: &Groups<'_>) -> Option { + let points: Vec = p.vertices.iter().filter(|v| !v.is_spline_frame()).map(|v| point(v.location)).collect(); + let size = |m: i64, n: i64| { + let (m, n) = (usize::try_from(m).ok()?, usize::try_from(n).ok()?); + (m > 0 && n > 0 && m.checked_mul(n) == Some(points.len())).then_some((m, n)) + }; + let (frame, surface) = ((p.m, p.n), (g.i_or(73, 0), g.i_or(74, 0))); + // Without the frame's vertices only the surface's counts describe the grid. + let dims = if p.vertices.iter().any(model::Vertex::is_spline_frame) { + size(surface.0, surface.1) + } else { + size(frame.0, frame.1).or_else(|| size(surface.0, surface.1)) + }; + let Some((m, n)) = dims else { + self.warn(MESH_VERTICES); + return None; + }; + let mut bp = BezPath::new(); + for row in points.chunks(n) { + line(&mut bp, row, p.flags & 32 != 0); + } + for col in 0..n { + let pts: Vec = (0..m).map(|r| points[r * n + col]).collect(); + line(&mut bp, &pts, p.closed()); + } + (!bp.elements().is_empty()).then_some(bp) + } + fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option { let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase(); let [sx, sy, _] = ins.scale; @@ -398,6 +459,46 @@ fn polygon(pts: &[Point]) -> BezPath { bp } +/// Adds the line through `pts` to `bp`, closed if `closed` (nothing for fewer than two points). +fn line(bp: &mut BezPath, pts: &[Point], closed: bool) { + if pts.len() < 2 { + return; + } + for (i, p) in pts.iter().enumerate() { + if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) } + } + if closed { + bp.close_path(); + } +} + +/// Adds a face's outline to `bp`: its corners with whether the edge from each to the next is +/// visible. All visible, the outline is closed; otherwise each run of visible edges is an open +/// line. +fn face(bp: &mut BezPath, corners: &[(Point, bool)]) { + let pts: Vec = corners.iter().map(|c| c.0).collect(); + let Some(hidden) = corners.iter().position(|c| !c.1) else { + line(bp, &pts, true); + return; + }; + // Start after a hidden edge, so that no run is split where the list wraps. + let n = corners.len(); + let mut run: Vec = Vec::new(); + for k in 1..=n { + let i = (hidden + k) % n; + if corners[i].1 { + if run.is_empty() { + run.push(pts[i]); + } + run.push(pts[(i + 1) % n]); + } else { + line(bp, &run, false); + run.clear(); + } + } + line(bp, &run, false); +} + fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] } diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 5faad39835..d53694343a 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -248,6 +248,125 @@ fn polyline_bulges_are_exact_arcs() { assert!((b.y1 - height(&doc)).abs() < 1e-4, "the arc's chord is at y 0: {b:?}"); } +/// The straight segments of the paths of the one object a drawing brings in, in drawing +/// coordinates (y up), each with its ends in order, sorted. +fn drawn_edges(r: &Imported) -> Vec<[(i64, i64); 2]> { + let doc = &r.document; + assert_eq!(doc.layers[0].children().map_or(0, Vec::len), 1, "one object: {:?}", r.warnings); + let h = height(doc); + let at = |p: Point| (p.x.round() as i64, (h - p.y).round() as i64); + let mut edges = vec![]; + for n in leaves(doc) { + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path: {:?}", n.kind) }; + for s in path.to_bezpath().segments() { + let kurbo::PathSeg::Line(l) = s else { panic!("not a line: {s:?}") }; + edges.push([at(l.p0), at(l.p1)]); + } + } + sorted(edges) +} + +/// Edges with their ends in order, sorted. +fn sorted(mut e: Vec<[(i64, i64); 2]>) -> Vec<[(i64, i64); 2]> { + for x in &mut e { + x.sort_unstable(); + } + e.sort_unstable(); + e +} + +fn vertex(flags: &'static str, x: &'static str, y: &'static str, z: &'static str) -> [(i32, &'static str); 5] { + [(0, "VERTEX"), (70, flags), (10, x), (20, y), (30, z)] +} + +#[test] +fn polyface_meshes_draw_their_faces_visible_edges_from_above() { + // A square at two heights as two triangles sharing a hidden diagonal, and a face naming a + // vertex the mesh doesn't have. + let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "64"), (71, "4"), (72, "3")]; + for (x, y, z) in [("0", "0", "5"), ("10", "0", "5"), ("10", "10", "0"), ("0", "10", "0")] { + e.extend(vertex("192", x, y, z)); + } + for f in [["1", "2", "-3"], ["3", "4", "-1"], ["1", "2", "9"]] { + e.extend(vertex("128", "0", "0", "0")); + e.extend([(71, f[0]), (72, f[1]), (73, f[2])]); + } + e.push((0, "SEQEND")); + let r = open(&entities(&e), &points()); + let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]); + assert_eq!(drawn_edges(&r), square, "the outline without the diagonal"); + assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings); + // With every edge visible, each face is a closed outline. + let e: Vec<(i32, &str)> = e.iter().map(|&(c, v)| (c, v.trim_start_matches('-'))).collect(); + let r = open(&entities(&e), &points()); + let diagonal = drawn_edges(&r).iter().filter(|e| **e == [(0, 0), (10, 10)]).count(); + assert_eq!(diagonal, 2, "the diagonal, once per face"); + let faces = leaves(&r.document); + assert_eq!(faces.len(), 2); + assert!(faces.iter().all(|f| f.path_data().is_some_and(|p| p.subpaths.iter().all(|s| s.closed)))); +} + +#[test] +fn polygon_meshes_draw_their_m_and_n_lines_from_above() { + // Rows of 3 vertices: N runs along x, M along y. + let grid = |flags: &'static str, m: &'static str, n: &'static str, rows: &[&'static str]| { + let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, flags), (71, m), (72, n)]; + for y in rows { + for x in ["0", "10", "20"] { + e.extend(vertex("64", x, y, "7")); + } + } + e.push((0, "SEQEND")); + e + }; + let edges = |e: &[(i32, &str)]| drawn_edges(&open(&entities(e), &points())); + let rows = vec![[(0, 0), (10, 0)], [(10, 0), (20, 0)], [(0, 10), (10, 10)], [(10, 10), (20, 10)]]; + let cols = vec![[(0, 0), (0, 10)], [(10, 0), (10, 10)], [(20, 0), (20, 10)]]; + let open_grid = sorted([rows.clone(), cols.clone()].concat()); + assert_eq!(edges(&grid("16", "2", "3", &["0", "10"])), open_grid); + // Closed in N (32): each row joins its last vertex to its first. + let wrap = vec![[(20, 0), (0, 0)], [(20, 10), (0, 10)]]; + assert_eq!(edges(&grid("48", "2", "3", &["0", "10"])), sorted([rows, cols, wrap].concat())); + // Closed in M (1): each column joins its last vertex to its first. + let tall = edges(&grid("17", "3", "3", &["0", "10", "20"])); + for e in [[(0, 0), (0, 20)], [(10, 0), (10, 20)], [(20, 0), (20, 20)]] { + assert_eq!(tall.iter().filter(|x| **x == e).count(), 1, "{e:?} in {tall:?}"); + } + // A smoothed mesh draws its surface (73 by 74 vertices), not the frame before it, even when + // the frame (3 by 2) has as many vertices. + let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "20"), (71, "3"), (72, "2"), (73, "2"), (74, "3"), (75, "6")]; + for (x, y) in [("-50", "-50"), ("50", "-50"), ("-50", "0"), ("50", "0"), ("-50", "50"), ("50", "50")] { + e.extend(vertex("80", x, y, "0")); + } + e.extend_from_slice(&grid("16", "2", "3", &["0", "10"])[5..]); + assert_eq!(edges(&e), open_grid); + // When the surface counts (2 by 4) don't fit, the frame's (3 by 2) don't describe the surface + // vertices either: the mesh is left out with a warning. + let i = e.iter().position(|t| *t == (74, "3")).unwrap_or_else(|| panic!("no group 74 in {e:?}")); + e[i] = (74, "4"); + let r = open(&entities(&e), &points()); + assert!(leaves(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings); + // Vertices that don't fill the grid: the mesh is left out with a warning. + let r = open(&entities(&grid("16", "2", "4", &["0", "10"])), &points()); + assert!(leaves(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings); +} + +#[test] +fn three_d_faces_leave_out_their_hidden_edges() { + let edges = |hidden: &'static str| { + let mut e: Vec<(i32, &str)> = vec![(0, "3DFACE"), (70, hidden)]; + e.extend([(10, "0"), (20, "0"), (11, "10"), (21, "0"), (12, "10"), (22, "10"), (13, "0"), (23, "10")]); + drawn_edges(&open(&entities(&e), &points())) + }; + let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]); + assert_eq!(edges("0"), square); + // Bit 0 hides the edge from the first corner, bit 2 the one from the third. + assert_eq!(edges("1"), sorted(vec![[(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]])); + assert_eq!(edges("5"), sorted(vec![[(10, 0), (10, 10)], [(0, 10), (0, 0)]])); +} + #[test] fn nurbs_splines_stay_within_a_hundredth() { // A rational quadratic circle of radius 100: nine weighted control points. diff --git a/crates/cad/src/import/tests_dwg.rs b/crates/cad/src/import/tests_dwg.rs new file mode 100644 index 0000000000..00ff6aa7da --- /dev/null +++ b/crates/cad/src/import/tests_dwg.rs @@ -0,0 +1,85 @@ +//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF +//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD +//! on aarch64. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, Unit}; +use vectorcraft_geom::{Rect, shapes}; + +use super::*; +use crate::{DxfOptions, DxfVersion}; + +/// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse. +fn dxf() -> Vec { + let mut d = Document::new(200.0, 100.0); + let layer = d.add_layer(Some("Walls")); + let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0); + let rect = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), stroke(Color::rgb(1.0, 0.0, 0.0))); + let oval = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), stroke(Color::rgb(0.0, 0.0, 1.0))); + for n in [rect, oval] { + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() }; + crate::export(&d, &o).unwrap().bytes +} + +fn dwg() -> Vec { + crate::dwg::allow_in_process(); + craft_dwg::dxf_to_dwg_as(&dxf(), "AC1018").unwrap() +} + +/// A layer's name, and each of its objects' bounds (to 0.01 pt) and stroke color. +type LayerArt = (Option, Vec<([i64; 4], Option<[u8; 4]>)>); + +/// Each layer holding art. +fn art(doc: &Document) -> Vec { + let r = |v: f64| (v * 100.0).round() as i64; + doc.layers + .iter() + .filter_map(|layer| { + let objects: Vec<_> = layer + .children()? + .iter() + .map(|n| { + let b = n.geometric_bounds().unwrap(); + let stroke = match n.appearance.stroke().map(|s| &s.paint) { + Some(Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), + _ => None, + }; + ([r(b.x0), r(b.y0), r(b.x1), r(b.y1)], stroke) + }) + .collect(); + (!objects.is_empty()).then(|| (layer.name.clone(), objects)) + }) + .collect() +} + +#[test] +fn a_dwg_drawing_comes_in_as_its_dxf_does() { + let (dxf, dwg) = (dxf(), dwg()); + assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf)); + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; + let want = art(&import(&dxf, &o).unwrap().document); + assert_eq!(want.len(), 1, "{want:?}"); + assert_eq!(want[0].0.as_deref(), Some("Walls")); + assert_eq!(want[0].1.len(), 2, "{want:?}"); + assert_eq!(art(&import(&dwg, &o).unwrap().document), want); + let i = info(&dwg).unwrap(); + assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model"))); + assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}"); +} + +#[test] +fn a_damaged_dwg_is_an_error_that_names_dwg() { + let mut cut = dwg(); + cut.truncate(cut.len() / 3); + let e = import(&cut, &ImportOptions::default()).unwrap_err(); + assert!(e.contains("DWG"), "{e}"); + assert!(info(&cut).is_err()); + // An R1.x or R2.x drawing is refused without reading it. + for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] { + let e = import(old, &ImportOptions::default()).unwrap_err(); + assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}"); + } +} diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index b54d9022bf..73e30bd2a9 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -14,15 +14,19 @@ //! clipping) is approximated or left out, and each such loss comes back as a warning. //! //! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`]. +//! It reads a DWG drawing too, converted to DXF by [`dwg`]. //! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`]. //! //! - `aci`: the 256-colour index palette and the nearest index of a colour. //! - The ASCII file around those entities is written by `craft_dxf::drawing`. //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. +//! - `dwg`: DWG drawings converted to DXF by craft-dwg, in a child process on desktop builds. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. +#![doc(test(attr(deny(unsafe_code))))] mod aci; +pub mod dwg; #[cfg(test)] mod expansion_test; pub mod hpgl; @@ -33,6 +37,7 @@ use vectorcraft_doc::{Document, Unit}; use vectorcraft_geom::Rect; pub use aci::{aci_rgb, nearest_aci}; +pub use dwg::is_dwg; pub use import::{DxfInfo, ImportOptions, Imported, import, info, is_dxf}; /// How deep symbols, blocks and brush art may nest in one another (deeper art is left out). diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bb4c88985..03aa259281 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -3,6 +3,7 @@ //! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB), //! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`]. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod blend; pub mod cms; diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 24228604a6..ba12eafabb 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -36,14 +36,14 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { let was_relative = live.radii_relative(); let base = match live { LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)), - LiveShape::Polygon { .. } => live.polygon_outline(), + LiveShape::Polygon { .. } | LiveShape::Star { .. } => live.polygon_outline(), LiveShape::Path { base, .. } => base.clone(), LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; let corners = path_corners(&base); let radii: &mut [f64] = match live { LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii, LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; @@ -62,6 +62,7 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { match live { LiveShape::Rectangle { radii_relative: rel, .. } | LiveShape::Polygon { radii_relative: rel, .. } + | LiveShape::Star { radii_relative: rel, .. } | LiveShape::Path { radii_relative: rel, .. } => { *rel = relative; } @@ -99,7 +100,7 @@ impl<'a> LiveCorners<'a> { let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = l.folded() else { return None }; (Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec(), radii_relative) } - Some(l @ LiveShape::Polygon { radii, kinds, radii_relative, .. }) => { + Some(l @ (LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. })) => { (Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative) } Some(LiveShape::Path { base, radii, kinds, radii_relative }) => { @@ -258,6 +259,14 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne edit(&outline, relative, radii, kinds, corners, radius, kind); trim_vec_radii(radii, kinds); } + LiveShape::Star { r1, r2, points, xf, radii, kinds, .. } => { + let outline = shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf); + let n = 2 * *points as usize; + radii.resize(n, 0.0); + kinds.resize(n, CornerKind::Round); + edit(&outline, relative, radii, kinds, corners, radius, kind); + trim_vec_radii(radii, kinds); + } LiveShape::Path { base, radii, kinds, .. } => { let n = base.anchor_count(); radii.resize(n, 0.0); @@ -277,6 +286,57 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne } } +/// Edit the anchors of the uncut outline that `anchors` (of the path as drawn) come from, while the +/// path keeps its Live Corners: `edit` gets the outline in document space and those of its anchors, +/// and the path is cut again with the same radii and kinds. A live rectangle or polygon becomes a +/// [`LiveShape::Path`] with that outline. [`LiveCorners::sources`] before and after the edit map +/// the anchors as drawn to the corners they come from. +/// Returns `None`, leaving the path unchanged, when the path has no live shape or +/// no cut corner, or is a rectangle sheared or scaled unevenly. +pub fn edit_corner_anchors( + path: &mut PathData, + live: &mut Option>, + anchors: &BTreeSet, + edit: impl FnOnce(&mut PathData, &BTreeSet), +) -> Option<()> { + live.as_ref()?; + if let Some(LiveShape::Rectangle { xf, .. }) = live.as_deref() { + let [a, b, c, d, _, _] = xf.as_coeffs(); + let scale = (a * a + b * b).max(c * c + d * d).max(1e-12); + if ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale { + return None; + } + } + let (mut base, moved, radii, kinds, relative) = { + let lc = LiveCorners::new(path, live.as_deref())?; + if !lc.drawn.iter().any(|r| *r > 0.0) { + return None; + } + let moved: BTreeSet = anchors.iter().filter_map(|(si, ai)| lc.sources.get(*si)?.get(*ai).copied()).collect(); + if moved.is_empty() { + return None; + } + let mut radii = lc.radii.clone(); + radii.resize(lc.base.anchor_count(), 0.0); + (lc.base.transformed(lc.xf), moved, radii, lc.kinds.clone(), lc.relative) + }; + let mut on_base = BTreeSet::new(); + let mut k = 0; + for (si, sp) in base.subpaths.iter().enumerate() { + for ai in 0..sp.anchors.len() { + if moved.contains(&k) { + on_base.insert((si, ai)); + } + k += 1; + } + } + edit(&mut base, &on_base); + let l = LiveShape::Path { base, radii, kinds, radii_relative: relative }; + *path = l.to_path(); + *live = Some(Box::new(l)); + Some(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index dc1e082ac0..7fdcf3a784 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -318,7 +318,7 @@ impl Document { /// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as /// [`Document::index_path`] finds it. pub fn node(&self, id: NodeId) -> Option<&Node> { - if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) { + if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id).or_else(|| cached.added_node_in(&self.layers, id))) { crate::id_index::note_path_lookup(); return Some(n); } @@ -365,10 +365,21 @@ impl Document { Some(None) => return self.walk_index_path(id), _ => {} } + let stale = cached.contains_key(&id); + // An id the table doesn't have, at the path an earlier walk found for it, while the node + // there still has the id. + if !stale + && let Some(p) = cached.added(&id) + && self.node_at(&p).is_some_and(|n| n.id == id) + { + return Some(p); + } // A stale path (the tree changed) or an id the cache doesn't have (deleted or added // since): walk, and rebuild now and then. let found = self.walk_index_path(id); - let stale = cached.contains_key(&id); + if !stale && let Some(p) = &found { + cached.note_added(id, p); + } if (stale || found.is_some()) && self.index.missed() { self.index.rebuild(&self.layers); } @@ -425,23 +436,37 @@ impl Document { // Cached paths that still check out ([`id_index`]); the rest take one walk. For a good // share of the document, one walk is quicker than checking each cached path. if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { - want.retain(|id| match cache.get(id) { - Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + want.retain(|id| match self.cached_path(&cache, *id) { + Some(p) => { out.insert(*id, p); false } - _ => true, + None => true, }); } if !want.is_empty() { crate::id_index::note_tree_walk(); let mut rest = HashMap::with_capacity(want.len()); walk(&self.layers, &want, &mut Vec::new(), &mut rest); + // The cache keeps the paths of found ids it doesn't have, for the next lookup. + if let Some(cache) = self.index.get().filter(|_| rest.len() <= crate::id_index::ADDED_PATHS) { + rest.iter().for_each(|(id, p)| cache.note_added(*id, p)); + } out.extend(rest); } out } + /// The path the lookup cache `cache` has for `id`, while the node there has the id: the table's + /// path, or for an id the table doesn't have, the path an earlier walk found ([`id_index`]). + fn cached_path(&self, cache: &crate::id_index::Paths, id: NodeId) -> Option> { + let p = match cache.get(&id) { + Some(p) => p?, + None => cache.added(&id)?, + }; + self.node_at(&p).is_some_and(|n| n.id == id).then_some(p) + } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still @@ -452,7 +477,8 @@ impl Document { let want: std::collections::HashSet> = ids.into_iter().collect(); // As in `index_paths`, one walk is quicker than checking the cached paths of a good share // of the document. - if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let cache = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()); + if let Some(cache) = &cache { let mut paths = Vec::with_capacity(want.len()); let cached = want.iter().all(|id| match cache.get(id) { Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { @@ -476,6 +502,10 @@ impl Document { out.push(n); } }); + // Found ids the table doesn't have count toward a rebuild for later ordered lookups. + if cache.is_some_and(|cache| out.iter().any(|n| !cache.contains_key(&n.id))) && self.index.missed() { + self.index.rebuild(&self.layers); + } } out } @@ -584,10 +614,14 @@ impl Document { /// Remove a node and return it. pub fn remove(&mut self, id: NodeId) -> Result, DocError> { - let parent = self.parent_of(id); let path = self.index_path(id).ok_or(DocError::NoNode(id))?; - let idx = *path.last().ok_or(DocError::NoNode(id))?; - let ch = self.children_mut(parent)?; + self.remove_at(id, &path) + } + + /// Remove the node at `path`, the index path [`Document::index_path`] gave for `id`, and return it. + fn remove_at(&mut self, id: NodeId, path: &[usize]) -> Result, DocError> { + let (&idx, up) = path.split_last().ok_or(DocError::NoNode(id))?; + let ch = self.children_at(up).ok_or(DocError::NoNode(id))?; if idx >= ch.len() { return Err(DocError::NoNode(id)); } @@ -602,10 +636,11 @@ impl Document { { return Err(DocError::Invalid("cannot move an object into itself".into())); } - if let Some(n) = self.node(id) { + let path = self.index_path(id).ok_or(DocError::NoNode(id))?; + if let Some(n) = self.node_at(&path) { self.check_ruler_guide_place(n, parent)?; } - let n = self.remove(id)?; + let n = self.remove_at(id, &path)?; let ch = self.children_mut(parent)?; let i = Node::insert_index(ch, index, &n); ch.insert(i, n); @@ -623,9 +658,15 @@ impl Document { /// Position of `id` within its parent: (parent, index, sibling count). pub fn position(&self, id: NodeId) -> Option<(Option, usize, usize)> { - let parent = self.parent_of(id); - let idx = *self.index_path(id)?.last()?; - let n = self.children(parent)?.len(); + let path = self.index_path(id)?; + let (&idx, up) = path.split_last()?; + let (parent, n) = match up { + [] => (None, self.layers.len()), + _ => { + let parent = self.node_at(up)?; + (Some(parent.id), parent.children()?.len()) + } + }; Some((parent, idx, n)) } diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c29e8464ea..fe2ffc0fd1 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -239,6 +239,52 @@ impl Document { round_json_paths(brushes, &round); } } + + /// Make every live star a plain path of the outline it draws, for a save that versions before + /// live stars read: in the art of the layers, symbols, graph designs, pattern swatches and the + /// pattern definition that pattern editing's Cancel puts back (opacity-mask art included), and + /// in the brush definitions. + pub fn live_stars_to_paths(&mut self) { + let is_star = |n: &Node| matches!(n.live_shape(), Some(LiveShape::Star { .. })); + let mut plain = |n: &mut Node| { + if let NodeKind::Path { live, .. } = &mut n.kind + && matches!(live.as_deref(), Some(LiveShape::Star { .. })) + { + *live = None; + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + edit_branches_where(root, &is_star, &mut plain); + } + if let Some(brushes) = self.unknown.get_mut("brushes") { + json_stars_to_paths(brushes); + } + } +} + +/// Take `live` off every serialized path object (`type: "path"`) in `v` whose live shape is a +/// star. +fn json_stars_to_paths(v: &mut serde_json::Value) { + use serde_json::Value; + match v { + Value::Object(o) => { + if o.get("type").and_then(Value::as_str) == Some("path") + && o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") + { + o.remove("live"); + } + o.values_mut().for_each(json_stars_to_paths); + } + Value::Array(a) => a.iter_mut().for_each(json_stars_to_paths), + _ => {} + } } /// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds, diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 0e1673580a..05f899efac 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -4,10 +4,15 @@ //! The tree is edited in many places through public fields, so the cache can't be kept in step //! with it. It is checked instead: a cached path is used only while the node at that path still //! has the id (a check as deep as the tree). A path that no longer checks out rebuilds the cache, -//! and an id the cache doesn't have (added since, or removed) is looked up by walking, as before. +//! and an id the cache doesn't have (added since, or removed) is looked up by walking. //! An id that appears more than once (a damaged file) is never cached, so lookups keep returning //! its first place in tree order. //! +//! The path a walk finds for an id the table doesn't have is kept beside the table, shared by every +//! document that reads it, and checked the same way before it is used. Documents that each start +//! from the same copy and add the same object (every preview of a drag starts from the document as +//! it was at the press) then find that object without walking the tree. +//! //! [`crate::Document::remove_many`] keeps the cache and notes the nodes it removes, so the cache //! places each node after a removed sibling one lower and finds no path for a removed node or one //! inside it. Once the removed nodes are half the cache's entries, the cache is let go. The first @@ -16,8 +21,10 @@ //! The one case a cached lookup can answer differently from a walk: a second node with an //! existing id put in the tree *after* the cache was built, earlier in tree order than the first. //! The lookup then returns the original node (also one with that id) instead of the new one. The -//! app never makes such a node (paste and duplicate give new ids, undo restores whole trees); -//! duplicated ids come from damaged files, which are cached afresh when opened. +//! same holds for an id the table doesn't have: once a walk in one document has found it, a copy +//! that holds a second node with that id earlier in tree order gets the node at the path the walk +//! found. The app never makes such a node (paste and duplicate give new ids, undo restores whole +//! trees); duplicated ids come from damaged files, which are cached afresh when opened. use std::collections::HashMap; use std::hash::{BuildHasherDefault, Hasher}; @@ -65,8 +72,15 @@ type Gaps = HashMap>; pub(crate) struct Paths { table: Arc, gaps: Arc, + /// The index paths that walks found for ids the table doesn't have, at most [`ADDED_PATHS`] of + /// them. Every document that reads the table reads them too, and checks a path against its own + /// tree before using it. + added: Arc>>>, } +/// The most paths [`Paths`] keeps for ids its table doesn't have; one more lets the kept ones go. +pub(crate) const ADDED_PATHS: usize = 4096; + /// Where each node was when the cache was built: its parent's entry (`u32::MAX` for a top-level /// layer) and its index among its siblings. One flat table, so building it allocates nothing per /// node. @@ -152,6 +166,36 @@ impl Paths { Err(k) => Some(i - k as u32), } } + /// The index path a walk found for `id`, an id the table doesn't have ([`Paths::note_added`]); + /// the caller checks that the node there has the id. + pub(crate) fn added(&self, id: &NodeId) -> Option> { + let path = self.added.read().ok()?.get(id)?.clone(); + note_path_copy(); + Some(path) + } + /// The node with `id` in `layers` at the path [`Paths::added`] has for it, found without copying + /// the path: `None` when there is none or the node there does not have the id. + pub(crate) fn added_node_in<'a>(&self, layers: &'a [Arc], id: NodeId) -> Option<&'a Node> { + let added = self.added.read().ok()?; + let (first, rest) = added.get(&id)?.split_first()?; + let mut node: &Node = layers.get(*first)?; + for &i in rest { + node = node.children()?.get(i)?; + } + (node.id == id).then_some(node) + } + /// Keep `path`, which a walk found for `id`, when the table doesn't have `id`. Past + /// [`ADDED_PATHS`] ids, the kept paths are let go first. + pub(crate) fn note_added(&self, id: NodeId, path: &[usize]) { + if self.table.ids.contains_key(&id) { + return; + } + let Ok(mut added) = self.added.write() else { return }; + if added.len() >= ADDED_PATHS && !added.contains_key(&id) { + added.clear(); + } + added.insert(id, path.to_vec()); + } } /// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out) @@ -297,7 +341,7 @@ impl IdIndex { note_tree_walk(); let mut table = Table::default(); walk(layers, u32::MAX, &mut table); - let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default() }); + let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default(), added: Arc::default() }); if let Ok(mut g) = self.0.write() { *g = Some(out.clone()); } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8f077dae..059a3d4bdc 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -4,6 +4,7 @@ //! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node. //! Keeping the previous `Document` value around is therefore a cheap undo snapshot. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; pub mod assets; @@ -102,7 +103,7 @@ pub use appearance::{ }; pub use assets::ExportAsset; pub use compound_shape::ShapeMode; -pub use corners::LiveCorners; +pub use corners::{LiveCorners, edit_corner_anchors}; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 0a17301331..33b3f10868 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -46,11 +46,32 @@ pub enum LiveShape { #[serde(default, skip_serializing_if = "is_false")] radii_relative: bool, }, + /// A star drawn with the Star tool or `shape.star`: its point count and radii stay editable. + Star { + /// Outer radius: centre to each tip. + r1: f64, + /// Inner radius: centre to each point between two tips. + r2: f64, + /// 2–1000, as [`LiveShape::set_points`] gives it; a file's count is clamped when read. + #[serde(deserialize_with = "de_points")] + points: u32, + /// Maps the star (centred on the origin, first tip straight up) into the document. + xf: Affine, + /// Corner radii in document units, by vertex from the first tip clockwise, tips and inner + /// points alternating (none: sharp). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + radii: Vec, + /// Corner kinds, in the same order (none: round). + #[serde(default, skip_serializing_if = "all_round")] + kinds: Vec, + #[serde(default, skip_serializing_if = "is_false")] + radii_relative: bool, + }, Line { a: Point, b: Point, }, - /// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut + /// Any other path whose corners Live Corners cut (a pen path, a star saved as a path): it keeps its uncut /// outline so the corners stay editable. Without a cut corner it is a plain path again. Path { /// The path with its corners uncut, in the document. @@ -74,9 +95,10 @@ fn is_false(b: &bool) -> bool { impl LiveShape { pub fn radii_relative(&self) -> bool { match self { - LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => { - *radii_relative - } + LiveShape::Rectangle { radii_relative, .. } + | LiveShape::Polygon { radii_relative, .. } + | LiveShape::Star { radii_relative, .. } + | LiveShape::Path { radii_relative, .. } => *radii_relative, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false, } } @@ -86,6 +108,7 @@ impl LiveShape { LiveShape::Rectangle { .. } => "Rectangle", LiveShape::Ellipse { .. } => "Ellipse", LiveShape::Polygon { .. } => "Polygon", + LiveShape::Star { .. } => "Star", LiveShape::Line { .. } => "Line", LiveShape::Path { .. } => "Path", } @@ -100,7 +123,7 @@ impl LiveShape { shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf) } LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf), - LiveShape::Polygon { radii, kinds, radii_relative, .. } => { + LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. } => { let outline = self.polygon_outline(); let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative); cut_corners(&outline, &radii, kinds).0 @@ -112,10 +135,12 @@ impl LiveShape { } } } - /// A polygon's outline with its corners uncut, in the document (empty for other shapes). + /// A polygon's or star's outline with its corners uncut, in the document (empty for other + /// shapes). pub fn polygon_outline(&self) -> PathData { match self { LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf), + LiveShape::Star { r1, r2, points, xf, .. } => shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf), _ => PathData::default(), } } @@ -123,16 +148,38 @@ impl LiveShape { /// the corners past the old last one are sharp. pub fn set_sides(&mut self, n: u64) { let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return }; + let old = *sides as usize; *sides = n.clamp(3, 1000) as u32; - fn spread(v: &mut Vec, n: usize) { - match v.first().copied() { - Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], - Some(_) => v.resize(n, T::default()), - None => {} - } + spread(radii, old, *sides as usize); + spread(kinds, old, *sides as usize); + } + /// A star's point count. None for other shapes. + pub fn star_points(&self) -> Option { + let LiveShape::Star { points, .. } = self else { return None }; + Some(*points) + } + /// Give a star `n` points (2–1000). Its corners keep the radius and kind they shared; else the + /// corners past the old last one are sharp. + pub fn set_points(&mut self, n: u64) { + let LiveShape::Star { points, radii, kinds, .. } = self else { return }; + let old = 2 * *points as usize; + *points = n.clamp(2, 1000) as u32; + spread(radii, old, 2 * *points as usize); + spread(kinds, old, 2 * *points as usize); + } + /// A star's ratio: its inner radius over its outer radius (0 when the outer radius is 0). None + /// for other shapes. + pub fn star_ratio(&self) -> Option { + let LiveShape::Star { r1, r2, .. } = self else { return None }; + Some(if *r1 > 0.0 { *r2 / *r1 } else { 0.0 }) + } + /// Give a star the ratio `ratio` (0 to 1, see [`LiveShape::star_ratio`]), keeping its outer + /// radius. Nothing changes for other shapes or a ratio outside 0 to 1. + pub fn set_star_ratio(&mut self, ratio: f64) { + let LiveShape::Star { r1, r2, .. } = self else { return }; + if ratio.is_finite() && (0.0..=1.0).contains(&ratio) { + *r2 = *r1 * ratio; } - spread(radii, *sides as usize); - spread(kinds, *sides as usize); } /// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of /// `xf` (exact while its sides are equal). None for other shapes. @@ -151,7 +198,9 @@ impl LiveShape { /// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for /// other shapes. pub fn shape_angle(&self) -> Option { - let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None }; + let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. }) = self else { + return None; + }; // No −0° or 360° from rounding: a shape drawn level reads 0°. let a = (-self.angle_deg()).rem_euclid(360.0); Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) @@ -168,7 +217,7 @@ impl LiveShape { let angle = angle.rem_euclid(360.0); let (xf, local) = match self { LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)), - LiveShape::Polygon { xf, .. } => (xf, Point::ZERO), + LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => (xf, Point::ZERO), LiveShape::Line { .. } | LiveShape::Path { .. } => return, }; let center = *xf * local; @@ -274,7 +323,7 @@ impl LiveShape { *xf = a * *xf; false } - LiveShape::Polygon { xf, radii, radii_relative, .. } => { + LiveShape::Polygon { xf, radii, radii_relative, .. } | LiveShape::Star { xf, radii, radii_relative, .. } => { *xf = a * *xf; scale_radii(radii, a, *radii_relative) } @@ -326,7 +375,7 @@ impl LiveShape { let relative = self.radii_relative(); let radii: &mut [f64] = match self { LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } | LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false, }; if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 { @@ -338,7 +387,7 @@ impl LiveShape { /// Rotation angle of the live shape in degrees, clockwise on the page (y points down). pub fn angle_deg(&self) -> f64 { match self { - LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => { + LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => { let c = xf.as_coeffs(); c[1].atan2(c[0]).to_degrees() } @@ -358,6 +407,28 @@ fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { u32::deserialize(d).map(|n| n.clamp(3, 1000)) } +/// A star's point count read from a file, clamped as the commands clamp it (see [`de_sides`]). +fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(2, 1000)) +} + +/// Give a corner list for `old` corners `n` entries: one value all `old` corners shared fills it; +/// otherwise entries past its end are the default (sharp, round) and entries past `n` go. A list +/// shorter than `old` holds the default for its missing corners, so it is shared only when that +/// default is; entries of a longer list past `old` name no corner and go first. An empty list +/// stays empty. +fn spread(v: &mut Vec, old: usize, n: usize) { + v.truncate(old); + if !v.is_empty() && v.len() < old { + v.resize(old, T::default()); + } + match v.first().copied() { + Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], + Some(_) => v.resize(n, T::default()), + None => {} + } +} + /// Whether `a` only moves (no rotation, scale, shear or reflection). pub(super) fn moves_only(a: Affine) -> bool { let [a0, a1, a2, a3, _, _] = a.as_coeffs(); diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 480e201e2d..2ecdda06bd 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -158,6 +158,77 @@ fn a_polygon_from_a_file_has_3_to_1000_sides() { assert_eq!(huge.polygon_outline().anchor_count(), 1000); } +/// A live star saves and reads back as it was, and one read from a file has 2 to 1000 points. +#[test] +fn a_star_round_trips_and_its_file_count_is_clamped() { + let star = LiveShape::Star { + r1: 40.0, + r2: 20.0, + points: 7, + xf: Affine::translate((10.0, 20.0)), + radii: vec![2.0; 14], + kinds: vec![], + radii_relative: false, + }; + let text = serde_json::to_string(&star).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), star); + assert_eq!(star.label(), "Star"); + let read = |points: u64| { + let json = serde_json::json!({"shape": "star", "r1": 10.0, "r2": 5.0, "points": points, "xf": [1, 0, 0, 1, 0, 0]}); + serde_json::from_value::(json).unwrap().star_points().unwrap() + }; + assert_eq!([0, 2, 5, 1000, 4_000_000_000].map(read), [2, 2, 5, 1000, 1000]); + // Points and ratio change; the outer radius stays. + let mut s = star.clone(); + s.set_points(9); + s.set_star_ratio(0.25); + assert!(matches!(&s, LiveShape::Star { r1, r2, points: 9, radii, .. } if *r1 == 40.0 && *r2 == 10.0 && *radii == vec![2.0; 18])); + assert_eq!(s.polygon_outline().anchor_count(), 18); +} + +/// A corner list shorter than the corners holds sharp corners past its end, so a new point or +/// side count does not give those corners the first corner's radius. +#[test] +fn a_short_corner_list_keeps_its_missing_corners_sharp() { + let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false }; + star.set_points(6); + let mut want = vec![0.0; 12]; + want[0] = 2.0; + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want), "{star:?}"); + let mut polygon = LiveShape::Polygon { radius: 40.0, sides: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false }; + polygon.set_sides(6); + let mut want = vec![0.0; 6]; + want[0] = 2.0; + assert!(matches!(&polygon, LiveShape::Polygon { radii, .. } if *radii == want), "{polygon:?}"); +} + +/// A corner list longer than the corners drops its entries past the old last corner, so the +/// corners a new point count adds are sharp and keep the default kind. +#[test] +fn a_long_corner_list_drops_its_entries_past_the_corners() { + let mut radii = vec![0.0; 12]; + radii[0] = 2.0; + radii[10] = 7.0; + radii[11] = 7.0; + let mut kinds = vec![CornerKind::Round; 12]; + kinds[0] = CornerKind::Chamfer; + kinds[10] = CornerKind::Chamfer; + kinds[11] = CornerKind::Chamfer; + let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii, kinds, radii_relative: false }; + star.set_points(6); + let mut want_radii = vec![0.0; 12]; + want_radii[0] = 2.0; + let mut want_kinds = vec![CornerKind::Round; 12]; + want_kinds[0] = CornerKind::Chamfer; + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want_radii), "{star:?}"); + assert!(matches!(&star, LiveShape::Star { kinds, .. } if *kinds == want_kinds), "{star:?}"); + // A complete list that all corners share still fills the new corners. + let mut star = + LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![3.0; 10], kinds: vec![], radii_relative: false }; + star.set_points(6); + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == vec![3.0; 12]), "{star:?}"); +} + #[test] fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { let close = |a: f64, b: f64| (a - b).abs() < 1e-9; diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 02c4391921..ead201ffab 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -78,7 +78,7 @@ pub struct Selection { } /// See [`Selection::symbol_part`]. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct SymbolPart { /// The symbol instance. pub instance: NodeId, diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 4a8f6a9d71..1bc90a68b0 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -608,3 +608,89 @@ fn node_lookups_copy_no_index_path() { agree(&d, &ids[..200], "after remove_many"); agree(&d, &nested, "nested"); } + +/// Copies of one document that each add the same object, as the previews of a drag do from the document at the press, +/// find that object where a walk finds it. The first copy walks the tree once for it and the later copies do not walk, +/// and [`Document::node`] finds it without copying an index path. +/// A copy that adds the object elsewhere, adds an object below it, groups it or deletes it, and the document they +/// were copied from, still find what a walk finds. A copy that adds it twice finds one node with its id, and +/// [`Document::nodes_in_order`] finds both. +#[test] +fn copies_that_add_an_object_find_it_without_walking_again() { + let (mut base, ids) = squares(2_000); + let layer = base.layers[0].id; + let added = base.alloc_id(); + let new = || Node::path(added, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art()); + base.drop_lookup_cache(); + base.node(layer); + let walks = tree_walks(); + let mut node_copies = 0; + for copy in 0..20 { + let mut d = base.clone(); + d.insert(Some(layer), usize::MAX, new()).unwrap(); + let copies = path_copies(); + assert!(d.node(added).is_some_and(|n| n.id == added), "copy {copy}"); + node_copies += path_copies() - copies; + assert_eq!(d.index_path(added), Some(vec![0, ids.len()]), "copy {copy}"); + assert_eq!(d.index_paths([added, ids[5]]).get(&added), Some(&vec![0, ids.len()]), "copy {copy}"); + assert_eq!(d.ancestry(added), Some(vec![layer, added]), "copy {copy}"); + } + assert_eq!(tree_walks() - walks, 1, "walks of the tree for 20 copies"); + assert_eq!(node_copies, 0, "index paths copied by node for 20 copies"); + + // A copy that adds the object twice: lookups give one node with its id, and nodes_in_order, + // which reads only the table's paths, gives both. + let mut d = base.clone(); + d.insert(Some(layer), usize::MAX, new()).unwrap(); + d.insert(Some(layer), 3, new()).unwrap(); + agree_except(&d, &[added, ids[3], ids[0]], Some(added), "added twice"); + assert_eq!(d.nodes_in_order([ids[7], added]).iter().map(|n| n.id).collect::>(), [added, ids[7], added], "added twice"); + let gone = d.index_path(added).unwrap(); + assert_eq!(d.remove(added).unwrap().id, added); + assert_eq!(d.walk_index_path(added).filter(|p| *p != gone).map(|_| ()), Some(()), "the other one stays"); + assert_eq!(d.layers[0].children().unwrap().len(), ids.len() + 1, "removed one node"); + + // The object lower in the layer, with another object below it, and the next copy back at the top. + let mut d = base.clone(); + d.insert(Some(layer), 10, new()).unwrap(); + agree(&d, &[added, ids[9], ids[10]], "added at 10"); + let below = square(&mut d); + let below = d.insert(Some(layer), 0, below).unwrap(); + agree(&d, &[added, below, ids[9]], "an object below it"); + let mut d = base.clone(); + d.insert(Some(layer), usize::MAX, new()).unwrap(); + agree(&d, &[added], "back at the top"); + + // Grouped with the object below it, then deleted. + let gid = d.alloc_id(); + let members = vec![d.remove(ids[ids.len() - 1]).unwrap(), d.remove(added).unwrap()]; + d.insert(Some(layer), usize::MAX, Node::group(gid, members)).unwrap(); + assert_eq!(d.index_path(added), Some(vec![0, ids.len() - 1, 1])); + agree(&d, &[added, gid, ids[ids.len() - 1]], "grouped"); + d.remove(gid).unwrap(); + assert!(d.node(added).is_none() && d.index_path(added).is_none(), "deleted with its group"); + agree(&d, &[added, gid], "deleted"); + + // The document the copies came from has no such object, and a copy that adds it again finds it. + assert!(base.node(added).is_none() && base.index_path(added).is_none() && base.index_paths([added]).is_empty()); + let mut d = base.clone(); + d.insert(Some(layer), usize::MAX, new()).unwrap(); + agree(&d, &[added, ids[0]], "added again"); +} + +/// Repeated ordered lookups of an added object rebuild the table and then use its cached path. +#[test] +fn ordered_lookups_of_an_added_object_stop_walking() { + let (mut d, _) = squares(2_000); + let layer = d.layers[0].id; + d.drop_lookup_cache(); + d.node(layer); + let new = square(&mut d); + let added = d.insert(Some(layer), usize::MAX, new).unwrap(); + assert!(d.node(added).is_some_and(|n| n.id == added)); + let walks = tree_walks(); + for lookup in 0..20 { + assert_eq!(d.nodes_in_order([added]).iter().map(|n| n.id).collect::>(), [added], "lookup {lookup}"); + } + assert!(tree_walks() - walks <= 5, "walks of the tree for 20 ordered lookups"); +} diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml index e737bc5ad8..679284ff97 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -24,6 +24,11 @@ craft-svg = { workspace = true, features = ["tree-render"] } # The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg). svgtypes = "0.16" serde_json = { workspace = true } +# Render Settings › Rendered: the 3D effects' solids drawn as an image with depth and shadow maps. +craft-raster3d = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +craft-raster3d = { workspace = true, features = ["parallel"] } [dev-dependencies] vectorcraft-color = { workspace = true } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 8138474736..a89005aa21 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -354,7 +354,7 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { if let Some(m) = crate::addons::halftone::halftone_art(d, n) { return Some(bake_pieces(d, m)); } - if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { + if let Some(m) = crate::revolve_art_drawn_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -871,7 +871,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, & /// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and /// effects are dropped. `None` for other kinds of objects. pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option { - if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { + if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -963,7 +963,7 @@ pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option { /// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`]. fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option { - if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) { + if let Some(m) = crate::revolve_art_drawn_in(doc, n).or_else(|| crate::solid_art_drawn_in(doc, n)) { return Some(m); } if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) { diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index c07f3b0413..7a6663b603 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,28 +241,28 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), 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), segments: integer (8..128, 64), 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, and how much it blurs the shadow), 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 shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), 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), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), 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), segments: integer (8..128, 64), 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, and how much it blurs the shadow), 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; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), 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), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"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,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( 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; or custom, a bevel of the user's own drawn by bevelProfile), 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), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), 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, and how much it blurs the shadow), 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 shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), 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 and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{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; or custom, a bevel of the user's own drawn by bevelProfile), 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), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), 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, and how much it blurs the shadow), 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; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), 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 and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. 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":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), 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, and how much it blurs the shadow), 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 shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), 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 puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), 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, and how much it blurs the shadow), 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; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), 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 puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Painted with the top fill (else the top stroke).", json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":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":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( 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, and how much it blurs the shadow), 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 shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), 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), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + "{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, and how much it blurs the shadow), 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; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), 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), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's; rendered mode checks the paint of every fill and stroke)}. 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":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aef398c64e..1b6bd49c85 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -33,6 +33,7 @@ //! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells, //! anchored at the object's centre. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod adjust; @@ -95,16 +96,19 @@ pub use reshape::{ has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ - CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, + CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_drawn_in, revolve_art_in, revolve_options, validate_revolve, + validate_revolve_in, }; +pub use solids::rendered::{rendered_warning, three_d_bounds_art_in}; pub use solids::{ BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic, - MeshGraphics, RENDER, RENDER_MODES, 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, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, - rename_graphic_symbol_in, renders_wireframe, 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, + MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings, + 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, mesh_graphics_art, missing_symbol, + names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, render_settings, rendered, renders_image, renders_wireframe, solid_art, + solid_art_drawn_in, 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, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 9ce14bbf47..ffbecebb17 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -172,8 +172,9 @@ fn highlight_fills(highlight: vectorcraft_three_d::Highlight) -> Vec Option { + use kurbo::{ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Shape}; + let bez = path.to_bezpath(); + let elements = bez.elements(); + if elements.len() > SEAMED_FILL_EDGES + 2 || !elements.iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))) { + return None; + } + let segments: Vec = bez.segments().collect(); + for (i, a) in segments.iter().enumerate() { + let b = &segments[(i + 1) % segments.len()]; + if matches!((a, b), (PathSeg::Line(_), PathSeg::Line(_))) { + continue; + } + let controls = |s: &PathSeg| match s { + PathSeg::Line(s) => vec![s.p0, s.p1], + PathSeg::Quad(s) => vec![s.p0, s.p1, s.p2], + PathSeg::Cubic(s) => vec![s.p0, s.p1, s.p2, s.p3], + }; + let seam = a.end(); + let directions: Vec<_> = controls(a) + .into_iter() + .map(|p| p - seam) + .chain(controls(b).into_iter().map(|p| seam - p)) + .filter(|v| v.hypot() > 0.0) + .map(|v| v / v.hypot()) + .collect(); + let separated = directions.iter().any(|a| { + directions.iter().any(|b| { + let axis = *a + *b; + directions.iter().all(|v| axis.dot(*v) > 1e-12) + }) + }); + if !separated { + return None; + } + } + let mut flat = vectorcraft_geom::BezPath::new(); + let mut overflow = false; + let mut last = kurbo::Point::ZERO; + for el in elements { + if overflow { + break; + } + let from = last; + let controls = match el { + PathEl::QuadTo(a, b) => Some([from, *a, *b, *b]), + PathEl::CurveTo(a, b, c) => Some([from, *a, *b, *c]), + _ => None, + }; + if let Some(controls) = controls { + let length: f64 = controls.windows(2).map(|pair| pair[0].distance(pair[1])).sum(); + if !length.is_finite() + || length > HIGHLIGHT_FLATNESS * vectorcraft_geom::MAX_FLATTEN_PER_CURVE.powi(2) + || controls.iter().any(|p| !(p.x.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH && p.y.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH)) + { + return None; + } + } + last = match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => *p, + PathEl::ClosePath => last, + }; + let curve = match el { + PathEl::QuadTo(a, b) => Some(PathSeg::Quad(kurbo::QuadBez::new(from, *a, *b))), + PathEl::CurveTo(a, b, c) => Some(PathSeg::Cubic(kurbo::CubicBez::new(from, *a, *b, *c))), + _ => None, + }; + // Each curve piece is monotonic in both coordinates before flattening. + let pieces = curve.map_or_else( + || vec![(from, *el)], + |curve| { + curve + .extrema_ranges() + .into_iter() + .map(|range| { + let piece = curve.subsegment(range); + (piece.start(), piece.as_path_el()) + }) + .collect() + }, + ); + for (from, el) in pieces { + if overflow { + break; + } + let start = [PathEl::MoveTo(from)].into_iter().filter(|_| !matches!(el, PathEl::MoveTo(_))); + let mut skip = usize::from(!matches!(el, PathEl::MoveTo(_))); + vectorcraft_geom::flatten(start.chain([el]), HIGHLIGHT_FLATNESS, |e| { + if skip > 0 { + skip -= 1; + } else if flat.elements().len() > SEAMED_FILL_EDGES + 2 { + overflow = true; + } else { + flat.push(e); + } + }); + } + } + if overflow { + return None; + } + // Each flattened edge may be HIGHLIGHT_FLATNESS away from its curve. + seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), seam, 2.0 * HIGHLIGHT_FLATNESS)?; + let fill = footprint(&bez, seam); + (fill.bounding_box().is_finite() && fill.area().abs() >= bez.area().abs()).then(|| vectorcraft_geom::PathData::from_bezpath(&fill)) +} + /// `face`, the art of a face of outline `path` closed by a seam `seam` wide, with `highlight` /// screened over it: a group of the face and the highlight's path on the face and its seam /// ([`highlight_over`]). An opacity mask on the face moves to the group, so it covers the @@ -255,7 +372,13 @@ const SEAMED_FILL_EDGES: usize = 256; /// a seam that is not a positive finite width, or a footprint with no finite bounds or less area /// than the facet. pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option { - use kurbo::{PathEl, Point, Shape}; + seamed_fill_with_clearance(path, seam, 0.0) +} + +/// [`seamed_fill`], also `None` when two edges that are not neighbors come within `clearance` of +/// each other. +fn seamed_fill_with_clearance(path: &vectorcraft_geom::PathData, seam: f64, clearance: f64) -> Option { + use kurbo::{Line, ParamCurveNearest, PathEl, Point, Shape}; if !(seam.is_finite() && seam > 0.0) { return None; } @@ -294,6 +417,19 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio if touch(a, b, c, d) { return None; } + if clearance > 0.0 { + let ab = Line::new(a, b); + let cd = Line::new(c, d); + let distance_sq = ab + .nearest(c, 1e-6) + .distance_sq + .min(ab.nearest(d, 1e-6).distance_sq) + .min(cd.nearest(a, 1e-6).distance_sq) + .min(cd.nearest(b, 1e-6).distance_sq); + if distance_sq <= clearance * clearance { + return None; + } + } } } let fill = footprint(&bez, seam); @@ -690,6 +826,98 @@ mod tests { } } + /// A material's highlight over a curved face reaches its seam too, as the face's clip does, + /// wound one way so a nonzero fill screens it once. A curved face that folds over itself keeps + /// its outline alone. + #[test] + fn a_highlight_over_a_curved_face_covers_its_seam() { + use kurbo::Shape; + let circle = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for path in [circle.clone(), vectorcraft_geom::PathData::from_bezpath(&circle.to_bezpath().reverse_subpaths())] { + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + let Some(shape) = over.path_data() else { panic!("a path") }; + let bez = shape.to_bezpath(); + assert_ne!(bez.winding(Point::new(5.0, 10.4)), 0, "the seam past the bottom edge"); + assert_ne!(bez.winding(Point::new(5.0, 5.0)), 0, "the face"); + assert_eq!(bez.winding(Point::new(5.0, 11.0)), 0, "past the seam"); + assert!(bez.elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count() >= 2); + } + // A curved face that folds over itself keeps its outline alone, as its own nonzero fill. + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.quad_to((5.0, -1.0), (10.0, 10.0)); + folded.line_to((10.0, 0.0)); + folded.quad_to((5.0, 1.0), (0.0, 10.0)); + folded.close_path(); + let folded = vectorcraft_geom::PathData::from_bezpath(&folded); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &folded, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&folded)); + } + + /// A curved face whose fold is smaller than the flattening tolerance, so that its flattened + /// outline does not cross itself, still keeps its outline alone, wound either way. + #[test] + fn a_highlight_over_a_fold_smaller_than_flatness_keeps_its_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.line_to((10.0, 0.0)); + folded.line_to((10.0, 10.0)); + folded.line_to((0.0, 10.0)); + folded.line_to((0.0, 0.01)); + folded.quad_to((5.0, -0.03), (9.0, 0.01)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the fold"); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&path)); + } + } + + /// A face with a collinear cubic that reverses direction keeps its highlight outline. + #[test] + fn a_highlight_over_a_retraced_cubic_keeps_its_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.curve_to((-8.0, 0.0), (-4.0, 0.0), (12.0, 0.0)); + folded.line_to((12.0, 10.0)); + folded.line_to((0.0, 10.0)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the reversal"); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") }; + assert_eq!(over.path_data(), Some(&path)); + } + } + + #[test] + fn a_curved_edge_crossing_its_neighbor_keeps_the_highlight_outline() { + let mut folded = vectorcraft_geom::BezPath::new(); + folded.move_to((0.0, 0.0)); + folded.line_to((1000.0, 1000.0)); + folded.quad_to((500.0, 499.999), (0.0, 0.2)); + folded.line_to((-1000.0, 1000.0)); + folded.line_to((-1000.0, -1000.0)); + folded.close_path(); + let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None }; + for bez in [folded.clone(), folded.reverse_subpaths()] { + let mut flat = vectorcraft_geom::BezPath::new(); + vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el)); + assert!(seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0, 2.0 * HIGHLIGHT_FLATNESS).is_some()); + let path = vectorcraft_geom::PathData::from_bezpath(&bez); + let over = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)).unwrap(); + assert_eq!(over.path_data(), Some(&path)); + } + } + /// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the /// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound /// either way and in a concave notch. A facet whose footprint would gain or lose area under a diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 5d49c52de2..601706a0ca 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -10,7 +10,7 @@ use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; use crate::solids::{ - Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds, + Build, 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}; @@ -845,7 +845,7 @@ pub fn revolve_art(n: &Node) -> Option { /// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be /// resolved. pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { - art(doc, n, false) + art_reporting(doc, n, false, Build::Vector, &mut None) } /// [`expand_revolve_art_in`] without a document. @@ -854,10 +854,11 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option { expand_revolve_art_in(None, n) } -/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared -/// command and UI remain unchanged. +/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]): in +/// Render Settings › Rendered, the rendered image where it can be made. The shared command and UI +/// remain unchanged. pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { - art(doc, n, true) + art_reporting(doc, n, true, Build::Draw, &mut None) } /// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on @@ -918,8 +919,9 @@ fn surface_meshes( graphics: bool, ) -> Result, String> { let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params)); + let projection = Some(vectorcraft_three_d::revolve_mesh_projection(b, options)); surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics) - .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, ..m }).collect()) + .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, projection, ..m }).collect()) } /// [`surface_meshes`] in the default material. @@ -1083,13 +1085,23 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, n: &Node, expand: bool) -> Option { +/// The art [`revolve_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, +/// the image of the lit surface where it can be made, in place of the shaded faces that +/// [`revolve_art_in`] keeps for bounds, hit testing and snapping. +pub fn revolve_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option { + art_reporting(doc, n, false, Build::Draw, &mut None) +} + +/// [`revolve_art_in`], or with `expand` Revolve's Expand Appearance art, built for `build`, with +/// the reason a rendered image can't be made kept in `warning`. +pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option) -> Option { + let check_only = build == Build::Check; if !has_revolve(n) { return None; } let n = &*resolve_for(doc, n, "Revolve", false).ok()?; if is_container(n) { - return group_art(doc, n, expand); + return group_art(doc, n, expand, check_only, warning); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -1103,7 +1115,43 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - if crate::solids::renders_wireframe(fx) { + let p = merged_params(&fx.id, &fx.params); + // Rendered, the surface's image, with the shadows of every light on the surface and on the + // shadow plane; the shaded faces when it can't be made, and for vector measurements. + let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| { + let result = if crate::solids::rendered::reshapes_paths_only(&n.appearance.effects[index + 1..]) { + Err(crate::solids::rendered::PATHS_ONLY.into()) + } else if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) { + let b = path.bounds()?; + let (paint, opacity, _) = paint_of(item); + let options = rule_options(fx, rule); + surface_meshes(&path, rule, b, fx, options, (&paint, opacity, 1.0), true).and_then(|meshes| { + let lighting = crate::solids::rendered::lighting(&fx.id, &p); + let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) { + Some(shadow) => { + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let faces = cast_surface(&mut caster, &path, b, options, None)?; + crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces]) + } + None => lighting, + }; + if build == Build::Bounds { + crate::solids::rendered::bounds_art(doc, n.id, &lighting, &meshes, settings) + } else { + crate::solids::rendered::art(doc, n.id, &lighting, &meshes, settings, check_only) + } + }) + } else { + Err(crate::solids::rendered::OPAQUE_ONLY.into()) + }; + crate::solids::rendered::reported(result, warning) + }); + if check_only { + return None; + } + if let Some(image) = image { + children.push(image); + } else if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of the faces, with no shadow. children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?); } else { @@ -1132,6 +1180,12 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { 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)?; + if crate::renders_image(fx) { + warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into()); + } + if check_only { + continue; + } 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)); if crate::solids::renders_wireframe(fx) { @@ -1284,9 +1338,15 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool { /// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them, /// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when /// the effect is only on the group's own fills or strokes or when its members can't be revolved. -fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { +fn group_art(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option) -> Option { let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?; let fx = n.appearance.effects.get(index)?; + if crate::renders_image(fx) { + warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into()); + } + if check_only { + return None; + } let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); let b = union_bounds(&shapes)?; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 786d3954e4..6a9ddfbbff 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -41,7 +41,12 @@ pub use vectorcraft_three_d::SurfaceKind; pub(crate) mod shadow; pub(crate) mod wireframe; -pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in}; +pub use wireframe::{ + RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, renders_wireframe, + three_d_wireframe_in, +}; + +pub mod rendered; pub(crate) mod material; pub use material::MATERIAL; @@ -1003,6 +1008,17 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, /// fill rule, its shape's scopes and the index of its shape. type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope], usize); +fn solid_items(shape: &Profile) -> impl Iterator { + let top_fill = shape.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); + shape.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| i) +} + +/// The fills and strokes 3D effect `id` draws for `shapes`: every one for Rotate, which draws a +/// plane for each ([`meshes_for`]), and [`solid_items`] for the other effects. +fn drawn_items<'a>(id: &str, shapes: &'a [Profile]) -> Box + 'a> { + if is_plane(id) { Box::new(shapes.iter().flat_map(|s| s.items.iter())) } else { Box::new(shapes.iter().flat_map(solid_items)) } +} + /// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes, /// a group's members from the back up, each with its shape's opacity, the region it paints and its /// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any): @@ -1012,8 +1028,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec>, Rect) { .iter() .enumerate() .flat_map(|(member, s)| { - let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); - s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(move |(_, i)| { + solid_items(s).map(move |i| { let (area, rule) = region(&s.path, s.rule, i); (i, s.opacity, area, rule, s.scopes.as_slice(), member) }) @@ -2053,12 +2068,57 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it /// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every /// surface of the object, and the surfaces. -fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option { +fn art_for( + doc: Option<&Document>, + n: &Node, + effects: &[Effect], + shapes: &[Profile], + build: Build, + warning: &mut Option, +) -> Option { + let (fx, later) = effects.split_first()?; + if build == Build::Check && !crate::renders_image(fx) { + return Some((vec![], vec![])); + } // In wireframe mode the effect draws the edges of the faces it builds, with no shadow. if wireframe::renders_wireframe(fx) { return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?)); } let p = crate::merged_params(&fx.id, &fx.params); + // Rendered, the solids' image, with the shadows of every light on the solids and on the shadow + // plane; the shaded faces when it can't be made, and for vector measurements. + if build != Build::Vector + && let Some(settings) = wireframe::render_settings(&fx.id, &p) + { + let image = if rendered::reshapes_paths_only(later) { + Err(rendered::PATHS_ONLY.into()) + } else if mapped_graphics(&p).is_empty() && rendered::takes(drawn_items(&fx.id, shapes), has_masks(shapes)) { + meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| { + let lighting = rendered::lighting(&fx.id, &p); + let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? { + Some((caster, shadow, cast)) => { + let faces: Vec> = cast.iter().map(|c| c.2.clone()).collect(); + rendered::with_receiver(lighting, &caster, shadow, &faces) + } + None => lighting, + }; + if build == Build::Bounds { + rendered::bounds_art(doc, n.id, &lighting, &meshes, settings) + } else { + rendered::art(doc, n.id, &lighting, &meshes, settings, build == Build::Check) + } + }) + } else { + Err(rendered::OPAQUE_ONLY.into()) + }; + let image = rendered::reported(image, warning); + if build == Build::Check { + return Some((vec![], vec![])); + } + if let Some(image) = image { + return Some((vec![], vec![image])); + } + } let cast = casts_shadow(&fx.id, &p); let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?; // A shadow past the limits draws the source path, as a solid past them does; commands report @@ -2091,10 +2151,20 @@ pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result< /// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to /// the part of the shadow they cast too ([`shadow::scoped_art`]). fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result>, String> { + cast_shadow_with(id, p, shapes, shadow::options(p)) +} + +/// [`cast_shadow`] with the shadow settings `settings` in place of those of `p`. +fn cast_shadow_with<'a>( + id: &str, + p: &Value, + shapes: &'a [Profile], + settings: Option, +) -> Result>, String> { if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE { return Ok(None); } - let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) }; + let (Some(settings), Some(b)) = (settings, union_bounds(shapes)) else { return Ok(None) }; let view = view_options(p); let mut caster = vectorcraft_three_d::ShadowCaster::new(); // The faces each solid of visible art added, with its member's scopes and its ink (opacity @@ -2823,21 +2893,48 @@ pub fn solid_art(n: &Node) -> Option { /// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be /// resolved. pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { + solid_art_reporting(doc, n, Build::Vector, &mut None) +} + +/// The art [`solid_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, the +/// image of the lit solids where it can be made ([`rendered`]), in place of the shaded faces that +/// [`solid_art_in`] keeps for bounds, hit testing and snapping. +pub fn solid_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option { + solid_art_reporting(doc, n, Build::Draw, &mut None) +} + +/// What a 3D effect's art is built for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Build { + /// The vector art: the shaded faces and the vector shadow, in every mode but wireframe. No + /// rendered image is made. + Vector, + /// Painted measurement art, with rendered images represented by their rectangles and no pixels. + Bounds, + /// Only whether the rendered image can be made, with the reason in the warning when it can't: + /// no art and no pixels. + Check, + /// The art drawn and exported: the rendered image where it can be made. + Draw, +} + +pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { if !has_solid(n) { return None; } let n = &*resolve(doc, n, "").ok()?; if is_container(n) { - return group_solid_art(doc, n); + return group_solid_art(doc, n, build, warning); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); let (sources, paints) = solid_paint_sources(n); let mut children = vec![]; let remaining: Vec; - if let Some((index, fx)) = solid(&n.appearance.effects) { + if let Some((index, _)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?; + let (shadow, surfaces) = + art_for(doc, n, &n.appearance.effects[index..], &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?; children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. remaining = past_effect(&n.appearance.effects, index); @@ -2851,9 +2948,16 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { // Every item's shadow goes behind every item's art. let mut shadows = vec![]; for (source, item) in sources.into_iter().zip(&paints) { - if let Some((index, fx)) = solid(item.effects()) { + if let Some((index, _)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item))); - let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; + let (shadow, surfaces) = art_for( + doc, + n, + &item.effects()[index..], + &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], + build, + warning, + )?; let later: Vec = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); let with_later = |mut art: Arc| { Arc::make_mut(&mut art).appearance.effects = later.clone(); @@ -2882,11 +2986,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { /// 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(doc: Option<&Document>, n: &Node) -> Option { - let (index, fx) = solid(&n.appearance.effects)?; +fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { + let (index, _) = 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(doc, n, fx, &shapes)?; + let (shadow, surfaces) = art_for(doc, n, &n.appearance.effects[index..], &shapes, build, warning)?; let children = shadow.into_iter().chain(surfaces).collect(); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); @@ -3195,12 +3299,15 @@ pub struct SolidMesh { /// The surface's Roughness and Metallic ([`MATERIAL`]); [`vectorcraft_three_d::Material::DEFAULT`] /// for the 3D (Classic) effects. pub material: vectorcraft_three_d::Material, + /// The projection that takes the mesh's points to where the effect draws them on the page; + /// `None` when it is not known. + pub projection: Option, } impl SolidMesh { - /// A mesh painted `color`, with no graphics, in the default material. + /// A mesh painted `color`, with no graphics, in the default material, with no projection. pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self { - Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT } + Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT, projection: None } } } @@ -3305,17 +3412,17 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let material = material::of(&fx.id, &p); let mut out = vec![]; // A solid's parts with and without graphics count together against the limit. - let mut keep = |out: &mut Vec, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| { + let mut keep = |out: &mut Vec, (mesh, projection): (Mesh, _), (paint, opacity): (&Paint, f32), bounds: Rect| { split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity)) .into_iter() - .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, ..part }, limit)) + .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, projection, ..part }, limit)) }; if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (paint, opacity, _) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?; + keep(&mut out, vectorcraft_three_d::plane_meshed(&area, rule, b, view)?, (&paint, opacity), b)?; } } return Ok(out); @@ -3352,7 +3459,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) match solid.mesh() { Ok(mesh) => { let (paint, opacity, _) = paint_of(item, *member); - keep(&mut out, mesh, (&paint, opacity), bounds)?; + keep(&mut out, (mesh, solid.projection()), (&paint, opacity), bounds)?; } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} Err(e) => return Err(e), diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs new file mode 100644 index 0000000000..59b425da48 --- /dev/null +++ b/crates/effects/src/solids/rendered.rs @@ -0,0 +1,779 @@ +//! Render Settings › Rendered: the solids of a 3D effect drawn as one image, with a depth buffer, +//! the metallic-roughness shading of every light and the shadows each light casts on the solids, +//! instead of the shaded vector faces. The image lies on the page where the vector faces lie: each +//! mesh point goes through the projection the effect draws its faces with +//! ([`vectorcraft_three_d::MeshProjection`]). +use std::io::Cursor; +use std::sync::Arc; + +use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps}; +use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_three_d::{Light, MeshProjection}; + +use super::SolidMesh; +use super::wireframe::RenderSettings; + +/// The message a rendered image that can't be made is reported with; the effect then draws its +/// shaded faces. +pub const TOO_LARGE: &str = "The 3D render is too large; showing the shaded faces instead"; + +/// The message for a solid painted with something other than an opaque solid color in Normal +/// blending, or with graphics; the effect then draws its shaded faces. +pub const OPAQUE_ONLY: &str = "The 3D render shows opaque solid colors only; showing the shaded faces instead"; + +/// The message for a later geometry effect that reshapes paths but leaves images unchanged. +pub const PATHS_ONLY: &str = "A later effect reshapes the 3D object's paths; showing the shaded faces instead"; + +/// Do any visible effects reshape paths without also reshaping images in `reshape_leaves`? +pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool { + effects.iter().any(|e| { + e.visible + && (crate::is_geometry(&e.id) || crate::is_pathfinder(&e.id)) + && e.id != "distort.transform" + && e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).is_none() + }) +} + +/// The message for Revolve on a group or on a fill or stroke, which draws its shaded faces. +pub const OBJECTS_ONLY: &str = "Revolve renders on a single object only; showing the shaded faces instead"; + +/// Why a visible 3D effect in rendered mode on `n` draws shaded faces instead of an image. +/// Messages are English, to be translated when displayed. `None` when no rendered effect falls back. +pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option { + let rendered = |fx: &vectorcraft_doc::Effect| fx.visible && crate::renders_image(fx); + if !n.appearance.effects.iter().any(rendered) && !n.appearance.items.iter().any(|i| i.effects().iter().any(rendered)) { + return None; + } + let mut warning = None; + if crate::has_revolve(n) { + let _ = crate::revolve::art_reporting(Some(doc), n, false, super::Build::Check, &mut warning); + } else { + let _ = super::solid_art_reporting(Some(doc), n, super::Build::Check, &mut warning); + } + warning +} + +/// The art of `n`'s 3D effect for painted bounds, with rendered images represented by their page +/// rectangles without pixels. Shaded fallback art and later effects keep their normal bounds. +/// This art is for measurement only; selection and snapping use the vector art instead. +pub fn three_d_bounds_art_in(doc: Option<&vectorcraft_doc::Document>, n: &Node) -> Option { + crate::revolve::art_reporting(doc, n, false, super::Build::Bounds, &mut None) + .or_else(|| super::solid_art_reporting(doc, n, super::Build::Bounds, &mut None)) +} + +/// The image rectangle for painted measurements, with the same eligibility and scene limits as +/// the rendered image, without rasterizing or adding an image to the cache. +pub(crate) fn bounds_art( + doc: Option<&vectorcraft_doc::Document>, + id: NodeId, + lighting: &Lighting, + meshes: &[SolidMesh], + settings: RenderSettings, +) -> Result>, String> { + art(doc, id, lighting, meshes, settings, true)?; + let m = measure(meshes, lighting, settings, doc.map_or(72.0, |d| d.raster_ppi()), false, &Limits::default())?; + let object = ImageObject { + key: String::new(), + width: m.cols, + height: m.rows, + xf: Affine::new([m.rect.width() / f64::from(m.cols), 0.0, 0.0, m.rect.height() / f64::from(m.rows), m.rect.x0, m.rect.y0]), + link: None, + placement: Default::default(), + pixels: None, + }; + Ok(Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object)))))) +} + +/// The rendered image of `result`, or `None` after a successful check. An error keeps its message +/// in `warning` when no earlier reason is there; the caller then draws its shaded faces. +pub(crate) fn reported(result: Result>, String>, warning: &mut Option) -> Option> { + match result { + Ok(image) => image, + Err(message) => { + warning.get_or_insert(message); + None + } + } +} + +/// The lights a rendered image is shaded with, as the effect's shaded faces are. +#[derive(Clone, Debug, PartialEq)] +pub struct Lighting { + /// The directional lights ([`vectorcraft_three_d::Revolve::active_lights`]). + pub lights: Vec, + /// Each light's shadow diffusion in points, in the same order as `lights`. + pub diffusion: Vec, + /// The ambient light, 0 to 2. + pub ambient: f64, + /// Shading on: off, the solids show their paint unlit, as the shaded faces do. + pub shade: bool, + /// Shadows on: each light that lights the art casts shadows on the solids and on + /// [`Lighting::receiver`]. Off, no light casts one. + pub shadows: bool, + /// The part of the shadow plane the shadows fall on, as four corners in mesh space (y up), in + /// order round it ([`receiver`]); `None` without one. + pub receiver: Option<[[f64; 3]; 4]>, +} + +impl Lighting { + /// Does light `l` cast shadows in the image: Shading and Shadows are on and it lights the art? + fn casts(&self, l: &Light) -> bool { + self.shade && self.shadows && l.intensity > 0.0 + } +} + +/// The opacity of the black the shadow plane shows where a shadow falls, as the effect's vector +/// shadow paints it. +const PLANE_SHADOW: f32 = 0.5; + +/// How far the shadow plane reaches past the shadows on it, as a share of the solids' largest size, +/// so a soft edge is not cut. VectorCraft's own value. +const PLANE_MARGIN: f64 = 0.05; + +/// `lighting` with the part of the shadow plane the shadows of the faces in `faces` of `caster` +/// fall on, with settings `shadow`, for every light that casts one ([`Lighting::casts`]). +pub(crate) fn with_receiver( + mut lighting: Lighting, + caster: &vectorcraft_three_d::ShadowCaster, + shadow: vectorcraft_three_d::Shadow, + faces: &[std::ops::Range], +) -> Lighting { + let toward: Vec<[f64; 3]> = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.direction()).collect(); + lighting.diffusion = lighting + .lights + .iter() + .map(|l| caster.shadow_blur(vectorcraft_three_d::Shadow { softness: l.softness, ..shadow }, faces).unwrap_or(0.0)) + .collect(); + let softness = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.softness).fold(0.0, f64::max); + let shadow = vectorcraft_three_d::Shadow { softness, ..shadow }; + lighting.receiver = caster.receiver(shadow, faces, &toward, PLANE_MARGIN).map(|q| q.map(|[x, y, z]| [x, -y, z])); + lighting +} + +/// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page, +/// made with `samples` × `samples` samples a pixel. +#[derive(Clone, Debug, PartialEq)] +pub struct Rendered { + pub rect: Rect, + pub cols: u32, + pub rows: u32, + pub samples: u32, + pub pixels: Vec, +} + +/// The margin, as a share of the depth range, the solids' nearest and farthest points keep from the +/// ends of the depth buffer. +const DEPTH_MARGIN: f64 = 0.01; + +/// The largest share of the eye's distance a point may lie in front of the projection origin: at it +/// the vector faces stop growing ([`vectorcraft_three_d::MeshProjection::project`]). +const NEAREST: f64 = 0.999; + +/// The image of `meshes` lit by `lighting`, with `settings`, at the document's raster effects +/// resolution `doc_ppi` when the settings take it, within `limits`. An error ([`TOO_LARGE`]) when a +/// mesh has no projection or a different one, when a point lies at or behind the eye, when the +/// image has more pixels than `limits` allow even at one sample a pixel, or when the rasterizer +/// refuses the scene. `draft` takes one sample a pixel and draft shadow maps, as Low quality does. +pub fn render( + meshes: &[SolidMesh], + lighting: &Lighting, + settings: RenderSettings, + doc_ppi: f64, + draft: bool, + limits: &Limits, +) -> Result { + let too_large = || TOO_LARGE.to_string(); + let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, lighting, settings, doc_ppi, draft, limits)?; + let scale = f64::from(cols * k) / rect.width(); + let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k), scale).ok_or_else(too_large)?; + scene.ssaa = k; + #[cfg(test)] + RASTERIZATIONS.with(|n| n.set(n.get() + 1)); + if scene.lights.iter().any(|l| l.shadow >= 0) { + try_shadow_maps(&mut scene, low, limits).map_err(|_| too_large())?; + } + let (mut image, _) = try_render_cpu(&scene, limits).map_err(|_| too_large())?; + try_encode(&mut image).map_err(|_| too_large())?; + let pixels = image + .data + .iter() + .flat_map(|p| { + let p = if settings.white { [p[0] + 1.0 - p[3], p[1] + 1.0 - p[3], p[2] + 1.0 - p[3], 1.0] } else { *p }; + let a = p[3].clamp(0.0, 1.0); + let straight = |c: f32| if a > 0.0 { (c / a).clamp(0.0, 1.0) } else { 0.0 }; + [straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8) + }) + .collect(); + Ok(Rendered { rect, cols, rows, samples: k, pixels }) +} + +#[cfg(test)] +thread_local! { + /// How many rendered images enter the rasterizing path on this thread. + static RASTERIZATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The projection, clip matrix and raster dimensions within the image's sample budget. +struct Measured { + projection: MeshProjection, + rect: Rect, + z: [f64; 2], + clip: [[f32; 4]; 4], + cols: u32, + rows: u32, + samples: u32, + low: bool, +} + +/// Measure the image of `meshes` and the shadow plane `lighting` places, and choose its samples, +/// without building a scene or producing pixels. +fn measure( + meshes: &[SolidMesh], + lighting: &Lighting, + settings: RenderSettings, + doc_ppi: f64, + draft: bool, + limits: &Limits, +) -> Result { + let too_large = || TOO_LARGE.to_string(); + let projection = meshes.first().and_then(|m| m.projection).ok_or_else(too_large)?; + if meshes.iter().any(|m| m.projection != Some(projection)) { + return Err(too_large()); + } + let (bounds, z) = extent(meshes, receiver(lighting), projection).ok_or_else(too_large)?; + let cell = 72.0 / settings.resolution.unwrap_or(doc_ppi).clamp(1.0, 2400.0); + let (cols, rows) = ((bounds.width() / cell).ceil().max(1.0), (bounds.height() / cell).ceil().max(1.0)); + let pixels = cols * rows; + if pixels.is_nan() || pixels > limits.max_pixels as f64 { + return Err(too_large()); + } + let (cols, rows) = (cols as u32, rows as u32); + let rect = Rect::new(bounds.x0, bounds.y0, bounds.x0 + f64::from(cols) * cell, bounds.y0 + f64::from(rows) * cell); + let low = draft || settings.quality == 0; + let mut k = if low { 1 } else { settings.samples() }; + while k > 1 && pixels * f64::from(k * k) > limits.max_pixels as f64 { + k -= 1; + } + let clip = clip(projection, rect, z).ok_or_else(too_large)?; + Ok(Measured { projection, rect, z, clip, cols, rows, samples: k, low }) +} + +/// Check scene limits without allocating raster or shadow depth buffers. The counts follow +/// craft-raster3d at 2680a3b3fe464c7afa3d260b33a828fa94e12f6d: lib.rs:178-223, +/// scene.rs:242-278,325-328, raster.rs:245-281,307-385,740-747 and +/// shadow.rs:109-135,262-276,316-356,413-449,500-515,533-538,576-657. +/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque, visible +/// materials, the plane's two triangles hold no texture and the lights are directional, so each +/// source triangle contributes one bounding box, without clipping or an alpha-discard search. Raster and shadow work have separate budgets, as in the renderer. +fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> { + let m = measure(meshes, lighting, settings, ppi, false, limits)?; + let size = (m.cols * m.samples, m.rows * m.samples); + let s = scene(meshes, lighting, m.projection, m.z, m.clip, size, f64::from(size.0) / m.rect.width()).ok_or(TOO_LARGE)?; + limits.check(s.width, s.height).map_err(|_| TOO_LARGE)?; + if s.indices.len() as u64 / 3 > limits.max_triangles || s.vertices.len() as u64 > limits.max_vertices || s.lights.len() > limits.max_lights { + return Err(TOO_LARGE.into()); + } + let transform = + |matrix: &[[f32; 4]], p: [f32; 3], row: usize| matrix[row][0] * p[0] + matrix[row][1] * p[1] + matrix[row][2] * p[2] + matrix[row][3]; + let mut work = 0u64; + for tri in s.indices.as_chunks::<3>().0 { + let mut points = [[0.0; 2]; 3]; + for (point, &i) in points.iter_mut().zip(tri) { + let p = s.vertices[i as usize].pos; + let c = [0, 1, 2, 3].map(|r| transform(&s.clip, p, r)); + // Refuse transforms whose rounding escapes the measured clip volume. + if !c.iter().all(|v| v.is_finite()) || c[3] <= 0.0 || c[2] < 0.0 || c[2] > c[3] { + return Err(TOO_LARGE.into()); + } + let iw = 1.0 / c[3]; + *point = [(f64::from(c[0] * iw) + 1.0) * 0.5 * f64::from(s.width), (1.0 - f64::from(c[1] * iw)) * 0.5 * f64::from(s.height)]; + } + let area = (0..3).map(|i| points[i][0] * points[(i + 1) % 3][1] - points[(i + 1) % 3][0] * points[i][1]).sum::(); + if !area.is_finite() { + return Err(TOO_LARGE.into()); + } + if area != 0.0 { + let pixels = bounding_work(points, [s.width, s.height]); + if pixels > 0 { + work = work.saturating_add(pixels + 1); + } + } + if work > limits.max_work { + return Err(TOO_LARGE.into()); + } + } + // Shadow maps are made only for the lights that cast shadows, from the triangles that cast them. + let casters: Vec<&[u32; 3]> = s + .indices + .as_chunks::<3>() + .0 + .iter() + .filter(|t| s.materials.get(s.vertices[t[0] as usize].material as usize).is_some_and(|m| m.casts_shadows)) + .collect(); + if casters.is_empty() || s.lights.iter().all(|l| l.shadow < 0) { + return Ok(()); + } + let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); + for v in &s.vertices { + for k in 0..3 { + lo[k] = lo[k].min(f64::from(v.pos[k])); + hi[k] = hi[k].max(f64::from(v.pos[k])); + } + } + let center = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5); + let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0; + let kinds: Vec = s.lights.iter().map(|l| u32::from(l.shadow >= 0)).chain(std::iter::once(0)).collect(); + let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &kinds); + let maps = sizes.iter().flatten().count() as u64; + if maps.saturating_mul(casters.len() as u64) > limits.max_work { + return Err(TOO_LARGE.into()); + } + let mut work = 0u64; + for (light, size) in s.lights.iter().zip(sizes) { + let (Some(size), true) = (size, light.shadow >= 0) else { continue }; + let dir = light.dir.map(f64::from); + let eye = [0, 1, 2].map(|k| center[k] - dir[k] * radius * 2.0); + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let unit = |v: [f64; 3]| v.map(|x| x / dot(v, v).sqrt()); + let forward = unit(dir); + let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }; + let down = unit([0, 1, 2].map(|k| hint[k] - forward[k] * dot(hint, forward))); + let right = unit([ + down[1] * forward[2] - down[2] * forward[1], + down[2] * forward[0] - down[0] * forward[2], + down[0] * forward[1] - down[1] * forward[0], + ]); + let view = [right, down].map(|row| [row[0] as f32, row[1] as f32, row[2] as f32, (-dot(row, eye)) as f32]); + let focal = (f64::from(size) * 0.5 / radius) as f32; + for tri in &casters { + let points = [0, 1, 2].map(|k| { + let p = s.vertices[tri[k] as usize].pos; + [0, 1].map(|r| f64::from(transform(&view, p, r) * focal + size as f32 * 0.5)) + }); + let [a, b, c] = points; + let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + if !area.is_finite() { + return Err(TOO_LARGE.into()); + } + let texels = if area.abs() < 1e-12 { 0 } else { bounding_work(points, [size; 2]) }; + work = work.saturating_add(texels + 1); + if work > limits.max_work { + return Err(TOO_LARGE.into()); + } + } + } + Ok(()) +} + +/// The pixels inside a triangle's bounding box, clamped to the raster. +fn bounding_work(points: [[f64; 2]; 3], size: [u32; 2]) -> u64 { + [0, 1] + .map(|k| { + let lo = points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min).floor().clamp(0.0, f64::from(size[k])) as u64; + let hi = points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max).ceil().clamp(0.0, f64::from(size[k])) as u64; + hi.saturating_sub(lo) + }) + .into_iter() + .product() +} + +/// The corners of the shadow plane of `lighting`, in mesh space; none without one. +fn receiver(lighting: &Lighting) -> &[[f64; 3]] { + lighting.receiver.as_ref().map_or(&[], |q| q.as_slice()) +} + +/// The page bounds the points of `meshes` and the shadow plane's corners `plane` project to, and +/// the range of their depths. `None` with no mesh point, a point that isn't finite, or one at or +/// behind the eye. +fn extent(meshes: &[SolidMesh], plane: &[[f64; 3]], projection: MeshProjection) -> Option<(Rect, [f64; 2])> { + let mut bounds: Option = None; + let mut z = [f64::INFINITY, f64::NEG_INFINITY]; + meshes.iter().flat_map(|m| &m.mesh.positions).next()?; + for p in meshes.iter().flat_map(|m| &m.mesh.positions).chain(plane) { + if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) { + return None; + } + let at = projection.project(*p); + let r = Rect::from_points(at, at); + bounds = Some(bounds.map_or(r, |b| b.union(r))); + z = [z[0].min(p[2]), z[1].max(p[2])]; + } + bounds.filter(|b| b.width().is_finite() && b.height().is_finite()).map(|b| (b, z)) +} + +/// The row-major clip matrix that takes a point of the solids' world space (mesh space with y down, +/// about the projection origin) to the image `rect` as [`MeshProjection::project`] places it, with +/// depths `z` kept inside the depth buffer and nearer points deeper in it. `None` when no depth +/// mapping keeps them in order. +fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4]; 4]> { + let (rw, rh) = (rect.width(), rect.height()); + let a = 2.0 * (projection.origin.x - rect.x0) / rw - 1.0; + let b = 1.0 - 2.0 * (projection.origin.y - rect.y0) / rh; + // w = 1 − z / eye without perspective's eye: 1. + let inv_eye = projection.eye.map_or(0.0, |e| 1.0 / e); + let (z0, z1) = if z[1] > z[0] { (z[0], z[1]) } else { (z[0] - 0.5, z[0] + 0.5) }; + let w = |z: f64| 1.0 - z * inv_eye; + // ndc depth (dz · z + d0) / w: the farthest at DEPTH_MARGIN, the nearest at 1 − DEPTH_MARGIN. + // With w positive over [z0, z1] the ndc depth is a linear-fractional function of z, so it rises + // monotonically between those two ends even when dz itself is negative (a near eye). + let (w0, w1) = (w(z0), w(z1)); + if !(w0 > 0.0 && w1 > 0.0) { + return None; + } + let (lo, hi) = (DEPTH_MARGIN * w0, (1.0 - DEPTH_MARGIN) * w1); + let dz = (hi - lo) / (z1 - z0); + let d0 = lo - dz * z0; + if !(dz.is_finite() && d0.is_finite() && hi / w1 > lo / w0) { + return None; + } + let m = [[2.0 / rw, 0.0, -a * inv_eye, a], [0.0, -2.0 / rh, -b * inv_eye, b], [0.0, 0.0, dz, d0], [0.0, 0.0, -inv_eye, 1.0]]; + let m = m.map(|row| row.map(|v| v as f32)); + m.iter().flatten().all(|v| v.is_finite()).then_some(m) +} + +/// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: every triangle in world +/// space (mesh space with y down, as the page is), opaque ones first, then +/// those of see-through solids from back to front; one material for each mesh; one parallel light, +/// casting shadows, for each of `lighting`'s lights. `scale` is raster pixels per point, including +/// the samples per image pixel. +fn scene( + meshes: &[SolidMesh], + lighting: &Lighting, + projection: MeshProjection, + z: [f64; 2], + clip: [[f32; 4]; 4], + size: (u32, u32), + scale: f64, +) -> Option { + let eye = projection.eye.unwrap_or(z[1] + 1.0); + let mut vertices = vec![]; + let mut opaque: Vec<[u32; 3]> = vec![]; + let mut clear: Vec<([u32; 3], f64)> = vec![]; + let mut materials = vec![]; + for (index, m) in meshes.iter().enumerate() { + let [r, g, b, alpha] = m.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 }); + materials.push(craft_raster3d::Material { + base: [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), 1.0], + metallic: m.material.metallic() as f32, + roughness: m.material.roughness() as f32, + opacity: alpha, + double_sided: true, + unlit: !lighting.shade, + casts_shadows: true, + ..Default::default() + }); + let base = vertices.len() as u32; + let mesh = &m.mesh; + for (i, p) in mesh.positions.iter().enumerate() { + let n = mesh.normals.get(i).copied().unwrap_or([0.0, 0.0, 1.0]); + vertices.push(Vertex { + pos: [p[0] as f32, -p[1] as f32, p[2] as f32], + normal: [n[0] as f32, -n[1] as f32, n[2] as f32], + uv: mesh.uvs.get(i).map_or([0.0; 2], |uv| [uv[0] as f32, uv[1] as f32]), + tangent: [1.0, 0.0, 0.0, 1.0], + material: index as u32, + }); + } + for t in &mesh.triangles { + if t.iter().any(|&i| i as usize >= mesh.positions.len()) { + return None; + } + let tri = t.map(|i| base + i); + if alpha >= 1.0 { + opaque.push(tri); + } else { + let depth = t.iter().map(|&i| mesh.positions[i as usize][2]).sum::() / 3.0; + clear.push((tri, depth)); + } + } + } + clear.sort_by(|a, b| a.1.total_cmp(&b.1)); + // The shadow plane: drawn only where a shadow falls on it, black at the vector shadow's + // opacity, behind every surface, so first in the see-through range. + let mut plane = vec![]; + if let Some(q) = lighting.receiver.filter(|_| lighting.shade && lighting.shadows) { + let edge = |a: [f64; 3], b: [f64; 3]| [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let (e1, e2) = (edge(q[0], q[1]), edge(q[0], q[3])); + let n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + if len.is_finite() && len > 0.0 { + let material = materials.len() as u32; + materials.push(craft_raster3d::Material { + base: [0.0, 0.0, 0.0, 1.0], + opacity: PLANE_SHADOW, + double_sided: true, + shadows_only: true, + receives_shadows: true, + casts_shadows: false, + ..Default::default() + }); + let base = vertices.len() as u32; + for p in q { + vertices.push(Vertex { + pos: [p[0] as f32, -p[1] as f32, p[2] as f32], + normal: [(n[0] / len) as f32, (-n[1] / len) as f32, (n[2] / len) as f32], + uv: [0.0; 2], + tangent: [1.0, 0.0, 0.0, 1.0], + material, + }); + } + plane = vec![[base, base + 1, base + 2], [base, base + 2, base + 3]]; + } + } + // Later meshes paint over earlier ones in the shaded faces. Submit their opaque triangles + // first so the strict depth test keeps that paint when surfaces share a depth. + let opaque_count = (opaque.len() * 3) as u32; + let indices = opaque.into_iter().rev().flatten().chain(plane.into_iter().flatten()).chain(clear.into_iter().flat_map(|(t, _)| t)).collect(); + let lights = lighting + .lights + .iter() + .enumerate() + .filter(|_| lighting.shade) + .map(|(i, l)| { + // The direction the light travels: away from it. + let [x, y, z] = l.direction().map(|v| -v); + let len = (x * x + y * y + z * z).sqrt(); + craft_raster3d::Light { + kind: 0, + pos: [0.0; 3], + dir: [(x / len) as f32, (y / len) as f32, (z / len) as f32], + color: l.color.map(|c| srgb_to_linear((c * l.intensity).clamp(0.0, 1.0) as f32)), + cos_inner: 1.0, + cos_outer: 1.0, + falloff: 0, + radius: 0.0, + falloff_distance: 0.0, + // With Shadows off no light casts one, on the solids or on a plane. + shadow: if lighting.casts(l) { 0 } else { -1 }, + shadow_darkness: 1.0, + shadow_diffusion: lighting.diffusion.get(i).map_or(l.softness, |blur| blur * scale) as f32, + } + }) + .collect(); + // Ambient light up to 100% goes through the sRGB curve; above it, the linear value scales with + // the intensity, as the shaded faces' ambient term does. + let ambient = lighting.ambient.clamp(0.0, 2.0) as f32; + let ambient = srgb_to_linear(ambient.min(1.0)) * ambient.max(1.0); + Some(Scene { + width: size.0, + height: size.1, + ssaa: 1, + clip, + // Camera depth: the distance in front of the eye, on the z axis. + view: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, eye as f32], [0.0, 0.0, 0.0, 1.0]], + eye: [0.0, 0.0, eye as f32], + cam_fwd: [0.0, 0.0, -1.0], + ortho: projection.eye.is_none(), + vertices, + indices, + opaque_count, + // Read only by the renderers with auxiliary outputs, which this one does not use. + part_ids: vec![], + materials, + textures: vec![], + texels: vec![], + lights, + shadows: vec![], + shadow_texels: vec![], + env: None, + ambient: [ambient; 3], + linear_io: false, + }) +} + +/// `image` as an image object of `id`'s art, holding its pixels as a PNG; `None` when it can't be +/// encoded. +pub fn image_node(id: NodeId, image: &Rendered) -> Option> { + Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(image_object(image)?))))) +} + +/// `image` as an image object holding its pixels as a PNG; `None` when it can't be encoded. +fn image_object(image: &Rendered) -> Option { + let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?; + let mut png = vec![]; + raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + let blob = ImageBlob::png(png); + let cell = image.rect.width() / f64::from(image.cols); + Some(ImageObject { + key: blob.content_key(), + width: image.cols, + height: image.rows, + xf: Affine::new([cell, 0.0, 0.0, image.rect.height() / f64::from(image.rows), image.rect.x0, image.rect.y0]), + link: None, + placement: Default::default(), + pixels: Some(Arc::new(blob)), + }) +} + +/// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with +/// the raster effects resolution of `doc` (72 ppi without one). An error when it can't be made: the +/// effect then draws its shaded faces. With `check_only`, validate the colors and scene limits +/// without producing pixels, returning `Ok(None)` when it fits. +pub(crate) fn art( + doc: Option<&vectorcraft_doc::Document>, + id: NodeId, + lighting: &Lighting, + meshes: &[SolidMesh], + settings: RenderSettings, + check_only: bool, +) -> Result>, String> { + // Mapped graphics and see-through solids keep their shaded faces, which draw the graphics and + // apply a solid's opacity once to the whole surface. + if meshes.iter().any(|m| m.graphics.is_some() || m.color[3].is_nan() || m.color[3] < 1.0) { + return Err(OPAQUE_ONLY.into()); + } + let ppi = doc.map_or(72.0, |d| d.raster_ppi()); + if check_only { + check(meshes, lighting, settings, ppi, &Limits::default())?; + return Ok(None); + } + let key = image_key(meshes, lighting, settings, ppi); + let made = match cached(key) { + Some(made) => made, + None => { + let made = render(meshes, lighting, settings, ppi, false, &Limits::default()) + .and_then(|image| image_object(&image).ok_or_else(|| TOO_LARGE.to_string())); + keep(key, &made); + made + } + }; + made.map(|object| Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object)))))) +} + +/// Most rendered images [`art`] keeps for reuse, and most PNG bytes they hold together. VectorCraft's +/// own values. +const KEPT_IMAGES: usize = 32; +const KEPT_BYTES: usize = 64 << 20; + +/// What [`art`] made, newest last, under the key of what it was made from ([`image_key`]). +type Kept = Vec<(u128, Result)>; + +#[cfg(not(test))] +static KEPT: std::sync::Mutex = std::sync::Mutex::new(Vec::new()); + +#[cfg(test)] +thread_local! { + /// Each test thread keeps its own images, so a test's count of rasterizations doesn't depend on + /// what other tests drew. + static KEPT: std::cell::RefCell = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Run `f` on the kept images; `None` when they can't be reached. +fn with_kept(f: impl FnOnce(&mut Kept) -> T) -> Option { + #[cfg(not(test))] + { + KEPT.lock().ok().map(|mut kept| f(&mut kept)) + } + #[cfg(test)] + { + KEPT.with(|kept| kept.try_borrow_mut().ok().map(|mut kept| f(&mut kept))) + } +} + +/// The image kept under `key`, moved to the newest place. +fn cached(key: u128) -> Option> { + with_kept(|kept| { + let at = kept.iter().position(|(k, _)| *k == key)?; + let entry = kept.remove(at); + let made = entry.1.clone(); + kept.push(entry); + Some(made) + }) + .flatten() +} + +/// Keep `made` under `key`, letting the oldest go past [`KEPT_IMAGES`] or [`KEPT_BYTES`]. +fn keep(key: u128, made: &Result) { + let bytes = |m: &Result| m.as_ref().ok().and_then(|o| o.pixels.as_ref()).map_or(0, |b| b.bytes.len()); + if bytes(made) > KEPT_BYTES { + return; + } + with_kept(|kept| { + kept.retain(|(k, _)| *k != key); + kept.push((key, made.clone())); + while kept.len() > KEPT_IMAGES || kept.iter().map(|(_, m)| bytes(m)).sum::() > KEPT_BYTES { + drop(kept.remove(0)); + } + }); +} + +/// A 128-bit hash of everything a rendered image is made from: every mesh's points, normals, +/// texture coordinates, triangles, color, material and projection, the lights, ambient light, +/// shading, shadows and shadow plane, the render settings and the resolution. Moving, turning or +/// reshaping the object, or changing any setting, changes it; panning and redrawing do not. +fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64) -> u128 { + use std::hash::{Hash, Hasher}; + let half = |seed: u8| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + seed.hash(&mut h); + let mut f = |v: f64| v.to_bits().hash(&mut h); + for m in meshes { + let mesh = &m.mesh; + mesh.positions.iter().chain(&mesh.normals).flatten().for_each(|v| f(*v)); + mesh.uvs.iter().flatten().for_each(|v| f(*v)); + m.color.iter().for_each(|c| f(f64::from(*c))); + f(m.material.roughness()); + f(m.material.metallic()); + if let Some(p) = m.projection { + [p.origin.x, p.origin.y, p.eye.unwrap_or(f64::NAN)].into_iter().for_each(&mut f); + } + f(mesh.positions.len() as f64); + f(mesh.triangles.len() as f64); + } + for l in &lighting.lights { + [l.rotation, l.height, l.intensity, l.softness, f64::from(u8::from(l.behind))].into_iter().chain(l.color).for_each(&mut f); + } + lighting.receiver.iter().flatten().flatten().for_each(|v| f(*v)); + lighting.diffusion.iter().for_each(|v| f(*v)); + f(lighting.diffusion.len() as f64); + [lighting.ambient, f64::from(u8::from(lighting.shade)), f64::from(u8::from(lighting.shadows)), lighting.lights.len() as f64] + .into_iter() + .for_each(&mut f); + [settings.quality as f64, settings.resolution.unwrap_or(f64::NAN), f64::from(u8::from(settings.white)), ppi].into_iter().for_each(&mut f); + for m in meshes { + m.mesh.triangles.hash(&mut h); + } + h.finish() + }; + (u128::from(half(1)) << 64) | u128::from(half(2)) +} + +/// Can the solids of `items` be drawn as a rendered image: is each painted with a solid color (or +/// nothing) in Normal blending, with no member's opacity mask or blending mode applying to them +/// (`masked`)? Otherwise the effect draws its shaded faces, which keep gradients, patterns, mapped +/// graphics, masks and blending. +pub(crate) fn takes<'a>(items: impl IntoIterator, masked: bool) -> bool { + use vectorcraft_doc::AppearanceItem; + use vectorcraft_doc::color::Paint; + !masked + && items.into_iter().all(|i| match i { + AppearanceItem::Fill(f) => matches!(f.paint, Paint::Solid { .. } | Paint::None) && f.blend == Default::default(), + AppearanceItem::Stroke(s) => matches!(s.paint, Paint::Solid { .. } | Paint::None) && s.blend == Default::default(), + }) +} + +/// The lights a 3D effect with parameters `p` shades its faces with: Revolve's ([`crate::revolve_options`]) +/// for Revolve, the other effects' ([`super::view_options`]) otherwise. +pub(crate) fn lighting(id: &str, p: &serde_json::Value) -> Lighting { + let (lights, ambient, shade) = if id == crate::REVOLVE { + let o = crate::revolve_options(p); + (o.active_lights(), o.ambient, o.shade) + } else { + let v = super::view_options(p); + (v.active_lights(), v.ambient, v.shade) + }; + let lit = lights.iter().any(|l| l.intensity > 0.0); + let shadows = super::shadow::rendered_options(p, lit).is_some(); + Lighting { lights, diffusion: vec![], ambient, shade, shadows, receiver: None } +} + +/// The shadow settings a rendered image of a 3D effect with parameters `p` and lights `lighting` +/// draws its shadow plane with; `None` with Shadows off or no light lighting the art. +pub(crate) fn plane_settings(p: &serde_json::Value, lighting: &Lighting) -> Option { + super::shadow::rendered_options(p, lighting.lights.iter().any(|l| l.intensity > 0.0)) +} + +#[cfg(test)] +#[path = "rendered/tests.rs"] +mod tests; diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs new file mode 100644 index 0000000000..403991b6ca --- /dev/null +++ b/crates/effects/src/solids/rendered/tests.rs @@ -0,0 +1,1114 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, 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 100 pt square filled `color`, with effect `id` and `params`. +fn solid_square(id: &str, color: Color, params: Value) -> Node { + let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(color), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + n +} + +/// The art the canvas draws for `n`: Revolve's, else the other 3D effects'. +fn drawn(n: &Node) -> Node { + crate::revolve_art_drawn_in(None, n).or_else(|| super::super::solid_art_drawn_in(None, n)).unwrap_or_else(|| panic!("no art for {n:?}")) +} + +/// The image objects in `art`. +fn images(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |c| { + if let NodeKind::Image(i) = &c.kind { + out.push((**i).clone()); + } + }); + out +} + +/// The bounds of every filled path in `art`. +fn faces_bounds(art: &Node) -> Option { + let mut out: Option = None; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + out = Some(out.map_or(b, |o| o.union(b))); + } + }); + out +} + +/// The straight-alpha RGBA8 pixel at column `x`, row `y` of `image`. +fn pixel(image: &Rendered, x: u32, y: u32) -> [u8; 4] { + let i = 4 * (y * image.cols + x) as usize; + [image.pixels[i], image.pixels[i + 1], image.pixels[i + 2], image.pixels[i + 3]] +} + +/// The meshes and lights of `n`'s 3D effect, as the rendered image takes them. +fn scene_of(n: &Node) -> (Vec, Lighting) { + let fx = &n.appearance.effects[0]; + let p = crate::merged_params(&fx.id, &fx.params); + (crate::three_d_meshes(n).unwrap(), lighting(&fx.id, &p)) +} + +const MEDIUM: RenderSettings = RenderSettings { quality: 1, resolution: None, white: false }; + +const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, super::super::ROTATE]; + +#[test] +fn rendered_eligibility_ignores_fills_below_the_top_fill() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, super::super::INFLATE] { + let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new( + Gradient::new(GradientKind::Linear, stops), + ))))); + n.appearance.items.insert(0, lower); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + n.appearance.items.swap(0, 1); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "{id}"); + assert!(images(&drawn(&n)).is_empty(), "{id}"); + } +} + +/// Rotate draws a plane for every fill and stroke, so a gradient fill below the top fill keeps it +/// from rendering, as a gradient top fill does. +#[test] +fn rotate_rendered_eligibility_checks_every_fill() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + assert_eq!(crate::rendered_warning(&doc, &n), None); + assert_eq!(images(&drawn(&n)).len(), 1); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + stops, + )))))); + for at in [0, 1] { + let mut n = n.clone(); + n.appearance.items.insert(at, lower.clone()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "gradient fill at {at}"); + assert!(images(&drawn(&n)).is_empty(), "gradient fill at {at}"); + } +} + +#[test] +fn later_pathfinder_uses_shaded_faces_and_reports_the_fallback() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + n.appearance.effects.push(crate::new_effect("pathfinder.add", &json!({})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(PATHS_ONLY), "{id}"); + assert!(images(&drawn(&n)).is_empty(), "{id}"); + assert!(faces_bounds(&drawn(&n)).is_some(), "{id}"); + n.appearance.effects[1].visible = false; + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + } +} + +/// The projection each mesh carries takes its points onto the page where the vector faces of the +/// same solid lie: every corner of every facet is a projected mesh point, with and without +/// perspective. +#[test] +fn projected_mesh_points_land_on_the_facets() { + for perspective in [0.0, 60.0] { + let path = square(100.0, 100.0, 100.0); + let b = path.bounds().unwrap(); + let view = vectorcraft_three_d::View { perspective, ..Default::default() }; + let solid = vectorcraft_three_d::extrude_meshed(&path, FillRule::NonZero, b, Default::default(), view).unwrap(); + let projection = solid.projection().unwrap(); + let points: Vec = solid.mesh().unwrap().positions.iter().map(|p| projection.project(*p)).collect(); + let corners: Vec = solid.facets.iter().flat_map(|f| f.contours.iter().flatten().copied()).collect(); + assert!(!corners.is_empty()); + for c in corners { + let near = points.iter().map(|p| p.distance(c)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "perspective {perspective}: facet corner {c:?} is {near} pt from every projected mesh point"); + } + } +} + +/// Rendered, each of the panel's four effects draws one image in place of its shaded faces, over +/// the area the shaded faces cover: at most one pixel larger on each side. +#[test] +fn rendered_mode_draws_one_image_over_the_shaded_faces() { + for id in FOUR { + let shaded = faces_bounds(&drawn(&solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({})))).unwrap(); + let art = drawn(&solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}}))); + let list = images(&art); + assert_eq!(list.len(), 1, "{id}"); + assert!(faces_bounds(&art).is_none(), "{id}: the shaded faces are drawn too"); + let i = &list[0]; + let rect = Rect::new(i.xf.as_coeffs()[4], i.xf.as_coeffs()[5], 0.0, 0.0); + let (x0, y0) = (rect.x0, rect.y0); + let (x1, y1) = (x0 + f64::from(i.width) * i.xf.as_coeffs()[0], y0 + f64::from(i.height) * i.xf.as_coeffs()[3]); + // At 72 ppi one pixel is one point. + for (got, want, grows) in [(x0, shaded.x0, false), (y0, shaded.y0, false), (x1, shaded.x1, true), (y1, shaded.y1, true)] { + let off = if grows { got - want } else { want - got }; + assert!((-1e-6..=1.0 + 1e-6).contains(&off), "{id}: image edge {got} against the faces' {want}"); + } + } +} + +/// Later path deformations keep shaded faces for drawing and bounds and report the fallback. +/// Hidden deformations, Gaussian Blur, Transform and Warp keep the rendered image. +#[test] +fn later_geometry_keeps_shaded_faces_only_when_images_cannot_take_it() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + n.appearance.effects.push(crate::new_effect("distort.puckerBloat", &json!({"amount": 20.0})).unwrap()); + let art = drawn(&n); + assert!(images(&art).is_empty(), "{id}"); + assert!(faces_bounds(&art).is_some(), "{id}"); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(PATHS_ONLY), "{id}"); + let measured = crate::three_d_bounds_art_in(Some(&doc), &n).unwrap(); + assert!(images(&measured).is_empty(), "{id}: bounds use shaded faces"); + assert!(faces_bounds(&measured).is_some(), "{id}"); + + n.appearance.effects[1].visible = false; + assert_eq!(images(&drawn(&n)).len(), 1, "{id}: hidden deformation"); + assert!(crate::rendered_warning(&doc, &n).is_none(), "{id}"); + for (later, params) in + [("blur.gaussian", json!({"radius": 5.0})), ("distort.transform", json!({"moveH": 10.0})), ("warp.arc", json!({"bend": 20.0}))] + { + n.appearance.effects[1] = crate::new_effect(later, ¶ms).unwrap(); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}: {later}"); + assert!(crate::rendered_warning(&doc, &n).is_none(), "{id}: {later}"); + } + } +} + +/// With ambient light alone at 100 %, the rendered surface shows its paint unchanged, as the shaded +/// faces do (brightness 1 times the paint); with no light at all it is black, as they are. +#[test] +fn ambient_light_alone_shows_the_paint_as_the_shaded_faces_do() { + let paint = Color::rgb(0.2, 0.5, 0.8); + for (ambient, want) in [(100.0, [51u8, 128, 204]), (0.0, [0, 0, 0])] { + let n = solid_square( + super::super::ROTATE, + paint, + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightIntensity": 0, "ambient": ambient}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + for c in 0..3 { + assert!(center[c].abs_diff(want[c]) <= 1, "ambient {ambient}: {center:?} against {want:?}"); + } + assert_eq!(center[3], 255); + } +} + +#[test] +fn coplanar_opaque_paints_keep_the_shaded_faces_order() { + use vectorcraft_doc::{AppearanceItem, FillLayer}; + + let lower = Color::rgb(0.8, 0.2, 0.1); + let upper = Color::rgb(0.1, 0.3, 0.9); + let params = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false, "render": {"mode": "rendered"}}); + let mut fills = solid_square(super::super::ROTATE, lower, params.clone()); + fills.appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(upper)))); + let mut group = Node::group( + NodeId(3), + vec![ + Arc::new(Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(lower), Paint::None, 0.0))), + Arc::new(Node::path(NodeId(2), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(upper), Paint::None, 0.0))), + ], + ); + group.appearance.effects.push(crate::new_effect(super::super::ROTATE, ¶ms).unwrap()); + for n in [fills, group] { + let mut shaded = n.clone(); + shaded.appearance.effects[0].params["render"]["mode"] = json!("shaded"); + let mut top = None; + drawn(&shaded).walk(&mut |face| { + if face.path_data().is_some() { + for item in &face.appearance.items { + if let AppearanceItem::Fill(f) = item { + top = f.paint.color(); + } + } + } + }); + assert_eq!(top, Some(upper)); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + let want = top.unwrap().to_rgb().map(|c| (c * 255.0).round() as u8); + assert!(center[..3].iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 1), "{center:?} against {want:?}"); + assert_eq!(center[3], 255); + } +} + +#[test] +fn side_mapped_graphics_draw_the_shaded_faces_and_report_the_fallback() { + let mut doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mark = Node::path(NodeId(0), square(0.0, 0.0, 10.0), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) }); + let n = solid_square( + super::super::EXTRUDE, + Color::rgb(0.5, 0.5, 0.5), + json!({ + "rotationX": -90, "rotationY": 0, "rotationZ": 0, "shade": false, + "graphics": [{"symbol": "Mark", "face": "side"}], "render": {"mode": "rendered"} + }), + ); + let art = super::super::solid_art_drawn_in(Some(&doc), &n).unwrap(); + assert!(images(&art).is_empty()); + assert!(faces_bounds(&art).is_some()); + let mut graphic_drawn = false; + art.walk(&mut |face| { + graphic_drawn |= face + .appearance + .items + .iter() + .any(|item| matches!(item, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint.color() == Some(Color::rgb(1.0, 0.0, 0.0)))); + }); + assert!(graphic_drawn); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY)); +} + +/// Ambient intensity retains the upper half of its range even where no directional light falls. +#[test] +fn ambient_200_percent_is_brighter_than_100_percent() { + let level = |ambient| { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.2, 0.3, 0.4), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightIntensity": 0, "ambient": ambient}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + pixel(&image, image.cols / 2, image.rows / 2) + }; + let (normal, bright) = (level(100.0), level(200.0)); + assert_eq!(normal[3], 255); + assert_eq!(bright[3], 255); + for c in 0..3 { + assert!(bright[c] > normal[c] + 10, "channel {c}: 100% {normal:?}, 200% {bright:?}"); + } +} + +/// An extruded U under a light from the right, with Shadows `shadow`. +fn concave_u(shadow: bool) -> Node { + let mut path = BezPath::new(); + path.move_to((100.0, 100.0)); + for p in [(125.0, 100.0), (125.0, 175.0), (175.0, 175.0), (175.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)] { + path.line_to(p); + } + path.close_path(); + let mut n = Node::path(NodeId(1), PathData::from_bezpath(&path), Appearance::basic(Paint::solid(Color::rgb(0.7, 0.7, 0.7)), Paint::None, 0.0)); + n.appearance.effects.push( + crate::new_effect( + super::super::EXTRUDE, + &json!({ + "depth": 80, "rotationX": -30, "rotationY": -30, "rotationZ": 0, + "lightRotation": 0, "lightHeight": 25, "lightIntensity": 100, "ambient": 10, "shadow": shadow + }), + ) + .unwrap(), + ); + n +} + +/// The most the solids' own shadows darken a pixel's linear red in the image of `n`, against the +/// same scene with no material casting shadows. +fn self_shadow_darkening(n: &Node) -> f32 { + let (meshes, lighting) = scene_of(n); + assert_eq!(meshes.len(), 1, "the caster and receiver belong to the same solid"); + let projection = meshes[0].projection.unwrap(); + let (rect, z) = extent(&meshes, &[], projection).unwrap(); + let mut shadowed = scene(&meshes, &lighting, projection, z, clip(projection, rect, z).unwrap(), (160, 160), 160.0 / rect.width()).unwrap(); + let mut unshadowed = shadowed.clone(); + for material in &mut unshadowed.materials { + material.casts_shadows = false; + } + let limits = Limits::default(); + let draw = |scene: &mut Scene| { + if scene.lights.iter().any(|l| l.shadow >= 0) { + try_shadow_maps(scene, false, &limits).unwrap(); + } + try_render_cpu(scene, &limits).unwrap().0 + }; + let (shadowed, unshadowed) = (draw(&mut shadowed), draw(&mut unshadowed)); + shadowed.data.iter().zip(&unshadowed.data).filter(|(a, b)| a[3] == 1.0 && b[3] == 1.0).map(|(a, b)| b[0] - a[0]).fold(0.0, f32::max) +} + +/// With Shadows on, the arms of an extruded U cast shadows across its recess under a light from +/// the right; with Shadows off the solid casts none on itself. +#[test] +fn a_concave_solid_casts_a_shadow_on_itself() { + let on = self_shadow_darkening(&concave_u(true)); + assert!(on > 0.05, "Shadows on: the solid's own shadow darkens linear red by {on}"); + let off = self_shadow_darkening(&concave_u(false)); + assert_eq!(off, 0.0, "Shadows off: the solid shadows itself by {off}"); +} + +/// Shading off, the surface shows its paint unlit, as the shaded faces do. +#[test] +fn unshaded_surfaces_show_their_paint() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"shade": false})); + let (meshes, lighting) = scene_of(&n); + assert!(!lighting.shade); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + let worst = center[..3].iter().zip([51u8, 128, 204]).map(|(a, b)| a.abs_diff(b)).max(); + assert!(matches!(worst, Some(0..=1)), "{center:?}"); +} + +/// A face turned toward the light is lit more than one turned away from it, and a light straight +/// in front of a face lights it more than one that grazes it. +#[test] +fn a_face_toward_the_light_is_brighter() { + let level = |height: f64| { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.5, 0.5, 0.5), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": height, "lightIntensity": 100, "ambient": 0}), + ); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + pixel(&image, image.cols / 2, image.rows / 2)[0] + }; + let (front, grazing) = (level(90.0), level(10.0)); + assert!(front > grazing + 40, "front {front}, grazing {grazing}"); + assert!(grazing > 0); +} + +/// Low, Medium and High take 1, 2 × 2 and 3 × 3 samples a pixel; a quality whose samples would +/// pass the pixel limit takes fewer, and an image past the limit at one sample a pixel is refused, +/// when the effect draws its shaded faces instead. +#[test] +fn quality_sets_the_samples_within_the_pixel_limit() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + for (quality, k) in [(0, 1), (1, 2), (2, 3)] { + let image = render(&meshes, &lighting, RenderSettings { quality, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap(); + assert_eq!(image.samples, k, "quality {quality}"); + } + let one = render(&meshes, &lighting, RenderSettings { quality: 2, ..MEDIUM }, 72.0, true, &Limits::default()).unwrap(); + assert_eq!(one.samples, 1, "a draft takes one sample"); + let pixels = u64::from(one.cols) * u64::from(one.rows); + let mut limits = Limits::default(); + limits.max_pixels = pixels * 4; + let image = render(&meshes, &lighting, RenderSettings { quality: 2, ..MEDIUM }, 72.0, false, &limits).unwrap(); + assert_eq!(image.samples, 2); + limits.max_pixels = pixels - 1; + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &limits), Err(TOO_LARGE.to_string())); +} + +/// The resolution sets the image's pixels: 144 ppi gives twice the columns and rows of 72 ppi over +/// the same area, and without one the document's raster effects resolution applies. +#[test] +fn resolution_sets_the_image_grid() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + let at = |resolution: Option, doc: f64| { + render(&meshes, &lighting, RenderSettings { resolution, ..MEDIUM }, doc, false, &Limits::default()).unwrap() + }; + let (base, fine, doc) = (at(Some(72.0), 300.0), at(Some(144.0), 300.0), at(None, 144.0)); + assert!( + fine.cols.abs_diff(2 * base.cols) <= 1 && fine.rows.abs_diff(2 * base.rows) <= 1, + "{}x{} against {}x{}", + fine.cols, + fine.rows, + base.cols, + base.rows + ); + assert_eq!((doc.cols, doc.rows), (fine.cols, fine.rows)); +} + +/// A white background makes every pixel opaque, white where no surface is; transparent, those +/// pixels are clear. +#[test] +fn the_background_is_white_or_clear() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, lighting) = scene_of(&n); + let clear = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let white = render(&meshes, &lighting, RenderSettings { white: true, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap(); + let corners = |i: &Rendered| [(0, 0), (i.cols - 1, 0), (0, i.rows - 1), (i.cols - 1, i.rows - 1)].map(|(x, y)| pixel(i, x, y)); + assert!(corners(&clear).iter().any(|p| p[3] == 0), "{:?}", corners(&clear)); + assert!(white.pixels.chunks(4).all(|p| p[3] == 255)); + assert!(corners(&white).contains(&[255; 4]), "{:?}", corners(&white)); +} + +/// A mesh without a projection, or meshes with different ones, can't be placed: the image is refused. +#[test] +fn meshes_without_one_projection_are_refused() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (mut meshes, lighting) = scene_of(&n); + let mut other = meshes[0].clone(); + other.projection = other.projection.map(|p| MeshProjection { origin: Point::new(p.origin.x + 1.0, p.origin.y), ..p }); + meshes.push(other); + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); + meshes[0].projection = None; + assert_eq!(render(&meshes[..1], &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); + assert_eq!(render(&[], &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); +} + +/// Depths reaching close to a near eye still map in order: with the eye at 100 and depths 0 to 99.5 +/// the farthest point lands at the depth margin and the nearest at one minus it. +#[test] +fn depths_close_to_a_near_eye_keep_a_clip_matrix() { + let projection = MeshProjection { origin: Point::new(50.0, 50.0), eye: Some(100.0) }; + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let Some(m) = clip(projection, rect, [0.0, 99.5]) else { panic!("a perspective range in front of the eye maps") }; + let ndc = |z: f64| { + let row = |r: [f32; 4]| f64::from(r[2]) * z + f64::from(r[3]); + row(m[2]) / row(m[3]) + }; + assert!((ndc(0.0) - DEPTH_MARGIN).abs() < 1e-3, "{}", ndc(0.0)); + assert!((ndc(99.5) - (1.0 - DEPTH_MARGIN)).abs() < 1e-3, "{}", ndc(99.5)); + assert!(ndc(50.0) > ndc(0.0) && ndc(99.5) > ndc(50.0)); + assert!(clip(projection, rect, [0.0, 100.0]).is_none()); +} + +/// A solid painted with a gradient, in a blending mode other than Normal or with an opacity below +/// 100% draws its shaded faces, which keep that paint: the image shows opaque solid colors only. +#[test] +fn gradients_and_blending_draw_the_shaded_faces() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + for id in FOUR { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + n.appearance.items[0] = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new( + GradientPaint::new(Gradient::new(GradientKind::Linear, stops)), + )))); + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: gradient"); + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.blend = vectorcraft_doc::color::BlendMode::Multiply; + } + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: blending"); + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = 0.5; + } + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: opacity"); + } +} + +/// A loaded file whose `render` breaks the rules draws the shaded faces. +#[test] +fn an_invalid_loaded_render_draws_shaded() { + let mut n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + n.appearance.effects[0].params["render"] = json!({"mode": "rendered", "quality": "ultra"}); + let art = drawn(&n); + assert!(images(&art).is_empty()); + assert!(faces_bounds(&art).is_some()); +} + +#[test] +fn rendered_warning_reports_the_fallback() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in FOUR { + let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}: plain solid"); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + n.appearance.items[0] = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new( + GradientPaint::new(Gradient::new(GradientKind::Linear, stops)), + )))); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "{id}: gradient"); + } + let mut large = Node::path(NodeId(2), square(0.0, 0.0, 100_000.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + large.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &large).as_deref(), Some(TOO_LARGE)); +} + +#[test] +fn rendered_warning_does_not_rasterize() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in FOUR { + let n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}})); + let before = RASTERIZATIONS.with(|count| count.get()); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{id}: warning rasterizes"); + assert_eq!(images(&drawn(&n)).len(), 1, "{id}"); + assert!(RASTERIZATIONS.with(|count| count.get()) > before, "{id}: drawing rasterizes"); + } +} + +#[test] +fn check_only_reports_rasterizer_limits_after_measure_succeeds() { + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false})); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + let measured = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + let triangles = meshes.iter().map(|m| m.mesh.triangles.len() as u64).sum::(); + let vertices = meshes.iter().map(|m| m.mesh.positions.len() as u64).sum::(); + for limit in ["triangles", "vertices", "work"] { + let mut limits = Limits::default(); + match limit { + "triangles" => limits.max_triangles = triangles - 1, + "vertices" => limits.max_vertices = vertices - 1, + _ => limits.max_work = u64::from(measured.cols) * u64::from(measured.rows), + } + assert!(measure(&meshes, &lighting, settings, 72.0, false, &limits).is_ok(), "{limit}: image fits"); + let before = RASTERIZATIONS.with(|count| count.get()); + let checked = check(&meshes, &lighting, settings, 72.0, &limits); + assert_eq!(checked.as_ref().map_err(String::as_str), Err(TOO_LARGE), "{limit}"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{limit}: check rasterizes"); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits).map(|_| ()), checked, "{limit}"); + } +} + +#[test] +fn check_only_counts_shadow_work_and_lights() { + let n = + solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadow": true})); + let (meshes, lighting) = scene_of(&n); + assert!(!lighting.lights.is_empty()); + assert!(lighting.shadows); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + for limit in ["lights", "shadow work"] { + let mut limits = Limits::default(); + if limit == "lights" { + limits.max_lights = 0; + } else { + // The 512-square draft shadow map takes more work than the 100-square image. + limits.max_work = 30_000; + let mut unlit = lighting.clone(); + unlit.shade = false; + assert!(check(&meshes, &unlit, settings, 72.0, &limits).is_ok()); + assert!(render(&meshes, &unlit, settings, 72.0, false, &limits).is_ok()); + // With Shadows off, no shadow map is made, so the same limit fits. + let mut unshadowed = lighting.clone(); + unshadowed.shadows = false; + assert!(check(&meshes, &unshadowed, settings, 72.0, &limits).is_ok()); + assert!(render(&meshes, &unshadowed, settings, 72.0, false, &limits).is_ok()); + } + assert!(measure(&meshes, &lighting, settings, 72.0, false, &limits).is_ok()); + assert_eq!(check(&meshes, &lighting, settings, 72.0, &limits), Err(TOO_LARGE.into()), "{limit}"); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.into()), "{limit}"); + } +} + +#[test] +fn check_only_art_reports_overlapping_faces_past_the_work_limit() { + let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false})); + let (mut meshes, lighting) = scene_of(&n); + for p in &mut meshes[0].mesh.positions { + p[0] *= 40.0; + p[1] *= 40.0; + } + let meshes = vec![meshes[0].clone(); 200]; + let settings = RenderSettings { quality: 0, ..MEDIUM }; + assert!(measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).is_ok()); + let before = RASTERIZATIONS.with(|count| count.get()); + assert_eq!(art(None, NodeId(1), &lighting, &meshes, settings, true).map(|_| ()), Err(TOO_LARGE.into())); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before); + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &Limits::default()), Err(TOO_LARGE.into())); +} + +/// The page cells (1 pt squares, by their top-left corner) where the rendered image of `n` shows +/// a shadow: covered past alpha 16 outside the bounds of `n`'s shaded faces without a shadow. +fn shadow_cells(n: &Node) -> Vec<(i64, i64)> { + let mut bare = n.clone(); + bare.appearance.effects[0].params["shadow"] = json!(false); + bare.appearance.effects[0].params["render"] = json!({"mode": "shaded"}); + let solid = faces_bounds(&drawn(&bare)).unwrap(); + let list = images(&drawn(n)); + assert_eq!(list.len(), 1, "one image"); + let i = &list[0]; + let decoded = image::load_from_memory(&i.pixels.as_ref().unwrap().bytes).unwrap().to_rgba8(); + let [sx, _, _, sy, x0, y0] = i.xf.as_coeffs(); + let mut out = vec![]; + for (x, y, p) in decoded.enumerate_pixels() { + let (px, py) = (x0 + (f64::from(x) + 0.5) * sx, y0 + (f64::from(y) + 0.5) * sy); + if p[3] > 16 && !solid.inflate(1.0, 1.0).contains(Point::new(px, py)) { + out.push((px.floor() as i64, py.floor() as i64)); + } + } + out +} + +/// A 100 pt square extruded face-on under two low lights, from the right and from the left, at +/// Intensity `right` and `left` (percent), with Shadows `shadow`, rendered. +fn two_lights(right: f64, left: f64, shadow: bool) -> Node { + solid_square( + super::super::EXTRUDE, + Color::rgb(0.7, 0.7, 0.7), + json!({ + "depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, "shadow": shadow, + "lights": [{"rotation": 0, "height": 30, "intensity": right}, {"rotation": 180, "height": 30, "intensity": left}], + "render": {"mode": "rendered", "quality": "low"} + }), + ) +} + +/// Rendered with Shadows on, each light casts its own shadow on the shadow plane: two lights from +/// opposite sides darken one region on each side of the solid. With Shadows off neither appears, +/// and a light at Intensity 0 casts none. +#[test] +fn every_light_casts_a_shadow_on_the_plane() { + let center = 150.0; + let sides = |cells: &[(i64, i64)]| { + let left = cells.iter().filter(|c| (c.0 as f64) < center).count(); + (left, cells.len() - left) + }; + let (left, right) = sides(&shadow_cells(&two_lights(100.0, 100.0, true))); + assert!(left > 50 && right > 50, "two lights: {left} shadow cells on the left, {right} on the right"); + let (left, right) = sides(&shadow_cells(&two_lights(100.0, 0.0, true))); + assert!(left > 50, "the light from the right casts {left} cells to the left"); + assert_eq!(right, 0, "the light at Intensity 0 casts {right} cells to the right"); + let (left, right) = sides(&shadow_cells(&two_lights(0.0, 100.0, true))); + assert!(right > 50 && left == 0, "the light from the left alone: {left} left, {right} right"); + assert_eq!(shadow_cells(&two_lights(100.0, 100.0, false)), vec![], "Shadows off"); +} + +/// Full Softness widens the shadow's transition on the plane by several image pixels at both +/// resolutions, including when the image uses multiple samples per pixel. +#[test] +fn softness_widens_the_shadow_edge_on_the_plane() { + for (resolution, quality) in [(72.0, "low"), (144.0, "medium")] { + let transition = |softness| { + let n = solid_square( + super::super::EXTRUDE, + Color::rgb(0.7, 0.7, 0.7), + json!({ + "depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, + "shadow": true, "shadowDistance": 50, "lightHeight": 45, "lightRotation": 0, + "lightIntensity": 100, "lightSoftness": softness, + "render": {"mode": "rendered", "quality": quality, "resolution": resolution} + }), + ); + let list = images(&drawn(&n)); + assert_eq!(list.len(), 1); + let image = &list[0]; + let decoded = image::load_from_memory(&image.pixels.as_ref().unwrap().bytes).unwrap().to_rgba8(); + let [sx, _, _, sy, x0, y0] = image.xf.as_coeffs(); + let y = ((150.0 - y0) / sy).floor() as u32; + assert!(y < decoded.height()); + let alpha: Vec = + (0..decoded.width()).filter(|x| x0 + (f64::from(*x) + 0.5) * sx < 99.0).map(|x| decoded.get_pixel(x, y)[3]).collect(); + assert!(alpha.contains(&0), "the plane includes an unshadowed region"); + assert!(alpha.iter().any(|a| *a >= 120), "the plane includes a fully shadowed region"); + alpha.iter().filter(|a| **a > 8 && **a < 120).count() + }; + let (hard, soft) = (transition(0), transition(100)); + assert!(soft > hard + (8.0 * resolution / 72.0) as usize, "{resolution} ppi, {quality}: {hard} hard transition pixels, {soft} soft"); + } +} + +/// Measuring the selection with Use Preview Bounds builds the vector art of a rendered 3D object +/// and makes no image; drawing it makes one. +#[test] +fn preview_bounds_do_not_rasterize() { + let mut doc = vectorcraft_doc::Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + for (k, id) in FOUR.into_iter().enumerate() { + let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + n.id = NodeId(100 + k as u64); + doc.insert(Some(layer), k, n).unwrap(); + } + let ids: Vec = (0..4).map(|k| NodeId(100 + k)).collect(); + let before = RASTERIZATIONS.with(|count| count.get()); + assert!(crate::preview::bounds_of(&doc, &ids, true).is_some()); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "measuring rasterizes"); + for id in &ids { + assert_eq!(images(&drawn(doc.node(*id).unwrap())).len(), 1, "{id:?}"); + } + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before + 4, "drawing rasterizes once for each object"); +} + +/// Painted measurements include the image rectangle under opposite lights without rasterizing, +/// while preview measurements keep the vector art. +#[test] +fn painted_bounds_include_every_lights_shadow_without_rasterizing() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = two_lights(100.0, 100.0, true); + n.appearance.effects[0].id = id.into(); + let before = RASTERIZATIONS.with(|count| count.get()); + let measured = crate::three_d_bounds_art_in(Some(&doc), &n).unwrap(); + let bounds = measured.visual_bounds().unwrap(); + let measured_images = images(&measured); + assert_eq!(measured_images.len(), 1, "{id}: measures the rendered image"); + assert!(measured_images[0].pixels.is_none(), "{id}: no pixels for measurement"); + assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{id}: measuring rasterizes"); + let drawn_images = images(&drawn(&n)); + assert_eq!(drawn_images.len(), 1, "{id}: draws the rendered image"); + let image = Node::new(n.id, NodeKind::Image(Box::new(drawn_images[0].clone()))).visual_bounds().unwrap(); + assert!(bounds.x0 <= image.x0 && bounds.y0 <= image.y0 && bounds.x1 >= image.x1 && bounds.y1 >= image.y1, "{id}: {bounds:?} holds {image:?}"); + let mut bare = n.clone(); + bare.appearance.effects[0].params["shadow"] = json!(false); + let bare = crate::three_d_bounds_art_in(Some(&doc), &bare).unwrap().visual_bounds().unwrap(); + assert!(bounds.x0 < bare.x0 && bounds.x1 > bare.x1, "{id}: shadows extend on both sides"); + let vector = crate::revolve_art_in(Some(&doc), &n).or_else(|| crate::solid_art_in(Some(&doc), &n)).unwrap(); + assert!(images(&vector).is_empty(), "{id}: preview keeps vector art"); + } +} + +/// Drawing the same object again reuses its image; changing its geometry, its material, the +/// resolution or the document's raster resolution makes a new one. +#[test] +fn rendered_images_are_reused_until_an_input_changes() { + let count = || RASTERIZATIONS.with(|count| count.get()); + let base = json!({"render": {"mode": "rendered", "quality": "low"}}); + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), base.clone()); + let doc = |ppi: f64| { + let mut d = vectorcraft_doc::Document::new(400.0, 400.0); + d.raster_effects_ppi = ppi; + d + }; + let draw = |d: &vectorcraft_doc::Document, n: &Node| images(&super::super::solid_art_drawn_in(Some(d), n).unwrap()).len(); + let start = count(); + assert_eq!(draw(&doc(72.0), &n), 1); + assert_eq!(count(), start + 1); + assert_eq!(draw(&doc(72.0), &n), 1); + assert_eq!(count(), start + 1, "a redraw rasterizes again"); + let mut moved = Node::path(NodeId(1), square(130.0, 100.0, 100.0), Appearance::default()); + moved.appearance = n.appearance.clone(); + assert_eq!(draw(&doc(72.0), &moved), 1); + assert_eq!(count(), start + 2, "moving the object reuses the image"); + let mut rough = n.clone(); + rough.appearance.effects[0].params["material"] = json!({"roughness": 0.9}); + assert_eq!(draw(&doc(72.0), &rough), 1); + assert_eq!(count(), start + 3, "a new roughness reuses the image"); + let mut fine = n.clone(); + fine.appearance.effects[0].params["render"] = json!({"mode": "rendered", "quality": "low", "resolution": 144}); + assert_eq!(draw(&doc(72.0), &fine), 1); + assert_eq!(count(), start + 4, "a new resolution reuses the image"); + assert_eq!(draw(&doc(150.0), &n), 1); + assert_eq!(count(), start + 5, "a new document resolution reuses the image"); +} + +/// A group whose 3D effect holds a member with a blending mode or an opacity mask draws the shaded +/// faces, which apply them; without either, the group draws the image. +#[test] +fn masked_or_blended_members_draw_the_shaded_faces() { + for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] { + let group = |member: Node| { + let mut g = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]); + g.appearance.effects.push(crate::new_effect(id, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + g + }; + let member = + || Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + let art = drawn(&group(member())); + assert_eq!(images(&art).len(), 1, "{id}: plain member"); + let mut blended = member(); + blended.blend = vectorcraft_doc::color::BlendMode::Multiply; + let art = drawn(&group(blended)); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: blended member"); + let mut masked = member(); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(member(), false))); + let art = drawn(&group(masked)); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: masked member"); + } +} + +/// Revolve on a group, or on a fill or stroke, draws the shaded faces and reports why. +#[test] +fn revolve_on_a_group_or_a_paint_reports_objects_only() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let rendered = || crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap(); + let member = || Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member())]); + group.appearance.effects.push(rendered()); + assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OBJECTS_ONLY), "group"); + assert!(images(&drawn(&group)).is_empty(), "group"); + let mut fill = member(); + fill.appearance.items[0].effects_mut().push(rendered()); + assert_eq!(crate::rendered_warning(&doc, &fill).as_deref(), Some(OBJECTS_ONLY), "fill"); + assert!(images(&drawn(&fill)).is_empty(), "fill"); + assert_eq!(crate::rendered_warning(&doc, &solid_square(crate::REVOLVE, Color::BLACK, json!({"render": {"mode": "rendered"}}))), None); +} + +/// Baking a rendered object's appearance, as an envelope with Distort Appearance does, keeps its +/// image, for Revolve and the other 3D effects. +#[test] +fn baked_appearance_keeps_the_rendered_image() { + for id in FOUR { + let n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + let baked = crate::bake_appearance(None, &n).unwrap_or_else(|| panic!("{id}: nothing baked")); + assert_eq!(images(&baked).len(), 1, "{id}: the baked appearance has no image"); + } +} + +/// The page point the clip matrix `m` takes mesh point `p` to over image `rect`: the point goes +/// into the scene's frame (y down), through `m`, and from the image's normalized coordinates onto +/// the page. +fn clipped(m: [[f32; 4]; 4], rect: Rect, p: [f64; 3]) -> Point { + let v = [p[0], -p[1], p[2], 1.0]; + let row = |r: usize| (0..4).map(|c| f64::from(m[r][c]) * v[c]).sum::(); + let w = row(3); + let (x, y) = (row(0) / w, row(1) / w); + Point::new(rect.x0 + (x + 1.0) / 2.0 * rect.width(), rect.y0 + (1.0 - y) / 2.0 * rect.height()) +} + +/// The scene's clip matrix places every mesh point where the effect's projection draws it, within +/// 1e-3 pt, for each of the four effects without perspective and at 60 and 160 degrees. +#[test] +fn the_clip_matrix_places_every_mesh_point_where_the_projection_does() { + for id in FOUR { + for perspective in [0.0, 60.0, 160.0] { + let n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"perspectiveAngle": perspective})); + let (meshes, lighting) = scene_of(&n); + let m = measure(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap_or_else(|e| panic!("{id} {perspective}: {e}")); + let mut worst = 0.0f64; + for p in meshes.iter().flat_map(|s| &s.mesh.positions) { + worst = worst.max(clipped(m.clip, m.rect, *p).distance(m.projection.project(*p))); + } + assert!(worst < 1e-3, "{id} at {perspective} degrees: a mesh point lands {worst} pt from its projected point"); + } + } +} + +/// A square facing the viewer covers every pixel more than one pixel inside its outline and none +/// more than one pixel outside it. +#[test] +fn the_image_covers_the_area_the_faces_cover() { + let n = solid_square(super::super::ROTATE, Color::rgb(0.2, 0.5, 0.8), json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let face = faces_bounds(&super::super::solid_art_in(None, &n).unwrap()).unwrap(); + let (mut inside, mut outside) = (0, 0); + for y in 0..image.rows { + for x in 0..image.cols { + let center = Point::new(image.rect.x0 + f64::from(x) + 0.5, image.rect.y0 + f64::from(y) + 0.5); + let a = pixel(&image, x, y)[3]; + if face.inset(-1.0).contains(center) { + inside += 1; + assert_eq!(a, 255, "pixel {x}, {y} inside the face"); + } else if !face.inset(1.0).contains(center) { + outside += 1; + assert_eq!(a, 0, "pixel {x}, {y} outside the face"); + } + } + } + assert!(inside > 9000, "{inside} pixels inside"); + assert!(outside + inside > 0); +} + +/// The depth buffer decides which surface shows: with the mesh's triangles in reverse order, every +/// pixel inside the turned solid shows the same surface. +#[test] +fn the_nearer_surface_shows_whatever_order_the_triangles_come_in() { + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"rotationX": 40, "rotationY": 50, "rotationZ": 0, "shade": true})); + let (meshes, lighting) = scene_of(&n); + let mut reversed = meshes.clone(); + for m in &mut reversed { + m.mesh.triangles.reverse(); + } + let a = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let b = render(&reversed, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + assert_eq!((a.cols, a.rows), (b.cols, b.rows)); + let differ = a + .pixels + .chunks(4) + .zip(b.pixels.chunks(4)) + .filter(|(p, q)| p[3] == 255 && q[3] == 255 && p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > 2)) + .count(); + let covered = a.pixels.chunks(4).filter(|p| p[3] == 255).count(); + assert!(covered > 5000, "{covered}"); + assert!(differ * 100 <= covered, "{differ} of {covered} covered pixels change with the triangle order"); +} + +/// Cook-Torrance with GGX, Smith-Schlick `k = (r + 1)² / 8` and Schlick's Fresnel, times N·L, for +/// linear base color `base`, `metallic` and `rough` along unit normal `n`, view `v` and light `l`. +fn cook_torrance(base: f64, metallic: f64, rough: f64, n: [f64; 3], v: [f64; 3], l: [f64; 3]) -> f64 { + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let h = [v[0] + l[0], v[1] + l[1], v[2] + l[2]]; + let len = dot(h, h).sqrt(); + let h = h.map(|c| c / len); + let (n_l, n_v, n_h, v_h) = (dot(n, l), dot(n, v), dot(n, h), dot(v, h)); + let a2 = (rough * rough).powi(2); + let d = a2 / (std::f64::consts::PI * (n_h * n_h * (a2 - 1.0) + 1.0).powi(2)); + let k = (rough + 1.0).powi(2) / 8.0; + let g = (n_v / (n_v * (1.0 - k) + k)) * (n_l / (n_l * (1.0 - k) + k)); + let f0 = 0.04 * (1.0 - metallic) + base * metallic; + let f = f0 + (1.0 - f0) * (1.0 - v_h).powi(5); + let spec = d * g / (4.0 * n_v * n_l); + let kd = (1.0 - f) * (1.0 - metallic); + (kd * base / std::f64::consts::PI + f * spec) * n_l * std::f64::consts::PI +} + +/// A face toward the viewer under one light at 45 degrees, Ambient 0, Roughness 0.5, Metallic 0 +/// and 1: its center equals the Cook-Torrance formula times the light's color, within 1e-3 linear. +#[test] +fn a_lit_face_matches_the_shading_formula() { + for metallic in [0.0, 1.0] { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.5, 0.5, 0.5), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 45, "lightIntensity": 100, "ambient": 0, + "material": {"roughness": 0.5, "metallic": metallic}}), + ); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 0, ..MEDIUM }; + let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + let scene = scene(&meshes, &lighting, m.projection, m.z, m.clip, (m.cols, m.rows), f64::from(m.cols) / m.rect.width()).unwrap(); + assert_eq!(scene.lights.len(), 1); + let light = &scene.lights[0]; + let target = craft_raster3d::try_render(&scene, &Limits::default()).unwrap(); + let got = target.color[(m.rows / 2 * m.cols + m.cols / 2) as usize]; + let l = light.dir.map(|c| -f64::from(c)); + let base = f64::from(srgb_to_linear(0.5)); + let want = cook_torrance(base, metallic, 0.5, [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], l) * f64::from(light.color[0]); + assert!((f64::from(got[0]) - want).abs() < 1e-3, "metallic {metallic}: {} against {want}", got[0]); + assert_eq!(got[3], 1.0); + } +} + +/// With the default light, Ambient 0, the default material and Softness 0, a face square to the +/// light has the color of the same shaded face within 3 levels. +#[test] +fn a_face_square_to_the_light_has_the_shaded_faces_color() { + let n = solid_square( + super::super::ROTATE, + Color::rgb(0.2, 0.5, 0.8), + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "ambient": 0, "lightSoftness": 0}), + ); + let mut face = None; + super::super::solid_art_in(None, &n).unwrap().walk(&mut |c| { + if c.path_data().is_some() + && let Some(Paint::Solid { color, .. }) = c.appearance.items.iter().map(|i| i.paint()).find(|p| matches!(p, Paint::Solid { .. })) + { + face.get_or_insert(color.to_rgba8(1.0)); + } + }); + let face = face.unwrap(); + let (meshes, lighting) = scene_of(&n); + let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let center = pixel(&image, image.cols / 2, image.rows / 2); + for c in 0..3 { + assert!(center[c].abs_diff(face[c]) <= 3, "{center:?} against the shaded face's {face:?}"); + } +} + +/// The specular term of the shaded faces (the separable Smith visibility of glTF 2.0) and of the +/// rendered image (Smith-Schlick with `k = (r + 1)² / 8`) differ by at most 0.002 of the light over +/// Roughness 0.05 to 1 and light angles of 0 to 80 degrees from the normal, at a view along it. +#[test] +fn the_two_specular_terms_differ_within_a_bound() { + let mut worst = (0.0f64, 0.0, 0.0); + for r in (1..=20).map(|i| f64::from(i) * 0.05) { + for degrees in (0..=8).map(|i| f64::from(i) * 10.0) { + let t = degrees.to_radians(); + let (n_l, n_v) = (t.cos(), 1.0); + let h_len = (2.0 + 2.0 * n_l).sqrt(); + let n_h = (1.0 + n_l) / h_len; + let a2 = (r * r).powi(2); + let d = a2 / (std::f64::consts::PI * (n_h * n_h * (a2 - 1.0) + 1.0).powi(2)); + let k = (r + 1.0).powi(2) / 8.0; + let schlick = (n_v / (n_v * (1.0 - k) + k)) * (n_l / (n_l * (1.0 - k) + k)) / (4.0 * n_v * n_l); + let one = |x: f64| x + (a2 + (1.0 - a2) * x * x).sqrt(); + let separable = 1.0 / (one(n_l) * one(n_v)); + // F0 0.04, the dielectric default, at the half vector. + let v_h = h_len / 2.0; + let f = 0.04 + 0.96 * (1.0 - v_h).powi(5); + let diff = (d * f * (schlick - separable) * n_l * std::f64::consts::PI).abs(); + if diff > worst.0 { + worst = (diff, r, degrees); + } + } + } + println!("largest specular difference {:.4} at roughness {:.2}, {} degrees", worst.0, worst.1, worst.2); + assert!(worst.0 <= 0.002, "{worst:?}"); +} + +/// An image past the pixel limit at one sample a pixel draws the shaded faces and reports why; the +/// largest mesh the effects make fits the rasterizer's triangle limit. +#[test] +fn an_image_past_the_limits_draws_the_shaded_faces() { + assert!(super::super::MAX_MESH_TRIANGLES as u64 <= Limits::default().max_triangles); + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mut n = Node::path(NodeId(1), square(0.0, 0.0, 3000.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + n.appearance + .effects + .push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "quality": "low", "resolution": 2400}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(TOO_LARGE)); + let art = drawn(&n); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some()); +} + +/// Rendering a 40 × 80 pt Extrude at 300 ppi, Medium (2 × 2 samples), fits a work limit of twice +/// the samples its triangles' bounding boxes cover plus one for each triangle, and a limit of half +/// those samples is refused. +#[test] +fn a_medium_render_stays_within_its_work_bound() { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((40.0, 0.0)); + b.line_to((40.0, 80.0)); + b.line_to((0.0, 80.0)); + b.close_path(); + let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "resolution": 300}})).unwrap()); + let (meshes, lighting) = scene_of(&n); + let settings = RenderSettings { quality: 1, resolution: Some(300.0), white: false }; + let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + assert_eq!(m.samples, 2); + let samples = u64::from(m.cols) * u64::from(m.rows) * 4; + // Each triangle's bounding box in raster samples, clipped to the raster. + let per_point = f64::from(m.cols * 2) / m.rect.width(); + let mut boxes = 0u64; + let mut triangles = 0u64; + for s in &meshes { + for t in &s.mesh.triangles { + let at: Vec = t.iter().map(|&i| m.projection.project(s.mesh.positions[i as usize])).collect(); + let span = |f: fn(&Point) -> f64, origin: f64, size: f64| { + let lo = at.iter().map(f).fold(f64::INFINITY, f64::min); + let hi = at.iter().map(f).fold(f64::NEG_INFINITY, f64::max); + (((hi - origin) * per_point).ceil().min(size) - ((lo - origin) * per_point).floor().max(0.0) + 1.0).max(0.0) as u64 + }; + boxes += span(|p| p.x, m.rect.x0, f64::from(m.cols * 2)) * span(|p| p.y, m.rect.y0, f64::from(m.rows * 2)); + triangles += 1; + } + } + let mut limits = Limits::default(); + limits.max_work = 2 * boxes + triangles; + assert!(render(&meshes, &lighting, settings, 72.0, false, &limits).is_ok(), "{samples} samples, {boxes} box samples, {triangles} triangles"); + limits.max_work = boxes / 2; + assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.to_string()), "the work is counted"); + println!("work bound: {samples} image samples, {boxes} box samples, {triangles} triangles"); +} + +/// Edge values: art with no area makes no image, a mesh with zero-area triangles renders, lights +/// with values that are not numbers are refused, resolutions 1 and 2400 render, and a solid behind +/// the eye at Perspective 160 is refused. +#[test] +fn edge_values_render_or_are_refused() { + let mut empty = Node::path(NodeId(1), PathData::from_bezpath(&BezPath::new()), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + empty.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}})).unwrap()); + assert!(super::super::solid_art_drawn_in(None, &empty).is_none_or(|a| images(&a).is_empty())); + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (mut meshes, mut lighting) = scene_of(&n); + let first = meshes[0].mesh.triangles[0]; + meshes[0].mesh.triangles.push([first[0], first[0], first[1]]); + assert!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).is_ok(), "zero-area triangle"); + for resolution in [1.0, 2400.0] { + let settings = RenderSettings { quality: 0, resolution: Some(resolution), white: false }; + let image = render(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); + assert!(image.cols >= 1 && image.rows >= 1, "{resolution} ppi"); + } + lighting.lights[0].intensity = f64::NAN; + lighting.lights[0].rotation = f64::INFINITY; + let bad = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()); + assert!(matches!(bad.as_ref().map_err(String::as_str), Ok(_) | Err(TOO_LARGE)), "{bad:?}"); + let behind = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"perspectiveAngle": 160})); + let (mut meshes, lighting) = scene_of(&behind); + let eye = meshes[0].projection.and_then(|p| p.eye).unwrap(); + meshes[0].mesh.positions[0][2] = eye * 2.0; + assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); +} diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs index 7b84214d29..dbdfbb9c30 100644 --- a/crates/effects/src/solids/shadow.rs +++ b/crates/effects/src/solids/shadow.rs @@ -25,12 +25,24 @@ pub(crate) fn options(p: &Value) -> Option { let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied()); let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity); let lit = flag(p, "shade", true) && intensity > 0.0; - (lit && flag(p, "shadow", false)).then(|| Shadow { + (lit && flag(p, "shadow", false)).then(|| settings(p, first)) +} + +/// The shadow a rendered image of `p` draws, in which every light casts one: as [`options`], but on +/// when any light lights the art (`lit`), not only the first. +pub(crate) fn rendered_options(p: &Value, lit: bool) -> Option { + let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied()); + (lit && flag(p, "shade", true) && flag(p, "shadow", false)).then(|| settings(p, first)) +} + +/// The plane settings of `p`, with the softness of light `first` (the single light's without one). +fn settings(p: &Value, first: Option) -> Shadow { + Shadow { position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(), distance: num(p, "shadowDistance", 0.0) / 100.0, bounds: num(p, "shadowBounds", 100.0) / 100.0, softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness), - }) + } } /// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind. diff --git a/crates/effects/src/solids/tests_material.rs b/crates/effects/src/solids/tests_material.rs index 1c7141dc8d..17f1878fa9 100644 --- a/crates/effects/src/solids/tests_material.rs +++ b/crates/effects/src/solids/tests_material.rs @@ -398,5 +398,7 @@ fn meshes_carry_the_material() { let mut n = square_node(); let Some(fx) = crate::new_effect(EXTRUDE, &json!({})) else { panic!("extrude") }; n.appearance.effects.push(fx); - assert!(three_d_meshes(&n).unwrap_or_default().iter().all(|m| m.material.is_default())); + let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("extrude: {e}")); + assert!(!meshes.is_empty(), "extrude"); + assert!(meshes.iter().all(|m| m.material.is_default())); } diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 12ab29423f..8170a3bfa7 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -356,7 +356,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() let (path, rule) = profile(&n).unwrap(); vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] }; - let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap(); + let (drawn, _) = art_for(None, &n, std::slice::from_ref(fx), &shapes, Build::Vector, &mut None).unwrap(); let p = crate::merged_params(&fx.id, &fx.params); let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 3c1b3f1f2e..9ad0597c5c 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -21,12 +21,84 @@ use crate::{GeomContext, is_geometry}; pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000; /// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of -/// [`RENDER_MODES`]. +/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution` and +/// `background` ([`RENDER_BACKGROUNDS`]). pub const RENDER: &str = "render"; /// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every -/// face ([`renders_wireframe`]). -pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"]; +/// face ([`renders_wireframe`]), and `rendered` an image of the lit solid with the shadows of its +/// lights ([`render_settings`]). +pub const RENDER_MODES: [&str; 3] = ["shaded", "wireframe", "rendered"]; + +/// The qualities of the rendered image, from fastest to finest: 1, 2 × 2 and 3 × 3 samples a pixel +/// ([`RenderSettings::samples`]). VectorCraft's own values. +pub const RENDER_QUALITIES: [&str; 3] = ["low", "medium", "high"]; + +/// What the rendered image shows where no surface is: nothing, or white. +pub const RENDER_BACKGROUNDS: [&str; 2] = ["transparent", "white"]; + +/// The index in [`RENDER_QUALITIES`] of the quality a `render` without one takes (VectorCraft's own +/// default). +const DEFAULT_QUALITY: usize = 1; + +/// The settings of a 3D effect's rendered image ([`render_settings`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RenderSettings { + /// The quality, as an index into [`RENDER_QUALITIES`] (0 low, 1 medium, 2 high). + pub quality: usize, + /// Pixels per inch, 1 to 2400; `None` takes Document Raster Effects Settings › Resolution. + pub resolution: Option, + /// A white background, which makes the image opaque; otherwise it is transparent where no + /// surface or shadow is. + pub white: bool, +} + +impl RenderSettings { + /// The samples a pixel takes along each side at this quality: 1, 2 or 3. + pub fn samples(&self) -> u32 { + self.quality.min(2) as u32 + 1 + } +} + +/// The settings of the image 3D effect `id` with parameters `p` draws, when its `render` passes +/// [`validate_render`] and sets `mode` to `rendered`; `None` otherwise, when the effect draws its +/// shaded faces or its wireframe (a loaded file whose `render` breaks the rules draws shaded). +pub fn render_settings(id: &str, p: &Value) -> Option { + let render = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id))?; + if check_render(render).is_err() || render.get("mode").and_then(Value::as_str) != Some("rendered") { + return None; + } + let quality = render.get("quality").and_then(Value::as_str).and_then(|q| RENDER_QUALITIES.iter().position(|k| *k == q)); + Some(RenderSettings { + quality: quality.unwrap_or(DEFAULT_QUALITY), + resolution: render.get("resolution").and_then(Value::as_f64), + white: render.get("background").and_then(Value::as_str) == Some("white"), + }) +} + +/// Does effect `fx` draw as a rendered image ([`render_settings`])? +pub fn renders_image(fx: &Effect) -> bool { + render_settings(&fx.id, &fx.params).is_some() +} + +/// The message a `render` that breaks the rules of [`validate_render`] is refused with. +const RENDER_RULES: &str = "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), \ + resolution (null or a number from 1 to 2400) and background (transparent or white)"; + +/// Check one `render` value against [`RENDER_RULES`]. +fn check_render(render: &Value) -> Result<(), String> { + let one_of = |v: &Value, list: &[&str]| v.as_str().is_some_and(|s| list.contains(&s)); + let valid = render.as_object().is_some_and(|fields| { + fields.iter().all(|(key, value)| match key.as_str() { + "mode" => one_of(value, &RENDER_MODES), + "quality" => one_of(value, &RENDER_QUALITIES), + "background" => one_of(value, &RENDER_BACKGROUNDS), + "resolution" => value.is_null() || value.as_f64().is_some_and(|r| (1.0..=2400.0).contains(&r)), + _ => false, + }) + }); + if valid { Ok(()) } else { Err(RENDER_RULES.into()) } +} /// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve, /// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface. @@ -50,17 +122,14 @@ pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool { } /// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the -/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a -/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take. +/// effects in [`TAKES_RENDER`], is an object that holds only `mode` (one of [`RENDER_MODES`]), +/// `quality` (one of [`RENDER_QUALITIES`]), `resolution` (`null`, or a number from 1 to 2400 pixels +/// per inch) and `background` (one of [`RENDER_BACKGROUNDS`]). A key left out takes its default: +/// `shaded`, `medium`, the document's raster effects resolution and `transparent`. The 3D (Classic) +/// effects refuse it as a parameter they do not take. pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> { let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) }; - let valid = render - .as_object() - .is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m)))); - if !valid { - return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into()); - } - Ok(()) + check_render(render) } /// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index b20d0fedf0..f99be96a94 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -418,12 +418,23 @@ fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() { assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT))); } -/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and -/// only on the panel's four effects. +/// `render` is checked before an edit: an object holding only `mode` (shaded, wireframe or +/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400) and `background` +/// (transparent or white), and only on the panel's four effects. #[test] fn render_settings_are_validated() { for id in WIRE { - for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] { + for good in [ + json!({}), + json!({"render": {}}), + json!({"render": {"mode": "shaded"}}), + json!({"render": {"mode": "wireframe"}}), + json!({"render": {"mode": "rendered"}}), + json!({"render": {"mode": "rendered", "quality": "high", "resolution": 300, "background": "white"}}), + json!({"render": {"mode": "rendered", "quality": "low", "resolution": null, "background": "transparent"}}), + json!({"render": {"resolution": 1}}), + json!({"render": {"resolution": 2400}}), + ] { assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}"); } for bad in [ @@ -431,10 +442,20 @@ fn render_settings_are_validated() { json!({"render": null}), json!({"render": {"mode": "raytrace"}}), json!({"render": {"mode": true}}), - json!({"render": {"mode": "wireframe", "quality": "high"}}), + json!({"render": {"mode": "rendered", "quality": "ultra"}}), + json!({"render": {"mode": "rendered", "resolution": 0.5}}), + json!({"render": {"mode": "rendered", "resolution": 2401}}), + json!({"render": {"mode": "rendered", "resolution": "300"}}), + json!({"render": {"mode": "rendered", "background": "black"}}), + json!({"render": {"mode": "rendered", "samples": 4}}), ] { let e = crate::validate_three_d_params(id, &bad).unwrap_err(); - assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}"); + assert_eq!( + e, + "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), resolution (null \ + or a number from 1 to 2400) and background (transparent or white)", + "{id} {bad}" + ); } // The command check on the object refuses it too. let n = solid_square(id, json!({})); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fe4f7d10e..2487dcd01d 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -114,6 +114,8 @@ apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] } zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] } [dev-dependencies] +# DWG files for the `.dwg` open and place tests, written from DXF by craft-dwg. +craft-dwg = { workspace = true } # JPEG XL files for the `.jxl` open and place tests. zune-jpegxl = { workspace = true } zune-core = { workspace = true } diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index ec18bbccd1..ab7a3808ce 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -8,10 +8,12 @@ //! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their //! visual bounds share, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in -//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object. +//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object, +//! and Add Artboard Guides puts a rectangular guide around artboards ([`artboard_guides`]). //! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view //! command) are the UI's. +mod artboard_guides; pub mod marks; #[cfg(test)] mod tests; @@ -31,8 +33,8 @@ use super::super::edit::selected_roots; use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; use super::super::object::{ - aligned_symbol_transforms, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, scaling, transform_node, - transform_patterns, + aligned_symbol_transforms, aligned_symbols, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, + object_bounds_transform_keeping, refit_drawn, scaling, snaps_after_edit, transform_node, transform_patterns, }; use super::super::objects_on_path; use super::super::typecmd::refresh_bounds_of; @@ -75,7 +77,7 @@ pub fn specs() -> Vec { "Swap Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", + "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", exactly_two, swap ), @@ -84,7 +86,7 @@ pub fn specs() -> Vec { "Replace with Top Object", ["Object", "Plug-ins", "Arrange Tools"], None, - "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", + "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", has_multi, replace ), @@ -93,7 +95,7 @@ pub fn specs() -> Vec { "Set Size of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", + "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", has_selection, size ), @@ -102,7 +104,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into or out of a locked layer or group, take a target out of the blend input it is in (to restack the blend itself, select the whole blend), put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match, as it is for a turned target that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol, with or without Use Preview Bounds; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -138,12 +140,13 @@ pub fn specs() -> Vec { "Sort Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), corners?: the Scale Corners preference, ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", has_multi, sort ), ] .into_iter() + .chain(artboard_guides::specs()) .chain(marks::specs()) .collect() } @@ -173,10 +176,10 @@ fn size_param(p: &Value, key: &str, cmd: &str) -> Result> { p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose() } -/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes` -/// and, when given, a width and height. -fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { - let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes }); +/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`, +/// Scale Corners `corners` and, when given, a width and height. +fn place(at: Point, size: Option<(f64, f64)>, strokes: bool, corners: bool) -> Value { + let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes, "corners": corners }); if let Some((w, h)) = size { q["width"] = json!(w); q["height"] = json!(h); @@ -185,14 +188,15 @@ fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { } /// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects -/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says. -/// When every transform is (within rounding) the identity, nothing changes. -fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { +/// scaling with Scale Strokes & Effects `strokes`, corners with Scale Corners `corners`, pattern +/// tiles as the command's params `p` or Transform Pattern Tiles say. When every transform is +/// (within rounding) the identity, nothing changes. +fn transform_each(s: &mut Session, label: &str, p: &Value, strokes: bool, corners: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); if xfs.iter().all(|(_, xf)| still(xf)) { return Ok(()); } - let p = json!({ "strokes": strokes }); + let p = scaling_params(p, strokes, corners); let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &ids)?; @@ -206,6 +210,17 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A }) } +/// The params [`scaling`] and [`transform_patterns`] read: Scale Strokes & Effects `strokes`, Scale +/// Corners `corners`, and the `patterns` value of the command's params `p`. That one is absent on a +/// first run, which takes the preference, and present when its journal entry is replayed. +fn scaling_params(p: &Value, strokes: bool, corners: bool) -> Value { + let mut q = json!({ "strokes": strokes, "corners": corners }); + if let Some(v) = p.get("patterns").filter(|v| v.is_boolean()) { + q["patterns"] = v.clone(); + } + q +} + /// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the /// command's journal entry, so replaying it scales the same way whatever the preference is then. fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result { @@ -214,6 +229,14 @@ fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result { Ok(on) } +/// The `corners` value of a replayed journal entry, else the Scale Corners preference. The value +/// joins the command's journal entry, so replaying it scales corners the same way. +fn scale_corners(s: &mut Session, p: &Value, cmd: &str) -> Result { + let on = switch_or(p, "corners", s.prefs.scale_corners, cmd)?; + s.note_journal("corners", json!(on)); + Ok(on) +} + /// The box of object `id` as `object.setBounds` measures it. fn box_of(s: &Session, id: NodeId) -> Result { s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into())) @@ -271,7 +294,7 @@ fn grid(s: &mut Session, p: &Value) -> Result { .enumerate() .filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center())))) .collect(); - transform_each(s, "Arrange in Grid", false, &xfs)?; + transform_each(s, "Arrange in Grid", p, false, s.prefs.scale_corners, &xfs)?; Ok(json!({ "count": n })) } @@ -308,7 +331,7 @@ fn offset(s: &mut Session, p: &Value) -> Result { if !moves { return Ok(json!({ "count": items.len() })); } - let p = json!({ "strokes": false }); + let p = scaling_params(p, false, s.prefs.scale_corners); let ids: Vec = items.iter().map(|(id, _, _)| *id).collect(); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &ids)?; @@ -362,12 +385,13 @@ fn swap(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.swap"; let size = switch_or(p, "size", false, C)?; let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let roots = selected_roots(s)?; let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) }; let (ba, bb) = (box_of(s, a)?, box_of(s, b)?); - let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes); + let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes, corners); let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)]; - transform_each(s, "Swap Objects", strokes, &xfs)?; + transform_each(s, "Swap Objects", p, strokes, corners, &xfs)?; Ok(json!({})) } @@ -375,6 +399,7 @@ fn replace(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.replace"; let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep"); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let keep = switch_or(p, "keep", false, C)?; let roots = selected_roots(s)?; let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else { @@ -394,9 +419,9 @@ fn replace(s: &mut Session, p: &Value) -> Result { } _ => None, }; - xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?)); + xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes, corners), top)?)); } - let p = json!({ "strokes": strokes }); + let p = scaling_params(p, strokes, corners); let mut sc = scaling(s, &p); sc.patterns = transform_patterns(s, &p, &[top])?; let ids = s.edit("Replace with Top Object", |d, sel| { @@ -426,7 +451,8 @@ fn size(s: &mut Session, p: &Value) -> Result { let proportional = switch_or(p, "proportional", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); let strokes = scale_strokes(s, p, C)?; - let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }); + let corners = scale_corners(s, p, C)?; + let mut q = json!({ "reference": reference, "strokes": strokes, "corners": corners, "proportional": proportional && (width.is_none() || height.is_none()) }); if let Some(w) = width { q["width"] = json!(w); } @@ -439,7 +465,7 @@ fn size(s: &mut Session, p: &Value) -> Result { xfs.push((id, object_bounds_transform(s, &q, id)?)); } } - transform_each(s, "Set Size of Each", strokes, &xfs)?; + transform_each(s, "Set Size of Each", p, strokes, corners, &xfs)?; Ok(json!({ "count": xfs.len() })) } @@ -471,6 +497,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let stacking = switch_or(p, "stacking", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?; if size == "none" && !rotate && !stacking { return Err(bad(C, "give `size`, `rotate` or `stacking`")); @@ -502,6 +529,11 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { }; let angle = s.doc()?.doc.bbox_angle(&[source]); let mut xfs = Vec::with_capacity(targets.len()); + // Where each turned target's reference point is before the match; it stays there. + let mut pinned: HashMap = HashMap::new(); + // The turned targets whose reference point is checked after pixel snapping. + let mut checked: HashMap = HashMap::new(); + let symbols = if rotate { aligned_symbols(&s.doc()?.doc) } else { HashMap::new() }; for &id in &targets { let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 }; let Some(b) = s.transform_box(&[id]) else { @@ -518,36 +550,29 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let mut q = q.clone(); q["reference"] = json!(reference); q["strokes"] = json!(strokes); - xf = object_bounds_transform(s, &q, id)?; + q["corners"] = json!(corners); + // Any scale the source's size asks for, however small. + xf = object_bounds_transform_keeping(s, &q, id, 0.0)?; } + // Rotation and the fit below keep the reference point in place. + let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); + let turned = Affine::rotate_about(-turn.to_radians(), at); if turn.abs() > 1e-9 { - // Rotation uses the reference point that sizing keeps in place. - let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); - xf = Affine::rotate_about(-turn.to_radians(), at) * xf; + xf = turned * xf; + let preview = s.bounds_measure().preview; + let d = &s.doc()?.doc; + if preview && d.node(id).is_some_and(|n| effects::preview::draws_geometry(&d.symbol_boxes(), n)) { + pinned.insert(id, at); + } + // Pixel snapping after the turn can move a pixel-aligned target: its point is checked + // too, but not put back, since that would move its aligned art off the grid. + if pinned.contains_key(&id) || d.node(id).is_some_and(|n| snaps_after_edit(n, &symbols)) { + checked.insert(id, at); + } } if wanted.is_some() { - let sc = scaling(s, &json!({ "strokes": strokes })); - let d = &s.doc()?.doc; - let symbols = d.symbol_boxes(); - let measure = |xf| { - d.node(id).and_then(|n| { - let mut n = n.clone(); - transform_node(&mut n, xf, sc, true); - let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO }; - effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure()) - }) - }; - let misses = |measured: Option| { - measured.is_none_or(|r| match size { - "width" => (r.width() - w).abs() > 1e-6, - "height" => (r.height() - h).abs() > 1e-6, - _ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6, - }) - }; - // The sized and turned object, measured in its final frame, must have the size asked for. - if misses(measure(xf)) { - return Err(bad(C, format!("object {} can't take the requested size", id.0))); - } + let fit = Fit { at, refi: reference as usize, goal: match_goal(size, (w, h), b.rect), strokes, corners }; + xf = fit_turned(s, id, (xf, turned), fit).ok_or_else(|| bad(C, format!("object {} can't take the requested size", id.0)))?; } xfs.push((id, xf)); } @@ -564,6 +589,32 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "a clipping path can't change its place in the stacking order")); } let parent = d.parent_of(source); + // Each target leaves its own container, so a target's locked container refuses too. + let locked = |p: Option| p.is_some_and(|p| crate::cmd::layer::locked_within(d, p)); + if locked(parent) || targets.iter().any(|t| locked(d.parent_of(*t))) { + return Err(bad(C, "the layer or group is locked")); + } + // A blend's input objects, and art inside them, stay in the blend: the whole blend can still be + // restacked, and art can still move within the blend's input it is in. + let is_blend = |a: &NodeId| d.node(*a).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. })); + let destination = parent.and_then(|p| d.ancestry(p)).unwrap_or_default(); + let leaves_blend = |t: &NodeId| { + let chain = d.ancestry(*t).unwrap_or_default(); + chain.windows(2).filter(|w| is_blend(&w[0])).any(|w| !destination.windows(2).any(|v| v == w)) + }; + if targets.iter().any(leaves_blend) { + return Err(bad(C, "a blend's input objects can't leave their blend input: to restack the blend, select the whole blend")); + } + // Live Paint art is rebuilt from its paths when they move: Match Objects leaves it in place. + let in_live_paint = + |id: NodeId| d.ancestry(id).unwrap_or_default().iter().any(|a| d.node(*a).is_some_and(vectorcraft_tools::builder::is_live_paint)); + if parent.is_some_and(in_live_paint) || targets.iter().any(|t| d.parent_of(*t).is_some_and(in_live_paint)) { + return Err(bad(C, "Live Paint art can't be restacked here: use the Layers panel")); + } + // The source's container takes each target only as the Layers panel would (not a blend's inputs). + if let Some(n) = targets.iter().filter_map(|id| d.node(*id)).find(|n| !crate::cmd::layer::accepts(d, parent, n)) { + return Err(bad(C, format!("{} can't go beside the source object", n.display_name()))); + } if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) { return Err(bad(C, format!("{what} can't be intertwined"))); } @@ -574,15 +625,30 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { if xfs.is_empty() && !restack { return Ok(count); } - let q = json!({ "strokes": strokes, "patterns": patterns }); + let q = json!({ "strokes": strokes, "corners": corners, "patterns": patterns }); let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &q); sc.patterns = transform_patterns(s, &q, &ids)?; + let measure = s.bounds_measure(); + let before = s.doc()?.doc.clone(); s.edit("Match Objects", |d, _| { for (id, xf) in &xfs { if let Some(n) = d.node_mut(*id) { transform_node(n, *xf, sc, true); } + // A live effect that moves the art in page space (a Transform effect's offset) does + // not turn with it: the measured reference point is put back where it was. + if let Some(at) = pinned.get(id) + && let Some(b) = effects::preview::oriented_bounds_with(d, &[*id], measure) + { + let now = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); + let off = *at - now; + if off.hypot() > 1e-9 + && let Some(n) = d.node_mut(*id) + { + transform_node(n, Affine::translate(off), sc, true); + } + } } if restack { let moved = d.remove_many(&targets)?; @@ -590,11 +656,113 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { // Targets moved out of an Intertwine group leave it as ordinary art. crate::cmd::intertwine::settle_members(d, &placed, &left)?; } + if !checked.is_empty() { + // Measured on a snapped copy: the edit itself snaps once, after Global Edit. + let mut snapped = d.clone(); + crate::cmd::refresh_pixel_aligned(&before, &mut snapped); + for (id, _) in &xfs { + let Some(at) = checked.get(id) else { continue }; + let ob = effects::preview::oriented_bounds_with(&snapped, &[*id], measure); + let kept = ob.is_some_and(|b| (*at - b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize)).hypot() <= 1e-6); + let misses = !kept + || ob.is_none_or(|b| match size { + "none" => false, + "width" => (b.rect.width() - w).abs() > 1e-6, + "height" => (b.rect.height() - h).abs() > 1e-6, + _ => (b.rect.width() - w).abs() > 1e-6 || (b.rect.height() - h).abs() > 1e-6, + }); + if misses { + return Err(bad(C, format!("object {} can't keep its size and reference point as it turns", id.0))); + } + } + } Ok(()) })?; Ok(count) } +/// The size a target of Match Objects ends with: for `size` "width" ("height") the source's width +/// `w` (height `h`), the other side following in proportion to the target's box `b`; for "both", the +/// source's width and height. +fn match_goal(size: &str, (w, h): (f64, f64), b: Rect) -> [f64; 2] { + let follow = |side: f64, from: f64, to: f64| if from > 0.0 { side * to / from } else { side }; + match size { + "width" => [w, follow(b.height(), b.width(), w)], + "height" => [follow(b.width(), b.height(), h), h], + _ => [w, h], + } +} + +/// What [`fit_turned`] fits a target of Match Objects to. +struct Fit { + /// The target's reference point, which stays in place. + at: Point, + /// That point's index on the 9-point grid. + refi: usize, + /// The width and height wanted ([`match_goal`]). + goal: [f64; 2], + /// Scale Strokes & Effects. + strokes: bool, + /// Scale Corners. + corners: bool, +} + +/// `xf`, which sizes and turns object `id`, made to give the object the size `fit.goal` (within +/// 1e-9 of the larger of 1 and each side) as `object.setBounds` measures it in the frame the object +/// ends in. When it misses, for example when a stroke or an effect does not turn with the art, +/// scales in that frame are fitted with [`refit_drawn`] from the object turned by `turned` alone, +/// and point `fit.refi` of the fitted box goes to `fit.at`. The object is measured before Align to +/// Pixel Grid snaps it, as every transform snaps it after. `None` when no scale gives the size. +fn fit_turned(s: &mut Session, id: NodeId, (xf, turned): (Affine, Affine), fit: Fit) -> Option { + let Fit { at, refi, goal, strokes, corners } = fit; + let sc = scaling(s, &json!({ "strokes": strokes, "corners": corners })); + let how = s.bounds_measure(); + let d = &s.doc().ok()?.doc; + let symbols = d.symbol_boxes(); + let n = d.node(id)?; + let moved = |xf: Affine| { + let mut n = n.clone(); + n.transform(xf, sc); + n + }; + // The angle the object's box ends at after `xf`, as `Node::transform` sets it (a layer keeps its own). + let angle_after = |xf: Affine| if n.is_layer() { n.bbox_angle } else { vectorcraft_doc::orient::transformed_angle(n.bbox_angle, xf) }; + // The frame the turn gives; sizing can leave the art without a width or a height to show it. + let frame = OrientedBox { angle: angle_after(turned), rect: Rect::ZERO }; + let to_local = frame.to_doc().inverse(); + let measure = |xf: Affine| effects::preview::bounds_in_with(&symbols, &moved(xf), to_local, how); + let tolerances = goal.map(|side| 1e-9 * side.max(1.0)); + let fits = |r: Rect| [r.width(), r.height()].into_iter().zip(goal).zip(tolerances).all(|((v, g), t)| (v - g).abs() <= t); + let keeps_angle = |xf: Affine| vectorcraft_geom::normalize_deg(angle_after(xf) - frame.angle).abs() <= 1e-6; + let rp = frame.to_local(at); + // The object turned by `turned`, then scaled by `sx` and `sy` in the frame about the reference point. + let scaled = |sx: f64, sy: f64| { + frame.conjugate(Affine::translate(rp.to_vec2()) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-rp.to_vec2())) * turned + }; + // `xf` with point `refi` of the box as measured moved to the reference point's place: a stroke + // or an effect that does not turn with the art moves it. + let placed = |xf: Affine| -> Option<(Affine, Rect)> { + let b = measure(xf)?; + let correction = rp - vectorcraft_geom::reference_point(b, refi); + if correction.x.abs() <= 1e-12 && correction.y.abs() <= 1e-12 { + return Some((xf, b)); + } + let xf = frame.conjugate(Affine::translate(correction)) * xf; + Some((xf, measure(xf)?)) + }; + let accepts = |xf: Affine, b: Rect| fits(b) && keeps_angle(xf); + if let Some((xf, _)) = placed(xf).filter(|(xf, b)| accepts(*xf, *b)) { + return Some(xf); + } + // The sizing above can leave the art without a width or a height that the turned object needs, + // so the fit starts again from the object as it is, turned. + let now = measure(turned)?; + let ratio = |g: f64, v: f64| if v > 1e-9 { g / v } else { 1.0 }; + let start = (ratio(goal[0], now.width()), ratio(goal[1], now.height())); + let (sx, sy, _) = refit_drawn(|sx, sy| measure(scaled(sx, sy)), refi, goal, start, [true, true], Some(tolerances))?; + placed(scaled(sx, sy)).filter(|(xf, b)| accepts(*xf, *b)).map(|(xf, _)| xf) +} + /// The sets of two or more of `items` (each in the order given) whose rects overlap or touch, /// chains included, among items of the same key (parent). A sweep along x: only the rects still /// open where each one starts are compared with it. @@ -841,6 +1009,7 @@ fn sort(s: &mut Session, p: &Value) -> Result { let distribute = switch_or(p, "distribute", false, C)?; let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); let strokes = scale_strokes(s, p, C)?; + let corners = scale_corners(s, p, C)?; let ids = checked_ids_or_selection(s, p, C)?; if ids.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); @@ -923,17 +1092,17 @@ fn sort(s: &mut Session, p: &Value) -> Result { let q = match apply { "x" => json!({ "x": v, "reference": 0 }), "y" => json!({ "y": v, "reference": 0 }), - "width" => json!({ "width": v, "strokes": strokes }), - "height" => json!({ "height": v, "strokes": strokes }), + "width" => json!({ "width": v, "strokes": strokes, "corners": corners }), + "height" => json!({ "height": v, "strokes": strokes, "corners": corners }), // An area: both sides in proportion; an object without one keeps its size. _ => { let (w, h) = (o.b.rect.width(), o.b.rect.height()); let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 }; - json!({ "width": w * k, "height": h * k, "strokes": strokes }) + json!({ "width": w * k, "height": h * k, "strokes": strokes, "corners": corners }) } }; xfs.push((o.id, object_bounds_transform(s, &q, o.id)?)); } - transform_each(s, "Sort Objects", strokes, &xfs)?; + transform_each(s, "Sort Objects", p, strokes, corners, &xfs)?; Ok(count) } diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs new file mode 100644 index 0000000000..d849047fb9 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -0,0 +1,202 @@ +//! Add Artboard Guides (`addon.arrange.artboardGuides`): a rectangular guide around each chosen +//! artboard, `offset` outside its edges (inside when negative), on a top-level layer named +//! Artboard Guides. Its dialog is the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::HashSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes}; + +use super::super::super::panelcmds::{artboard_at, listed_artboards}; +use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; +use super::{LIMIT, number_in}; +use crate::sanity::rect_in_range; +use crate::{DocState, Result, Session}; + +/// The command. +pub(crate) const COMMAND: &str = "addon.arrange.artboardGuides"; +/// The top-level layer the guides go on, made when the document has none of that name. +pub(crate) const LAYER: &str = "Artboard Guides"; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.arrange.artboardGuides", + "Add Artboard Guides", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{offset?: pt −1000000..1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside), artboards?: [index…] (0-based; default: the active artboard, `artboard`), artboard?: index (the active artboard, which the app passes; default the view's, which the journal then records as `artboard` for a replay), all?: false (true: every artboard; not with `artboards`)} add a rectangular guide path around each of those artboards, `offset` from its edges, as one undo step. The guides go on the topmost top-level layer named Artboard Guides, which keeps its lock and visibility; a new one is made above the others when there is none. The guide paths have the current paint (Release Guides makes them paths with it). A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. It is an error when an inset leaves an artboard no width or no height, and when an edge of a guide would lie more than 4,000,000 pt from the origin along either axis. Off without artboards → {ids, layer: id (null when nothing was added and there is no such layer), skipped (guides already there)}", + has_artboards, + artboard_guides + )] +} + +/// A document with at least one artboard is open. +fn has_artboards(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.doc().map_err(|e| e.to_string())?.doc.artboards.is_empty() { Err("the document has no artboards".into()) } else { Ok(()) } +} + +/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no +/// longer has it, the artboard the document opened on, else the first. +fn active_artboard(st: &DocState) -> usize { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).unwrap_or(0) +} + +/// The topmost top-level layer named [`LAYER`]. +fn guide_layer(d: &Document) -> Option { + d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id) +} + +/// `r`'s corners as an exact hash key, whichever way round `r` runs. +fn rect_key(r: Rect) -> [u64; 4] { + let r = r.abs(); + [r.x0, r.y0, r.x1, r.y1].map(|v| if v == 0.0 { 0 } else { v.to_bits() }) +} + +#[cfg(test)] +thread_local! { + static GUIDE_NODES_VISITED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn guide_rectangles(d: &Document, layer: Option) -> HashSet<[u64; 4]> { + let mut rects = HashSet::new(); + if let Some(n) = layer.and_then(|id| d.node(id)) { + n.walk(&mut |c| { + #[cfg(test)] + GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1)); + // The anchors' bounds: `traces` only accepts segments that stay between their anchors. + if let NodeKind::Path { path, guide: true, .. } = &c.kind + && let [sp] = &path.subpaths[..] + && let Some(first) = sp.anchors.first() + { + let r = sp.anchors.iter().fold(Rect::from_points(first.p, first.p), |r, a| r.union_pt(a.p)); + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + if traces(path, &corners) { + rects.insert(rect_key(r)); + } + } + }); + } + rects +} + +/// Does the segment from `a` to `b` run straight along a horizontal or vertical line, from `a` to `b` +/// without turning back? Its handles lie on that line, and the curve's position along it never reverses. +fn straight(a: &Anchor, b: &Anchor) -> bool { + let along = |f: fn(Point) -> f64, g: fn(Point) -> f64| { + if [a.h_out, b.h_in].iter().any(|h| g(*h) != g(a.p)) || g(a.p) != g(b.p) { + return false; + } + let s = (f(b.p) - f(a.p)).signum(); + let [p0, p1, p2, p3] = [a.p, a.h_out, b.h_in, b.p].map(|p| f(p) * s); + // The derivative along the line, as a quadratic Bernstein form: never negative on [0, 1]. + let (u, v, w) = (p1 - p0, p2 - p1, p3 - p2); + let curve = u - 2.0 * v + w; + let vertex = if curve > 0.0 && (0.0..=1.0).contains(&((u - v) / curve)) { u - (u - v) * (u - v) / curve } else { 0.0 }; + u >= 0.0 && w >= 0.0 && vertex >= 0.0 + }; + if a.p == b.p { + return a.h_out == a.p && b.h_in == a.p; + } + along(|p| p.x, |p| p.y) || along(|p| p.y, |p| p.x) +} + +/// Is `path` one closed run of straight segments through `corners`, from any corner, either way round? +fn traces(path: &PathData, corners: &[Point; 4]) -> bool { + let [sp] = &path.subpaths[..] else { return false }; + if !sp.closed || sp.anchors.len() < 4 { + return false; + } + let n = sp.anchors.len(); + if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) { + return false; + } + let points: Vec = sp + .anchors + .iter() + .enumerate() + .filter_map(|(i, a)| { + let prev = sp.anchors[(i + sp.anchors.len() - 1) % sp.anchors.len()].p; + let next = sp.anchors[(i + 1) % sp.anchors.len()].p; + let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y)) + || (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x)); + (!interior).then_some(a.p) + }) + .collect(); + let [first, second, _, _] = &points[..] else { return false }; + let (Some(start), Some(next)) = (corners.iter().position(|c| c == first), corners.iter().position(|c| c == second)) else { + return false; + }; + // 1 runs the way `corners` does, 3 the other way. + let step = (next + 4 - start) % 4; + (step == 1 || step == 3) && points.iter().enumerate().all(|(k, p)| *p == corners[(start + k * step) % 4]) +} + +fn artboard_guides(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?; + let all = switch_or(p, "all", false, C)?; + let listed = p.get("artboards").filter(|v| !v.is_null()); + if all && listed.is_some() { + return Err(bad(C, "give `all` or `artboards`, not both")); + } + let st = s.doc()?; + let d = &st.doc; + if d.artboards.is_empty() { + return Err(bad(C, "the document has no artboards")); + } + // The active artboard: the one the app passes, else the view's, recorded for a replay. + let active = artboard_at(d, p, "artboard", C)?; + let indices: Vec = match listed { + Some(v) => listed_artboards(d, v, "artboards", C)?, + None if all => (0..d.artboards.len()).collect(), + None => vec![active.unwrap_or_else(|| active_artboard(st))], + }; + if let (false, None, None, Some(&i)) = (all, listed, active, indices.first()) { + s.note_journal("artboard", json!(i)); + } + let st = s.doc()?; + let d = &st.doc; + let layer = guide_layer(d); + let mut existing = guide_rectangles(d, layer); + let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0); + for i in indices { + let Some(board) = d.artboards.get(i) else { continue }; + let r = board.rect.inflate(offset, offset); + if !(r.width() > 0.0 && r.height() > 0.0) { + return Err(bad(C, format!("the inset leaves artboard {i} ({}) no width or height", board.name))); + } + if !rect_in_range(r) { + return Err(bad(C, "the guide would reach past the edge of the canvas")); + } + if !existing.insert(rect_key(r)) { + skipped += 1; + } else { + rects.push(r); + } + } + if rects.is_empty() { + return Ok(json!({ "ids": [], "layer": layer.map(|l| l.0), "skipped": skipped })); + } + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let (layer, ids) = s.edit("Add Artboard Guides", |d, _| { + let layer = guide_layer(d).unwrap_or_else(|| d.add_layer(Some(LAYER))); + let mut ids = Vec::with_capacity(rects.len()); + for r in &rects { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), Default::default()); + look.apply(d, &mut n); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + ids.push(d.insert(Some(layer), usize::MAX, n)?); + } + Ok((layer, ids)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "skipped": skipped })) +} diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs new file mode 100644 index 0000000000..5152dcffe9 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -0,0 +1,312 @@ +//! Add Artboard Guides: the guide rectangles it adds and where, the artboards it takes, the layer +//! it reuses, one undo step (none when nothing is added), when it is off, and bad params refused +//! without a change. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + +use super::{COMMAND, LAYER}; +use crate::Session; + +/// A new document with one 400 × 300 pt artboard and a second one beside it. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("artboard.new", &json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn board(s: &Session, i: usize) -> Rect { + s.doc().unwrap().doc.artboards[i].rect +} + +fn ids(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() +} + +/// The guide rectangle of path `id`: its bounds, and that it is a guide on layer `layer`. +fn guide(s: &Session, layer: NodeId, id: NodeId) -> Rect { + let d = &s.doc().unwrap().doc; + let n = d.node(id).unwrap(); + assert!(matches!(n.kind, NodeKind::Path { guide: true, .. }), "{id:?} is a guide path"); + assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == id), "{id:?} is on the guides layer"); + n.geometric_bounds().unwrap() +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9) +} + +fn layer_names(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +#[test] +fn a_positive_offset_puts_a_guide_outside_the_active_artboard_on_a_new_layer() { + let mut s = session(); + let n = steps(&s); + let before = layer_names(&s); + let r = s.execute(COMMAND, &json!({"offset": 9})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let layer = NodeId(r["layer"].as_u64().unwrap()); + assert_eq!(r["skipped"], json!(0)); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + // The active artboard is the first when the view has not picked one. + assert!(near(guide(&s, layer, id), board(&s, 0).inflate(9.0, 9.0)), "{:?}", guide(&s, layer, id)); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.last().unwrap().id, layer, "the new layer goes above the others"); + assert_eq!(d.layers.last().unwrap().display_name(), LAYER); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_names(&s), before, "undo takes the layer away with the guide"); +} + +#[test] +fn the_active_artboard_is_the_one_the_view_keeps() { + let mut s = session(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 1)), "offset 0: on the artboard's edges"); + assert_eq!(s.journal.last().unwrap().1["artboard"], json!(1), "the journal records the artboard for a replay"); + // The artboard the app passes wins over the view's. + let r = s.execute(COMMAND, &json!({"offset": 4, "artboard": 0})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 0).inflate(4.0, 4.0))); + assert!(s.execute(COMMAND, &json!({"artboard": 5})).is_err(), "no such artboard"); +} + +#[test] +fn a_negative_offset_insets_every_artboard_and_reuses_the_layer_keeping_its_lock_and_visibility() { + let mut s = session(); + let layer = NodeId(s.execute("layer.new", &json!({"name": LAYER})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap(); + let (layers, n) = (s.doc().unwrap().doc.layers.len(), steps(&s)); + let r = s.execute(COMMAND, &json!({"offset": -12, "all": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step for every artboard"); + assert_eq!(r["layer"], json!(layer.0), "the layer of that name is reused"); + assert_eq!(s.doc().unwrap().doc.layers.len(), layers, "no layer is added"); + let added = ids(&r); + assert_eq!(added.len(), 2); + for (i, id) in added.into_iter().enumerate() { + assert!(near(guide(&s, layer, id), board(&s, i).inflate(-12.0, -12.0)), "artboard {i}"); + } + let l = s.doc().unwrap().doc.node(layer).unwrap().clone(); + assert!(l.locked && !l.visible, "the layer keeps its lock and visibility"); +} + +#[test] +fn listed_artboards_get_a_guide_each_and_a_guide_already_there_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1]})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 1).inflate(5.0, 5.0))); + // Again: nothing to add, and no undo step. + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1, 1]})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1})); + assert_eq!(steps(&s), n, "a run that adds nothing makes no step"); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before) || *s.doc().unwrap().doc == *before); + // Both artboards: only the new one is added. + let both = s.execute(COMMAND, &json!({"offset": 5, "artboards": [0, 1]})).unwrap(); + assert_eq!(both["skipped"], json!(1)); + let [first] = ids(&both)[..] else { panic!("one guide: {both}") }; + assert!(near(guide(&s, layer, first), board(&s, 0).inflate(5.0, 5.0))); + assert_eq!(steps(&s), n + 1); +} + +#[test] +fn a_guide_grouped_inside_the_layer_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == group)); + assert!(d.node(group).unwrap().children().unwrap().iter().any(|c| c.id == id)); + let (before, n) = (d.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1})); + assert_eq!(steps(&s), n, "a run that adds nothing makes no step"); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); +} + +#[test] +fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0).inflate(5.0, 5.0); + let corners = [Point::new(b.x0, b.y1), Point::new(b.x1, b.y1), Point::new(b.x1, b.y0), Point::new(b.x0, b.y0)]; + // Reversed from the top-left corner, reversed from the bottom-left one, and the same way round from the bottom-right one. + for points in [vec![corners[3], corners[0], corners[1], corners[2]], corners.to_vec(), vec![corners[1], corners[0], corners[3], corners[2]]] { + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(NodeKind::Path { path, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = PathData::single(SubPath::polyline(&points, true)); + } + let n = steps(&s); + let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}), "{points:?}"); + assert_eq!(steps(&s), n); + } +} + +#[test] +fn collinear_midpoints_do_not_add_another_guide_or_history_step() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0); + let points = [ + Point::new(b.center().x, b.y0), + Point::new(b.x1, b.y0), + Point::new(b.x1, b.center().y), + Point::new(b.x1, b.y1), + Point::new(b.center().x, b.y1), + Point::new(b.x0, b.y1), + Point::new(b.x0, b.center().y), + Point::new(b.x0, b.y0), + ]; + for reverse in [false, true] { + let mut points = points.to_vec(); + if reverse { + points.reverse(); + } + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") }; + *path = PathData::single(SubPath::polyline(&points, true)); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1})); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc, before); + } +} + +#[test] +fn handles_along_a_side_still_match_and_handles_off_it_do_not() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0); + let mid = Point::new(b.center().x, b.y0); + let points = [mid, Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1), Point::new(b.x0, b.y0)]; + let corner = points[1]; + let set = |s: &mut Session, h_in: Point, h_out: Point, corner_in: Point| { + let mut sp = SubPath::polyline(&points, true); + sp.anchors[0].h_in = h_in; + sp.anchors[0].h_out = h_out; + sp.anchors[1].h_in = corner_in; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") }; + *path = PathData::single(sp); + }; + // The extra anchor's handles lie along the top side: the guide still matches. + // Then a handle past the corner on a segment that still runs one way (along x: 0, 9, 6, 8 eighths). + let eighth = (corner.x - mid.x) / 8.0; + for (h_out, corner_in) in + [(Point::new(mid.x + 20.0, b.y0), corner), (Point::new(mid.x + 9.0 * eighth, b.y0), Point::new(mid.x + 6.0 * eighth, b.y0))] + { + set(&mut s, Point::new(mid.x - 20.0, b.y0), h_out, corner_in); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "{h_out:?} {corner_in:?}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc, before); + } + // A handle off the side bends it: the path is not that guide, so one is added. + set(&mut s, Point::new(mid.x - 20.0, b.y0), Point::new(mid.x + 20.0, b.y0 + 10.0), corner); + let other = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(other["skipped"], json!(0)); + assert_eq!(ids(&other).len(), 1); +} + +#[test] +fn every_artboard_shares_one_walk_of_existing_guides() { + let mut s = session(); + s.execute(COMMAND, &json!({"all": true})).unwrap(); + super::GUIDE_NODES_VISITED.with(|count| count.set(0)); + s.execute(COMMAND, &json!({})).unwrap(); + let single = super::GUIDE_NODES_VISITED.with(|count| count.replace(0)); + assert!(single > 0); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"all": true})).unwrap(); + assert_eq!(super::GUIDE_NODES_VISITED.with(|count| count.get()), single); + assert!(ids(&r).is_empty()); + assert_eq!(r["skipped"], json!(2)); + assert_eq!(steps(&s), n); +} + +#[test] +fn release_guides_gives_back_a_rectangle_path() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 3})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + s.execute("view.guides.release", &json!({"ids": [id.0]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(n.kind, NodeKind::Path { guide: false, .. })); + assert!(near(n.geometric_bounds().unwrap(), board(&s, 0).inflate(3.0, 3.0))); +} + +#[test] +fn an_inset_that_leaves_no_width_or_height_and_bad_params_are_refused_without_a_change() { + let mut s = session(); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + // The second artboard is 100 pt tall: an inset of 50 leaves it no height. + for p in [ + json!({"offset": -50, "all": true}), + json!({"offset": -200}), + json!({"offset": "9 pt"}), + json!({"offset": 1_000_001}), + json!({"offset": -1e308}), + json!({"all": 1}), + json!({"all": true, "artboards": [0]}), + json!({"artboards": []}), + json!({"artboards": [2]}), + json!({"artboards": [-1]}), + json!({"artboards": [0.5]}), + json!({"artboards": "0"}), + ] { + assert!(s.execute(COMMAND, &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); + let e = s.execute(COMMAND, &json!({"offset": -150})).unwrap_err().to_string(); + assert!(e.contains("no width or height"), "{e}"); +} + +#[test] +fn a_guide_past_the_edge_of_the_canvas_is_refused() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 3_999_000, "y": 0, "width": 500, "height": 100})).unwrap(); + let n = steps(&s); + let e = s.execute(COMMAND, &json!({"offset": 600, "artboards": [2]})).unwrap_err().to_string(); + assert!(e.contains("past the edge of the canvas"), "{e}"); + assert_eq!(steps(&s), n); + s.execute(COMMAND, &json!({"offset": 400, "artboards": [2]})).unwrap(); +} + +#[test] +fn it_is_off_without_artboards() { + let mut s = session(); + let enabled = |s: &Session| s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled; + assert!(enabled(&s)); + Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear(); + assert!(!enabled(&s)); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index bb38e9437e..b98d45ae0a 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -439,6 +439,19 @@ fn match_gives_the_others_the_key_objects_size() { assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c)); } +#[test] +fn match_keeps_the_proportion_of_a_very_thin_target() { + let b = Rect::new(0.0, 0.0, 1e-10, 1.0); + let [w, h] = super::match_goal("width", (1.0, 5.0), b); + assert_eq!(w, 1.0); + assert!((h - 1e10).abs() <= 1.0, "{h}"); + let [w, h] = super::match_goal("height", (5.0, 1.0), Rect::new(0.0, 0.0, 1.0, 1e-10)); + assert!((w - 1e10).abs() <= 1.0, "{w}"); + assert_eq!(h, 1.0); + // A target with no width keeps its height. + assert_eq!(super::match_goal("width", (1.0, 5.0), Rect::new(0.0, 0.0, 0.0, 3.0)), [1.0, 3.0]); +} + #[test] fn match_takes_the_top_or_the_bottom_object_without_a_key() { let mut s = session(); @@ -512,6 +525,67 @@ fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() { } } +#[test] +fn match_rotation_refuses_when_pixel_snapping_would_move_the_reference_point() { + for wrap in ["path", "group", "compound"] { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 10.0, 11.0); + if wrap != "compound" { + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + } + let target = match wrap { + "group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()), + "compound" => NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()), + _ => target, + }; + select(&mut s, &[target]); + if wrap == "compound" { + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + } + let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0); + select(&mut s, &[source]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + // Turned a quarter about its center (5, 5.5), the 10 x 11 path's edges land on half points, + // and snapping them back to the grid would move that center. + let e = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string(); + assert!(e.contains("reference point"), "{wrap}: {e}"); + assert_eq!(steps(&s), n, "{wrap}: no undo step"); + assert!(*s.doc().unwrap().doc == *before, "{wrap}"); + } +} + +#[test] +fn match_rotation_keeps_a_mixed_group_in_one_piece_or_refuses() { + let mut s = session(); + let aligned = rect(&mut s, 0.0, 0.0, 10.0, 11.0); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let loose = rect(&mut s, 20.0, 0.0, 10.0, 11.0); + select(&mut s, &[aligned, loose]); + let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0); + select(&mut s, &[source]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let gap = |s: &Session| { + let (a, b) = (s.transform_box(&[aligned]).unwrap().center(), s.transform_box(&[loose]).unwrap().center()); + b - a + }; + let before = s.doc().unwrap().doc.clone(); + match s.execute("addon.arrange.match", &json!({"rotate": true})) { + // Turned a quarter, the members' centers keep their distance and only change direction. + Ok(_) => assert!((gap(&s).hypot() - 20.0).abs() < 1e-6, "the members moved apart: {:?}", gap(&s)), + Err(e) => { + assert!(e.to_string().contains("reference point"), "{e}"); + assert!(*s.doc().unwrap().doc == *before); + } + } +} + #[test] fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() { for angle in [0, 30] { @@ -638,6 +712,44 @@ fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) { assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s)); } +/// Running `cmd` with Scale Corners on doubles the 2 pt corner radius of a 10 pt rounded square, +/// and replaying its journal entry after the preference is turned off scales the corners the same way. +fn replays_the_corner_scaling_it_ran_with(cmd: &str, p: Value) { + let mut s = session(); + let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10, "radius": 2})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + let radius = |s: &Session| match s.doc().unwrap().doc.node(a).unwrap().live_shape() { + Some(vectorcraft_doc::LiveShape::Rectangle { radii, xf, .. }) => radii[0] * xf.as_coeffs()[0], + _ => panic!("not a live rectangle"), + }; + select(&mut s, &[a, b]); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap(); + s.execute(cmd, &p).unwrap(); + assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", radius(&s)); + let (id, q) = s.journal.last().unwrap().clone(); + assert_eq!(id, cmd); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap(); + select(&mut s, &[a, b]); + s.replay(&id, &q).unwrap(); + assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", radius(&s)); +} + +#[test] +fn match_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); +} + +#[test] +fn set_size_of_each_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20})); +} + +#[test] +fn swap_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_scaling_it_ran_with("addon.arrange.swap", json!({"size": true})); +} + #[test] fn match_stacking_leaves_a_clipping_path_in_place() { let mut s = session(); @@ -664,6 +776,16 @@ fn match_size_refuses_a_target_with_no_width() { assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line)); } +#[test] +fn match_size_refuses_a_target_with_no_width_for_a_narrow_tall_source() { + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 100.0, 0.0, 0.05, 100000.0); + select(&mut s, &[line, b]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"size": "both"})]); +} + #[test] fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() { let mut s = session(); @@ -750,6 +872,234 @@ fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() { assert!(*s.doc().unwrap().doc == *before); } +#[test] +fn match_refuses_restacking_into_a_locked_container() { + for lock_ancestor in [false, true] { + let mut s = session(); + let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[source]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[group]); + let ancestor = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let locked = if lock_ancestor { ancestor } else { group }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(locked).unwrap().locked = true; + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"size": "both", "stacking": true})).unwrap_err(); + assert!(e.to_string().contains("the layer or group is locked"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + } +} + +#[test] +fn match_refuses_restacking_among_a_blends_inputs() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let target = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, target]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("can't go beside the source object"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn match_refuses_taking_a_target_out_of_a_locked_container() { + let mut s = session(); + let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0); + select(&mut s, &[target]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().locked = true; + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("the layer or group is locked"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn match_refuses_taking_a_target_out_of_a_blend_but_restacks_the_whole_blend() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let blend = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let source = rect(&mut s, 250.0, 0.0, 20.0, 20.0); + assert_eq!(layer_order(&s), [blend, between, source]); + select(&mut s, &[a, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("a blend's input objects"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + select(&mut s, &[blend, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(layer_order(&s), [between, source, blend]); +} + +#[test] +fn match_refuses_restacking_live_paint_art_but_moves_beside_a_whole_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let target = rect(&mut s, 250.0, 0.0, 20.0, 20.0); + assert_eq!(layer_order(&s), [g, between, target]); + let member = s.doc().unwrap().doc.children(Some(g)).unwrap()[0].id; + select(&mut s, &[member, target]); + s.execute("select.key", &json!({"id": member.0})).unwrap(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("Live Paint art"), "{e}"); + assert_eq!(steps(&s), n); + select(&mut s, &[g, target]); + s.execute("select.key", &json!({"id": g.0})).unwrap(); + let before = s.doc().unwrap().doc.node(g).unwrap().clone(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(layer_order(&s), [g, target, between]); + assert_eq!(s.doc().unwrap().doc.node(g).unwrap(), &before); +} + +#[test] +fn match_turns_art_with_a_moving_effect_about_its_measured_point() { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + s.execute("effect.apply", &json!({"ids": [b.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let center = |s: &Session| { + let bx = s.transform_box(&[b]).unwrap(); + bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4) + }; + let before = center(&s); + select(&mut s, &[a, b]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap(); + let after = center(&s); + assert!((after - before).hypot() < 1e-6, "{before:?} -> {after:?}"); +} + +#[test] +fn match_checks_a_pixel_aligned_symbols_measured_point_after_snapping() { + for size in ["none", "both"] { + for dx in [0.0, 0.25] { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0); + let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + select(&mut s, &[art]); + let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("object.move", &json!({"dx": dx})).unwrap(); + s.execute("effect.apply", &json!({"ids": [target.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let center = |s: &Session| { + let b = s.transform_box(&[target]).unwrap(); + b.to_doc() * vectorcraft_geom::reference_point(b.rect, 4) + }; + let at = center(&s); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let result = s.execute("addon.arrange.match", &json!({"rotate": true, "size": size})); + if dx == 0.0 { + result.unwrap(); + assert!((center(&s) - at).hypot() < 1e-6, "{size}"); + let b = s.transform_box(&[target]).unwrap(); + assert!(b.angle.abs() < 1e-6, "{size}: {b:?}"); + if size == "both" { + let wanted = s.transform_box(&[source]).unwrap(); + assert!((b.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {b:?}"); + assert!((b.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {b:?}"); + } + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + } else { + let error = result.unwrap_err().to_string(); + assert!(error.contains("can't keep its size and reference point as it turns"), "{size}: {error}"); + } + assert_eq!(steps(&s), n, "{size}, dx={dx}"); + assert!(*s.doc().unwrap().doc == *before, "{size}, dx={dx}"); + } + } +} + +#[test] +fn match_refuses_when_snapping_moves_a_pixel_aligned_symbol_instance_without_preview_bounds() { + let mut s = session(); + s.prefs.use_preview_bounds = false; + let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0); + let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + select(&mut s, &[art]); + let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("object.move", &json!({"dx": 0.25})).unwrap(); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + // Turned back to its natural angle, the instance snaps to whole points, which moves its center. + let error = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string(); + assert!(error.contains("can't keep its size and reference point as it turns"), "{error}"); + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn match_turns_art_with_a_moving_fill_effect_about_its_measured_point() { + for grouped in [false, true] { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + s.execute("effect.apply", &json!({"ids": [b.0], "item": 0, "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let b = if grouped { + select(&mut s, &[b]); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + } else { + b + }; + let center = |s: &Session| { + let bx = s.transform_box(&[b]).unwrap(); + bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4) + }; + let before = center(&s); + select(&mut s, &[a, b]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap(); + let after = center(&s); + assert!((after - before).hypot() < 1e-6, "grouped={grouped}: {before:?} -> {after:?}"); + let d = &s.doc().unwrap().doc; + assert!((d.bbox_angle(&[b]) - d.bbox_angle(&[a])).abs() < 1e-6); + } +} + #[test] fn match_replays_with_the_stroke_scaling_it_ran_with() { replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); @@ -765,6 +1115,169 @@ fn swap_replays_with_the_stroke_scaling_it_ran_with() { replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true})); } +/// Running `cmd` with Scale Corners on scales the 2 pt corners of two rounded squares with them, +/// and replaying its journal entry after the preference is turned off scales them the same way. +fn replays_the_corner_shapes_it_ran_with(cmd: &str, p: Value) { + let mut s = session(); + let square = |s: &mut Session, x: f64, w: f64| { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": w, "height": w, "radius": 2})).unwrap()["id"].as_u64().unwrap()) + }; + let a = square(&mut s, 0.0, 10.0); + let b = square(&mut s, 100.0, 20.0); + let shapes = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind))); + out.sort(); + out + }; + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap(); + select(&mut s, &[a, b]); + s.execute(cmd, &p).unwrap(); + let ran = shapes(&s); + let (id, q) = s.journal.last().unwrap().clone(); + assert_eq!(id, cmd); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap(); + select(&mut s, &[a, b]); + s.replay(&id, &q).unwrap(); + assert_eq!(shapes(&s), ran, "{cmd} replayed with other corners"); +} + +#[test] +fn match_replays_two_rounded_squares_with_the_corners_it_ran_with() { + replays_the_corner_shapes_it_ran_with("addon.arrange.match", json!({"size": "both"})); +} + +#[test] +fn set_size_of_each_replays_two_rounded_squares_with_the_corners_it_ran_with() { + replays_the_corner_shapes_it_ran_with("addon.arrange.size", json!({"width": 30, "height": 30})); +} + +#[test] +fn swap_replays_two_rounded_squares_with_the_corners_it_ran_with() { + replays_the_corner_shapes_it_ran_with("addon.arrange.swap", json!({"size": true})); +} + +#[test] +fn replace_replays_with_the_corner_scaling_it_ran_with() { + replays_the_corner_shapes_it_ran_with("addon.arrange.replace", json!({"fit": "bounds"})); +} + +#[test] +fn match_size_reaches_a_size_that_pixel_alignment_then_snaps() { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + select(&mut s, &[target]); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 15.5, 15.5); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "width"})).unwrap(); + let b = bounds(&s, target); + assert!((b.width() - 15.5).abs() <= 1.0 && (b.height() - 15.5).abs() <= 1.0, "{b:?}"); +} + +#[test] +fn match_size_fits_a_transform_copy_once_the_target_is_turned() { + for size in ["width", "both"] { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 30.0, 20.0); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": size, "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}"); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}"); + if size == "both" { + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}"); + } + } +} + +#[test] +fn match_size_fits_a_turned_target_whose_copy_fills_the_height_before_the_turn() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveV": 10, "copies": 1}})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 20.0, 5.0); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}"); +} + +#[test] +fn match_size_keeps_the_center_of_a_turned_target_whose_copy_stays_on_the_page() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 2000.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap(); + let center = s.transform_box(&[target]).unwrap().center(); + let source = rect(&mut s, 100.0, 100.0, 11.0, 20.0); + s.execute("object.rotate", &json!({"angle": 180})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}"); + assert!((measured.center() - center).hypot() < 1e-6, "{measured:?} {center:?}"); +} + +#[test] +fn match_size_refuses_a_width_below_a_fixed_transform_copy() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 100000.05, "copies": 1}})).unwrap(); + let before = s.transform_box(&[target]).unwrap(); + assert!((before.rect.width() - 100020.05).abs() < 1e-6, "{before:?}"); + let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let out = s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})); + assert!(out.is_err(), "{out:?} {:?}", s.transform_box(&[target])); +} + +#[test] +fn match_size_refuses_dimensions_a_fixed_rotated_copy_cannot_reach_together() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.execute( + "effect.apply", + &json!({"effect": "distort.transform", "item": null, "params": {"rotate": 90, "reference": 4, "moveH": 99990.05, "copies": 1}}), + ) + .unwrap(); + let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]); +} + +#[test] +fn match_size_takes_a_huge_object_down_to_a_point() { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 20000.0, 20000.0); + let source = rect(&mut s, 100.0, 0.0, 1.0, 1.0); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap(); + let b = bounds(&s, target); + assert!((b.width() - 1.0).abs() < 1e-6 && (b.height() - 1.0).abs() < 1e-6, "{b:?}"); +} + #[test] fn match_refuses_bad_params() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs index 7fc935546e..43e8948118 100644 --- a/crates/engine/src/cmd/addons/shapes.rs +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -298,7 +298,7 @@ fn star(s: &mut Session, p: &Value) -> Result { pie, arc_mode, }; - insert_custom(s, "Star", None, cs) + insert_custom(s, "Star", cs.to_live_shape(), cs) } fn spiral(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs index bc5f1359e2..274678dd62 100644 --- a/crates/engine/src/cmd/addons/shapes/tests.rs +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -144,6 +144,68 @@ fn shape_of(s: &Session, id: NodeId) -> CustomShape { CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()).unwrap() } +#[test] +fn configuring_a_live_star_keeps_its_live_shape() { + let mut s = new_session(); + for cmd in ["shape.star", "addon.shapes.star"] { + let id = id_of(&mut s, cmd, json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(live), .. } if matches!(live.as_ref(), LiveShape::Star { points: 5, .. }))); + assert!(matches!(CustomShape::read(n), Some(CustomShape::Polygon { sides: 5, spoke_ratio: Some(_), .. }))); + + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 7})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. })); + assert_eq!(path, &live.to_path()); + + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "spokeRatio": 0.4})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. })); + assert!((live.star_ratio().unwrap() - 0.4).abs() < 1e-9); + assert_eq!(path, &live.to_path()); + } +} + +/// A live star with a ratio below 0.01, which `object.setLiveShape` accepts, keeps its inner +/// radius and stays live when it is configured without a ratio. +#[test] +fn configuring_a_live_star_keeps_a_small_ratio() { + let mut s = new_session(); + let id = id_of(&mut s, "shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 60.0, "radius2": 30.0, "points": 5})); + s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": 0.0001})).unwrap(); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 6})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { r1, r2, points: 6, .. } if *r1 == 60.0 && (r2 - 0.006).abs() < 1e-9), "{live:?}"); + assert_eq!(path, &live.to_path()); +} + +/// Angles configured on a whole shape stay live and are kept for a later arc mode. +#[test] +fn angles_configured_on_a_whole_shape_are_kept_for_a_later_arc_mode() { + let mut s = new_session(); + let shapes = [ + ("shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})), + ("shape.polygon", json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5})), + ("shape.rectangle", json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 50.0})), + ("shape.ellipse", json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})), + ]; + for (cmd, p) in shapes { + let id = id_of(&mut s, cmd, p); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "startAngle": 0.0, "endAngle": 90.0})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(_), .. }), "{cmd} stays live"); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "arcMode": "pie"})).unwrap(); + let pie = match CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()) { + Some(CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. }) => pie, + other => panic!("{cmd}: {other:?}"), + }; + assert_eq!(pie, (0.0, 90.0), "{cmd}"); + } +} + /// Runs `cmd` with `p`, which must fail with `msg` and leave the document and its history as they /// were. fn refused(s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str) { diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 9a5be1fc4f..3a3c981229 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -903,7 +903,7 @@ pub struct SymbolOptions { impl SymbolOptions { /// The options `d` keeps for symbol `name`. - fn of(d: &Document, name: &str) -> Self { + pub(in crate::cmd) fn of(d: &Document, name: &str) -> Self { Self { size: stored_natural_size(d, name), registration: d.symbol_registration(name), @@ -914,7 +914,7 @@ impl SymbolOptions { } /// Make them the options of `d`'s symbol `name`. - fn give(&self, d: &mut Document, name: &str) { + pub(in crate::cmd) fn give(&self, d: &mut Document, name: &str) { set_natural_size(d, name, self.size); d.set_symbol_registration(name, self.registration); d.set_symbol_export_type(name, self.export_type); diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index b9f304ddf4..54c1db0f41 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -10,9 +10,12 @@ //! custom character sets: //! . +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + use serde_json::{Map, Value, json}; use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX}; -use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet}; +use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind}; use vectorcraft_text::FontDb; use super::fileio::{read_file_head, write_file}; @@ -77,6 +80,194 @@ pub fn specs() -> Vec { ] } +/// Every stored family name, including regeneration settings and retained style defaults. +/// Planning reads a private clone so gathering names never changes the destination. +fn family_names(d: &Document) -> Result> { + let mut view = d.clone(); + let mut names = BTreeSet::new(); + let mut note = |family: &mut String| { + names.insert(family.to_lowercase()); + }; + super::textstyles::each_text_mut(&mut view, &mut |text| { + for run in &mut text.runs { + note(&mut run.style.font_family); + } + Ok(()) + })?; + for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) { + if let Some(Value::String(family)) = style.attrs.get_mut("font_family") { + note(family); + } + } + let mut graphs = Vec::new(); + view.visit_stored(|node, _| { + if node.extras().graph.is_some() { + graphs.push(node.id); + } + }); + for id in graphs { + if let Some(node) = view.stored_node_mut(id) { + graph_families(node, &mut note); + } + } + fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) { + graph_families(node, note); + if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) { + brush_graphs(Arc::make_mut(&mut mask.art), note); + } + for child in node.children_mut().into_iter().flatten() { + brush_graphs(Arc::make_mut(child), note); + } + } + for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) { + brush_graphs(art, &mut note); + } + Ok(names) +} + +fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) { + if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) { + let labels = &mut graph.label_styles; + for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() { + visit(&mut style.font_family); + } + } +} + +/// Family fields held directly by one node; the adoption walker owns tree/resource traversal. +pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) { + if let NodeKind::Text(text) = &mut node.kind { + for run in &mut text.runs { + visit(&mut run.style.font_family); + } + // The fonts the file carried for this type are found by the family its runs name. + for font in text.file_fonts.iter_mut().flat_map(|fonts| fonts.fonts.iter_mut()) { + visit(&mut font.family); + } + } + // A live dimension makes its label again from its options. + if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_deref_mut()) { + visit(&mut dimension.options.font_family); + } + graph_families(node, visit); +} + +/// A fully checked incoming-only rename map and the destination's prospective definitions. +pub(super) struct CompositeImport { + names: BTreeMap, + pub(super) combined: Vec, +} + +impl CompositeImport { + pub(super) fn rename(&self, family: &mut String) -> bool { + if let Some(name) = self.names.get(&family.to_lowercase()) { + let changed = family.as_str() != name.as_str(); + *family = name.clone(); + changed + } else { + false + } + } +} + +fn composite_alias(base: &str, reserved: &BTreeSet, cmd: &str) -> Result { + let db = FontDb::global(); + let mut number = 2_u64; + loop { + let suffix = format!(" {number}"); + let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect(); + let name = format!("{}{suffix}", stem.trim_end()); + if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str()) + && !reserved.contains(&name.to_lowercase()) + && !db.has_installed_family(&name) + { + return Ok(name); + } + number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?; + } +} + +/// Plan used incoming definitions before changing either document or the font database. +/// Keep existing meanings even for an uninstalled family that destination art still names. +pub(super) fn plan_import(source: Vec, source_families: BTreeSet, target: &Document, cmd: &str) -> Result { + if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX { + return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); + } + let mut source_names = BTreeSet::new(); + for font in &source { + font.check().map_err(|why| bad(cmd, why))?; + if !source_names.insert(font.name.to_lowercase()) { + return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name))); + } + } + let target_families = family_names(target)?; + let mut target_taken = target_families.clone(); + for font in target.composite_fonts.iter() { + target_taken.insert(font.name.to_lowercase()); + target_taken.extend(font.part_fonts().map(str::to_lowercase)); + } + // Families the source names without defining them as composite fonts, which the target does + // define: they stay undefined under a free name instead of taking the target's meaning. + let undefined: Vec = source_families + .iter() + .filter(|family| !source_names.contains(*family) && !FontDb::global().has_installed_family(family)) + .filter_map(|family| CompositeFont::named(&target.composite_fonts, family).map(|font| font.name.clone())) + .collect(); + // Their alias may be a family the target's art already names without defining it, as an + // earlier placement of the same art left it, so that placement and this one share resources. + let mut alias_reserved = source_families.clone(); + for font in source.iter().chain(target.composite_fonts.iter()) { + alias_reserved.insert(font.name.to_lowercase()); + alias_reserved.extend(font.part_fonts().map(str::to_lowercase)); + } + let mut reserved = source_families; + reserved.extend(target_families); + for font in source.iter().chain(target.composite_fonts.iter()) { + reserved.insert(font.name.to_lowercase()); + reserved.extend(font.part_fonts().map(str::to_lowercase)); + } + let db = FontDb::global(); + let mut names = BTreeMap::new(); + let mut combined = target.composite_fonts.to_vec(); + for font in source { + let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom; + let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent); + let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name)); + if needs_alias { + // A repeated import reuses its already-installed equal alias. + reused = target.composite_fonts.iter().find(equivalent); + } + let name = match reused { + Some(other) => other.name.clone(), + None if needs_alias => composite_alias(&font.name, &reserved, cmd)?, + None => font.name.clone(), + }; + reserved.insert(name.to_lowercase()); + names.insert(font.name.to_lowercase(), name.clone()); + if reused.is_none() { + combined.push(CompositeFont { name, ..font }); + } + } + alias_reserved.extend(names.values().map(|name| name.to_lowercase())); + for family in undefined { + let name = composite_alias(&family, &alias_reserved, cmd)?; + alias_reserved.insert(name.to_lowercase()); + names.insert(family.to_lowercase(), name); + } + // A source document may currently lend fonts to the database. Validate the prospective + // document, not composite names temporarily registered by a different document. + if combined.len() > COMPOSITE_FONTS_MAX { + return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); + } + if let Some(font) = combined.iter().skip(target.composite_fonts.len()).find(|font| db.has_installed_family(&font.name)) { + return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name))); + } + if CompositeFont::usable(&combined).is_some() { + return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together")); + } + Ok(CompositeImport { names, combined }) +} + /// Register the active document's composite fonts in the font database, and remove the ones the /// other open documents (or an earlier active document) defined. Run after each command and when /// another document takes the front, so an undo, a revert, an opened or closed file or a document diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 083cfa65d9..934151589b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}: a live star whose points and ratio object.setLiveShape changes", has_doc, star ), @@ -655,14 +655,11 @@ fn star(s: &mut Session, p: &Value) -> Result { let r2 = f64_or(p, "radius2", r1 / 2.0).abs(); let n = count_or(p, "points", 5, "shape.star")?.clamp(2, 1000) as u32; let rot = f64_or(p, "rotation", 0.0); - let turn = vectorcraft_geom::rotate_deg(rot); // A quarter or whole turn (a Constrain Angle of 90°, say) turns the upright star exactly. - let path = if rot != 0.0 && turn.as_coeffs()[..4].iter().all(|c| c.fract() == 0.0) { - shapes::star(Point::ZERO, r1, r2, n, 0.0).transformed(Affine::translate(c.to_vec2()) * turn) - } else { - shapes::star(c, r1, r2, n, rot) - }; - add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot)) + let xf = Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + // The star stays live: its point count and ratio can change later (`object.setLiveShape`). + let live = LiveShape::Star { r1, r2, points: n, xf, radii: vec![], kinds: vec![], radii_relative: false }; + add_art_turned(s, "Star", path_kind(live.to_path(), Some(live)), constrained_turn(s, rot)) } fn line(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 5d849cfed2..073c35e88c 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -5,6 +5,7 @@ //! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"` //! the objects inside them (see `appearance`). +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; @@ -115,7 +116,7 @@ fn effect_specs() -> Vec { "Move Effect", [], None, - "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", + "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", has_doc, move_effect ), @@ -288,6 +289,15 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result { Ok(json!({"refreshed": counts.refreshed, "stillDeferred": counts.still_deferred, "failed": counts.failed})) } +/// Report the first rendered 3D effect that keeps its shaded faces after an edit. +fn with_render_warning(s: &Session, ids: &[NodeId], mut out: Value) -> Result { + let d = &s.doc()?.doc; + if let Some(message) = ids.iter().filter_map(|id| d.node(*id)).find_map(|n| effects::rendered_warning(d, n)) { + out["warning"] = json!(message); + } + Ok(out) +} + fn ids_json(ids: &[NodeId]) -> Value { json!(ids.iter().map(|i| i.0).collect::>()) } @@ -568,7 +578,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { }; let landed = first.and_then(|n| at.effects_item(&n.appearance, C).ok().flatten()); let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1)); - Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed })) + with_render_warning(s, &ids, json!({ "ids": ids_json(&ids), "index": index, "item": landed })) } /// The selected objects a Pathfinder effect should group before it applies: it combines the @@ -678,6 +688,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids) })) } +impl Session { + /// Can the Appearance panel reorder shared effects on the exact subjects it displays? + /// A generated graph design or a selection normalized to different objects has no matching row. + pub fn can_reorder_selected_effects(&self) -> bool { + let Ok(st) = self.doc() else { return false }; + let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false }; + let selected: HashSet<_> = st.selection.subjects().iter().copied().collect(); + roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id)) + } +} + +/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the +/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing. +fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option>> { + let mut seen = HashSet::with_capacity(ids.len()); + let mut appearances: Vec<&vectorcraft_doc::Appearance> = + ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::>()?; + let first = *appearances.get(anchor)?; + if source == ItemTarget::Top { + return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]); + } + let item = source.effects_item(first, "effect.move").ok()??; + appearances.swap(0, anchor); + let shared = SharedStack::of(&appearances); + let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::>>()?; + slots.swap(0, anchor); + Some(slots) +} + /// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s. fn move_effect(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.move"; @@ -694,17 +733,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src }; let copy = switch_or(p, "copy", false, C)?; let roots = edit_targets(s, p, C)?; - // Where an aligned effect would go in each of several different stacks isn't one place. - if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) { - return Err(bad(C, "effects of objects whose appearances differ can't be moved together")); - } + let reference = design_reference(s, p, C)?; + let d = &s.doc()?.doc; + let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) { + // An omitted item and a numbered item can use different anchors and still name the same row. + let shared = (!copy && reference.is_none()) + .then(|| { + shared_reorder_slots(d, &roots, src, src.anchor(s, &roots)) + .filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source)) + }) + .flatten(); + Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?) + } else { + None + }; // Where the effect landed in each object it moved in, in the order of `ids`. let mut landed = vec![]; let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| { let mut done = vec![]; - for id in &roots { + for (k, id) in roots.iter().enumerate() { let Some(n) = d.node_mut(*id) else { continue }; - let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?); + let (si, di) = match &slots { + Some(slots) => (slots[k], slots[k]), + None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?), + }; let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue }; // Taken out from the top down, so the lower positions stay valid; put back in order. let mut taken: Vec = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect(); @@ -848,7 +900,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let ids: Vec<&str> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index).map(|e| e.id.as_str())).collect(); if !ids.is_empty() && ids.iter().all(|id| *id == to) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // Pathfinder effects given the values they already evaluate with, and nothing else to change, @@ -857,7 +909,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect(); if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, ¶ms)) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // An SVG filter is named by its id: another filter renames the effect. @@ -904,7 +956,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect(); if !fx.is_empty() && fx.iter().all(|e| three_d_edit_changes_nothing(e, ¶ms)) { - return Ok(json!({ "ids": [] })); + return with_render_warning(s, &targets.iter().map(|t| t.0).collect::>(), json!({ "ids": [] })); } } // The effect edited, when every target has one at `index` and all are the same: a dialog's @@ -939,7 +991,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { true }) })?; - Ok(json!({ "ids": ids_json(&ids) })) + with_render_warning(s, &ids, json!({ "ids": ids_json(&ids) })) } /// Does effect `id` take a `bevel` (Extrude & Bevel, Extrude & Bevel (Classic)), which may be a diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index fad6df1e40..67e6981139 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -74,7 +74,7 @@ use serde_json::{Value, json}; pub(crate) use action_batch::action_step; pub use action_batch::batch_overwrites_one_file; -pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; +pub use dxf::{UNSUPPORTED, Unsupported, unsupported, write_hint}; pub use encode::{ ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds, note_texts, @@ -246,6 +246,8 @@ mod tests_svgimport; #[cfg(test)] mod tests_eps; +#[cfg(test)] +mod tests_dwgimport; #[cfg(test)] mod tests_dxfimport; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index c341f03e69..04aef3563a 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -29,6 +29,14 @@ const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under th const LENSES: &str = "CDR lenses and object transparency were not applied, and the objects they are on show opaque"; const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out"; const DAMAGED: &str = "damaged parts of the drawing were left out"; +/// Shown with [`UNSUPPORTED_OBJECTS`] or [`TOO_DEEP`]: `craft-cdr` opens a PowerClip frame whose +/// contents were all left out as a plain shape. Its warnings name neither the kinds of objects +/// left out nor the frames that lost their contents, so this line is shown whenever objects were +/// left out. Once `craft-cdr` reports which frames lost their contents, show it only for those. +const EMPTY_FRAMES: &str = "CDR PowerClip frames whose contents were left out opened empty, as plain shapes"; +/// The first version, in hundreds, whose PowerClip frames `craft-cdr` reads: earlier versions +/// store their objects' styles inline, and the reader opens none of them as frames. +const FRAMES_FROM: u16 = 400; const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; const CMX_UNSUPPORTED_OBJECTS: &str = @@ -103,7 +111,11 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec)> { } why => err(format!("this CDR drawing can't be read ({why})")), })?; - Ok(build(&d, note, PAGES_CUT)) + let (doc, mut warnings) = build(&d, note, PAGES_CUT); + if d.version >= FRAMES_FROM && d.warnings.iter().any(|w| matches!(w, Warning::UnsupportedObjects | Warning::TooDeep)) { + warnings.push(EMPTY_FRAMES.to_string()); + } + Ok((doc, warnings)) } /// Is `bytes` a `.cmx` file, of any byte order or coordinate size? diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index bddd245b71..c35ad702f4 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each addon.arrange.artboardGuides, edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as PageMaker, with what to use instead)}", always, formats ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8004234c07..c92d9b8ad0 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -1,6 +1,7 @@ //! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As //! → DXF Options): the options parsed from the params, one drawing per artboard with Use -//! Artboards, and the formats that can't be written (DWG, PageMaker) with what to use instead. +//! Artboards, and the formats that can't be written (DWG, which opens, and PageMaker) with what to +//! use instead. use std::sync::Arc; @@ -99,20 +100,12 @@ pub struct Unsupported { } /// Formats people ask for that VectorCraft doesn't read or write. Append-only. -pub const UNSUPPORTED: &[Unsupported] = &[ - Unsupported { - id: "dwg", - label: "DWG", - extensions: &["dwg"], - hint: "DWG is not available (no openly licensed writer exists): export DXF instead, which CAD apps open", - }, - Unsupported { - id: "pmd", - label: "PageMaker", - extensions: &["pmd"], - hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here", - }, -]; +pub const UNSUPPORTED: &[Unsupported] = &[Unsupported { + id: "pmd", + label: "PageMaker", + extensions: &["pmd"], + hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here", +}]; /// The unsupported format an id or extension (any case, leading dot allowed) names. pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> { @@ -120,6 +113,16 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> { UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str())) } +/// Formats VectorCraft opens but doesn't write, with what to export instead. +const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")]; + +/// What to write instead of the format an id or extension (any case, leading dot allowed) names, +/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG). +pub fn write_hint(id_or_ext: &str) -> Option<&'static str> { + let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase(); + unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(id, _)| *id == k).map(|(_, hint)| *hint)) +} + impl Unsupported { pub fn to_json(&self) -> Value { json!({ "id": self.id, "label": self.label, "extensions": self.extensions, "hint": self.hint }) diff --git a/crates/engine/src/cmd/fileio/dxfimport.rs b/crates/engine/src/cmd/fileio/dxfimport.rs index eef7aca4cd..2d16034c09 100644 --- a/crates/engine/src/cmd/fileio/dxfimport.rs +++ b/crates/engine/src/cmd/fileio/dxfimport.rs @@ -1,4 +1,4 @@ -//! Opening and placing DXF drawings: the `dxf` options `document.open` and `file.place` read +//! Opening and placing DXF and DWG drawings: the `dxf` options `document.open` and `file.place` read //! (layout, scale or fit, lineweights, centring, merged layers) and `document.dxfInfo` (layouts, //! layers, units) for the DXF Import Options dialog. @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "DXF Info", [], None, - "{path} or {name?, dataBase64} what a DXF drawing holds → {version (2018, R12…), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}; a DWG answers an error saying to save it as DXF", + "{path} or {name?, dataBase64} what a DXF or DWG drawing holds → {version (2018, R12…; a DWG's is that of the DXF it converts to), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}", always, dxf_info )] @@ -70,7 +70,7 @@ pub(super) fn options(cmd: &str, p: Option<&Value>) -> Result { }) } -/// Import a DXF drawing → the document and import notes. +/// Import a DXF or DWG drawing → the document and import notes. pub(super) fn import(bytes: &[u8], o: &ImportOptions) -> Result<(Document, Vec)> { let r = vectorcraft_cad::import(bytes, o).map_err(err)?; Ok((r.document, r.warnings)) diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 4fee998d8e..f8da5b941c 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -561,6 +561,9 @@ pub const FORMATS: &[Format] = &[ // Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size // composite, the layers combined, or the preview with a note. Exports don't write them. reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true), + // DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF + // reader with the DXF import options. Exports don't write them. + reader("dwg", "DWG", &["dwg"], "image/vnd.dwg", false), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -622,6 +625,7 @@ pub const OPEN_EXTS: &[&str] = &[ "cdt", "cmx", "pcraft", + "dwg", ]; /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to @@ -629,11 +633,11 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. -/// The packaging declares no type for HP-GL plot files, PICT pictures or layered raster `.pcraft` -/// documents either. +/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft` +/// documents or DWG drawings either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -724,6 +728,7 @@ pub const PLACE_EXTS: &[&str] = &[ "cdt", "cmx", "pcraft", + "dwg", "txt", "rtf", "docx", @@ -1087,6 +1092,8 @@ pub fn writable_format(format_param: Option<&str>, path: Option<&str>) -> std::r Ok(f) } else if TEMPLATE_FORMATS.contains(&f.id) { Err(format!("{} files are written by file.saveAsTemplate", f.label)) + } else if let Some(hint) = super::dxf::write_hint(f.id) { + Err(hint.to_string()) } else { Err(format!("{} files can be opened but not written (see document.formats)", f.label)) } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 53cac16bee..f152132c69 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -47,12 +47,12 @@ impl Loaded { /// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or /// what an importer plug-in reads, as the reference app opens such files (#5820). A native /// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the - /// units of its root's size, pixels when it gives none), a DXF drawing (the unit it was read - /// in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows + /// units of its root's size, pixels when it gives none), a DXF or DWG drawing (the unit it was + /// read in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows /// change, not its art. pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self { let records_units = - self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf"); + self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf" | "dwg"); if !records_units { self.doc.units = crate::units::pref_unit(&prefs.units_general); } @@ -125,6 +125,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if vectorcraft_cad::is_dxf(bytes) { return format("dxf"); } + if vectorcraft_cad::is_dwg(bytes) { + return format("dwg"); + } if let Some(kind) = vectorcraft_metafile::sniff(bytes) { return format(kind.id()); } @@ -560,7 +563,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } read } - "dxf" => { + // A DWG drawing is read as the DXF craft-dwg converts it to. + "dxf" | "dwg" => { let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?; (doc, warnings, false) } diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 954a345ae0..005cc4a557 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -176,8 +176,8 @@ impl LoadOptions { self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages } - /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible - /// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default, + /// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible + /// `.ai` with Illustrator private data opens on its trim boxes by default, /// with the bleed around them. An explicit crop-box request uses its crop box. fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { @@ -257,7 +257,7 @@ pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page /// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box; -/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the +/// a PDF-compatible `.ai` that names no box gets its trim box, as it opens), in a row from the /// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box, /// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the /// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens @@ -289,8 +289,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?, }; let bounding = o.crop == CropTo::Bounding; - // A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]). - let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop }; + // A PDF-compatible `.ai` that names no box opens on its trim boxes ([`LoadOptions::import_options`]); + // an explicit crop-box request keeps its crop boxes. + let crop = if !o.explicit_crop_box && o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop }; let mut doc = Document::new(1.0, 1.0); let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?; doc.artboards.clear(); diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 2645e86c76..2e4d82822b 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -89,6 +89,8 @@ fn versions_3_and_4_open_and_place_as_editable_art() { assert_eq!(r["format"], "cdr", "{version} {name}"); let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}"); + // The reader opens PowerClip frames from version 4 on. + assert_eq!(w.iter().any(|w| w.contains("PowerClip")), version >= 400, "{version}: {w:?}"); } let doc = &s.doc().unwrap().doc; assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}"); @@ -535,6 +537,35 @@ fn containers_open_as_clipping_groups() { assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. }))); } +/// A container whose clipped group holds only objects the reader leaves out (a bitmap here), or +/// whose group holds a container of that same group, opens as a plain shape, and the warnings +/// say that such frames opened empty. +#[test] +fn containers_whose_contents_were_left_out_are_named_in_the_warnings() { + let v = V(1100); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let open = |clipped: Vec| { + let doc = list(b"doc ", vec![synth::clpt(vec![(5, clipped)])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]); + super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap() + }; + let frames = "PowerClip frames whose contents were left out opened empty"; + let (doc, warnings) = open(vec![synth::object(v, 5, &[(30, v.rect(10.0, 10.0, 0.0))], None)]); + let p = paths(&doc); + let [frame] = p.as_slice() else { panic!("{p:?}") }; + assert!(matches!(frame.kind, NodeKind::Path { clipping: false, .. }), "{:?}", frame.kind); + assert!(warnings.iter().any(|w| w.contains("text, bitmaps")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); + // The inner container names the group already being read, so it is left out at the limit. + let (_, warnings) = open(vec![rect(10.0, vec![synth::container(5)])]); + assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}"); +} + /// An object with a lens or transparency opens opaque, and the warnings say so. #[test] fn lenses_and_transparency_are_named_in_the_warnings() { diff --git a/crates/engine/src/cmd/fileio/tests_dwgimport.rs b/crates/engine/src/cmd/fileio/tests_dwgimport.rs new file mode 100644 index 0000000000..d4aa2ad348 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_dwgimport.rs @@ -0,0 +1,113 @@ +//! DWG through the commands: `document.open`, `document.dxfInfo` and File → Place read a DWG +//! drawing as the DXF it converts to, with the DXF options; DWG is in the format table as read +//! only, and exporting one says to write DXF. craft-dwg reads and writes DWG everywhere but wasm32 +//! and FreeBSD on aarch64. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; + +use super::tests_dxfimport::plan; +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// The DXF test drawing as a DWG 2004 file, written by craft-dwg. +fn plan_dwg() -> Vec { + vectorcraft_cad::dwg::allow_in_process(); + craft_dwg::dxf_to_dwg_as(&plan(), "AC1018").unwrap() +} + +fn open(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> crate::Result { + let mut p = json!({"name": name, "dataBase64": b64(bytes)}); + if let (Some(p), Value::Object(e)) = (p.as_object_mut(), extra) { + p.extend(e); + } + s.execute("document.open", &p) +} + +fn layer_names(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().filter_map(|l| l.name.clone()).collect() +} + +fn leaves(s: &Session) -> Vec { + let mut out = vec![]; + s.doc().unwrap().doc.walk(|n| { + if n.children().is_none() { + out.push(n.clone()); + } + }); + out +} + +#[test] +fn document_open_reads_a_dwg_drawing_as_its_dxf() { + let mut s = Session::new(); + open(&mut s, "plan.dxf", &plan(), json!({})).unwrap(); + let (want_layers, want_board, want_leaves) = (layer_names(&s), s.doc().unwrap().doc.artboards[0].rect, leaves(&s).len()); + let r = open(&mut s, "plan.dwg", &plan_dwg(), json!({})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("dwg"), Some("plan.dwg"))); + assert_eq!(layer_names(&s), want_layers); + let st = s.doc().unwrap(); + let board = st.doc.artboards[0].rect; + assert!((board.width() - want_board.width()).abs() < 1e-6 && (board.height() - want_board.height()).abs() < 1e-6, "{board:?}"); + assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters); + assert_eq!(leaves(&s).len(), want_leaves); + assert_eq!(leaves(&s).iter().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).count(), 2, "the block's two inserts"); + // The DXF options apply. + open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"fit": true, "mergeLayers": true}})).unwrap(); + assert_eq!(layer_names(&s), ["Layer 1"]); + assert!(open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"layout": "Sheet 9"}})).is_err()); +} + +#[test] +fn a_dwg_opened_is_never_written_back_as_dwg() { + let dir = std::env::temp_dir().join(format!("vc-dwg-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("plan.dwg"); + let dwg = plan_dwg(); + std::fs::write(&path, &dwg).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap(); + let e = s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("not DWG"), "{e}"); + let e = s.execute("document.export", &json!({"format": "dwg"})).unwrap_err().to_string(); + assert!(e.contains("export DXF instead"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), dwg, "the drawing is unchanged"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn dxf_info_and_place_read_a_dwg() { + let mut s = Session::new(); + let dxf = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&plan())})).unwrap(); + let dwg = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&plan_dwg())})).unwrap(); + for k in ["units", "layouts", "unit", "scale"] { + assert_eq!(dwg[k], dxf[k], "{k}"); + } + let layers: Vec<&str> = dwg["layers"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(layers.contains(&"Walls") && layers.contains(&"Notes"), "{layers:?}"); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("file.place", &json!({"name": "plan.dwg", "dataBase64": b64(&plan_dwg()), "dxf": {"fit": true}})).unwrap(); + assert_eq!(r["format"], "dwg"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + assert!((b.width() - 600.0).abs() < 1.0 && (b.center().y - 200.0).abs() < 0.5, "fitted to the artboard: {b:?}"); +} + +#[test] +fn dwg_is_read_only_and_detected_by_content() { + let f = format("dwg").unwrap(); + assert!(f.read && !f.write); + assert!(OPEN_EXTS.contains(&"dwg") && PLACE_EXTS.contains(&"dwg") && UNASSOCIATED_EXTS.contains(&"dwg")); + assert_eq!(detect("drawing.bin", &plan_dwg()).map(|f| f.id), Some("dwg"), "the content tells"); + let mut s = Session::new(); + let r = s.execute("document.formats", &json!({})).unwrap(); + assert!(r["readable"].as_array().unwrap().contains(&json!("dwg"))); + assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg"))); + assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg")); +} diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index b5129d1910..7a04d93ddc 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -1,5 +1,5 @@ //! DXF export through the commands: options, artboards, selection, images, and the formats that -//! can't be written (DWG, PageMaker). +//! can't be written (DWG, which opens, and PageMaker). use serde_json::{Value, json}; @@ -293,7 +293,7 @@ fn formats_list_dxf_and_what_can_not_be_written() { } assert!(r["writable"].as_array().unwrap().contains(&json!("dxf"))); let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap()).collect(); - assert_eq!(unsupported, ["dwg", "pmd"]); + assert_eq!(unsupported, ["pmd"]); } #[test] @@ -301,7 +301,7 @@ fn dwg_and_pagemaker_say_what_to_use_instead() { let mut s = two_boards(); for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] { let e = s.execute("document.export", &p).unwrap_err().to_string(); - assert!(e.contains("DWG is not available") && e.contains("DXF"), "{p}: {e}"); + assert!(e.contains("DWG files open but can't be written") && e.contains("export DXF instead"), "{p}: {e}"); } // PICT opens; it isn't written. let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string(); @@ -315,7 +315,8 @@ fn dwg_and_pagemaker_say_what_to_use_instead() { .execute("document.open", &json!({"name": "site.dwg", "dataBase64": vectorcraft_format::base64_encode(b"AC1032\0\0")})) .unwrap_err() .to_string(); - assert!(e.contains("DWG is not available"), "{e}"); + // A DWG that can't be converted says so (DWG drawings open: see tests_dwgimport). + assert!(e.contains("DWG"), "{e}"); let e = s .execute("document.open", &json!({"name": "brochure.PMD", "dataBase64": vectorcraft_format::base64_encode(b"PageMaker")})) .unwrap_err() diff --git a/crates/engine/src/cmd/fileio/tests_dxfimport.rs b/crates/engine/src/cmd/fileio/tests_dxfimport.rs index d3dcdcb86c..524913dcb7 100644 --- a/crates/engine/src/cmd/fileio/tests_dxfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_dxfimport.rs @@ -14,7 +14,7 @@ fn b64(bytes: &[u8]) -> String { /// A millimetre drawing: a 200 × 100 rectangle on layer Walls, a circle on layer Notes, a block /// "Mark" (a short line) inserted twice, and a paper layout holding a line. -fn plan() -> Vec { +pub(super) fn plan() -> Vec { let pairs: &[(i32, &str)] = &[ (0, "SECTION"), (2, "HEADER"), diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3a52534ac8..ca4a9d7022 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard (unless it is new art there that is still selected), and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -1051,7 +1051,8 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when - // the path was, or when the compound path it leaves was. + // the path was, or when the compound path it leaves was. A compound path that is + // pixel-aligned snaps the path it takes in. if let Some(c) = into { let mut aligned = from_aligned; if let Some(m) = d.node_mut(id) { @@ -1061,9 +1062,12 @@ fn move_node(s: &mut Session, p: &Value) -> Result { *live = None; } } - if aligned && let Some(cn) = d.node_mut(c) { - cn.extras_mut().pixel_aligned = true; - super::object::snap_if_aligned(cn); + if let Some(cn) = d.node_mut(c) { + aligned |= cn.extras().pixel_aligned; + if aligned { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } } } if let Some((appearance, aligned)) = out_of diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index a5e00eab67..3851aeefac 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -40,6 +40,12 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_do pub fn specs() -> Vec { vec![ + cmd!(query "view.showMissingLinks", "Show Missing Links", ["View"], None, + "{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}", + has_doc, show_missing_links), + cmd!(query "links.marked", "Marked Missing Links", [], None, + "{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off; a caller whose read folders do not cover the same files as the document's, or a script command, gets its own answer and the canvas markers stay as they are → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}", + has_doc, marked), cmd!( query "links.check", "Check Links", @@ -518,6 +524,8 @@ fn refused(link: &LinkInfo, doc_path: Option<&str>) -> Option (Status, Option) { + #[cfg(test)] + probe_gate::hold(&g.link.path); let Some(mut f) = locate(&g.link, base) else { return (Status::Missing, None) }; let l = &g.link; if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) { @@ -536,6 +544,24 @@ fn probe(g: &Group, base: LinkBase) -> (Status, Option) { (if same { Status::Ok } else { Status::Modified }, Some(f)) } +/// Whether [`probe`] would find group `g`'s file missing, without reading or hashing its content. +/// A changed file is opened to check it can be read, and nothing more: the canvas markers ask only +/// this, and with Update Links set to Manually a changed file keeps differing from its stored link, +/// so a full probe would read the whole file again on every look while the markers are on. +fn missing(g: &Group, base: LinkBase) -> bool { + #[cfg(test)] + probe_gate::hold(&g.link.path); + let Some(f) = locate(&g.link, base) else { return true }; + let l = &g.link; + if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) { + return false; + } + if l.size == Some(f.size) && l.modified.is_some() && l.modified == f.modified { + return false; + } + fileio::read_file_head(&f.path, 0).is_err() +} + /// Is image `key` of `d` showing its preview (its file not read)? fn previewing(d: &Document, key: &str) -> bool { d.images.get(key).is_none_or(ImageBlob::is_proxy) @@ -2159,6 +2185,7 @@ fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) - editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g)))) })?; } + clear_markers(s, &updated)?; let mut out = json!({ "updated": updated, "missing": missing }); if !warnings.is_empty() { out["warnings"] = json!(warnings); @@ -2451,6 +2478,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { } not_found.sort(); not_found.dedup(); + clear_markers(s, &relinked)?; let mut out = json!({ "relinked": relinked, "notFound": not_found }); if !warnings.is_empty() { out["warnings"] = json!(warnings); @@ -2630,6 +2658,68 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap